问:
I am getting an error when I am trying to runn ansible playbook that creates a ec2 security group
```<code>---
- hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Create a security group
      ec2_group:
        - name: Ansible
          description: Ansible security group
          region: us-east-1
          rules:
            - proto: tcp
              from_port: 80
              to_port: 80
              cidr_ip: 0.0.0.0/0

            - proto: tcp
              from_port: 22
              to_port: 22
              cidr_ip: 0.0.0.0/0
</code>```

When I run this playbook I am getting the error below

[root]#ansible-playbook aws1.yaml
 ERROR! unexpected parameter type in action:

The error appears to be in '/root/Desktop/ansible_pro/aws/1/aws1.yaml': line 6, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

```<code>tasks:
    - name: Create a security group
      ^ here
</code>```

I am new with aws with ansible. Please help

答:
@Zellounator is correct.

first you should check your playbook syntax by using below command:

```<code>  #ansible-playbook aws1.yaml --syntax-check
</code>```

Then you can do dry run of same playbook:
     #ansible-playbook aws1.yaml --check

the corrected code can look like the below :

```<code>---
 - hosts: localhost
   connection: local
   gather_facts: false
   tasks:
 - name: Create a security group
   ec2_group:
      name: Ansible
      description: Ansible security group
      region: us-east-1
      rules:
        - proto: tcp
          from_port: 80
          to_port: 80
          cidr_ip: 0.0.0.0/0

        - proto: tcp
          from_port: 22
          to_port: 22
          cidr_ip: 0.0.0.0/0
</code>```

and another example for the below you can allow multiple ports at a time.

```<code>---
- hosts: localhost
  connection: local
  gather_facts: false

  tasks:

  - name: Create a security group
    ec2_group:
     name: Ansible
     description: Ansible security group
     region: us-east-1
     rules:
      - proto: tcp
        ports:
        - 22
        - 80
        cidr_ip: 0.0.0.0/0
</code>```

make sure you have configured IAM role or Secret key, access key which can be attached to ec2 and able to create Security group.

You can go through the example with below link:
https://docs.ansible.com/ansible/latest/modules/ec2_group_module.html & its always recommended to go through examples of ansible playbook.

Hope this helps.

Body:
---
- hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Create a security group
      ec2_group:
        - name: Ansible
          description: Ansible security group
          region: us-east-1
          rules:
            - proto: tcp
              from_port: 80
              to_port: 80
              cidr_ip: 0.0.0.0/0

            - proto: tcp
              from_port: 22
              to_port: 22
              cidr_ip: 0.0.0.0/0

When I run this playbook I am getting the error below

[root]#ansible-playbook aws1.yaml
 ERROR! unexpected parameter type in action:

The error appears to be in '/root/Desktop/ansible_pro/aws/1/aws1.yaml': line 6, column 7, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

tasks:
    - name: Create a security group
      ^ here

I am new with aws with ansible. Please help

Body:
@Zellounator is correct.

first you should check your playbook syntax by using below command:

  #ansible-playbook aws1.yaml --syntax-check

Then you can do dry run of same playbook:
     #ansible-playbook aws1.yaml --check

the corrected code can look like the below :

---
 - hosts: localhost
   connection: local
   gather_facts: false
   tasks:
 - name: Create a security group
   ec2_group:
      name: Ansible
      description: Ansible security group
      region: us-east-1
      rules:
        - proto: tcp
          from_port: 80
          to_port: 80
          cidr_ip: 0.0.0.0/0

        - proto: tcp
          from_port: 22
          to_port: 22
          cidr_ip: 0.0.0.0/0

and another example for the below you can allow multiple ports at a time.

---
- hosts: localhost
  connection: local
  gather_facts: false

  tasks:

  - name: Create a security group
    ec2_group:
     name: Ansible
     description: Ansible security group
     region: us-east-1
     rules:
      - proto: tcp
        ports:
        - 22
        - 80
        cidr_ip: 0.0.0.0/0

make sure you have configured IAM role or Secret key, access key which can be attached to ec2 and able to create Security group.

You can go through the example with below link:
https://docs.ansible.com/ansible/latest/modules/ec2_group_module.html & its always recommended to go through examples of ansible playbook.

Hope this helps.


来源: stackexchange

问:
What does the red arrow pointing up and right mean in the Package Explorer in Eclipse?
I am using SpringSource Tool Suite (essentially Eclipse Helios ++) and I just started using Subversive.  I've been using all of the tools except Subversive for quite a while and I've never seen these red arrow icons before (or are these called "adornments"?), so I suspect Subversive is the source, but I can't find anything on line that says what they mean.

答:
Yup those are Subversive's decorations ( the arrow is for "switched")

http://www.eclipse.org/subversive/documentation/teamSupport/svn_label_decor.php

ContentLicense: CC BY-SA 3.0


问:
Difference between Role and GrantedAuthority in Spring Security
There are concepts and implementations in Spring Security, such as the GrantedAuthority interface to get an authority to authorize/control an access.

I would like that to permissible operations, such as createSubUsers, or deleteAccounts, which I would allow to an admin (with role ROLE_ADMIN).

I am getting confused as the tutorials/demos I see online. I try to connect what I read, but I think we treat the two interchangeably.

I see hasRole consuming a GrantedAuthority string? I most definitely am doing it wrong in understanding. What are these conceptually in Spring Security?

How do I store the role of a user, separate from the authorities for that role?

I'm also looking at the org.springframework.security.core.userdetails.UserDetails interface which is used in the authentication-provider referenced DAO, which consumes a User (note last GrantedAuthority):

```<code>public User(String username,
            String password,
            boolean enabled,
            boolean accountNonExpired,
            boolean credentialsNonExpired,
            boolean accountNonLocked,
            Collection<? extends GrantedAuthority> authorities)
</code>```

Or is there any other way to differentiate the other two? Or is it not supported and we have to make our own?

答:
Like others have mentioned, I think of roles as containers for more granular permissions.

Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.

So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.

I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.

Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST

These permissions are relatively static, but the relationship of roles to them may be dynamic.

Example -

```<code>@Autowired
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}
</code>```

You may create APIs to manage the relationship of these permissions to a role.

I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.

https://stackoverflow.com/a/60251931/1308685

To re-use my implementation, I created a repo. Please feel free to contribute!

https://github.com/savantly-net/spring-role-permissions

Body:
There are concepts and implementations in Spring Security, such as the GrantedAuthority interface to get an authority to authorize/control an access.

I would like that to permissible operations, such as createSubUsers, or deleteAccounts, which I would allow to an admin (with role ROLE_ADMIN).

I am getting confused as the tutorials/demos I see online. I try to connect what I read, but I think we treat the two interchangeably.

I see hasRole consuming a GrantedAuthority string? I most definitely am doing it wrong in understanding. What are these conceptually in Spring Security?

How do I store the role of a user, separate from the authorities for that role?

I'm also looking at the org.springframework.security.core.userdetails.UserDetails interface which is used in the authentication-provider referenced DAO, which consumes a User (note last GrantedAuthority):

public User(String username,
            String password,
            boolean enabled,
            boolean accountNonExpired,
            boolean credentialsNonExpired,
            boolean accountNonLocked,
            Collection<? extends GrantedAuthority> authorities)

Or is there any other way to differentiate the other two? Or is it not supported and we have to make our own?

Body:
Like others have mentioned, I think of roles as containers for more granular permissions.

Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.

So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.

I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.

Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST

These permissions are relatively static, but the relationship of roles to them may be dynamic.

Example -

@Autowired
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}

You may create APIs to manage the relationship of these permissions to a role.

I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.

https://stackoverflow.com/a/60251931/1308685

To re-use my implementation, I created a repo. Please feel free to contribute!

https://github.com/savantly-net/spring-role-permissions

ContentLicense: CC BY-SA 4.0


问:
Rowfilter and checkbox with access C#
I would like to filter an ms access database and have a preview in a DataGridView. Actually, I'm able to filter with combobox or textbox like this :

```<code>dvhotline.RowFilter = "Quand LIKE '%" + textBox1.Text + "%' AND Qui LIKE '%" + textBox2.Text + "%' AND Quoi LIKE '%" + textBox3.Text + "%' AND Pb LIKE '%" + textBox5.Text + "%' AND Solutions LIKE '%" + textBox4.Text + "%' AND Statut LIKE '%" + comboBox1.Text + "%' AND Axi = '%"+checkBox1.Checked+"%' ";
</code>```

But I have a column with checkbox true/false.

How can I filter with a checkbox like (I know it's false but it's my only idea) :

```<code>...AND columnname LIKE '"+checkbox1.checked+"'
</code>```

Thank you ;)

答:
In SQL the boolean is stored as bit datatype (so either 1 or 0), so you need to do something like this: </p>

```<code>AND columnname = "+(checkbox1.checked ? "1" : "0")
</code>```

Title: Rowfilter and checkbox with access C#

Body:
I would like to filter an ms access database and have a preview in a DataGridView. Actually, I'm able to filter with combobox or textbox like this :

dvhotline.RowFilter = "Quand LIKE '%" + textBox1.Text + "%' AND Qui LIKE '%" + textBox2.Text + "%' AND Quoi LIKE '%" + textBox3.Text + "%' AND Pb LIKE '%" + textBox5.Text + "%' AND Solutions LIKE '%" + textBox4.Text + "%' AND Statut LIKE '%" + comboBox1.Text + "%' AND Axi = '%"+checkBox1.Checked+"%' ";

But I have a column with checkbox true/false.

How can I filter with a checkbox like (I know it's false but it's my only idea) :

...AND columnname LIKE '"+checkbox1.checked+"'

Thank you ;)

Body:
In SQL the boolean is stored as bit datatype (so either 1 or 0), so you need to do something like this:

AND columnname = "+(checkbox1.checked ? "1" : "0")


问:
Unable to get image data in an API along with json data for registration
I want to create a register API in which I have username,email, password input along with an image field.I am unable to receive and process the data properly.The default user class is extended to store image field.
I have this extended user model:-

```<code>from django.contrib.auth.models import User
import os
def get_upload_path(instance, filename):
    fileName, fileExtension = os.path.splitext(filename)
    return os.path.join("user_%s" % instance.user.username,"user_{0}.{1}" .format(instance.user.username,fileExtension))

# Create your models here.
class Userprofile(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    display_picture=models.ImageField(upload_to=get_upload_path)
    has_voted=models.BooleanField(default=False)
    voted_item=models.CharField(max_length=200,default='none')
    def __str__(self):
        return self.user.username
</code>```

These are the serializers:-

```<code>from django.contrib.auth.models import User
from .models import Userprofile

class UserprofileSerializer(serializers.ModelSerializer):
    class Meta:
        model=Userprofile
        fields=['display_picture']

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model=User
        fields=['username','email','password1','password2']
</code>```

this is the path/url:-

```<code>path('register',views.FileUploadView.as_view(),name='Register'),
</code>```

this is the view:-

```<code>@csrf_exempt
class FileUploadView(APIView):
    parser_classes=[MultiPartParser,FormParser]

    def register(self,request):
        display_picture=request.FILES["display_picture"]
        data=json.loads(request.data["data"])
        #saving data using serializers
        return JsonResponse({'message': "Registered Successfully!"},status=200)
</code>```

I am getting this issue which says:-

path('register',views.FileUploadView.as_view(),name='Register'),
AttributeError: 'function' object has no attribute 'as_view'

答:
You are decorating a class like a function,thats why your code is breaking.

In order to use a decorator on a class, you can do either of the two approaches:

1) Decorating the class:

```<code>from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

@method_decorator(csrf_exempt,name='dispatch')
class FileUploadView(APIView):
    parser_classes=[MultiPartParser,FormParser]
    def register(self,request):

        display_picture=request.FILES["display_picture"]
        data=json.loads(request.data["data"])

        #saving data using serializers
        return JsonResponse({'message': "Registered Successfully!"},status=200)
</code>```

2) Decorating in URL only:

```<code>from django.views.decorators.csrf import csrf_exempt

path('register',csrf_exempt(view.FileUploadView.as_view()))
</code>```

You can read in detail here.

Body:
I want to create a register API in which I have username,email, password input along with an image field.I am unable to receive and process the data properly.The default user class is extended to store image field.
I have this extended user model:-

from django.contrib.auth.models import User
import os
def get_upload_path(instance, filename):
    fileName, fileExtension = os.path.splitext(filename)
    return os.path.join("user_%s" % instance.user.username,"user_{0}.{1}" .format(instance.user.username,fileExtension))

# Create your models here.
class Userprofile(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    display_picture=models.ImageField(upload_to=get_upload_path)
    has_voted=models.BooleanField(default=False)
    voted_item=models.CharField(max_length=200,default='none')
    def __str__(self):
        return self.user.username

These are the serializers:-

from django.contrib.auth.models import User
from .models import Userprofile

class UserprofileSerializer(serializers.ModelSerializer):
    class Meta:
        model=Userprofile
        fields=['display_picture']

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model=User
        fields=['username','email','password1','password2']

this is the path/url:-

path('register',views.FileUploadView.as_view(),name='Register'),

this is the view:-

@csrf_exempt
class FileUploadView(APIView):
    parser_classes=[MultiPartParser,FormParser]

    def register(self,request):
        display_picture=request.FILES["display_picture"]
        data=json.loads(request.data["data"])
        #saving data using serializers
        return JsonResponse({'message': "Registered Successfully!"},status=200)

I am getting this issue which says:-

path('register',views.FileUploadView.as_view(),name='Register'),
AttributeError: 'function' object has no attribute 'as_view'

Body:
You are decorating a class like a function,thats why your code is breaking.

In order to use a decorator on a class, you can do either of the two approaches:

1) Decorating the class:

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

@method_decorator(csrf_exempt,name='dispatch')
class FileUploadView(APIView):
    parser_classes=[MultiPartParser,FormParser]
    def register(self,request):

        display_picture=request.FILES["display_picture"]
        data=json.loads(request.data["data"])

        #saving data using serializers
        return JsonResponse({'message': "Registered Successfully!"},status=200)

2) Decorating in URL only:

from django.views.decorators.csrf import csrf_exempt

path('register',csrf_exempt(view.FileUploadView.as_view()))

You can read in detail here.


问:
How to retrieve similar values inside of objects in List of similar objects and create a map based on the values
I have a class named People

```<code>public class People{
       private String name;
       private String email;
       private String accountnum;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getAccountnum() {
    return accountnum;
}

public void setAccountnum(String accountnum) {
    this.accountnum= accountnum;
}

public People(String name, String email, String accountnum) {
    this.name = name;
    this.email = email;
    this.accountnum= accountnum;
}
</code>```

}

I have a ArrayList of objects that created from this class

```<code>People peop1 = new People("john", "john@gmail.com", "56hk");
People peop2 = new People("Rose", "rose@gmail.com", "5689hk");
People peop3 = new People("john", "john@gmail.com", "5676hk");
People peop4 = new People("Rose", "rose@gmail.com", "6799hk");
People peop5 = new People("Jack", "jack@gmail.com", "7009hk");

List<People> peoplelist = new ArrayList<People>();

peoplelist .add(peop1);
peoplelist.add(peop2 );
peoplelist .add(peop3 );
</code>```

What i want to do is to retrieve the email and its accountnums.
like this

```<code>john@gmail.com = {56hk,5676hk};
rose@gmail.com = {5689hk,6799hk};
jack@gmail.com = {7009hk}
</code>```

I know i can loop through and  return a map or use java streams and collection framework. But I don't know how to do it.

I tried to find similar solution but couldn't find any sorry if this is already asked.

Are there any way to do that?

答:
The collect all different accountnums of each person, you could use a HashSet. It would automatically eliminate duplicate values.

To collect the data of all persons, you could use a HashMap with email address as the key and the set of accountnums as the value.

Example:

```<code>import java.util.*;

class Main
{
    public static void main(String[] args)
    {
        // Create example input data
        List<People> peopleList = new ArrayList<People>();
        peopleList.add(new People("john", "john@gmail.com", "56hk"));
        peopleList.add(new People("Rose", "rose@gmail.com", "5689hk"));
        peopleList.add(new People("john", "john@gmail.com", "5676hk"));
        peopleList.add(new People("Rose", "rose@gmail.com", "6799hk"));
        peopleList.add(new People("Jack", "jack@gmail.com", "7009hk"));

        // To collect the result. key=email, value=set of accountnum
        Map<String, Set<String>> map = new HashMap<>();

        // Iterate over the input
        for (People person : peopleList)
        {
            // Get the existing data for the email address of this person
            Set<String> acountNumbers = map.get(person.getEmail());

            // If this is the first record for the email...
            if (acountNumbers == null)
            {
                // Create a new HashSet to collect the account numbers for this email
                acountNumbers = new HashSet<String>();
                acountNumbers.add(person.getAccountnum());
                map.put(person.getEmail(), acountNumbers);
            }
            else
            {
                // Add the accountnum to the existing set of account numbers
                acountNumbers.add(person.getAccountnum());
            }
        }

        // Output the result
        for (Map.Entry<String, Set<String>> entry : map.entrySet())
        {
            String email = entry.getKey();
            Set<String> acountNumbers = entry.getValue();
            System.out.println(email + " = " + acountNumbers);
        }
    }
}
</code>```

Outputs:

```<code>rose@gmail.com = [5689hk, 6799hk]
john@gmail.com = [5676hk, 56hk]
jack@gmail.com = [7009hk]
</code>```

Body:
I have a class named People

public class People{
       private String name;
       private String email;
       private String accountnum;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getAccountnum() {
    return accountnum;
}

public void setAccountnum(String accountnum) {
    this.accountnum= accountnum;
}

public People(String name, String email, String accountnum) {
    this.name = name;
    this.email = email;
    this.accountnum= accountnum;
}

}

I have a ArrayList of objects that created from this class

People peop1 = new People("john", "john@gmail.com", "56hk");
People peop2 = new People("Rose", "rose@gmail.com", "5689hk");
People peop3 = new People("john", "john@gmail.com", "5676hk");
People peop4 = new People("Rose", "rose@gmail.com", "6799hk");
People peop5 = new People("Jack", "jack@gmail.com", "7009hk");

List<People> peoplelist = new ArrayList<People>();

peoplelist .add(peop1);
peoplelist.add(peop2 );
peoplelist .add(peop3 );

What i want to do is to retrieve the email and its accountnums.
like this

john@gmail.com = {56hk,5676hk};
rose@gmail.com = {5689hk,6799hk};
jack@gmail.com = {7009hk}

I know i can loop through and  return a map or use java streams and collection framework. But I don't know how to do it.

I tried to find similar solution but couldn't find any sorry if this is already asked.

Are there any way to do that?

Body:
The collect all different accountnums of each person, you could use a HashSet. It would automatically eliminate duplicate values.

To collect the data of all persons, you could use a HashMap with email address as the key and the set of accountnums as the value.

Example:

import java.util.*;

class Main
{
    public static void main(String[] args)
    {
        // Create example input data
        List<People> peopleList = new ArrayList<People>();
        peopleList.add(new People("john", "john@gmail.com", "56hk"));
        peopleList.add(new People("Rose", "rose@gmail.com", "5689hk"));
        peopleList.add(new People("john", "john@gmail.com", "5676hk"));
        peopleList.add(new People("Rose", "rose@gmail.com", "6799hk"));
        peopleList.add(new People("Jack", "jack@gmail.com", "7009hk"));

        // To collect the result. key=email, value=set of accountnum
        Map<String, Set<String>> map = new HashMap<>();

        // Iterate over the input
        for (People person : peopleList)
        {
            // Get the existing data for the email address of this person
            Set<String> acountNumbers = map.get(person.getEmail());

            // If this is the first record for the email...
            if (acountNumbers == null)
            {
                // Create a new HashSet to collect the account numbers for this email
                acountNumbers = new HashSet<String>();
                acountNumbers.add(person.getAccountnum());
                map.put(person.getEmail(), acountNumbers);
            }
            else
            {
                // Add the accountnum to the existing set of account numbers
                acountNumbers.add(person.getAccountnum());
            }
        }

        // Output the result
        for (Map.Entry<String, Set<String>> entry : map.entrySet())
        {
            String email = entry.getKey();
            Set<String> acountNumbers = entry.getValue();
            System.out.println(email + " = " + acountNumbers);
        }
    }
}

Outputs:

rose@gmail.com = [5689hk, 6799hk]
john@gmail.com = [5676hk, 56hk]
jack@gmail.com = [7009hk]


问:
Spacing timestamp in pandas plot using seaborn
Please my code is shown below. I want to space the timestamp as the plot looks so squeezed.

```<code>    import seaborn as sns
    import matplotlib.pyplot as plt
    import pandas as pd

    dataset = pd.read_csv('../Data/User/DataSample.csv')
    dataset.head(10)

        Grade   Time
0   Pass    2020-02-13 13:24:56
1   Pass    2020-02-13 13:25:00
2   Pass    2020-02-13 13:25:04
3   Pass    2020-02-13 13:25:08
4   Pass    2020-02-13 13:25:13
5   Pass    2020-02-13 13:25:17
6   Pass    2020-02-13 13:25:21
7   Pass    2020-02-13 13:25:27
8   Pass    2020-02-13 13:25:31
9   Pass    2020-02-13 13:26:19

    sns.scatterplot(x='Time', y='Grade', hue='Grade', data=dataset)
    plt.gcf().autofmt_xdate()
</code>```

Result of the plot

答:
Thanks for including a sample dataset.

Give this a shot:

```<code>import matplotlib.dates as mdates

ax = sns.scatterplot(x='Time',y='Grade',hue='Grade',data=df)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax.xaxis.set_major_locator(mdates.HourLocator())
plt.gcf().autofmt_xdate()
plt.show()
</code>```

Body:
Please my code is shown below. I want to space the timestamp as the plot looks so squeezed.

    import seaborn as sns
    import matplotlib.pyplot as plt
    import pandas as pd

    dataset = pd.read_csv('../Data/User/DataSample.csv')
    dataset.head(10)

        Grade   Time
0   Pass    2020-02-13 13:24:56
1   Pass    2020-02-13 13:25:00
2   Pass    2020-02-13 13:25:04
3   Pass    2020-02-13 13:25:08
4   Pass    2020-02-13 13:25:13
5   Pass    2020-02-13 13:25:17
6   Pass    2020-02-13 13:25:21
7   Pass    2020-02-13 13:25:27
8   Pass    2020-02-13 13:25:31
9   Pass    2020-02-13 13:26:19

    sns.scatterplot(x='Time', y='Grade', hue='Grade', data=dataset)
    plt.gcf().autofmt_xdate()

Result of the plot

Body:
Thanks for including a sample dataset.

Give this a shot:

import matplotlib.dates as mdates

ax = sns.scatterplot(x='Time',y='Grade',hue='Grade',data=df)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
ax.xaxis.set_major_locator(mdates.HourLocator())
plt.gcf().autofmt_xdate()
plt.show()


问:
Parsing data from function in POSIX
I'm using POSIX. I have a function called get_data which returns:

```<code>4;Fix README;feature4;develop;URL5
2;Fix file3;feature2;develop;URL2
5;Fix README;feature2;develop;URL3
1;Fix file2;feature1;develop;URL1
</code>```

I want to get to the URL (last part) of latest feature2 (based on the first index). In the above example, it will return URL3 because it has feature2 in the third field and 5 > 2 in the first field.

The first thing I tried is:

```<code>url=$(get_data | grep feature2)
</code>```

But I don't like this solution because the other lines also can contain feature2 on other fields. If it was Bash I would use BASH_REMATCH with regex, but here I'm not sure what is the best most elegant way to get that URL.

Is it possible to get some suggestion on how to do it?

答:
Use awk:

```<code>url=$(get_data | awk -F";" '$3 == "feature2" && $1 > idx {idx=$1; url=$5} END {print url}')
</code>```

After splitting each line into ;-delimited fields, save the fifth field from a line whose third field is the desired feature, if the index is greater than the one you last saved. Once you have checked each line, output the final value of url.

Title: Parsing data from function in POSIX

Body:
I'm using POSIX. I have a function called get_data which returns:

4;Fix README;feature4;develop;URL5
2;Fix file3;feature2;develop;URL2
5;Fix README;feature2;develop;URL3
1;Fix file2;feature1;develop;URL1

I want to get to the URL (last part) of latest feature2 (based on the first index). In the above example, it will return URL3 because it has feature2 in the third field and 5 > 2 in the first field.

The first thing I tried is:

url=$(get_data | grep feature2)

But I don't like this solution because the other lines also can contain feature2 on other fields. If it was Bash I would use BASH_REMATCH with regex, but here I'm not sure what is the best most elegant way to get that URL.

Is it possible to get some suggestion on how to do it?

Body:
Use awk:

url=$(get_data | awk -F";" '$3 == "feature2" && $1 > idx {idx=$1; url=$5} END {print url}')

After splitting each line into ;-delimited fields, save the fifth field from a line whose third field is the desired feature, if the index is greater than the one you last saved. Once you have checked each line, output the final value of url.


问:
Using debounce with React hooks causes endless requests
I need to get data from server on changes in search input but I don't want to send a new request on every new character there so I'm trying use debounce from use-debounce package https://github.com/xnimorz/use-debounce. But my code below causes only endless requests before even any changes in search input happens.

App.js

```<code>import React, { useState, useEffect } from "react";
import axios from "axios";
import moment from "moment";
import { useDebounce } from "use-debounce";
import { Layout } from "./../Layout";
import { List } from "./../List";
import { Loader } from "./../Loader";
import { Header } from "./../Header";
import { Search } from "./../Search";
import { Licenses } from "./../Licenses";
import { Pagination } from "./../Pagination";

import "./App.css";

const PER_PAGE = 20;

export const App = () => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [nameSearch, setNameSearch] = useState("");
  const [license, setLicense] = useState({});
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);

  const debouncedNameSearch = useDebounce(nameSearch, 2000);

  const fetchData = async () => {
    setHasError(false);
    setIsLoading(true);

    try {
      const prevMonth = moment()
        .subtract(30, "days")
        .format("YYYY-MM-DD");

      const licenseKey = (license && license.key) || "";

      const url = `https://api.github.com/search/repositories?q=${nameSearch}+in:name+language:javascript+created:${prevMonth}${
        licenseKey ? `+license:${licenseKey}` : ""
      }&sort=stars&order=desc&page=${currentPage}&per_page=${PER_PAGE}`;

      const response = await axios(url);
      setData(response.data.items);
      setTotal(response.data.total_count);
    } catch (error) {
      setHasError(true);
      setData([]);
    }
    setIsLoading(false);
  };

  useEffect(() => {
    fetchData();
  }, [license, nameSearch, currentPage]);

  return (
    <Layout>
      <Header>
        <Search
          handleNameSearchChange={setNameSearch}
          nameSearch={nameSearch}
        />
        <Licenses license={license} handleLicenseChange={setLicense} />
      </Header>

      <main>
        {hasError && <div>Error...</div>}

        {isLoading && <Loader />}

        {data && !isLoading && !hasError && (
          <>
            <List data={data} />
            <Pagination
              currentPage={currentPage}
              total={total}
              itemsPerPage={PER_PAGE}
              handlePageChange={setCurrentPage}
            />
          </>
        )}
      </main>
    </Layout>
  );
};

</code>```

Search.js

```<code>import React from "react";
import PropTypes from "prop-types";

export const Search = ({ handleNameSearchChange, nameSearch }) => (
  <div className="flex-grow-1 mx-lg-3 mb-4 mb-lg-0">
    <input
      type="text"
      name="search"
      placeholder="Enter name..."
      onChange={e => handleNameSearchChange(e.target.value)}
      className="form-control"
      value={nameSearch}
    />
  </div>
);

Search.propTypes = {
  nameSearch: PropTypes.string,
  handleNameSearchChange: PropTypes.func
};
</code>```

How to make debounce work properly?

答:
You never refer to debouncedNameSearch.

I think the issue is with your useEffect:

```<code>useEffect(() => {
  fetchData();
}, [license, nameSearch, currentPage]);
</code>```

The first issue is that it will fire every time nameSearch changes, so you should change it to use debouncedNameSearch:

```<code>useEffect(() => {
  fetchData();
}, [license, debouncedNameSearch, currentPage]);
</code>```

You are also firing the request on initial render when debouncedNameSearch is an empty string, so you could wrap the call to fetchData in a conditional to prevent the request firing when debouncedNameSearch === "":

```<code>useEffect(() => {
  if(debouncedNameSearch) {
    fetchData();
  }
}, [license, debouncedNameSearch, currentPage]);
</code>```

Also, your request is using nameSearch when it should be using debouncedNameSearch:

```<code>const url = `https://api.github.com/search/repositories?q=${nameSearch}...
</code>```

Change to:

```<code>const url = `https://api.github.com/search/repositories?q=${debouncedNameSearch}...
</code>```

And it's recommended that any function that is declared inside a component and called inside a useEffect should either be declared inside the useEffect, or set as a dependency of that useEffect:

Read the docs: is it safe to omit functions from the list of dependencies?

So you can either do something like this:

```<code>useEffect(() => {
  // Declare fetchData inside useEffect
  const fetchData = async () => {...};

  if (debouncedNameSearch) {
    // Call it inside useEffect too
    fetchData();
  }
}, [
  // Don't forget to add the function's dependencies
  license,
  debouncedNameSearch,
  currentPage,
  setHasError,
  setIsLoading,
  setData,
  setTotal
]);
</code>```

Or you can make the function itself a dependency of the useEffect, but you should wrap the function in a useCallback to make sure its state dependencies are up to date (as per the documentation linked above):

```<code>const fetchData = useCallback(
  async () => {
    // Function defined here
  },
  [ // function dependencies
    setHasError,
    setIsLoading,
    license,
    debouncedNameSearch,
    currentPage,
    setData,
    setTotal,
    setHasError
  ]
);

useEffect(() => {
  if(debouncedNameSearch) {
    fetchData();
  }
}, [license, debouncedNameSearch, currentPage, fetchData]); // Add as dependency
</code>```

Body:
I need to get data from server on changes in search input but I don't want to send a new request on every new character there so I'm trying use debounce from use-debounce package https://github.com/xnimorz/use-debounce. But my code below causes only endless requests before even any changes in search input happens.

App.js

import React, { useState, useEffect } from "react";
import axios from "axios";
import moment from "moment";
import { useDebounce } from "use-debounce";
import { Layout } from "./../Layout";
import { List } from "./../List";
import { Loader } from "./../Loader";
import { Header } from "./../Header";
import { Search } from "./../Search";
import { Licenses } from "./../Licenses";
import { Pagination } from "./../Pagination";

import "./App.css";

const PER_PAGE = 20;

export const App = () => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [nameSearch, setNameSearch] = useState("");
  const [license, setLicense] = useState({});
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);

  const debouncedNameSearch = useDebounce(nameSearch, 2000);

  const fetchData = async () => {
    setHasError(false);
    setIsLoading(true);

    try {
      const prevMonth = moment()
        .subtract(30, "days")
        .format("YYYY-MM-DD");

      const licenseKey = (license && license.key) || "";

      const url = `https://api.github.com/search/repositories?q=${nameSearch}+in:name+language:javascript+created:${prevMonth}${
        licenseKey ? `+license:${licenseKey}` : ""
      }&sort=stars&order=desc&page=${currentPage}&per_page=${PER_PAGE}`;

      const response = await axios(url);
      setData(response.data.items);
      setTotal(response.data.total_count);
    } catch (error) {
      setHasError(true);
      setData([]);
    }
    setIsLoading(false);
  };

  useEffect(() => {
    fetchData();
  }, [license, nameSearch, currentPage]);

  return (
    <Layout>

        <Search
          handleNameSearchChange={setNameSearch}
          nameSearch={nameSearch}
        />
        <Licenses license={license} handleLicenseChange={setLicense} />

        {hasError &&
Error...
}

        {isLoading && <Loader />}

        {data && !isLoading && !hasError && (
          <>
            <List data={data} />
            <Pagination
              currentPage={currentPage}
              total={total}
              itemsPerPage={PER_PAGE}
              handlePageChange={setCurrentPage}
            />
          </>
        )}

    </Layout>
  );
};

Search.js

import React from "react";
import PropTypes from "prop-types";

export const Search = ({ handleNameSearchChange, nameSearch }) => (

    <input
      type="text"
      name="search"
      placeholder="Enter name..."
      onChange={e => handleNameSearchChange(e.target.value)}
      className="form-control"
      value={nameSearch}
    />

);

Search.propTypes = {
  nameSearch: PropTypes.string,
  handleNameSearchChange: PropTypes.func
};

How to make debounce work properly?

Body:
You never refer to debouncedNameSearch.

I think the issue is with your useEffect:

useEffect(() => {
  fetchData();
}, [license, nameSearch, currentPage]);

The first issue is that it will fire every time nameSearch changes, so you should change it to use debouncedNameSearch:

useEffect(() => {
  fetchData();
}, [license, debouncedNameSearch, currentPage]);

You are also firing the request on initial render when debouncedNameSearch is an empty string, so you could wrap the call to fetchData in a conditional to prevent the request firing when debouncedNameSearch === "":

useEffect(() => {
  if(debouncedNameSearch) {
    fetchData();
  }
}, [license, debouncedNameSearch, currentPage]);

Also, your request is using nameSearch when it should be using debouncedNameSearch:

const url = `https://api.github.com/search/repositories?q=${nameSearch}...

Change to:

const url = `https://api.github.com/search/repositories?q=${debouncedNameSearch}...

And it's recommended that any function that is declared inside a component and called inside a useEffect should either be declared inside the useEffect, or set as a dependency of that useEffect:

Read the docs: is it safe to omit functions from the list of dependencies?

So you can either do something like this:

useEffect(() => {
  // Declare fetchData inside useEffect
  const fetchData = async () => {...};

  if (debouncedNameSearch) {
    // Call it inside useEffect too
    fetchData();
  }
}, [
  // Don't forget to add the function's dependencies
  license,
  debouncedNameSearch,
  currentPage,
  setHasError,
  setIsLoading,
  setData,
  setTotal
]);

Or you can make the function itself a dependency of the useEffect, but you should wrap the function in a useCallback to make sure its state dependencies are up to date (as per the documentation linked above):

const fetchData = useCallback(
  async () => {
    // Function defined here
  },
  [ // function dependencies
    setHasError,
    setIsLoading,
    license,
    debouncedNameSearch,
    currentPage,
    setData,
    setTotal,
    setHasError
  ]
);

useEffect(() => {
  if(debouncedNameSearch) {
    fetchData();
  }
}, [license, debouncedNameSearch, currentPage, fetchData]); // Add as dependency


问:
How to use a type from a child package / generic package instantiation
I can make the primitive subprograms of a type directly visible with
use all type like this:

```<code>package Type_Package is
   type T is null record;
   procedure Action(X: T) is null;
end Type_Package;

with Type_Package;
procedure Use_Type is
   use all type Type_Package.T;
   X: Type_Package.T;
begin
   Action(X);
end Use_Type;
</code>```

However, it does not seem to work when I move Type_Package inside
Use_Type.

```<code>procedure Use_Type is
   package Type_Package is
      type T is null record;
      procedure Action(X: T) is null;
   end Type_Package;
   use all type Type_Package.T;
   X: Type_Package.T;
begin
   Action(X);
end Use_Type;
</code>```

I get

```<code>gcc -c use_type.adb
use_type.adb:9:04: "Action" is not visible
use_type.adb:9:04: non-visible declaration at line 4
gnatmake: "use_type.adb" compilation error
</code>```

The same thing occurs when I instantiate a generic package.  For
example, when I want to use the data types in Ada.Containers.

```<code>package Element_Set is
   new Ada.Containers.Hashed_Sets(Element_Type, Hash, "=");
use all type Element_Set.Set;
</code>```

The use type clause here seems to have no effect.

How to use a type when the type is declared in a child package or an
instantiation of a generic package?

答:
I"m not sure if this is a compiler bug (Update: Simon Wright confirmed it as a bug)  or intended, but your workaround options include:

Use "use Type_Package" for the whole package - Probably the easiest but most heavy handed

Use some procedure/function rename clauses - this takes more work but doesn't make the whole package visible. EX:

procedure Hello is
    package Type_Package is
        type T is null record;
        procedure Action(X: T) is null;
    end Type_Package;

    use all type Type_Package.T;
    X: Type_Package.T;

    procedure Action(X : Type_Package.T) renames Type_Package.Action;

begin
    Action(X);
end Hello;
```

<p><strong>for generic packages, declare them at library level</strong> - This won't help with nested packages, but will for generic.  You can do this for a single generic package doing the following:</p>

<p><em>Type_Package.ads</em></p>

<pre class="lang-ada prettyprint-override"><code>with Use_All_Type;
package Type_Package is new Use_All_Type;
</code>```

Use_All_Type.ads

generic
package Use_All_Type is

   type T is null record;
   procedure Action(X: T) is null;

end Use_All_Type;
```

<p>or for multiple generic packages:</p>

<p><em>Type_Package.ads</em></p>

<pre class="lang-ada prettyprint-override"><code>with Use_All_Type;
package Type_Package is
   package UAT is new Use_All_Type;
   subtype T is UAT.T;
   use all type UAT.T;

   -- repeat for other generics
end Type_Package;
</code>```

Use_All_Type.ads

generic
package Use_All_Type is

   type T is null record;
   procedure Action(X: T) is null;

end Use_All_Type;
```

<p>Both of those methods will work with the following main:</p>

<pre class="lang-ada prettyprint-override"><code>with Type_Package;

procedure Main is

   use all type Type_Package.T;
   X: Type_Package.T;

begin
   Action(X);
end Main;
</code>```

Side Note:  You might consider sending AdaCore a bug report if no one here answers definitively on whether this is intended or not.

Body:
I can make the primitive subprograms of a type directly visible with
use all type like this:

package Type_Package is
   type T is null record;
   procedure Action(X: T) is null;
end Type_Package;

with Type_Package;
procedure Use_Type is
   use all type Type_Package.T;
   X: Type_Package.T;
begin
   Action(X);
end Use_Type;

However, it does not seem to work when I move Type_Package inside
Use_Type.

procedure Use_Type is
   package Type_Package is
      type T is null record;
      procedure Action(X: T) is null;
   end Type_Package;
   use all type Type_Package.T;
   X: Type_Package.T;
begin
   Action(X);
end Use_Type;

I get

gcc -c use_type.adb
use_type.adb:9:04: "Action" is not visible
use_type.adb:9:04: non-visible declaration at line 4
gnatmake: "use_type.adb" compilation error

The same thing occurs when I instantiate a generic package.  For
example, when I want to use the data types in Ada.Containers.

package Element_Set is
   new Ada.Containers.Hashed_Sets(Element_Type, Hash, "=");
use all type Element_Set.Set;

The use type clause here seems to have no effect.

How to use a type when the type is declared in a child package or an
instantiation of a generic package?

Body:
I"m not sure if this is a compiler bug (Update: Simon Wright confirmed it as a bug)  or intended, but your workaround options include:

Use "use Type_Package" for the whole package - Probably the easiest but most heavy handed

Use some procedure/function rename clauses - this takes more work but doesn't make the whole package visible. EX:

procedure Hello is
    package Type_Package is
        type T is null record;
        procedure Action(X: T) is null;
    end Type_Package;

    use all type Type_Package.T;
    X: Type_Package.T;

    procedure Action(X : Type_Package.T) renames Type_Package.Action;

begin
    Action(X);
end Hello;

for generic packages, declare them at library level - This won't help with nested packages, but will for generic.  You can do this for a single generic package doing the following:

Type_Package.ads

with Use_All_Type;
package Type_Package is new Use_All_Type;

Use_All_Type.ads

generic
package Use_All_Type is

   type T is null record;
   procedure Action(X: T) is null;

end Use_All_Type;

or for multiple generic packages:

Type_Package.ads

with Use_All_Type;
package Type_Package is
   package UAT is new Use_All_Type;
   subtype T is UAT.T;
   use all type UAT.T;

   -- repeat for other generics
end Type_Package;

Use_All_Type.ads

generic
package Use_All_Type is

   type T is null record;
   procedure Action(X: T) is null;

end Use_All_Type;

Both of those methods will work with the following main:

with Type_Package;

procedure Main is

   use all type Type_Package.T;
   X: Type_Package.T;

begin
   Action(X);
end Main;

Side Note:  You might consider sending AdaCore a bug report if no one here answers definitively on whether this is intended or not.


问:
Checking stock of every size for a specific product using requests and BS4
So here is my code to check stock of sizes 7.5-9 of a certain product:

```<code>import requests
from bs4 import BeautifulSoup
r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
soup = BeautifulSoup(r.text, 'html.parser')
attrs = soup.find_all(class_="box_wrapper")[0].findChildren()

output = str(attrs[0].attrs)
if "piunavailable" in output:
    print("Size 7.5 OOS")
else:
    print("Size 7.5 in stock!")

output = str(attrs[1].attrs)
if "piunavailable" in output:
    print("Size 8 OOS")
else:
    print("Size 8 in stock!")

output = str(attrs[2].attrs)
if "piunavailable" in output:
    print("Size 8.5 OOS")
else:
    print("Size 8.5 in stock!")

output = str(attrs[3].attrs)
if "piunavailable" in output:
    print("Size 9 OOS")
else:
    print("Size 9 in stock!")
</code>```

The actual htmls for the sizes on that website is as follows:

```<code><div class="box_wrapper">
     <a href="#" id="itemcode_11468285" class="box">7.5</a>
     <a id="itemcode_11468286" class="box piunavailable">8</a>
     <a id="itemcode_11468287" class="box piunavailable">8.5</a>
     <a id="itemcode_11468288" class="box piunavailable">9</a>
     <a id="itemcode_11468289" class="box piunavailable">9.5</a>
     <a id="itemcode_11468290" class="box piunavailable">10</a>
     <a id="itemcode_11468291" class="box piunavailable">10.5</a>
     <a id="itemcode_11468292" class="box piunavailable">11</a>
     <a id="itemcode_11468293" class="box piunavailable">11.5</a>
     <a id="itemcode_11468294" class="box piunavailable">12</a>
     <a id="itemcode_11468295" class="box piunavailable">13</a>
     <a id="itemcode_11468296" class="box piunavailable">14</a>
</div>
</code>```

So when i run my code, as expected, i get:

```<code>PS C:\Users\jokzc\Desktop\python\learning requests> py test3.py
Size 7.5 in stock!
Size 8 OOS
Size 8.5 OOS
Size 9 OOS
</code>```

What i would like to do is be able to check every size and return if it is in stock or out of stock without 10 different output blocks in my main code. Is there some forevery function or something i could do that would satisfy this need?

答:
Yes you can do it like this.

```<code>import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
soup = BeautifulSoup(r.text, 'html.parser')
for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
    if "piunavailable" in anchor_tag['class']:
        print(f"Size {anchor_tag.text} OOS")
    else:
        print(f"Size {anchor_tag.text}  in stock!")
</code>```

Outputs:

```<code>Size 7.5  in stock!
Size 8 OOS
Size 8.5 OOS
Size 9 OOS
Size 9.5 OOS
Size 10 OOS
Size 10.5 OOS
Size 11 OOS
Size 11.5 OOS
Size 12 OOS
Size 13 OOS
Size 14 OOS
</code>```

You can also use for anchor_tag in soup.select('div.box_wrapper a'): instead of for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():

Body:
So here is my code to check stock of sizes 7.5-9 of a certain product:

import requests
from bs4 import BeautifulSoup
r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
soup = BeautifulSoup(r.text, 'html.parser')
attrs = soup.find_all(class_="box_wrapper")[0].findChildren()

output = str(attrs[0].attrs)
if "piunavailable" in output:
    print("Size 7.5 OOS")
else:
    print("Size 7.5 in stock!")

output = str(attrs[1].attrs)
if "piunavailable" in output:
    print("Size 8 OOS")
else:
    print("Size 8 in stock!")

output = str(attrs[2].attrs)
if "piunavailable" in output:
    print("Size 8.5 OOS")
else:
    print("Size 8.5 in stock!")

output = str(attrs[3].attrs)
if "piunavailable" in output:
    print("Size 9 OOS")
else:
    print("Size 9 in stock!")

The actual htmls for the sizes on that website is as follows:

     7.5
     8
     8.5
     9
     9.5
     10
     10.5
     11
     11.5
     12
     13
     14

So when i run my code, as expected, i get:

PS C:\Users\jokzc\Desktop\python\learning requests> py test3.py
Size 7.5 in stock!
Size 8 OOS
Size 8.5 OOS
Size 9 OOS

What i would like to do is be able to check every size and return if it is in stock or out of stock without 10 different output blocks in my main code. Is there some forevery function or something i could do that would satisfy this need?

Body:
Yes you can do it like this.

import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.jimmyjazz.com/mens/footwear/adidas-solar-hu-nmd/BB9528')
soup = BeautifulSoup(r.text, 'html.parser')
for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():
    if "piunavailable" in anchor_tag['class']:
        print(f"Size {anchor_tag.text} OOS")
    else:
        print(f"Size {anchor_tag.text}  in stock!")

Outputs:

Size 7.5  in stock!
Size 8 OOS
Size 8.5 OOS
Size 9 OOS
Size 9.5 OOS
Size 10 OOS
Size 10.5 OOS
Size 11 OOS
Size 11.5 OOS
Size 12 OOS
Size 13 OOS
Size 14 OOS

You can also use for anchor_tag in soup.select('div.box_wrapper a'): instead of for anchor_tag in soup.find_all(class_="box_wrapper")[0].findChildren():


问:
Scrolling div inside a div appear over div with higher z-index
https://jsfiddle.net/09rcqwdf/1/

The sidebar has a higher z-index. The container .main has overflow: none, the div inside it has overflow: scroll but for some reason when you drag the text it thinks its over the .scrolling div when in fact its over the sidebar div.

<!doctype html>

  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="theme-color" content="#fafafa">

Drag

```

答:
It does not think it’s over the .scrolling div. It it just that the .scrolling div is transparent and you can see “through” it. To see what I am saying, add a background color to your .scrolling div, which will prevent you to see what is happening behind it.

<!doctype html>

  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="theme-color" content="#fafafa">

Drag

```

Body:
It does not think it’s over the .scrolling div. It it just that the .scrolling div is transparent and you can see “through” it. To see what I am saying, add a background color to your .scrolling div, which will prevent you to see what is happening behind it.

<!doctype html>
<html class="no-js" lang="">

<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="theme-color" content="#fafafa">
  <style>
    body,
    html {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }

    #content {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      overflow: hidden;
    }

    .main {
      position: absolute;
      bottom: 0;
      left: 300px;
      right: 0;
      top: 0;
      overflow: hidden;
    }

    .scroll-container {
      display: block;
      position: absolute;
      top: 0px;
      bottom: 0px;
      left: 0px;
      right: 0px;
      overflow: scroll;
      z-index: 1;
    }

    .scrolling {
      display: block;
      overflow: hidden;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 2;
      width: 3500px;
      height: 4000px;
      background: orange; <!-- Background Color to prevent transparency -->
    }

    .sidebar {
      display: block;
      position: absolute;
      background-color: #5555;
      overflow: hidden;
      z-index: 100000;
      width: 300px;
      bottom: 0;
      top: 0;
      left: 0;
    }

  </style>
</head>

<body>
  <div id="content">
    <div class="main">
      <div class="scroll-container">
        <div class="scrolling">

        </div>
      </div>
    </div>
    <div class="sidebar">
      <div>
        <div class="drag">Drag</div>
      </div>
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  <script>
    window.jQuery || document.write('<script src="js/vendor/jquery-3.4.1.min.js"><\/script>')

  </script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
  <script>
    $('.scrolling').droppable({
      tolerance: 'pointer',
      accept: '.drag',
      drop(event, ui) {
        console.log(event);
        console.log(ui);
        if (ui.helper.hasClass('cancelled')) {
          return;
        }
      },
    });
    $('.drag').draggable({
      helper() {
        const $helper = $('<div></div>');
        $helper.text('drag');
        return $helper.clone().addClass('dragged-component-helper');
      },
      start() {},
      stop(event, ui) {
        ui.helper[0].remove();
      },
      cursorAt: {
        left: 0,
        top: 5,
      },
      cancelOnEscape: true,
      appendTo: '#content',
      disabled: false,
      distance: 0,
      revert: 'invalid',
    });

  </script>
</body>

</html>


问:
append url parameter if exists or add if not exists jQuery
I am creating a filter based on size, color etc. So it is possible to select multiple items. When I click each item it should append to current URL. Please check the below URL,

If parameter not exists in URL

```<code>http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White
</code>```

If parameter exists and selected same color

```<code>http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White
</code>```

If parameter exists and selected multiple colors

```<code>http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White-Black
</code>```

How to implement the same using jQuery. I have tried using below code,

```<code>function setGetParameter(paramName, paramValue) {
    var url = window.location.href;
    var hash = location.hash;
    url = url.replace(hash, '');
    if (url.indexOf(paramName + "=") >= 0) {
        var prefix = url.substring(0, url.indexOf(paramName + "="));
        var suffix = url.substring(url.indexOf(paramName + "="));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + paramName + "=" + paramValue + suffix + "-";
    } else {
        if (url.indexOf("?") < 0)
            url += "?" + paramName + "=" + paramValue + "-";
        else
            url += "&" + paramName + "=" + paramValue + "-";
    }
    window.location.href = url + hash;
}
</code>```

The above code works with single parameter value. For multiple values how to alter the above code.

答:
I recommend not using this code at all to build a URL.

Use something like https://medialize.github.io/URI.js/ which happen to have a jQuery plugin.

Why?

Your query parameters here are not encoded, so it could "break" the url. Using a library such as URI.js with a builder to append your query parameters will tackle your issues. Parsing and building URLs is not as trivial as it may seem, so it is better to rely on tested code.

```<code>var url = URI(window.location.href); // no need to remove and add the hash back anymore
var queryMap = url.query(true);
if (queryMap[paramName]) {
    // param already exists
    var values = queryMap[paramName].split('-');
    if (!values.includes(paramValue)) {
        // paramValue not found: add it
        values.push(paramValue);
        url.setQuery(paramName, values.join('-'));
    }
} else {
    // param does not exist yet
    url.setQuery(paramName, paramValue);
}

window.location.href = url.toString();
</code>```

Body:
I am creating a filter based on size, color etc. So it is possible to select multiple items. When I click each item it should append to current URL. Please check the below URL,

If parameter not exists in URL

http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White

If parameter exists and selected same color

http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White

If parameter exists and selected multiple colors

http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White-Black

How to implement the same using jQuery. I have tried using below code,

function setGetParameter(paramName, paramValue) {
    var url = window.location.href;
    var hash = location.hash;
    url = url.replace(hash, '');
    if (url.indexOf(paramName + "=") >= 0) {
        var prefix = url.substring(0, url.indexOf(paramName + "="));
        var suffix = url.substring(url.indexOf(paramName + "="));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + paramName + "=" + paramValue + suffix + "-";
    } else {
        if (url.indexOf("?") < 0)
            url += "?" + paramName + "=" + paramValue + "-";
        else
            url += "&" + paramName + "=" + paramValue + "-";
    }
    window.location.href = url + hash;
}

The above code works with single parameter value. For multiple values how to alter the above code.

Body:
I recommend not using this code at all to build a URL.

Use something like https://medialize.github.io/URI.js/ which happen to have a jQuery plugin.

Why?

Your query parameters here are not encoded, so it could "break" the url. Using a library such as URI.js with a builder to append your query parameters will tackle your issues. Parsing and building URLs is not as trivial as it may seem, so it is better to rely on tested code.

var url = URI(window.location.href); // no need to remove and add the hash back anymore
var queryMap = url.query(true);
if (queryMap[paramName]) {
    // param already exists
    var values = queryMap[paramName].split('-');
    if (!values.includes(paramValue)) {
        // paramValue not found: add it
        values.push(paramValue);
        url.setQuery(paramName, values.join('-'));
    }
} else {
    // param does not exist yet
    url.setQuery(paramName, paramValue);
}

window.location.href = url.toString();


问:
Python Tkinter destroying all Buttons next to chosen one with same text
I'm tying to recreate Minesweeper in python and i'm trying to recreate how in the game if the player chooses a tile without anything on it (In my code, a tile that has a 0) it will reveal all the tiles close to it that aren't mines (In my code, a tile that has an X). I've tried to to do this many times but nothing has worked. It would be written in the autoShow(i, j) function.

Can anyone help (Any other suggestions would be appreciated)?

```<code>import tkinter as tk
from tkinter import messagebox
from random import randint

def difficulty(diff):
    global rows, cols, mines, size
    if diff == 1:
        rows = 9
        cols = 9
        mines = 10
        size = "341x368"
    elif diff == 2:
        rows = 16
        cols = 16
        mines = 40
        size = "606x654"
    else:
        rows = 16
        cols = 30
        mines = 99
        size = "1139x606"
    play()

def firstT(l, m):
    global firstTurn
    if firstTurn:
        mPos = []
        firstTurn = False
        for x in range(mines):
            minesLoop = True
            while minesLoop:
                x = randint(0, rows - 1)
                y = randint(0, cols - 1)
                if grid_text[x][y].get() != "X":
                    near = False
                    if near == False:
                        mPos.append([x, y])
                        minesLoop = False
                        grid_text[x][y].set("X")
        [[labels[i][j].configure(text = grid_text[i][j].get()) for j in range(cols)] for i in range(rows)]
        for i in range(rows):
            for j in range(cols):
                nearby = 0
                for ii in range(i - 1, i + 2):
                    for jj in range(j - 1, j + 2):
                        if ii >= 0 and jj >= 0 and ii < rows and jj < cols:
                            if labels[i][j]["text"] == "" and labels[ii][jj]["text"] == "X" and not (i, j) in mPos:
                                nearby += 1
                if labels[i][j]["text"] != "X":
                    grid_text[i][j] = str(nearby)
                    labels[i][j].configure(text = grid_text[i][j])

def autoShow(i, j):
    pass

def show(i, j):
    global gameOver
    if gameOver:
        return
    firstT(i, j)
    if labels[i][j]["text"] == "0":
        autoShow(i, j)
    elif labels[i][j]["text"] == "X":
        messagebox.showinfo("Lose!", "You Lose")
        game.focus_force()
        gameOver = True
    else:
        grid[i][j].destroy()

def play():
    global firstTurn, gameOver, game, grid, grid_text, labels
    firstTurn = True
    gameOver = False
    game = tk.Toplevel(root)
    game.title("Minesweeper")
    game.geometry(size)
    grid_text = [[tk.StringVar() for j in range(cols)] for i in range(rows)]
    labels = [[tk.Label(game, text = grid_text[i][j].get()) for j in range(cols)] for i in range(rows)]
    [[labels[i][j].grid(row = i, column = j) for j in range(cols)] for i in range(rows)]
    grid = [[tk.Button(game, width = 4, height = 2, command = lambda i = i, j = j: show(i, j)) for j in range(cols)] for i in range(rows)]
    [[grid[i][j].grid(row = i, column = j) for j in range(cols)] for i in range(rows)]
    xoutside = [[tk.Button(game, width = 4, height = 2).grid(row = i, column = cols + 1) for j in range(cols)] for i in range(rows)]
    youtside = [[tk.Button(game, width = 4, height = 2).grid(row = rows + 1, column = j) for j in range(cols)] for i in range(rows)]

diff(1)
</code>```

答:
You have to use recursion to run show(i-1, j), etc.

Because I run show(i-1, j) without clicking button so I need also grid[i][j] = None to recognize if button still exists.

I don't know if it doesn't need other tests in which place is shown.

```<code>def autoShow(i, j):

    grid[i][j].destroy()
    grid[i][j] = None

    if i > 0:
        show(i-1, j)
    if j > 0:
        show(i, j-1)

    if i < rows-1:
        show(i+1, j)
    if j < cols-1:
        show(i, j+1)

    if i > 0 and j > 0:
        show(i-1, j-1)
    if i > 0 and j < cols-1:
        show(i-1, j+1)

    if i < rows-1 and j < cols-1:
        show(i+1, j+1)

    if i < rows-1 and j > 0:
        show(i+1, j-1)

def show(i, j):
    global gameOver

    if gameOver:
        return

    firstT(i, j)

    # check if button still exists
    if grid[i][j] is None:
        return

    if labels[i][j]["text"] == "0":
        autoShow(i, j)

    elif labels[i][j]["text"] == "X":
        grid[i][j].destroy()
        grid[i][j] = None
        messagebox.showinfo("Lose!", "You Lose")
        game.focus_force()
        gameOver = True
    else:
        grid[i][j].destroy()
        grid[i][j] = None
</code>```

Full code which I tested

```<code>import tkinter as tk
from tkinter import messagebox
from random import randint

def difficulty(diff):
    global rows, cols, mines, size
    if diff == 1:
        rows = 9
        cols = 9
        mines = 10
        size = "341x368"
    elif diff == 2:
        rows = 16
        cols = 16
        mines = 40
        size = "606x654"
    else:
        rows = 16
        cols = 30
        mines = 99
        size = "1139x606"
    play()

def firstT(l, m):
    global firstTurn
    if firstTurn:
        mPos = []
        firstTurn = False
        for x in range(mines):
            minesLoop = True
            while minesLoop:
                x = randint(0, rows - 1)
                y = randint(0, cols - 1)
                if grid_text[x][y].get() != "X":
                    near = False
                    if near == False:
                        mPos.append([x, y])
                        minesLoop = False
                        grid_text[x][y].set("X")
        [[labels[i][j].configure(text = grid_text[i][j].get()) for j in range(cols)] for i in range(rows)]
        for i in range(rows):
            for j in range(cols):
                nearby = 0
                for ii in range(i - 1, i + 2):
                    for jj in range(j - 1, j + 2):
                        if ii >= 0 and jj >= 0 and ii < rows and jj < cols:
                            if labels[i][j]["text"] == "" and labels[ii][jj]["text"] == "X" and not (i, j) in mPos:
                                nearby += 1
                if labels[i][j]["text"] != "X":
                    grid_text[i][j] = str(nearby)
                    labels[i][j].configure(text = grid_text[i][j])

def autoShow(i, j):

    grid[i][j].destroy()
    grid[i][j] = None

    if i > 0:
        show(i-1, j)
    if j > 0:
        show(i, j-1)

    if i < rows-1:
        show(i+1, j)
    if j < cols-1:
        show(i, j+1)

    if i > 0 and j > 0:
        show(i-1, j-1)
    if i > 0 and j < cols-1:
        show(i-1, j+1)

    if i < rows-1 and j < cols-1:
        show(i+1, j+1)

    if i < rows-1 and j > 0:
        show(i+1, j-1)

def show(i, j):
    global gameOver
    if gameOver:
        return
    firstT(i, j)

    if grid[i][j] is None:
        return

    if labels[i][j]["text"] == "0":
        autoShow(i, j)

    elif labels[i][j]["text"] == "X":
        grid[i][j].destroy()
        grid[i][j] = None
        messagebox.showinfo("Lose!", "You Lose")
        game.focus_force()
        gameOver = True
    else:
        grid[i][j].destroy()
        grid[i][j] = None

def play():
    global firstTurn, gameOver, game, grid, grid_text, labels
    firstTurn = True
    gameOver = False
    game = tk.Toplevel(root)
    game.title("Minesweeper")
    game.geometry(size)
    grid_text = [[tk.StringVar() for j in range(cols)] for i in range(rows)]
    labels = [[tk.Label(game, text = grid_text[i][j].get()) for j in range(cols)] for i in range(rows)]
    [[labels[i][j].grid(row = i, column = j) for j in range(cols)] for i in range(rows)]
    grid = [[tk.Button(game, width = 4, height = 2, command = lambda i = i, j = j: show(i, j)) for j in range(cols)] for i in range(rows)]
    [[grid[i][j].grid(row = i, column = j) for j in range(cols)] for i in range(rows)]
    xoutside = [[tk.Button(game, width = 4, height = 2).grid(row = i, column = cols + 1) for j in range(cols)] for i in range(rows)]
    youtside = [[tk.Button(game, width = 4, height = 2).grid(row = rows + 1, column = j) for j in range(cols)] for i in range(rows)]

root = tk.Tk()
difficulty(1)
root.mainloop()
</code>```

Body:
I'm tying to recreate Minesweeper in python and i'm trying to recreate how in the game if the player chooses a tile without anything on it (In my code, a tile that has a 0) it will reveal all the tiles close to it that aren't mines (In my code, a tile that has an X). I've tried to to do this many times but nothing has worked. It would be written in the autoShow(i, j) function.

Can anyone help (Any other suggestions would be appreciated)?

import tkinter as tk
from tkinter import messagebox
from random import randint

def difficulty(diff):
    global rows, cols, mines, size
    if diff == 1:
        rows = 9
        cols = 9
        mines = 10
        size = "341x368"
    elif diff == 2:
        rows = 16
        cols = 16
        mines = 40
        size = "606x654"
    else:
        rows = 16
        cols = 30
        mines = 99
        size = "1139x606"
    play()

def firstT(l, m):
    global firstTurn
    if firstTurn:
        mPos = []
        firstTurn = False
        for x in range(mines):
            minesLoop = True
            while minesLoop:
                x = randint(0, rows - 1)
                y = randint(0, cols - 1)
                if grid_text[x][y].get() != "X":
                    near = False
                    if near == False:
                        mPos.append([x, y])
                        minesLoop = False
                        grid_text[x][y].set("X")
        [[labels[i][j].configure(text = grid_text[i][j].get()) for j in range(cols)] for i in range(rows)]
        for i in range(rows):
            for j in range(cols):
                nearby = 0
                for ii in range(i - 1, i + 2):
                    for jj in range(j - 1, j + 2):
                        if ii >= 0 and jj >= 0 and ii < rows and jj < cols:
                            if labels[i][j]["text"] == "" and labels[ii][jj]["text"] == "X" and not (i, j) in mPos:
                                nearby += 1
                if labels[i][j]["text"] != "X":
                    grid_text[i][j] = str(nearby)
                    labels[i][j].configure(text = grid_text[i][j])

def autoShow(i, j):
    pass

def show(i, j):
    global gameOver
    if gameOver:
        return
    firstT(i, j)
    if labels[i][j]["text"] == "0":
        autoShow(i, j)
    elif labels[i][j]["text"] == "X":
        messagebox.showinfo("Lose!", "You Lose")
        game.focus_force()
        gameOver = True
    else:
        grid[i][j].destroy()

def play():
    global firstTurn, gameOver, game, grid, grid_text, labels
    firstTurn = True
    gameOver = False
    game = tk.Toplevel(root)
    game.title("Minesweeper")
    game.geometry(size)
    grid_text = [[tk.StringVar() for j in range(cols)] for i in range(rows)]
    labels = [[tk.Label(game, text = grid_text[i][j].get()) for j in range(cols)] for i in range(rows)]
    [[labels[i][j].grid(row = i, column = j) for j in range(cols)] for i in range(rows)]
    grid = [[tk.Button(game, width = 4, height = 2, command = lambda i = i, j = j: show(i, j)) for j in range(cols)] for i in range(rows)]
    [[grid[i][j].grid(row = i, column = j) for j in range(cols)] for i in range(rows)]
    xoutside = [[tk.Button(game, width = 4, height = 2).grid(row = i, column = cols + 1) for j in range(cols)] for i in range(rows)]
    youtside = [[tk.Button(game, width = 4, height = 2).grid(row = rows + 1, column = j) for j in range(cols)] for i in range(rows)]

diff(1)

Body:
You have to use recursion to run show(i-1, j), etc.

Because I run show(i-1, j) without clicking button so I need also grid[i][j] = None to recognize if button still exists.

I don't know if it doesn't need other tests in which place is shown.

def autoShow(i, j):

    grid[i][j].destroy()
    grid[i][j] = None

    if i > 0:
        show(i-1, j)
    if j > 0:
        show(i, j-1)

    if i < rows-1:
        show(i+1, j)
    if j < cols-1:
        show(i, j+1)

    if i > 0 and j > 0:
        show(i-1, j-1)
    if i > 0 and j < cols-1:
        show(i-1, j+1)

    if i < rows-1 and j < cols-1:
        show(i+1, j+1)

    if i < rows-1 and j > 0:
        show(i+1, j-1)

def show(i, j):
    global gameOver

    if gameOver:
        return

    firstT(i, j)

    # check if button still exists
    if grid[i][j] is None:
        return

    if labels[i][j]["text"] == "0":
        autoShow(i, j)

    elif labels[i][j]["text"] == "X":
        grid[i][j].destroy()
        grid[i][j] = None
        messagebox.showinfo("Lose!", "You Lose")
        game.focus_force()
        gameOver = True
    else:
        grid[i][j].destroy()
        grid[i][j] = None

Full code which I tested

import tkinter as tk
from tkinter import messagebox
from random import randint

def difficulty(diff):
    global rows, cols, mines, size
    if diff == 1:
        rows = 9
        cols = 9
        mines = 10
        size = "341x368"
    elif diff == 2:
        rows = 16
        cols = 16
        mines = 40
        size = "606x654"
    else:
        rows = 16
        cols = 30
        mines = 99
        size = "1139x606"
    play()

def firstT(l, m):
    global firstTurn
    if firstTurn:
        mPos = []
        firstTurn = False
        for x in range(mines):
            minesLoop = True
            while minesLoop:
                x = randint(0, rows - 1)
                y = randint(0, cols - 1)
                if grid_text[x][y].get() != "X":
                    near = False
                    if near == False:
                        mPos.append([x, y])
                        minesLoop = False
                        grid_text[x][y].set("X")
        [[labels[i][j].configure(text = grid_text[i][j].get()) for j in range(cols)] for i in range(rows)]
        for i in range(rows):
            for j in range(cols):
                nearby = 0
                for ii in range(i - 1, i + 2):
                    for jj in range(j - 1, j + 2):
                        if ii >= 0 and jj >= 0 and ii < rows and jj < cols:
                            if labels[i][j]["text"] == "" and labels[ii][jj]["text"] == "X" and not (i, j) in mPos:
                                nearby += 1
                if labels[i][j]["text"] != "X":
                    grid_text[i][j] = str(nearby)
                    labels[i][j].configure(text = grid_text[i][j])

def autoShow(i, j):

    grid[i][j].destroy()
    grid[i][j] = None

    if i > 0:
        show(i-1, j)
    if j > 0:
        show(i, j-1)

    if i < rows-1:
        show(i+1, j)
    if j < cols-1:
        show(i, j+1)

    if i > 0 and j > 0:
        show(i-1, j-1)
    if i > 0 and j < cols-1:
        show(i-1, j+1)

    if i < rows-1 and j < cols-1:
        show(i+1, j+1)

    if i < rows-1 and j > 0:
        show(i+1, j-1)

def show(i, j):
    global gameOver
    if gameOver:
        return
    firstT(i, j)

    if grid[i][j] is None:
        return

    if labels[i][j]["text"] == "0":
        autoShow(i, j)

    elif labels[i][j]["text"] == "X":
        grid[i][j].destroy()
        grid[i][j] = None
        messagebox.showinfo("Lose!", "You Lose")
        game.focus_force()
        gameOver = True
    else:
        grid[i][j].destroy()
        grid[i][j] = None

def play():
    global firstTurn, gameOver, game, grid, grid_text, labels
    firstTurn = True
    gameOver = False
    game = tk.Toplevel(root)
    game.title("Minesweeper")
    game.geometry(size)
    grid_text = [[tk.StringVar() for j in range(cols)] for i in range(rows)]
    labels = [[tk.Label(game, text = grid_text[i][j].get()) for j in range(cols)] for i in range(rows)]
    [[labels[i][j].grid(row = i, column = j) for j in range(cols)] for i in range(rows)]
    grid = [[tk.Button(game, width = 4, height = 2, command = lambda i = i, j = j: show(i, j)) for j in range(cols)] for i in range(rows)]
    [[grid[i][j].grid(row = i, column = j) for j in range(cols)] for i in range(rows)]
    xoutside = [[tk.Button(game, width = 4, height = 2).grid(row = i, column = cols + 1) for j in range(cols)] for i in range(rows)]
    youtside = [[tk.Button(game, width = 4, height = 2).grid(row = rows + 1, column = j) for j in range(cols)] for i in range(rows)]

root = tk.Tk()
difficulty(1)
root.mainloop()


问:
Python itertools permutations without repetitions
I have a string show the step going in m x n grid like this problem:
https://leetcode.com/problems/unique-paths/

```<code>step = 'DDRR'
</code>```

D mean go Down and R mean go to Right
I want to show permutations without replacement, and i found the itertools built-in on Python.But it's say:

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values.

So that when I using itertools.permutation(step,4), it's contain many replications.

```<code>>>> itertools.permutations(step,4)
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
</code>```

I want something like:

```<code>('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('R', 'R', 'D', 'D')
</code>```

I found some answer using set(itertools.permutations(step,4)), but because apply set() method, the itertools.permutation() method still calculate all possibilities. Is there anyway to avoid it, or is there any built-in function can do permutation without repetitions in Python?

答:
The leetcode problem only asks about the number of unique paths, not a list of unique paths, so to calculate the number you only need to use the combination formula of C(n, k) = n! / (k! x (n - k)!) to find the number of positions where Ds (or Rs) can be placed out of all positions:

```<code>from math import factorial

def f(m, n):
    return factorial(m + n - 2) / factorial(m - 1) / factorial(n - 1)
</code>```

so that f(3, 2) returns: 3

and that f(7, 3) returns: 28

On the other hand, if you're interested in producing a list of unique paths, you can use itertools.combinations to do the same as above; that is, to find the positions where Ds (or Rs) can be placed out of all positions:

```<code>from itertools import combinations
def f(m, n):
    for positions in map(set, combinations(range(m + n - 2), m - 1)):
        yield ''.join('DR'[i in positions] for i in range(m + n - 2))
</code>```

so that:

```<code>print(*f(7, 3), sep='\n')
</code>```

outputs:

```<code>RRRRRRDD
RRRRRDRD
RRRRRDDR
RRRRDRRD
RRRRDRDR
RRRRDDRR
RRRDRRRD
RRRDRRDR
RRRDRDRR
RRRDDRRR
RRDRRRRD
RRDRRRDR
RRDRRDRR
RRDRDRRR
RRDDRRRR
RDRRRRRD
RDRRRRDR
RDRRRDRR
RDRRDRRR
RDRDRRRR
RDDRRRRR
DRRRRRRD
DRRRRRDR
DRRRRDRR
DRRRDRRR
DRRDRRRR
DRDRRRRR
DDRRRRRR
</code>```

Body:
I have a string show the step going in m x n grid like this problem:
https://leetcode.com/problems/unique-paths/

step = 'DDRR'

D mean go Down and R mean go to Right
I want to show permutations without replacement, and i found the itertools built-in on Python.But it's say:

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values.

So that when I using itertools.permutation(step,4), it's contain many replications.

>>> itertools.permutations(step,4)
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'R', 'D', 'R')
('D', 'R', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('R', 'D', 'R', 'D')
('R', 'R', 'D', 'D')
('R', 'R', 'D', 'D')

I want something like:

('R', 'D', 'R', 'D')
('R', 'D', 'D', 'R')
('D', 'R', 'R', 'D')
('D', 'D', 'R', 'R')
('D', 'R', 'D', 'R')
('R', 'R', 'D', 'D')

I found some answer using set(itertools.permutations(step,4)), but because apply set() method, the itertools.permutation() method still calculate all possibilities. Is there anyway to avoid it, or is there any built-in function can do permutation without repetitions in Python?

Body:
The leetcode problem only asks about the number of unique paths, not a list of unique paths, so to calculate the number you only need to use the combination formula of C(n, k) = n! / (k! x (n - k)!) to find the number of positions where Ds (or Rs) can be placed out of all positions:

from math import factorial

def f(m, n):
    return factorial(m + n - 2) / factorial(m - 1) / factorial(n - 1)

so that f(3, 2) returns: 3

and that f(7, 3) returns: 28

On the other hand, if you're interested in producing a list of unique paths, you can use itertools.combinations to do the same as above; that is, to find the positions where Ds (or Rs) can be placed out of all positions:

from itertools import combinations
def f(m, n):
    for positions in map(set, combinations(range(m + n - 2), m - 1)):
        yield ''.join('DR'[i in positions] for i in range(m + n - 2))

so that:

print(*f(7, 3), sep='\n')

outputs:

RRRRRRDD
RRRRRDRD
RRRRRDDR
RRRRDRRD
RRRRDRDR
RRRRDDRR
RRRDRRRD
RRRDRRDR
RRRDRDRR
RRRDDRRR
RRDRRRRD
RRDRRRDR
RRDRRDRR
RRDRDRRR
RRDDRRRR
RDRRRRRD
RDRRRRDR
RDRRRDRR
RDRRDRRR
RDRDRRRR
RDDRRRRR
DRRRRRRD
DRRRRRDR
DRRRRDRR
DRRRDRRR
DRRDRRRR
DRDRRRRR
DDRRRRRR


问:
How to check if MySQL table is empty or not when I reload page PHP
I work on a CRUD PHP page and everything works perfectly. The data that I take is from JSON url (https://jsonplaceholder.typicode.com/todos/).

How can I check and populate MySQL table if is empty every time when i load my index page.

This my PHP code how I connect to database. And function to inset JSON data to MySQL(I'm not sure that works correctly) :

```<code>class Database
{
    private $db_host;
    private $db_name;
    private $db_username;
    private $db_password;

    public function dbConnection()
    {
        $this->db_host = 'localhost';
        $this->db_name = 'items';
        $this->db_username = 'root';
        $this->db_password = '';
        try {
            $conn = new PDO('mysql:host=' . $this->db_host . ';dbname=' . $this->db_name, $this->db_username, $this->db_password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;
        } catch (PDOException $e) {
            echo "Connection error " . $e->getMessage();
            exit;
        }
    }
}
</code>```

Function getDati() that works correctly and returns array with 200 objects

```<code>function getDati()
{
    $url = 'https://jsonplaceholder.typicode.com/todos/';
    $cURL = curl_init();
    curl_setopt($cURL, CURLOPT_URL, $url);
    curl_setopt($cURL, CURLOPT_HTTPGET, true);
    curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Accept: application/json'
    ));

    $result = curl_exec($cURL);
    curl_close($cURL);

    $all_items = json_decode($result);

    return $all_items;
}

function intoDB()
{
    $database = new Database;
    $db = $database->dbConnection();
    $all_items = getDati();

    $sql = "SELECT count(*) FROM posts ";
    $result = $db->prepare($sql);
    $result->execute();
    $number_of_rows = $result->fetchColumn();
    if ($number_of_rows <= 0) {
        foreach ($all_items as $k => $item) {

            $sql = "INSERT INTO posts (id, userId, title, completed) VALUES (?,?,?,?)";
            $stmt = $db->prepare($sql);
            $stmt->execute([$item->id, $item->userId, $item->title, $item->completed]);
        }
    }
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documents</title>
    <link rel="stylesheet" href="./style.css">
    <script src="https://kit.fontawesome.com/12883fd222.js" crossorigin="anonymous"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>

<?php
require_once 'process.php';
intoDB();  // this is where i call the function.
</code>```

It should be IF that will check if table is full or empty but I donk know how to do that.

When I recall  intoDB() nothing happens. MySQL table remain empty. I want to check every time when I reload or open index page that my MySQL table is populated and if it is empty to populate it. Any suggestion how to do that? Thanks in advance!

答:
When selecting count(*), one row is returned, which contains the count so the response will be something like ['count(*)' => 0].

```<code>$number_of_rows = $result->fetchColumn(); // This contains 1 row, with the column indicating the count and so your condition will never be executed
</code>```

Rather alias the column SELECT count(*) as total_posts FROM posts

```<code>$row = $stmt->fetch(PDO::FETCH_ASSOC); // Fetch the first row
$total_posts = $row['total_posts']; // Get the column containing the result of the count
// Run your condition $total_posts
</code>```

Checkout this answer

Body:
I work on a CRUD PHP page and everything works perfectly. The data that I take is from JSON url (https://jsonplaceholder.typicode.com/todos/).

How can I check and populate MySQL table if is empty every time when i load my index page.

This my PHP code how I connect to database. And function to inset JSON data to MySQL(I'm not sure that works correctly) :

class Database
{
    private $db_host;
    private $db_name;
    private $db_username;
    private $db_password;

    public function dbConnection()
    {
        $this->db_host = 'localhost';
        $this->db_name = 'items';
        $this->db_username = 'root';
        $this->db_password = '';
        try {
            $conn = new PDO('mysql:host=' . $this->db_host . ';dbname=' . $this->db_name, $this->db_username, $this->db_password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;
        } catch (PDOException $e) {
            echo "Connection error " . $e->getMessage();
            exit;
        }
    }
}

Function getDati() that works correctly and returns array with 200 objects

function getDati()
{
    $url = 'https://jsonplaceholder.typicode.com/todos/';
    $cURL = curl_init();
    curl_setopt($cURL, CURLOPT_URL, $url);
    curl_setopt($cURL, CURLOPT_HTTPGET, true);
    curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Accept: application/json'
    ));

    $result = curl_exec($cURL);
    curl_close($cURL);

    $all_items = json_decode($result);

    return $all_items;
}

function intoDB()
{
    $database = new Database;
    $db = $database->dbConnection();
    $all_items = getDati();

    $sql = "SELECT count(*) FROM posts ";
    $result = $db->prepare($sql);
    $result->execute();
    $number_of_rows = $result->fetchColumn();
    if ($number_of_rows <= 0) {
        foreach ($all_items as $k => $item) {

            $sql = "INSERT INTO posts (id, userId, title, completed) VALUES (?,?,?,?)";
            $stmt = $db->prepare($sql);
            $stmt->execute([$item->id, $item->userId, $item->title, $item->completed]);
        }
    }
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documents</title>
    <link rel="stylesheet" href="./style.css">

    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

<?php
require_once 'process.php';
intoDB();  // this is where i call the function.

It should be IF that will check if table is full or empty but I donk know how to do that.

When I recall  intoDB() nothing happens. MySQL table remain empty. I want to check every time when I reload or open index page that my MySQL table is populated and if it is empty to populate it. Any suggestion how to do that? Thanks in advance!

Body:
When selecting count(*), one row is returned, which contains the count so the response will be something like ['count(*)' => 0].

$number_of_rows = $result->fetchColumn(); // This contains 1 row, with the column indicating the count and so your condition will never be executed

Rather alias the column SELECT count(*) as total_posts FROM posts

$row = $stmt->fetch(PDO::FETCH_ASSOC); // Fetch the first row
$total_posts = $row['total_posts']; // Get the column containing the result of the count
// Run your condition $total_posts

Checkout this answer


问:
Typescript complains when passing a possibly null (but not null) value to anonymous callback
When I have a property that initially begins as null, how can I pass this as an argument to an anonymous callback function that expects a non null value, without typescript complaining?

I can wrap my function call in an if statement to check for null, which stops typescript complaining at the function call level, but in the callback, typescript still complains.

Here's a snippet of the code. I allow some DatabaseState properties to be null, as this is how they are initialized.

```<code>//types.ts
export interface DatabaseState {
  db: PouchDB.Database | null;
  remoteDb: PouchDB.Database | null;
  dbReplication: PouchDB.Replication.Sync<{}> | null;
  dbSyncStatus: number;
  dbSyncInfo: string;
  dbSyncError: string;
}

//state typing - state: DatabaseState

//An action in database.ts
async startDatabaseSyncronisation({ state, commit, dispatch }) {
  var opts = { live: true, retry: true };

  if (state.remoteDb != null && state.db != null) {

    /* THE IF STATEMENT PREVENTS THE BELOW FUNCTION FROM CAUSING TYPESCRIPT TO COMPLAIN */

    await PouchDB.replicate(state.remoteDb, state.db, opts).on("complete",
      function(info) {

        /* WITHIN THE CALLBACK FUNCTION THOUGH, TYPESCRIPT COMPLAINS THAT state.remoteDb and state.db
        COULD BE NULL AND THE FUNCTION DOESN'T ACCEPT A NULL VALUE */

        let replication = PouchDB.sync(state.remoteDb, state.db, opts)
          .on("paused", function(err: {}) {
            dispatch("onSyncPaused", err);
          })
          .on("active", function() {
            dispatch("onSyncActive");
          })
          .on("denied", function(err: {}) {
            dispatch("onSyncError", err);
          })
          .on("error", function(err: {}) {
            dispatch("onSyncError", err);
          })
          .on("complete", function() {});
        commit(SET_DB_REPLICATION, replication);
      }
    );
  }
},
</code>```

How should I approach these kinds of typing checks?
Is there a more "Typescript-friendly" way of describing an initial value as unset?

The project uses Vue, with Vuex for state management.

答: The value of the state could change somewhere between the if check and complate callback. If you're sure the state hasn't changed you can tell the compiler to think that these values are not nullable by using null assertion operator: state!.remoteDb.

Body:
When I have a property that initially begins as null, how can I pass this as an argument to an anonymous callback function that expects a non null value, without typescript complaining?

I can wrap my function call in an if statement to check for null, which stops typescript complaining at the function call level, but in the callback, typescript still complains.

Here's a snippet of the code. I allow some DatabaseState properties to be null, as this is how they are initialized.

//types.ts
export interface DatabaseState {
  db: PouchDB.Database | null;
  remoteDb: PouchDB.Database | null;
  dbReplication: PouchDB.Replication.Sync<{}> | null;
  dbSyncStatus: number;
  dbSyncInfo: string;
  dbSyncError: string;
}

//state typing - state: DatabaseState

//An action in database.ts
async startDatabaseSyncronisation({ state, commit, dispatch }) {
  var opts = { live: true, retry: true };

  if (state.remoteDb != null && state.db != null) {

    /* THE IF STATEMENT PREVENTS THE BELOW FUNCTION FROM CAUSING TYPESCRIPT TO COMPLAIN */

    await PouchDB.replicate(state.remoteDb, state.db, opts).on("complete",
      function(info) {

        /* WITHIN THE CALLBACK FUNCTION THOUGH, TYPESCRIPT COMPLAINS THAT state.remoteDb and state.db
        COULD BE NULL AND THE FUNCTION DOESN'T ACCEPT A NULL VALUE */

        let replication = PouchDB.sync(state.remoteDb, state.db, opts)
          .on("paused", function(err: {}) {
            dispatch("onSyncPaused", err);
          })
          .on("active", function() {
            dispatch("onSyncActive");
          })
          .on("denied", function(err: {}) {
            dispatch("onSyncError", err);
          })
          .on("error", function(err: {}) {
            dispatch("onSyncError", err);
          })
          .on("complete", function() {});
        commit(SET_DB_REPLICATION, replication);
      }
    );
  }
},

How should I approach these kinds of typing checks?
Is there a more "Typescript-friendly" way of describing an initial value as unset?

The project uses Vue, with Vuex for state management.