问:
Symfony 4 "code": 401, "message": "Invalid credentials." jwt authentication error
I'm trying to make a jwt authentication with Symfony 4

I configured my project as follow

// security.yaml

security:
    encoders:
        App\Entity\User:
            algorithm: auto

    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            json_login:
                check_path:               /api/login_check
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure

        api:
                pattern:   ^/api
                stateless: true
                guard:
                    authenticators:
                        - lexik_jwt_authentication.jwt_token_authenticator

        main:
            anonymous: true
            provider: app_user_provider

            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#firewalls-authentication

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }
```

<pre class="lang-yaml prettyprint-override"><code>// routes.yaml

api_login_check:
    path: /api/login_check
</code>```

```<code>// .env

###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$
###< nelmio/cors-bundle ###

###> lexik/jwt-authentication-bundle ###
JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem
JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem
JWT_PASSPHRASE=d96058cb8b34d7061148465f3d286ae4
###< lexik/jwt-authentication-bundle ###
</code>```

//lexik_jwt_authentication.yaml

lexik_jwt_authentication:
    secret_key:       '%kernel.project_dir%/config/jwt/private.pem' # required for token creation
    public_key:       '%kernel.project_dir%/config/jwt/public.pem'  # required for token verification
    pass_phrase:      'd96058cb8b34d7061148465f3d286ae4'
    token_ttl:        3600
```

<pre class="lang-php prettyprint-override"><code>//UserRepository.php

class UserRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }

    // /**
    //  * @return User[] Returns an array of User objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('u')
            ->andWhere('u.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('u.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?User
    {
        return $this->createQueryBuilder('u')
            ->andWhere('u.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */
</code>```

and I generated 2 keys (private and public) in a folder named Jwt inside the config folder.

Now according to a documentation that I followed if I run:

curl -X POST -H "Content-Type: application/json" http://localhost/api/login_check -d '{"username":"johndoe","password":"test"}'
```

<p>I'll be able to get a token like that in return </p>

```{
   "token" : "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9.eyJleHAiOjE0MzQ3Mjc1MzYsInVzZXJuYW1lIjoia29ybGVvbiIsImlhdCI6IjE0MzQ2NDExMzYifQ.nh0L_wuJy6ZKIQWh6OrW5hdLkviTs1_bau2GqYdDCB0Yqy_RplkFghsuqMpsFls8zKEErdX5TYCOR7muX0aQvQxGQ4mpBkvMDhJ4-pE4ct2obeMTr_s4X8nC00rBYPofrOONUOR4utbzvbd4d2xT_tj4TdR_0tsr91Y7VskCRFnoXAnNT-qQb7ci7HIBTbutb9zVStOFejrb4aLbr7Fl4byeIEYgp2Gd7gY"
}
```

<p>but instead I got this error:</p>

```{"error":{"code":400,"message":"Bad Request","exception":[{"message":"Invalid JSON.","class":"Symfony\\Component\\HttpKernel\\Exception\\B [...]
```

<p>and when I used postman
and send</p>

```{
  "username": "test",
  "password": "test"
}`
url : `http://localhost:8000/api/login_check`
method : `POST`
```

I got this error
 {
    "code": 401,
    "message": "Invalid credentials."
}

could you please tell me why i got this error and how to fix it
Postman

答:
Add this at the end of your httpd.conf:

```<code>SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1"
</code>```

Body:
I'm trying to make a jwt authentication with Symfony 4

I configured my project as follow

// security.yaml

security:
    encoders:
        App\Entity\User:
            algorithm: auto

    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        login:
            pattern:  ^/api/login
            stateless: true
            anonymous: true
            json_login:
                check_path:               /api/login_check
                success_handler:          lexik_jwt_authentication.handler.authentication_success
                failure_handler:          lexik_jwt_authentication.handler.authentication_failure

        api:
                pattern:   ^/api
                stateless: true
                guard:
                    authenticators:
                        - lexik_jwt_authentication.jwt_token_authenticator

        main:
            anonymous: true
            provider: app_user_provider

            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#firewalls-authentication

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }

// routes.yaml

api_login_check:
    path: /api/login_check

// .env

###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$
###< nelmio/cors-bundle ###

###> lexik/jwt-authentication-bundle ###
JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem
JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem
JWT_PASSPHRASE=d96058cb8b34d7061148465f3d286ae4
###< lexik/jwt-authentication-bundle ###

//lexik_jwt_authentication.yaml

lexik_jwt_authentication:
    secret_key:       '%kernel.project_dir%/config/jwt/private.pem' # required for token creation
    public_key:       '%kernel.project_dir%/config/jwt/public.pem'  # required for token verification
    pass_phrase:      'd96058cb8b34d7061148465f3d286ae4'
    token_ttl:        3600

//UserRepository.php

class UserRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }

    // /**
    //  * @return User[] Returns an array of User objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('u')
            ->andWhere('u.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('u.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?User
    {
        return $this->createQueryBuilder('u')
            ->andWhere('u.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */

and I generated 2 keys (private and public) in a folder named Jwt inside the config folder.

Now according to a documentation that I followed if I run:

curl -X POST -H "Content-Type: application/json" http://localhost/api/login_check -d '{"username":"johndoe","password":"test"}'

I'll be able to get a token like that in return

{
   "token" : "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9.eyJleHAiOjE0MzQ3Mjc1MzYsInVzZXJuYW1lIjoia29ybGVvbiIsImlhdCI6IjE0MzQ2NDExMzYifQ.nh0L_wuJy6ZKIQWh6OrW5hdLkviTs1_bau2GqYdDCB0Yqy_RplkFghsuqMpsFls8zKEErdX5TYCOR7muX0aQvQxGQ4mpBkvMDhJ4-pE4ct2obeMTr_s4X8nC00rBYPofrOONUOR4utbzvbd4d2xT_tj4TdR_0tsr91Y7VskCRFnoXAnNT-qQb7ci7HIBTbutb9zVStOFejrb4aLbr7Fl4byeIEYgp2Gd7gY"
}

but instead I got this error:

{"error":{"code":400,"message":"Bad Request","exception":[{"message":"Invalid JSON.","class":"Symfony\\Component\\HttpKernel\\Exception\\B [...]

and when I used postman
and send

{
  "username": "test",
  "password": "test"
}`
url : `http://localhost:8000/api/login_check`
method : `POST`

I got this error
 {
    "code": 401,
    "message": "Invalid credentials."
}

could you please tell me why i got this error and how to fix it
Postman

Body:
Add this at the end of your httpd.conf:

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1"


来源: stackexchange

问:
C++ const string literals and custom string class
In C++ string literals "Hello" are const and are immutable.  I wanted to make a custom string class whose strings are not const chars, so they can be changeable

Here is a snippet of code that might illustrate what I'm trying to do:

```<code>#include <iostream>

class String {
  public:
    char * p_start;

    String(char * strSourc) // Constructor
      {
        p_start = strSourc;
      }
};

int main()
{
  String myString("Hello");
// Create object myString, send "Hello" string literal as argument

  std::cout << myString.p_start << std::endl;
// Prints "Hello"

  *myString.p_start = 'Y';
// Attempt to change value at first byte of myString.p_start

  std::cout << myString.p_start << std::endl;
// Prints "Hello" (no change)

  myString.p_start = "Yellow";
// Assigning a string literal to p_start pointer

  std::cout << myString.p_start << std::endl;
// Prints Yellow, change works.  I thought myString "Hello" was const chars, immutable

  return 0;
}
</code>```

So, I'm confused.  I've looked everywhere and it says that string literals, like "Hello", are immutable, each of their char bytes are unchangeable.  Though I managed to assign Yellow to the p_start pointer, changing the first letter.  Though changing the single letter H to a Y through dereferencing the H pointer didn't do anything.

Any insights would help me, thanks.

答:
not sure if anyone finds this helpful after so long but since I am learning myself I took your above code and made it work by copying. It now has a member variable for size and cleans up using delete when you assign a new string literal to it (const char*).

```<code>#include <iostream>

class String {
public:
char * p_start;
int m_size;

String(const char * strSourc) // Constructor
  {
    //The following will get the size of the parameter.
     int SizeParameter=0;
     while (*(strSourc+SizeParameter) != '\0')
     {
         SizeParameter++;
     }
     // size of string saved.
     m_size = SizeParameter;
     // allocate enough memory so we can copy strSourc
     p_start = new char[SizeParameter+1];
     //copy the contents strSourc
    for(int i=0; i<SizeParameter+1; i++)
    {
    *(p_start+i) = *(strSourc+i);
    }
  }
  //Handle change of string value.
  char* AssignNewString (const char* newtext)
  {
      //clean
      delete p_start;

      int SizeParameter=0;
     while (*(newtext+SizeParameter) != '\0')
     {
         SizeParameter++;
     }
     // size of string saved.
     m_size = SizeParameter;
     // allocate enough memory so we can copy strSourc
     p_start = new char[SizeParameter+1];
     //copy the contents strSourc
    for(int i=0; i<SizeParameter+1; i++)
    {
    *(p_start+i) = *(newtext+i);
    }
    return p_start;
  }
  char* operator=(const char* newtext)
  {
  AssignNewString(newtext);
  }
  };

 int main()
 {
 String myString("Hello");
 // Create object myString, send "Hello" string literal as argument
 std::cout << "string size: " << myString.m_size << std::endl;

 std::cout << myString.p_start << std::endl;
// Prints "Hello"

*myString.p_start = 'Y';
// Attempt to change value at first byte of myString.p_start

std::cout << myString.p_start << std::endl;
// Prints "Hello" (no change)

myString = "yellow";
// Assigning a string literal to p_start pointer
myString = "THIS IS A LONGER STRING";

std::cout << myString.p_start << std::endl;

std::cout << "string size: " << myString.m_size << std::endl;
return 0;
}
</code>```

Note I am learning myself so do let me know if I am doing something wrong. But so far, it seems to work.

ContentLicense: CC BY-SA 3.0

Body:
In C++ string literals "Hello" are const and are immutable.  I wanted to make a custom string class whose strings are not const chars, so they can be changeable

Here is a snippet of code that might illustrate what I'm trying to do:

#include <iostream>

class String {
  public:
    char * p_start;

    String(char * strSourc) // Constructor
      {
        p_start = strSourc;
      }
};

int main()
{
  String myString("Hello");
// Create object myString, send "Hello" string literal as argument

  std::cout << myString.p_start << std::endl;
// Prints "Hello"

  *myString.p_start = 'Y';
// Attempt to change value at first byte of myString.p_start

  std::cout << myString.p_start << std::endl;
// Prints "Hello" (no change)

  myString.p_start = "Yellow";
// Assigning a string literal to p_start pointer

  std::cout << myString.p_start << std::endl;
// Prints Yellow, change works.  I thought myString "Hello" was const chars, immutable

  return 0;
}

So, I'm confused.  I've looked everywhere and it says that string literals, like "Hello", are immutable, each of their char bytes are unchangeable.  Though I managed to assign Yellow to the p_start pointer, changing the first letter.  Though changing the single letter H to a Y through dereferencing the H pointer didn't do anything.

Any insights would help me, thanks.

Body:
not sure if anyone finds this helpful after so long but since I am learning myself I took your above code and made it work by copying. It now has a member variable for size and cleans up using delete when you assign a new string literal to it (const char*).

#include <iostream>

class String {
public:
char * p_start;
int m_size;

String(const char * strSourc) // Constructor
  {
    //The following will get the size of the parameter.
     int SizeParameter=0;
     while (*(strSourc+SizeParameter) != '\0')
     {
         SizeParameter++;
     }
     // size of string saved.
     m_size = SizeParameter;
     // allocate enough memory so we can copy strSourc
     p_start = new char[SizeParameter+1];
     //copy the contents strSourc
    for(int i=0; i<SizeParameter+1; i++)
    {
    *(p_start+i) = *(strSourc+i);
    }
  }
  //Handle change of string value.
  char* AssignNewString (const char* newtext)
  {
      //clean
      delete p_start;

      int SizeParameter=0;
     while (*(newtext+SizeParameter) != '\0')
     {
         SizeParameter++;
     }
     // size of string saved.
     m_size = SizeParameter;
     // allocate enough memory so we can copy strSourc
     p_start = new char[SizeParameter+1];
     //copy the contents strSourc
    for(int i=0; i<SizeParameter+1; i++)
    {
    *(p_start+i) = *(newtext+i);
    }
    return p_start;
  }
  char* operator=(const char* newtext)
  {
  AssignNewString(newtext);
  }
  };

 int main()
 {
 String myString("Hello");
 // Create object myString, send "Hello" string literal as argument
 std::cout << "string size: " << myString.m_size << std::endl;

 std::cout << myString.p_start << std::endl;
// Prints "Hello"

*myString.p_start = 'Y';
// Attempt to change value at first byte of myString.p_start

std::cout << myString.p_start << std::endl;
// Prints "Hello" (no change)

myString = "yellow";
// Assigning a string literal to p_start pointer
myString = "THIS IS A LONGER STRING";

std::cout << myString.p_start << std::endl;

std::cout << "string size: " << myString.m_size << std::endl;
return 0;
}

Note I am learning myself so do let me know if I am doing something wrong. But so far, it seems to work.

ContentLicense: CC BY-SA 4.0


问:
.NET Core API - Send array of object as FormData via Postman
How can I send an array of objects through postman using form-data?

Object

public class Relations
{
    public short RelationTypeID { get; set; } = 0;
    public List<UserMessageType> UserList { get; set; } = new List<UserMessageType>();
}

public class UserMessageType
{
    public int UserId { get; set; }
    public short MessageTypeID { get; set; }

    public string UserEmailAddress { get; set; } = string.Empty;
}
```
<p>I do not know how can I send a list of Relations through Postman. I read somewhere that I can write multiple Relations but what about child objects. I tried the following on Postman. This is the bulk edit version of the form</p>
```ConversationID:0
Relations:[{RelationTypeID:1,UserList:[{UserId:15,MessageTypeID:1}]}]
```
<p>This is another try</p>
```ConversationID:0
Relations:RelationTypeID:1, UserList: UserId:15,MessageTypeID:1
```

答:
To post via form-data, you can't straight send the value with object nor array.

You can import the below cURL script to Postman by following these steps.

```<code>curl --location --request POST "<YOUR API URL>" \
--form 'ConversationId="1"' \
--form 'Relations[0].RelationTypeID="1"' \
--form 'Relations[0].UserList[0].UserId="15"' \
--form 'Relations[0].UserList[0].MessageTypeID="1"'
</code>```

API controller

Assume that your API method should be similar as below:

[HttpPost]
[Route("PostConversation")]
public async Task<JsonResult> PostConversation([FromForm] Conversations conversation)
{
    // Implementation
}
```

Sample Request and Response in Postman

Debugging Output in Visual Studio

Body:
How can I send an array of objects through postman using form-data?

Object

public class Relations
{
    public short RelationTypeID { get; set; } = 0;
    public List<UserMessageType> UserList { get; set; } = new List<UserMessageType>();
}

public class UserMessageType
{
    public int UserId { get; set; }
    public short MessageTypeID { get; set; }

    public string UserEmailAddress { get; set; } = string.Empty;
}

I do not know how can I send a list of Relations through Postman. I read somewhere that I can write multiple Relations but what about child objects. I tried the following on Postman. This is the bulk edit version of the form

ConversationID:0
Relations:[{RelationTypeID:1,UserList:[{UserId:15,MessageTypeID:1}]}]

This is another try

ConversationID:0
Relations:RelationTypeID:1, UserList: UserId:15,MessageTypeID:1

Body:
To post via form-data, you can't straight send the value with object nor array.

You can import the below cURL script to Postman by following these steps.

curl --location --request POST "<YOUR API URL>" \
--form 'ConversationId="1"' \
--form 'Relations[0].RelationTypeID="1"' \
--form 'Relations[0].UserList[0].UserId="15"' \
--form 'Relations[0].UserList[0].MessageTypeID="1"'

API controller

Assume that your API method should be similar as below:

[HttpPost]
[Route("PostConversation")]
public async Task<JsonResult> PostConversation([FromForm] Conversations conversation)
{
    // Implementation
}

Sample Request and Response in Postman

Debugging Output in Visual Studio


问:
R, dplyr: Get number of repeated cells in list of matrices

EDIT

Adding an example with 4x4 matrices to test

Matrices:

```<code>> mat1
[,1] [,2] [,3] [,4]
[1,]    0    0    1    0
[2,]    0    1    0    1
[3,]    1    1    1    1
[4,]    0    1    0    1
> mat2
[,1] [,2] [,3] [,4]
[1,]    1    1    1    0
[2,]    1    1    1    1
[3,]    1    1    1    1
[4,]    0    1    0    0
> mat3
[,1] [,2] [,3] [,4]
[1,]    1    1    0    1
[2,]    1    0    0    1
[3,]    0    0    0    1
[4,]    1    0    1    0
> mat4
[,1] [,2] [,3] [,4]
[1,]    0    0    1    0
[2,]    0    0    0    0
[3,]    0    0    1    1
[4,]    0    0    1    1

sample_list <- list(mat1, mat2, mat3, mat4)
</code>```
```<code>m12     <- as.matrix(sample_list[[1]] + sample_list[[2]])
sum_row <- rowSums(m12*(m12 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m12 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame()%>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep2    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep2 = sum_row - num_rep) %>%
           select(., id, sum_rep2)

m123    <- as.matrix(sample_list[[1]] + sample_list[[2]] + sample_list[[3]])
sum_row <- rowSums(m123*(m123 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m123 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep3    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep3 = sum_row - num_rep) %>%
           select(., id, sum_rep3)

m1234   <- as.matrix(sample_list[[1]] + sample_list[[2]] + sample_list[[3]] + sample_list[[4]])
sum_row <- rowSums(m1234*(m1234 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m1234 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep4    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep4 = sum_row - num_rep) %>%
           select(., id, sum_rep4)

all_reps <- full_join(rep2, rep3) %>%
            full_join(., rep4)
</code>```

The final output:

```<code>id sum_rep2 sum_rep3 sum_rep4
1        1        3        4
2        2        4        4
3        4        5        7
4        1        1        3
</code>```

ORIGINAL POST

I have a list of adjacency matrices. I'm trying to count up the number of times a filled cell is repeated for each observation. My goal is to do this with the matrices sequentially. So, the number of repeats with M1 and M2, then M1, M2, and M3, etc.

I'm trying to create a function to do this with as many matrices as provided in the list. The code below is what I've been using to do this one step at a time.

Example matrices:

```<code>set.seed(0)

mat1 <- matrix(sample(0:1, 10*10, replace=TRUE),10,10) %>%
        replace(., col(.) == row(.), 0)
mat2 <- matrix(sample(0:1, 10*10, replace=TRUE),10,10) %>%
        replace(., col(.) == row(.), 0)
mat3 <- matrix(sample(0:1, 10*10, replace=TRUE),10,10) %>%
        replace(., col(.) == row(.), 0)
mat4 <- matrix(sample(0:1, 10*10, replace=TRUE),10,10) %>%
        replace(., col(.) == row(.), 0)

sample_list <- list(mat1, mat2, mat3, mat4)
</code>```

Code I've used:

Here I calculate the sum of cells by row and the number of filled cells greater than 1. I subtract the number of cells from the total row sums to get the total number of repeats.

```<code>m12     <- as.matrix(sample_list[[1]] + sample_list[[2]])
sum_row <- rowSums(m12*(m12 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m12 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame()%>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep2    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep2 = sum_row - num_rep) %>%
           select(., id, sum_rep2)

m123    <- as.matrix(sample_list[[1]] + sample_list[[2]] + sample_list[[3]])
sum_row <- rowSums(m123*(m123 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m123 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep3    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep3 = sum_row - num_rep) %>%
           select(., id, sum_rep3)

m1234   <- as.matrix(sample_list[[1]] + sample_list[[2]] + sample_list[[3]] + sample_list[[4]])
sum_row <- rowSums(m1234*(m1234 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m1234 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep4    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep4 = sum_row - num_rep) %>%
           select(., id, sum_rep4)

all_reps <- full_join(rep2, rep3) %>%
            full_join(., rep4)
</code>```

The final output, all_reps gives me this dataset (with the random matrices I created in the first chunk of code):

```<code>  id sum_rep2 sum_rep3 sum_rep4
1   1        1        7       10
2   2        3        8       10
3   3        1        5       10
4   4        0        1        4
5   5        2        4        9
6   6        0        2        4
7   7        3        6       10
8   8        5        8       12
9   9        3        7       11
10 10        3        9       12
</code>```

Is there a way to use a loop or an apply function to do this in a more automated way, that also will take a list of more matrices?

Matrices:

```<code>sample_list[[1]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    1    0    1    1    0    0    1    1     1
 [2,]    0    0    0    1    1    1    0    1    1     0
 [3,]    1    0    0    1    1    0    1    1    1     0
 [4,]    0    0    0    0    0    1    1    0    0     1
 [5,]    0    0    0    1    0    1    1    0    0     1
 [6,]    1    0    0    0    1    0    1    0    0     0
 [7,]    0    1    0    0    1    0    0    1    1     0
 [8,]    0    1    1    1    1    1    1    0    0     0
 [9,]    0    1    0    0    1    1    0    0    0     1
[10,]    1    1    0    1    0    1    1    0    0     0

sample_list[[2]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    0    1    0    0    0    1    1    0     0
 [2,]    1    0    1    0    1    1    0    0    1     0
 [3,]    1    0    0    0    0    0    0    0    0     1
 [4,]    1    0    0    0    0    0    0    1    0     0
 [5,]    0    1    0    0    0    0    1    0    0     1
 [6,]    0    1    1    1    0    0    0    0    0     1
 [7,]    0    1    0    0    1    1    0    1    0     1
 [8,]    0    1    0    1    1    1    1    0    1     0
 [9,]    1    0    1    1    1    1    0    1    0     1
[10,]    0    1    1    1    0    1    0    1    1     0

sample_list[[3]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    0    0    1    1    1    1    1    1     1
 [2,]    1    0    1    0    1    0    1    1    1     0
 [3,]    1    0    0    0    1    1    0    1    1     0
 [4,]    0    0    1    0    0    0    0    0    0     1
 [5,]    1    1    1    0    0    0    0    1    1     1
 [6,]    1    0    1    0    0    0    0    0    1     0
 [7,]    1    0    0    1    1    0    0    0    1     1
 [8,]    0    0    0    1    0    1    0    0    1     1
 [9,]    0    1    0    1    1    0    0    1    0     0
[10,]    1    1    0    1    0    0    1    1    1     0

sample_list[[4]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    1    1    0    0    0    0    0    0     1
 [2,]    0    0    0    0    1    0    0    0    1     0
 [3,]    0    0    0    1    1    1    1    0    1     0
 [4,]    0    0    1    0    1    0    0    1    0     1
 [5,]    0    0    0    1    0    1    1    1    0     1
 [6,]    0    0    0    0    1    0    1    0    0     0
 [7,]    0    0    1    1    0    1    0    1    1     0
 [8,]    1    0    1    1    0    0    1    0    1     0
 [9,]    1    0    1    0    1    1    1    0    0     0
[10,]    1    0    1    1    1    0    0    0    0     0
</code>```

答:
I think this gives you what you're after:

```<code>library(tidyverse)

accumulate(sample_list, `+`) %>%
  tail(-1) %>%
  map(~ rowSums(pmax(.x - 1, 0))) %>%
  bind_cols(.name_repair = ~ paste0("sum_rep", seq_along(.x)+1)) %>%
  rowid_to_column()

# A tibble: 4 x 4
  rowid sum_rep2 sum_rep3 sum_rep4
  <int>    <dbl>    <dbl>    <dbl>
1     1        0        0        0
2     2        0        1        2
3     3        1        3        4
4     4        0        0        2
</code>```

Sample data:

```<code>set.seed(0)
n <- 4
sample_list <- replicate(4, `diag<-`(matrix(sample(0:1, n*n, replace=TRUE),n), 0), simplify = FALSE)
</code>```

Body:
EDIT

Adding an example with 4x4 matrices to test

Matrices:

> mat1
[,1] [,2] [,3] [,4]
[1,]    0    0    1    0
[2,]    0    1    0    1
[3,]    1    1    1    1
[4,]    0    1    0    1
> mat2
[,1] [,2] [,3] [,4]
[1,]    1    1    1    0
[2,]    1    1    1    1
[3,]    1    1    1    1
[4,]    0    1    0    0
> mat3
[,1] [,2] [,3] [,4]
[1,]    1    1    0    1
[2,]    1    0    0    1
[3,]    0    0    0    1
[4,]    1    0    1    0
> mat4
[,1] [,2] [,3] [,4]
[1,]    0    0    1    0
[2,]    0    0    0    0
[3,]    0    0    1    1
[4,]    0    0    1    1

sample_list <- list(mat1, mat2, mat3, mat4)

m12     <- as.matrix(sample_list[[1]] + sample_list[[2]])
sum_row <- rowSums(m12*(m12 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m12 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame()%>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep2    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep2 = sum_row - num_rep) %>%
           select(., id, sum_rep2)

m123    <- as.matrix(sample_list[[1]] + sample_list[[2]] + sample_list[[3]])
sum_row <- rowSums(m123*(m123 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m123 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep3    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep3 = sum_row - num_rep) %>%
           select(., id, sum_rep3)

m1234   <- as.matrix(sample_list[[1]] + sample_list[[2]] + sample_list[[3]] + sample_list[[4]])
sum_row <- rowSums(m1234*(m1234 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m1234 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep4    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep4 = sum_row - num_rep) %>%
           select(., id, sum_rep4)

all_reps <- full_join(rep2, rep3) %>%
            full_join(., rep4)

The final output:

id sum_rep2 sum_rep3 sum_rep4
1        1        3        4
2        2        4        4
3        4        5        7
4        1        1        3

ORIGINAL POST

I have a list of adjacency matrices. I'm trying to count up the number of times a filled cell is repeated for each observation. My goal is to do this with the matrices sequentially. So, the number of repeats with M1 and M2, then M1, M2, and M3, etc.

I'm trying to create a function to do this with as many matrices as provided in the list. The code below is what I've been using to do this one step at a time.

Example matrices:

set.seed(0)

mat1 <- matrix(sample(0:1, 10*10, replace=TRUE),10,10) %>%
        replace(., col(.) == row(.), 0)
mat2 <- matrix(sample(0:1, 10*10, replace=TRUE),10,10) %>%
        replace(., col(.) == row(.), 0)
mat3 <- matrix(sample(0:1, 10*10, replace=TRUE),10,10) %>%
        replace(., col(.) == row(.), 0)
mat4 <- matrix(sample(0:1, 10*10, replace=TRUE),10,10) %>%
        replace(., col(.) == row(.), 0)

sample_list <- list(mat1, mat2, mat3, mat4)

Code I've used:

Here I calculate the sum of cells by row and the number of filled cells greater than 1. I subtract the number of cells from the total row sums to get the total number of repeats.

m12     <- as.matrix(sample_list[[1]] + sample_list[[2]])
sum_row <- rowSums(m12*(m12 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m12 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame()%>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep2    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep2 = sum_row - num_rep) %>%
           select(., id, sum_rep2)

m123    <- as.matrix(sample_list[[1]] + sample_list[[2]] + sample_list[[3]])
sum_row <- rowSums(m123*(m123 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m123 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep3    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep3 = sum_row - num_rep) %>%
           select(., id, sum_rep3)

m1234   <- as.matrix(sample_list[[1]] + sample_list[[2]] + sample_list[[3]] + sample_list[[4]])
sum_row <- rowSums(m1234*(m1234 > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "sum_row" = ".")
num_rep <- m1234 %>%
           apply(.,1,function(x) sum(x > 1)) %>% as.data.frame() %>%
           rowid_to_column(., var = "id") %>%
           rename(., "num_rep" = ".")
rep4    <- full_join(sum_row, num_rep) %>%
           mutate(sum_rep4 = sum_row - num_rep) %>%
           select(., id, sum_rep4)

all_reps <- full_join(rep2, rep3) %>%
            full_join(., rep4)

The final output, all_reps gives me this dataset (with the random matrices I created in the first chunk of code):

  id sum_rep2 sum_rep3 sum_rep4
1   1        1        7       10
2   2        3        8       10
3   3        1        5       10
4   4        0        1        4
5   5        2        4        9
6   6        0        2        4
7   7        3        6       10
8   8        5        8       12
9   9        3        7       11
10 10        3        9       12

Is there a way to use a loop or an apply function to do this in a more automated way, that also will take a list of more matrices?

Matrices:

sample_list[[1]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    1    0    1    1    0    0    1    1     1
 [2,]    0    0    0    1    1    1    0    1    1     0
 [3,]    1    0    0    1    1    0    1    1    1     0
 [4,]    0    0    0    0    0    1    1    0    0     1
 [5,]    0    0    0    1    0    1    1    0    0     1
 [6,]    1    0    0    0    1    0    1    0    0     0
 [7,]    0    1    0    0    1    0    0    1    1     0
 [8,]    0    1    1    1    1    1    1    0    0     0
 [9,]    0    1    0    0    1    1    0    0    0     1
[10,]    1    1    0    1    0    1    1    0    0     0

sample_list[[2]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    0    1    0    0    0    1    1    0     0
 [2,]    1    0    1    0    1    1    0    0    1     0
 [3,]    1    0    0    0    0    0    0    0    0     1
 [4,]    1    0    0    0    0    0    0    1    0     0
 [5,]    0    1    0    0    0    0    1    0    0     1
 [6,]    0    1    1    1    0    0    0    0    0     1
 [7,]    0    1    0    0    1    1    0    1    0     1
 [8,]    0    1    0    1    1    1    1    0    1     0
 [9,]    1    0    1    1    1    1    0    1    0     1
[10,]    0    1    1    1    0    1    0    1    1     0

sample_list[[3]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    0    0    1    1    1    1    1    1     1
 [2,]    1    0    1    0    1    0    1    1    1     0
 [3,]    1    0    0    0    1    1    0    1    1     0
 [4,]    0    0    1    0    0    0    0    0    0     1
 [5,]    1    1    1    0    0    0    0    1    1     1
 [6,]    1    0    1    0    0    0    0    0    1     0
 [7,]    1    0    0    1    1    0    0    0    1     1
 [8,]    0    0    0    1    0    1    0    0    1     1
 [9,]    0    1    0    1    1    0    0    1    0     0
[10,]    1    1    0    1    0    0    1    1    1     0

sample_list[[4]]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    1    1    0    0    0    0    0    0     1
 [2,]    0    0    0    0    1    0    0    0    1     0
 [3,]    0    0    0    1    1    1    1    0    1     0
 [4,]    0    0    1    0    1    0    0    1    0     1
 [5,]    0    0    0    1    0    1    1    1    0     1
 [6,]    0    0    0    0    1    0    1    0    0     0
 [7,]    0    0    1    1    0    1    0    1    1     0
 [8,]    1    0    1    1    0    0    1    0    1     0
 [9,]    1    0    1    0    1    1    1    0    0     0
[10,]    1    0    1    1    1    0    0    0    0     0

Body:
I think this gives you what you're after:

library(tidyverse)

accumulate(sample_list, `+`) %>%
  tail(-1) %>%
  map(~ rowSums(pmax(.x - 1, 0))) %>%
  bind_cols(.name_repair = ~ paste0("sum_rep", seq_along(.x)+1)) %>%
  rowid_to_column()

# A tibble: 4 x 4
  rowid sum_rep2 sum_rep3 sum_rep4
  <int>    <dbl>    <dbl>    <dbl>
1     1        0        0        0
2     2        0        1        2
3     3        1        3        4
4     4        0        0        2

Sample data:

set.seed(0)
n <- 4
sample_list <- replicate(4, `diag<-`(matrix(sample(0:1, n*n, replace=TRUE),n), 0), simplify = FALSE)


问:
Unknown File Encoding in Mysqlworkbench 5.7.34
Mysql : 5.7,
workbench : 5.7.34

I want to import sql dump file, Problem is :

```<code>Unknown File Encoding

The file '/xxx.sql' is not UTF-8 encoded.

Please select the encoding of the file and press OK for Workbench to convert and open it.
Note that as Workbench works with UTF-8 text, if you save back to the original file,
its contents will be replaced with the converted data.

WARNING: If your file contains binary data, it may become corrupted.

Click "Run SQL Script..." to execute the file without opening for editing.

Character Set Encoding Name: latin1
</code>```

img : enter image description here.
After importing with this latin1 encoding, site content will change to wrong encoding format. sample : ă‚¤ăƒ™ăƒłăƒˆăƒťäźšč°ăƒŹăƒăƒźă.

How to import dump file without encoding alert?

答:
thanks to my senior.
I fix it.

Importing Process : in workbench, Server > Data Import > Import from
Selt-Contained File. choose export sql dump file. And then choose
Target db name. OK, that is all.

Error Importing Process : double-click sql dump file, workbench will auto open, Unknown Encoding Alert will occurs.

Body:
Mysql : 5.7,
workbench : 5.7.34

I want to import sql dump file, Problem is :

Unknown File Encoding

The file '/xxx.sql' is not UTF-8 encoded.

Please select the encoding of the file and press OK for Workbench to convert and open it.
Note that as Workbench works with UTF-8 text, if you save back to the original file,
its contents will be replaced with the converted data.

WARNING: If your file contains binary data, it may become corrupted.

Click "Run SQL Script..." to execute the file without opening for editing.

Character Set Encoding Name: latin1

img : enter image description here.
After importing with this latin1 encoding, site content will change to wrong encoding format. sample : ă‚¤ăƒ™ăƒłăƒˆăƒťäźšč°ăƒŹăƒăƒźă.

How to import dump file without encoding alert?


问:
Disable X-Powered-By in nestjs does not work
I want to disable X-Powered-By in nestjs like the following, but it does not work.

main.ts:

```<code>async function bootstrap() {
    const logger = new Logger('bootstrap')
    const app = await NestFactory.create<NestExpressApplication>(AppModule);

    app.disable('X-Powered-By') // this line
    ...

    const PORT = process.env.PORT
    await app.listen(PORT);
    logger.log(`Application is start on port : ${PORT}`)
  }

  bootstrap();
</code>```

After disabling the X-Powered-By header, in the next requests, that X-Powered-By header still exists.

Where am I doing something wrong?

答:
If you are using TypeScript and you get an error in your IDE saying Property 'disable' does not exist on type 'INestApplication', then specify the app type in your NestFactory.create call.

Your code should look like below, and the error on the app.disable call will be gone.

```<code>const app = await NestFactory.create<NestExpressApplication>(AppModule)

app.disable('x-powered-by')
</code>```

Body:
I want to disable X-Powered-By in nestjs like the following, but it does not work.

main.ts:

async function bootstrap() {
    const logger = new Logger('bootstrap')
    const app = await NestFactory.create<NestExpressApplication>(AppModule);

    app.disable('X-Powered-By') // this line
    ...

    const PORT = process.env.PORT
    await app.listen(PORT);
    logger.log(`Application is start on port : ${PORT}`)
  }

  bootstrap();

After disabling the X-Powered-By header, in the next requests, that X-Powered-By header still exists.

Where am I doing something wrong?

Body:
If you are using TypeScript and you get an error in your IDE saying Property 'disable' does not exist on type 'INestApplication', then specify the app type in your NestFactory.create call.

Your code should look like below, and the error on the app.disable call will be gone.

const app = await NestFactory.create<NestExpressApplication>(AppModule)

app.disable('x-powered-by')


问:
Create Step Functions from JSON File in CDK
With an existing Step Functions definition JSON file, how can I use it directly in CDK to create a Step Function?</p>

答:
Here is the code snippet if it is useful to anyone.

  private createStepFunction(props: {
    stepfunction_name: string;
    stepfunctions_role_arn: string;
  }): stepfunctions.CfnStateMachine {
    const file = fs.readFileSync("../step_functions/definition.asl.json");

    const stepFunction = new stepfunctions.CfnStateMachine(
      this,
      "cfnStepFunction",
      {
        roleArn: props.stepfunctions_role_arn,
        definitionString: file.toString(),
        stateMachineName: props.stepfunction_name,
      }
    );

    return stepFunction;
  }
```


问:
How to make a custom python class to support memoryview conversion
Is it possible for a custom class to implement memoryview(obj)?

For example,

class A:
    def __init__(self):
        self.b = b'sdfajsdfjkasdf'

    def __memoryview__(self):
        return self.b
```
<p>so that</p>
<pre class="lang-py prettyprint-override"><code>a = A()
mv = memoryview(a) # returns the memoryview of a.b
</code>```

is a valid operation.

答:
Not possible. memoryview only accepts arguments that support the buffer protocol, and the buffer protocol is C-only. There are no Python-level hooks.

I don't know of any explicit statement regarding this in the docs, but all the buffer protocol documentation is C-only, and if you're comfortable with C, you can check the type object implementation and see that nothing ever sets bf_getbuffer or bf_releasebuffer to any sort of wrapper around a Python-level hook.

You can define a class that subclasses an existing class with buffer support, but that will make your objects actually be instances of that existing class. For example, if you make your class a subclass of bytes, then memoryview(a) will create a memoryview over your object. It will not create a memoryview of a.b, and there will be all sorts of usually-undesirable side effects. Do not do this just to provide memoryview support; use memoryview(a.b).

Body:
Is it possible for a custom class to implement memoryview(obj)?

For example,

class A:
    def __init__(self):
        self.b = b'sdfajsdfjkasdf'

    def __memoryview__(self):
        return self.b

so that

a = A()
mv = memoryview(a) # returns the memoryview of a.b

is a valid operation.


问:
How to find and count emoticons in a string using python?
This topic has been addressed for text based emoticons at link1, link2, link3. However, I would like to do something slightly different than matching simple emoticons. I'm sorting through tweets that contain the emoticons' icons. The following unicode information contains just such emoticons: pdf.

Using a string with english words that also contains any of these emoticons from the pdf, I would like to be able to compare the number of emoticons to the number of words.

The direction that I was heading down doesn't seem to be the best option and I was looking for some help. As you can see in the script below, I was just planning to do the work from the command line:

```<code>$cat <file containing the strings with emoticons> | ./emo.py
</code>```

emo.py psuedo script:

```<code>import re
import sys

for row in sys.stdin:
    print row.decode('utf-8').encode("ascii","replace")
    #insert regex to find the emoticons
    if match:
       #do some counting using .split(" ")
       #print the counting
</code>```

The problem that I'm running into is the decoding/encoding. I haven't found a good option for how to encode/decode the string so I can correctly find the icons. An example of the string that I want to search to find the number of words and emoticons is as follows:

"Smiley emoticon rocks! I like you."

The challenge: can you make a script that counts the number of words and emoticons in this string? Notice that the emoticons are both sitting next to the words with no space in between.

答:
This is my solution using re:

```<code>import re
text = "your text with emojis"
em_count = len(re.findall(r'[^\w\s,.]', text))
print(em_count)
</code>```

Body:
This topic has been addressed for text based emoticons at link1, link2, link3. However, I would like to do something slightly different than matching simple emoticons. I'm sorting through tweets that contain the emoticons' icons. The following unicode information contains just such emoticons: pdf.

Using a string with english words that also contains any of these emoticons from the pdf, I would like to be able to compare the number of emoticons to the number of words.

The direction that I was heading down doesn't seem to be the best option and I was looking for some help. As you can see in the script below, I was just planning to do the work from the command line:

$cat <file containing the strings with emoticons> | ./emo.py

emo.py psuedo script:

import re
import sys

for row in sys.stdin:
    print row.decode('utf-8').encode("ascii","replace")
    #insert regex to find the emoticons
    if match:
       #do some counting using .split(" ")
       #print the counting

The problem that I'm running into is the decoding/encoding. I haven't found a good option for how to encode/decode the string so I can correctly find the icons. An example of the string that I want to search to find the number of words and emoticons is as follows:

"Smiley emoticon rocks! I like you."

The challenge: can you make a script that counts the number of words and emoticons in this string? Notice that the emoticons are both sitting next to the words with no space in between.

Body:
This is my solution using re:

import re
text = "your text with emojis"
em_count = len(re.findall(r'[^\w\s,.]', text))
print(em_count)


问:
How can I animate simultaneously all the graph points inside Manim?
I made this class : 50 points of a spiral change to a cirle.

But the animation is sequential and I would like to start it at the same time.

```<code>class SpiralToCircle(Scene):
    def construct(self):
        vertices1 = range(50)
        vertices2 = range(50)
        edges = [(48, 49),(3, 4)]
        g1 = Graph(vertices1, edges, layout="spiral")
        g2 = Graph(vertices2, edges, layout="circular")

        # self.add(graph)
        self.play(Create(g1))
        self.wait(5)
        for i in vertices1:
            self.play(g1[i].animate.move_to(g2[i]))
        self.wait()
</code>```

I thought about this trick, but I returns an error :

```<code>self.play((g1[i].animate.move_to(g2[i])) for i in vertices1)
</code>```

TypeError: Unexpected argument <generator object GraphCircular.construct.. at 0x00000229667509E0> passed to Scene.play().

答:
Try unpacking the animation list and pass them as parameters to the play method:

self.play(*[g1[i].animate.move_to(g2[i]) for i in vertices1])

So, the code would be:

class SpiralToCircle(Scene):

```<code>def construct(self):
    vertices1 = range(50)
    vertices2 = range(50)
    edges = [(48, 49), (3, 4)]
    g1 = Graph(vertices1, edges, layout="spiral")
    g2 = Graph(vertices2, edges, layout="circular")

    # self.add(graph)
    self.play(Create(g1))
    self.wait(5)
    self.play(*[g1[i].animate.move_to(g2[i]) for i in vertices1])
    self.wait()
</code>```

Generating this output:

Output Animation

Body:
I made this class : 50 points of a spiral change to a cirle.

But the animation is sequential and I would like to start it at the same time.

class SpiralToCircle(Scene):
    def construct(self):
        vertices1 = range(50)
        vertices2 = range(50)
        edges = [(48, 49),(3, 4)]
        g1 = Graph(vertices1, edges, layout="spiral")
        g2 = Graph(vertices2, edges, layout="circular")

        # self.add(graph)
        self.play(Create(g1))
        self.wait(5)
        for i in vertices1:
            self.play(g1[i].animate.move_to(g2[i]))
        self.wait()

I thought about this trick, but I returns an error :

self.play((g1[i].animate.move_to(g2[i])) for i in vertices1)

TypeError: Unexpected argument <generator object GraphCircular.construct.. at 0x00000229667509E0> passed to Scene.play().

Body:
Try unpacking the animation list and pass them as parameters to the play method:

self.play(*[g1[i].animate.move_to(g2[i]) for i in vertices1])

So, the code would be:

class SpiralToCircle(Scene):

def construct(self):
    vertices1 = range(50)
    vertices2 = range(50)
    edges = [(48, 49), (3, 4)]
    g1 = Graph(vertices1, edges, layout="spiral")
    g2 = Graph(vertices2, edges, layout="circular")

    # self.add(graph)
    self.play(Create(g1))
    self.wait(5)
    self.play(*[g1[i].animate.move_to(g2[i]) for i in vertices1])
    self.wait()

Generating this output:

Output Animation


问:
Failed to evaluate transaction: Error: You've asked to invoke a function that does not exist: getLastPatientId
I want to do inheritance in Hyperledger Fabric Chaincode using NodeJs.
I have created two classes CommonContract and AdminContract. CommonContract is the base class and AdminContract child class. But I got error when I invoke getLastPatiendId function from AdminContract. Error is as follows.

```<code>Failed to evaluate transaction: Error: You've asked to invoke a function that does not exist: getLastPatientId
[nodemon] app crashed - waiting for file changes before starting...
</code>```

Even though getLastPatientId function is written in contract it is giving error function does not exists.

Below are the code of AdminContract, CommonContract, index.js file for chaincode and the server API  which invoke transaction

CommonContract.js

This is CommonContract smart contract which is a base class.

```<code>'use strict';

const { Contract } = require('fabric-contract-api');

class CommonContract extends Contract {

    async initLedger(ctx) {
        console.info('============= START : Initialize Ledger ===========');
        const initData = [
            {
                "firstName": "ABC",
                "middleName": "D",
                "lastName": "BCA",
                "password": "d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1",
                "age": "16",
                "phoneNumber": "1234567890",
                "address": "India",
                "bloodGroup": "O+ve",
                "updatedBy": "initLedger",
                "symptoms": "fever",
                "diagnosis": "Covid",
                "treatment": "dolo 2 times",
                "other": "no",
            },
            {
                "firstName": "Five",
                "middleName": ".H.",
                "lastName": "CDA",
                "password": "d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1",
                "age": "16",
                "phoneNumber": "1234567890",
                "address": "India",
                "bloodGroup": "O+ve",
                "updatedBy": "initLedger",
                "symptoms": "fever",
                "diagnosis": "Covid",
                "treatment": "dolo 2 times",
                "other": "no",
            }
        ]

        for (let i = 0; i < initData.length; i++) {
            initData[i].docType = 'patient';
            await ctx.stub.putState('PID' + i, Buffer.from(JSON.stringify(initData[i])));
            console.log('Data Added:---', initData[i]);
        }
    }

    async getPatient(ctx, patientId){
        const patient = await ctx.stub.getState(patientId);
        if(patient.length || patient.length > 0)
        console.log(patient);
        let data = JSON.parse(patient.toString());
        return data;
    }

    async getAllPatient(ctx){
        const startKey = '';
        const endKey = '';
        const allResults = [];
        for await (const {key, value} of ctx.stub.getStateByRange(startKey, endKey)){
            const strValue = Buffer.from(value).toString('utf8');
            let record;
            try {
                record = JSON.parse(strValue);
            } catch (err) {
                console.log(err);
                record = strValue;
            }
            allResults.push({ Key: key, Record: record });
        }
        console.info(allResults);
        return JSON.stringify(allResults);
    }
}

module.exports = CommonContract;
</code>```

AdminContract.js

This is an AdminContract smart contract that inherits CommonContract and has a single function getLastPatientId() it generally returns the patient id of the last patient created in the ledger.

```<code>
'use strict';

let Patient = require('./PatientAssets.js');
const CommonContract = require('./CommonContract.js');

class AdminContract extends CommonContract {

    async getLastPatientId(ctx) {
        let result = await getAllPatient(ctx);
        console.log(result);
        return result[result.length - 1].patiendId;
    }
}

module.exports = AdminContract;
</code>```

index.js

This file is main entry point all smart contract.

```<code>'use strict';

const CommonContract = require('./lib/CommonContract.js');
const AdminContract = require('./lib/AdminContract.js');

module.exports.contracts = [CommonContract, AdminContract];
</code>```

admin.js

This is server side route file which invoke the getLastPatientId function which is in AdminContract.js smart contract file.

```<code>router.get('/getAllPatient', async (req, res) => {
    try {
        // load the network configuration
        const ccpPath = path.resolve(__dirname, '..', '..', 'network-config', 'organizations', 'peerOrganizations', 'doctor.hospital_network.com', 'connection-doctor.json');
        const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));

        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), 'wallet');
        const wallet = await Wallets.newFileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        // Check to see if we've already enrolled the user.
        const identity = await wallet.get('appUser1');
        if (!identity) {
            console.log('An identity for the user "appUser" does not exist in the wallet');
            console.log('Run the registerUser.js application before retrying');
            return;
        }

        // Create a new gateway for connecting to our peer node.
        const gateway = new Gateway();
        await gateway.connect(ccp, { wallet, identity: 'appUser1', discovery: { enabled: true, asLocalhost: true } });

        // Get the network (channel) our contract is deployed to.
        const network = await gateway.getNetwork('hospital');

        // Get the contract from the network.
        const contract = network.getContract('basic');

        const result = await contract.evaluateTransaction('getLastPatientId');
        const data = JSON.parse(result);
        console.log(`Transaction has been evaluated, result is: ${result}`);

        // Disconnect from the gateway.
        await gateway.disconnect();
        return data;

    } catch (error) {
        console.error(`Failed to evaluate transaction: ${error}`);
        process.exit(1);
    }
});
</code>```

I found out that evalutateTransaction() invokes the function in CommonContract but was not able to invoke AdminContract functions. Please help me out. What is the error in my code ?

答:
First I was implementing multiple contracts.

By getting the metadata for the contracts there is one default contract.

```<code>{
  CommonContract: {
    name: 'CommonContract',
    contractInstance: { name: 'CommonContract', default: true },
    transactions: [ [Object], [Object], [Object], [Object], [Object] ],
    info: { title: '', version: '' }
  },
  AdminContract: {
    name: 'AdminContract',
    contractInstance: { name: 'AdminContract' },
    transactions: [ [Object], [Object], [Object], [Object], [Object] ],
    info: { title: '', version: '' }
  },
  DoctorContract: {
    name: 'DoctorContract',
    contractInstance: { name: 'DoctorContract' },
    transactions: [ [Object], [Object], [Object] ],
    info: { title: '', version: '' }
  },
  PatientContract: {
    name: 'PatientContract',
    contractInstance: { name: 'PatientContract' },
    transactions: [ [Object], [Object] ],
    info: { title: '', version: '' }
  },
  'org.hyperledger.fabric': {
    name: 'org.hyperledger.fabric',
    contractInstance: { name: 'org.hyperledger.fabric' },
    transactions: [ [Object] ],
    info: { title: '', version: '' }
  }
}
</code>```

Now in the admin.js file, looking at the line where we getting the contract

```<code>const contract = network.getContract('basic');
</code>```

Here this statement was using default contract i.e. CommonContract, But I was implementing multiple contracts so I have to give the reference of that contract, so I make this change.

```<code>const contract = network.getContract('basic', 'AdminContract');
</code>```

and now when I invoke the contract

```<code>const result = await contract.evaluateTransaction('getLastPatientId');
</code>```

or

```<code>const contract = network.getContract('basic');
const result = await contract.evaluateTransaction('AdminContract:getLastPatientId');
</code>```

It works...

Body:
I want to do inheritance in Hyperledger Fabric Chaincode using NodeJs.
I have created two classes CommonContract and AdminContract. CommonContract is the base class and AdminContract child class. But I got error when I invoke getLastPatiendId function from AdminContract. Error is as follows.

Failed to evaluate transaction: Error: You've asked to invoke a function that does not exist: getLastPatientId
[nodemon] app crashed - waiting for file changes before starting...

Even though getLastPatientId function is written in contract it is giving error function does not exists.

Below are the code of AdminContract, CommonContract, index.js file for chaincode and the server API  which invoke transaction

CommonContract.js

This is CommonContract smart contract which is a base class.

'use strict';

const { Contract } = require('fabric-contract-api');

class CommonContract extends Contract {

    async initLedger(ctx) {
        console.info('============= START : Initialize Ledger ===========');
        const initData = [
            {
                "firstName": "ABC",
                "middleName": "D",
                "lastName": "BCA",
                "password": "d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1",
                "age": "16",
                "phoneNumber": "1234567890",
                "address": "India",
                "bloodGroup": "O+ve",
                "updatedBy": "initLedger",
                "symptoms": "fever",
                "diagnosis": "Covid",
                "treatment": "dolo 2 times",
                "other": "no",
            },
            {
                "firstName": "Five",
                "middleName": ".H.",
                "lastName": "CDA",
                "password": "d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1",
                "age": "16",
                "phoneNumber": "1234567890",
                "address": "India",
                "bloodGroup": "O+ve",
                "updatedBy": "initLedger",
                "symptoms": "fever",
                "diagnosis": "Covid",
                "treatment": "dolo 2 times",
                "other": "no",
            }
        ]

        for (let i = 0; i < initData.length; i++) {
            initData[i].docType = 'patient';
            await ctx.stub.putState('PID' + i, Buffer.from(JSON.stringify(initData[i])));
            console.log('Data Added:---', initData[i]);
        }
    }

    async getPatient(ctx, patientId){
        const patient = await ctx.stub.getState(patientId);
        if(patient.length || patient.length > 0)
        console.log(patient);
        let data = JSON.parse(patient.toString());
        return data;
    }

    async getAllPatient(ctx){
        const startKey = '';
        const endKey = '';
        const allResults = [];
        for await (const {key, value} of ctx.stub.getStateByRange(startKey, endKey)){
            const strValue = Buffer.from(value).toString('utf8');
            let record;
            try {
                record = JSON.parse(strValue);
            } catch (err) {
                console.log(err);
                record = strValue;
            }
            allResults.push({ Key: key, Record: record });
        }
        console.info(allResults);
        return JSON.stringify(allResults);
    }
}

module.exports = CommonContract;

AdminContract.js

This is an AdminContract smart contract that inherits CommonContract and has a single function getLastPatientId() it generally returns the patient id of the last patient created in the ledger.

'use strict';

let Patient = require('./PatientAssets.js');
const CommonContract = require('./CommonContract.js');

class AdminContract extends CommonContract {

    async getLastPatientId(ctx) {
        let result = await getAllPatient(ctx);
        console.log(result);
        return result[result.length - 1].patiendId;
    }
}

module.exports = AdminContract;

index.js

This file is main entry point all smart contract.

'use strict';

const CommonContract = require('./lib/CommonContract.js');
const AdminContract = require('./lib/AdminContract.js');

module.exports.contracts = [CommonContract, AdminContract];

admin.js

This is server side route file which invoke the getLastPatientId function which is in AdminContract.js smart contract file.

router.get('/getAllPatient', async (req, res) => {
    try {
        // load the network configuration
        const ccpPath = path.resolve(__dirname, '..', '..', 'network-config', 'organizations', 'peerOrganizations', 'doctor.hospital_network.com', 'connection-doctor.json');
        const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));

        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), 'wallet');
        const wallet = await Wallets.newFileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        // Check to see if we've already enrolled the user.
        const identity = await wallet.get('appUser1');
        if (!identity) {
            console.log('An identity for the user "appUser" does not exist in the wallet');
            console.log('Run the registerUser.js application before retrying');
            return;
        }

        // Create a new gateway for connecting to our peer node.
        const gateway = new Gateway();
        await gateway.connect(ccp, { wallet, identity: 'appUser1', discovery: { enabled: true, asLocalhost: true } });

        // Get the network (channel) our contract is deployed to.
        const network = await gateway.getNetwork('hospital');

        // Get the contract from the network.
        const contract = network.getContract('basic');

        const result = await contract.evaluateTransaction('getLastPatientId');
        const data = JSON.parse(result);
        console.log(`Transaction has been evaluated, result is: ${result}`);

        // Disconnect from the gateway.
        await gateway.disconnect();
        return data;

    } catch (error) {
        console.error(`Failed to evaluate transaction: ${error}`);
        process.exit(1);
    }
});

I found out that evalutateTransaction() invokes the function in CommonContract but was not able to invoke AdminContract functions. Please help me out. What is the error in my code ?

Body:
First I was implementing multiple contracts.

By getting the metadata for the contracts there is one default contract.

{
  CommonContract: {
    name: 'CommonContract',
    contractInstance: { name: 'CommonContract', default: true },
    transactions: [ [Object], [Object], [Object], [Object], [Object] ],
    info: { title: '', version: '' }
  },
  AdminContract: {
    name: 'AdminContract',
    contractInstance: { name: 'AdminContract' },
    transactions: [ [Object], [Object], [Object], [Object], [Object] ],
    info: { title: '', version: '' }
  },
  DoctorContract: {
    name: 'DoctorContract',
    contractInstance: { name: 'DoctorContract' },
    transactions: [ [Object], [Object], [Object] ],
    info: { title: '', version: '' }
  },
  PatientContract: {
    name: 'PatientContract',
    contractInstance: { name: 'PatientContract' },
    transactions: [ [Object], [Object] ],
    info: { title: '', version: '' }
  },
  'org.hyperledger.fabric': {
    name: 'org.hyperledger.fabric',
    contractInstance: { name: 'org.hyperledger.fabric' },
    transactions: [ [Object] ],
    info: { title: '', version: '' }
  }
}

Now in the admin.js file, looking at the line where we getting the contract

const contract = network.getContract('basic');

Here this statement was using default contract i.e. CommonContract, But I was implementing multiple contracts so I have to give the reference of that contract, so I make this change.

const contract = network.getContract('basic', 'AdminContract');

and now when I invoke the contract

const result = await contract.evaluateTransaction('getLastPatientId');

or

const contract = network.getContract('basic');
const result = await contract.evaluateTransaction('AdminContract:getLastPatientId');

It works...


问:
x86: how to get user input for 2 variables?
The following program prints star symbols in this pattern

```<code>%
%%
%%%
%%%%
%%%%%
</code>```

My source code:

```<code>.model small
.stack 100h
.data
sRepeats db "repeats: $"
sSymbol db "Number of lines to print: $"

star db 0
line db 1
nl db 0dh, 0ah, "$"

.code
main proc
mov ax, @data
mov ds, ax

print:
mov ah, 2
mov dl, '*'          ; symbol
int 21h

inc star

mov bl, star
cmp bl, line

je newline
jmp print

newline:
mov ah, 9
lea dx, nl
int 21h

cmp bl, 5            ; number of repeats
je exit

inc line
mov star, 0
jmp print

exit:
mov ah, 4ch
int 21h

main endp
end main
</code>```

I want to be able to take in a number of lines from the user instead of the 5 (on the line with ; comment that says repeat)

and also a symbol other than the * (on the line with the ; comment that says symbol)

I have been trying to do it but can seem to get it correctly?

get 2 inputs from the user

number of desired lines

symbol

instead of the 5 and *, how do I do that

The program runs fine but I just want the user to be able to decide the number of lines and which symbol instead of the default 5 and * that I have in place

答:
Read newline terminated integer; doesn't seem that hard. We will need dos function AH=1 It's been a long time since I've done this. Let's break this down.

We first need to be able to read a digit. That should look like this:

```<code>readdigit proc
    mov ah, 01h
    int 21h
    sub al, '0'
    ret
endp readdigit
</code>```

Given that we could write the loop that reads all the digits; but there's a bit of an issue. When do you stop. Why, on a newline of course. If I recall correctly, a newline gives you a 13 (CR) followed by a 10 (LF). I could be wrong and it's just the CR; in which case you'll have to adjust below. The following loop would consume its input until LF.

```<code>consumeline proc
consumeline_loop:
    mov ah, 01h
    int 21h
    cmp al, 10
    jne consumeline_loop
    ret
endp consumeline
</code>```

To put digits together, the loop body would be:

```<code>    mov cx, 10
    mul ax, cx
    add ax, bx
</code>```

Weaving all of these together yields the result:

```<code>    ; Reads integer from standard input; output in AX
    ; clobbers BX, CX, DX
readint16 proc
    ; Initial state
    xor ax, ax
    mov cx, 10
readint16_loop:
    xchg ax, bx
    mov ah, 01h
    int 21h
    mov ah, 0
    xchg ax, bx
    cmp bl, 13
    je readint16_loop
    cmp bl, 10
    je readint16_exit
    mul cx
    sub bl, '0'
    add ax, bx
    jmp readint16_loop
readint16_exit:
    ret
endp readint16
</code>```

Copying and pasting this block will get you caught. You need to understand it and write it anew in your own code.

Body:
The following program prints star symbols in this pattern

%
%%
%%%
%%%%
%%%%%

My source code:

.model small
.stack 100h
.data
sRepeats db "repeats: $"
sSymbol db "Number of lines to print: $"

star db 0
line db 1
nl db 0dh, 0ah, "$"

.code
main proc
mov ax, @data
mov ds, ax

print:
mov ah, 2
mov dl, '*'          ; symbol
int 21h

inc star

mov bl, star
cmp bl, line

je newline
jmp print

newline:
mov ah, 9
lea dx, nl
int 21h

cmp bl, 5            ; number of repeats
je exit

inc line
mov star, 0
jmp print

exit:
mov ah, 4ch
int 21h

main endp
end main

I want to be able to take in a number of lines from the user instead of the 5 (on the line with ; comment that says repeat)

and also a symbol other than the * (on the line with the ; comment that says symbol)

I have been trying to do it but can seem to get it correctly?

get 2 inputs from the user

number of desired lines

symbol

instead of the 5 and *, how do I do that

The program runs fine but I just want the user to be able to decide the number of lines and which symbol instead of the default 5 and * that I have in place

Body:
Read newline terminated integer; doesn't seem that hard. We will need dos function AH=1 It's been a long time since I've done this. Let's break this down.

We first need to be able to read a digit. That should look like this:

readdigit proc
    mov ah, 01h
    int 21h
    sub al, '0'
    ret
endp readdigit

Given that we could write the loop that reads all the digits; but there's a bit of an issue. When do you stop. Why, on a newline of course. If I recall correctly, a newline gives you a 13 (CR) followed by a 10 (LF). I could be wrong and it's just the CR; in which case you'll have to adjust below. The following loop would consume its input until LF.

consumeline proc
consumeline_loop:
    mov ah, 01h
    int 21h
    cmp al, 10
    jne consumeline_loop
    ret
endp consumeline

To put digits together, the loop body would be:

    mov cx, 10
    mul ax, cx
    add ax, bx

Weaving all of these together yields the result:

    ; Reads integer from standard input; output in AX
    ; clobbers BX, CX, DX
readint16 proc
    ; Initial state
    xor ax, ax
    mov cx, 10
readint16_loop:
    xchg ax, bx
    mov ah, 01h
    int 21h
    mov ah, 0
    xchg ax, bx
    cmp bl, 13
    je readint16_loop
    cmp bl, 10
    je readint16_exit
    mul cx
    sub bl, '0'
    add ax, bx
    jmp readint16_loop
readint16_exit:
    ret
endp readint16

Copying and pasting this block will get you caught. You need to understand it and write it anew in your own code.


问:
Difference between [[NSDate date] retain] and [[NSDate alloc] init]
As both of the following serves the same purpose,

```<code>today = [[NSDate date] retain];
</code>```

and

```<code>today = [[NSDate alloc] init];
</code>```

Then what's the difference between them?

Does anything here is related to memory allocation methods or something else is the reason for using them accordingly.

答:
When you do this:

```<code>[NSDate date];
</code>```

…a new NSDate is created which will automatically be released (not deallocated!) at the end of the event loop. You can, of course, retain it to keep it around longer.

When you do this:

```<code>[[NSDate alloc] init];
</code>```

…a new NSDate is created which you should release when you’re done with it.

From a memory management standpoint, the main differece between [[NSDate date] retain] and the alternative is that this NSDate will be around at least until the end of the event loop. If you’re just creating a few objects, it doesn’t matter. But, if you create (and release) a lot of objects — say, while processing data in a loop — using the former pattern could cause the memory usage of your application to spike (and then drop suddenly at the end of the event loop). With the latter pattern, the object gets destroyed as soon as you release it.

Body:
As both of the following serves the same purpose,

today = [[NSDate date] retain];

and

today = [[NSDate alloc] init];

Then what's the difference between them?

Does anything here is related to memory allocation methods or something else is the reason for using them accordingly.

Body:
When you do this:

[NSDate date];

…a new NSDate is created which will automatically be released (not deallocated!) at the end of the event loop. You can, of course, retain it to keep it around longer.

When you do this:

[[NSDate alloc] init];

…a new NSDate is created which you should release when you’re done with it.

From a memory management standpoint, the main differece between [[NSDate date] retain] and the alternative is that this NSDate will be around at least until the end of the event loop. If you’re just creating a few objects, it doesn’t matter. But, if you create (and release) a lot of objects — say, while processing data in a loop — using the former pattern could cause the memory usage of your application to spike (and then drop suddenly at the end of the event loop). With the latter pattern, the object gets destroyed as soon as you release it.


问:
Adding hyperlink with text in the ClipBoard
I am using ClipBoard as follows to store the url string, however, when I paste it into textview, then it shows as it is, however, I want to add custom text and when user clicks on it, it takes him to the url.

```<code>ClipboardManager clipboardManager = (ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Click Here URL", "http://www.youtube.com");
clipboardManager.setPrimaryClip(clipData);
</code>```

As we are adding hyperlink into text, if you click on the url below, it will take you to the youtube.
Click here

Custom clickable links with text, I am wondering how to achieve this functionality.

I tried the following but it did not work:

```<code>ClipData clipData = ClipData.newPlainText("Click Here URL", "<a href=“http://www.youtube.com”>here</a>");
</code>```

答:
Try newHtmlText instead of newPlainText

```<code>    ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    String url = "<a href=\"http://www.youtube.com\">Click Here URL</a>";
    ClipData clipData = ClipData.newHtmlText("Click Here URL", "Click Here URL",url);
    clipboardManager.setPrimaryClip(clipData);
</code>```

Body:
I am using ClipBoard as follows to store the url string, however, when I paste it into textview, then it shows as it is, however, I want to add custom text and when user clicks on it, it takes him to the url.

ClipboardManager clipboardManager = (ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Click Here URL", "http://www.youtube.com");
clipboardManager.setPrimaryClip(clipData);

As we are adding hyperlink into text, if you click on the url below, it will take you to the youtube.
Click here

Custom clickable links with text, I am wondering how to achieve this functionality.

I tried the following but it did not work:

ClipData clipData = ClipData.newPlainText("Click Here URL", "here");

Body:
Try newHtmlText instead of newPlainText

    ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    String url = "<a href=\"http://www.youtube.com\">Click Here URL</a>";
    ClipData clipData = ClipData.newHtmlText("Click Here URL", "Click Here URL",url);
    clipboardManager.setPrimaryClip(clipData);


问:
Laravel login and register forms on the same page in Laravel 8
In laravel 8 how can i do login registration in same page , Problem is in both form email and password are same . valiadation error shows in both form .

Thanks in advance

答:
If you want to have multiple forms with the same input names on one page you need to take a look at named error bags.

If you are using FormRequests, it's quite easy. You can set a custom ErrorBag on the specific FormRequest.

<?php

use Illuminate\Foundation\Http\FormRequest;

class LoginFormRequest extends FormRequest
{
    protected $errorBag = 'loginForm';
}
```
<pre class="lang-php prettyprint-override"><code><?php

use Illuminate\Foundation\Http\FormRequest;

class RegisterFormRequest extends FormRequest
{
    protected $errorBag = 'registerForm';
}
</code>```

Earlier you have been used to use something like this in your blade files:

{{ $errors->first('email') }}

```
<p>This uses the default ErrorBag. But in our case, we have overwritten the bag with our custom ones. The syntax changes a little bit if you want to access them. Here's how.</p>
<pre class="lang-html prettyprint-override"><code><div>{{ $errors->loginForm->first('email') }}</div>
<div>{{ $errors->registerForm->first('email') }}</div>
</code>```

Body:
If you want to have multiple forms with the same input names on one page you need to take a look at named error bags.

If you are using FormRequests, it's quite easy. You can set a custom ErrorBag on the specific FormRequest.

<?php

use Illuminate\Foundation\Http\FormRequest;

class LoginFormRequest extends FormRequest
{
    protected $errorBag = 'loginForm';
}

<?php

use Illuminate\Foundation\Http\FormRequest;

class RegisterFormRequest extends FormRequest
{
    protected $errorBag = 'registerForm';
}

Earlier you have been used to use something like this in your blade files:

<div>{{ $errors->first('email') }}</div>

This uses the default ErrorBag. But in our case, we have overwritten the bag with our custom ones. The syntax changes a little bit if you want to access them. Here's how.

<div>{{ $errors->loginForm->first('email') }}</div>
<div>{{ $errors->registerForm->first('email') }}</div>


问:
Implement countall in prolog
Need prolog code to implement countall(List1, List2, N), which counts the number of any element in List1 in List2

Test cases for checking code

```<code>   ?- countall([a], [b, a, c, a], Number).
   Number=2.

   ?- countall([a, b], [b, b, a, c, a], Number).
   Number=4.

   ?- countall([a], [b, c, d], Number).
   Number=0.

   ?- countall([e, e], [e], Number).
   Number=2.
</code>```

答:
```<code>countall(List1, List2, Count):-
    findall(Elem, (member(Elem, List1), member(Elem, List2)), Matches),
    length(Matches, Count).
</code>```

"Find all the ways Elem is something found in both List1 and List2, gather them up and count them".

```<code>?- countall([a], [b, a, c, a], Number).
             ^       ^
             ^             ^
</code>```

and

```<code>?- countall([a, b], [b, b, a, c, a], Number).
             ^             ^
             ^                   ^
                ^    ^
                ^       ^
</code>```

Title: Implement countall in prolog

Body:
Need prolog code to implement countall(List1, List2, N), which counts the number of any element in List1 in List2

Test cases for checking code

   ?- countall([a], [b, a, c, a], Number).
   Number=2.

   ?- countall([a, b], [b, b, a, c, a], Number).
   Number=4.

   ?- countall([a], [b, c, d], Number).
   Number=0.

   ?- countall([e, e], [e], Number).
   Number=2.

Body:
countall(List1, List2, Count):-
    findall(Elem, (member(Elem, List1), member(Elem, List2)), Matches),
    length(Matches, Count).

"Find all the ways Elem is something found in both List1 and List2, gather them up and count them".

?- countall([a], [b, a, c, a], Number).
             ^       ^
             ^             ^

and

?- countall([a, b], [b, b, a, c, a], Number).
             ^             ^
             ^                   ^
                ^    ^
                ^       ^


问:
My reverse method doesn't reverse anything?
Here is my code:

public static void numberToWords(int number){
    int lastDigit;

    if(number < 0){
        System.out.println("Invalid Value");
    }
    while(number != 0) {
        lastDigit = number % 10; // lastDigit = 3
        number = number / 10;
        reverse(number);

        if (lastDigit == 0) {
            System.out.println("ZERO");
        }
        if (lastDigit == 1) {
            System.out.println("ONE");
        }
        if (lastDigit == 2) {
            System.out.println("TWO");
        }
        if (lastDigit == 3) {
            System.out.println("THREE");
        }
        if (lastDigit == 4) {
            System.out.println("FOUR");
        }
        if (lastDigit == 5) {
            System.out.println("FIVE");
        }
        if (lastDigit == 6) {
            System.out.println("SIX");
        }
        if (lastDigit == 7) {
            System.out.println("SEVEN");
        }
        if (lastDigit == 8) {
            System.out.println("EIGHT");
        }
        if (lastDigit == 9) {
            System.out.println("NINE");
        }
    }
}

public static void reverse(int a){
    int finalDigit = 0;
    int reverse1 = 0;

    while(a > 0) {
        finalDigit = a % 10;
        reverse1 = reverse1 * 10 + finalDigit;
        a = a / 10;
    }
}
```

My digits are printed as strings as desired, but they come in reverse order.

I tried to add the reverse method into the conversion method but the results are always the same, can't figure out how to reverse it.

答: if you do use a condition lastdigit>10 than it is make simple program</p>

Body:
Here is my code:

public static void numberToWords(int number){
    int lastDigit;

    if(number < 0){
        System.out.println("Invalid Value");
    }
    while(number != 0) {
        lastDigit = number % 10; // lastDigit = 3
        number = number / 10;
        reverse(number);

        if (lastDigit == 0) {
            System.out.println("ZERO");
        }
        if (lastDigit == 1) {
            System.out.println("ONE");
        }
        if (lastDigit == 2) {
            System.out.println("TWO");
        }
        if (lastDigit == 3) {
            System.out.println("THREE");
        }
        if (lastDigit == 4) {
            System.out.println("FOUR");
        }
        if (lastDigit == 5) {
            System.out.println("FIVE");
        }
        if (lastDigit == 6) {
            System.out.println("SIX");
        }
        if (lastDigit == 7) {
            System.out.println("SEVEN");
        }
        if (lastDigit == 8) {
            System.out.println("EIGHT");
        }
        if (lastDigit == 9) {
            System.out.println("NINE");
        }
    }
}

public static void reverse(int a){
    int finalDigit = 0;
    int reverse1 = 0;

    while(a > 0) {
        finalDigit = a % 10;
        reverse1 = reverse1 * 10 + finalDigit;
        a = a / 10;
    }
}

My digits are printed as strings as desired, but they come in reverse order.

I tried to add the reverse method into the conversion method but the results are always the same, can't figure out how to reverse it.


问:
How to get each hashtag inside the element and hide it?
so I have a div containing a description of the item in which there is a hashtag. I want to get every existing hashtag and want to hide all existing hashtags so that they have a hidden class. How can I do that?

var element = $('#product-nav-description');
var rgxp = new RegExp(/^#\!/, 'g');
var hashtag = '#';
var repl = '' + hashtag + '';

element.html(element.html().replace(hashtag, repl));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  background-color: yellow;
  font-weight: bold;
}</code>```

    Dummy Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum #machine #vendingmachine #mach #tech

```

答:
You can use regex I change. You can run code to test

var element = $('#product-nav-description');
var rgxp = new RegExp(/([#])\w+/g);
//var hashtag = '#';
//var repl = '' + hashtag + '';
var str_content_origin = String(element.get(0).outerHTML);
var str_content = str_content_origin.match(rgxp);
$.each(str_content, function(i,v){
    var hashtag = v.trim();
    var repl = '' + v + '';
    //console.log(element.html());
    element.html(element.html().replace(hashtag, repl));
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  background-color: yellow;
  font-weight: bold;
}</code>```

  Dummy Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum #machine #vendingmachine #math #tech

```

Body:
so I have a div containing a description of the item in which there is a hashtag. I want to get every existing hashtag and want to hide all existing hashtags so that they have a hidden class. How can I do that?

var element = $('#product-nav-description');
var rgxp = new RegExp(/^#\!/, 'g');
var hashtag = '#';
var repl = '' + hashtag + '';

element.html(element.html().replace(hashtag, repl));

.hidden {
  background-color: yellow;
  font-weight: bold;
}

    Dummy Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum #machine #vendingmachine #mach #tech

Body:
You can use regex I change. You can run code to test

var element = $('#product-nav-description');
var rgxp = new RegExp(/([#])\w+/g);
//var hashtag = '#';
//var repl = '<span class="hidden">' + hashtag + '</span>';
var str_content_origin = String(element.get(0).outerHTML);
var str_content = str_content_origin.match(rgxp);
$.each(str_content, function(i,v){
    var hashtag = v.trim();
    var repl = '<span class="hidden">' + v + '</span>';
    //console.log(element.html());
    element.html(element.html().replace(hashtag, repl));
})

.hidden {
  background-color: yellow;
  font-weight: bold;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="product-nav-description">
  <p>
  Dummy Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum #machine #vendingmachine #math #tech
  </p>
</div>


问:
SQL How to convert a date into hours per minute? Then subtract two of the colums (end-start) and set it as a new column?
I am wondering, how can I convert datetime into hours per minute? I want the following. To minus the end_trip with the start_trip that is in hours and minutes. Moreover, I want to create a new column for the result. However, I am getting nowhere. I want to use basic arithmetic for this not some built in functions like DATEDIFF. Please help.

Below is my code

```<code>INSERT INTO TRIP VALUES(
TO_DATE('26-01-2022 14:00:00', 'DD/MM/YYYY HH24:MI:SS'), - start_time
TO_DATE('26-01-2022 14:50:00', 'DD/MM/YYYY HH24:MI:SS')  - end_time
;

SELECT
trip_start_actual as start_time, trip_end_actual as end_time, (trip_end_actual - trip_start_actual)
from trip;
commit;
</code>```

答:
when we subtract two dates in oracle the difference integer also comes in days. we need to multiply that by 24 to get hours and multiply by 24 * 60 = 1440 to get minutes and multiply by 24 * 60 * 60 = 86400 to get seconds.</p>
```<code>SELECT
trip_start_actual as start_time, trip_end_actual as end_time,
round ((trip_end_actual - trip_start_actual) * 24 * 60) as
time_diff_minutes from trip;
</code>```

Body:
I am wondering, how can I convert datetime into hours per minute? I want the following. To minus the end_trip with the start_trip that is in hours and minutes. Moreover, I want to create a new column for the result. However, I am getting nowhere. I want to use basic arithmetic for this not some built in functions like DATEDIFF. Please help.

Below is my code

INSERT INTO TRIP VALUES(
TO_DATE('26-01-2022 14:00:00', 'DD/MM/YYYY HH24:MI:SS'), - start_time
TO_DATE('26-01-2022 14:50:00', 'DD/MM/YYYY HH24:MI:SS')  - end_time
;

SELECT
trip_start_actual as start_time, trip_end_actual as end_time, (trip_end_actual - trip_start_actual)
from trip;
commit;

Body:
when we subtract two dates in oracle the difference integer also comes in days. we need to multiply that by 24 to get hours and multiply by 24 * 60 = 1440 to get minutes and multiply by 24 * 60 * 60 = 86400 to get seconds.

SELECT
trip_start_actual as start_time, trip_end_actual as end_time,
round ((trip_end_actual - trip_start_actual) * 24 * 60) as
time_diff_minutes from trip;


问:
Tkinter Button Command switches when new Button is used
I face an issue which is that my first button is using the second button's command. I have faced this logic error multiple times when trying to create buttons programmatically with different functions, is there a way to resolve this or is this a limitation to Tkinter? The gif below illustrates my issue.

import tkinter as tk
root = tk.Tk()
root.geometry("400x400")

def print_when_clicked(message):
    print(message)

array = ["hi", "bye"]

for i in array:
    tk.Button(root, text=i, command=lambda:print_when_clicked(i)).pack()
```

答:
You have fallen in to one of the classic Python traps.  The issue is that the lambda captures the i variable, NOT the value of i.  So, after the loop finishes, i is bound to "bye", and both functions use it.

The trick to work around this is to use a fake default argument:

```<code>for i in array:
    tk.Button(root, text=i, command=lambda i=i:print_when_clicked(i)).pack()
</code>```

Body:
You have fallen in to one of the classic Python traps.  The issue is that the lambda captures the i variable, NOT the value of i.  So, after the loop finishes, i is bound to "bye", and both functions use it.

The trick to work around this is to use a fake default argument:

for i in array:
    tk.Button(root, text=i, command=lambda i=i:print_when_clicked(i)).pack()