问:
python if files in directory all share same permissions, run a regex
How to test every dir recursively and if all files in specific dir share same uid, gid, mode, capabilities, selabel. run a command if they do.

example contents of file1.txt:

```<code>set_metadata("/system/system/vendor/app/mcRegistry/00060308060501020000000000000000.tlbin", "uid", 0, "gid", 0, "mode", 0644, "capabilities", 0x0, "selabel", "u:object_r:mobicore_file:s0");
set_metadata("/system/system/vendor/app/mcRegistry/ffffffffd00000000000000000000062.tlbin", "uid", 0, "gid", 0, "mode", 0644, "capabilities", 0x0, "selabel", "u:object_r:mobicore_file:s0");
set_metadata("/system/system/vendor/app/mcRegistry", "uid", 0, "gid", 0, "mode", 0755, "capabilities", 0x0, "selabel", "u:object_r:mobicore_file:s0");
</code>```

Wanted output:

```<code>set_metadata("/system/system/vendor/app/mcRegistry", "uid", 0, "gid", 0, "dmode", 0755, "fmode", 0644, "capabilities", 0x0, "selabel", "u:object_r:mobicore_file:s0");
</code>```

So basically if all share common uid, gid, mode, rewrite the full directory, rename its mode to dmode, save all the files common mode add it as fmode

also I am using https://github.com/cubinator/ext4/blob/master/ext4.py35.py library to check all this.

How would I do it. It's too difficult for me. I managed to rename "mode" to "dmode" with re.sub and thats about it nothing else.

EDIT: assume you can get the uid of file with {uid} and same goes for gid etc.

EDIT2: I find directories with

import glob

files = glob.glob("system" + '/**/*', recursive=True)
```

答: A common and simple method for checking if all items in some collection share the same values over a set of attributes is to collect these attributes (UID, GID, etc.) in a tuple, for each item in the collection, and insert that tuple into a set. After you finish iterating over all the items, check if the set is exactly of size 1. If it is, that means all the items have the same values over the observed attributes.

Body:
How to test every dir recursively and if all files in specific dir share same uid, gid, mode, capabilities, selabel. run a command if they do.

example contents of file1.txt:

set_metadata("/system/system/vendor/app/mcRegistry/00060308060501020000000000000000.tlbin", "uid", 0, "gid", 0, "mode", 0644, "capabilities", 0x0, "selabel", "u:object_r:mobicore_file:s0");
set_metadata("/system/system/vendor/app/mcRegistry/ffffffffd00000000000000000000062.tlbin", "uid", 0, "gid", 0, "mode", 0644, "capabilities", 0x0, "selabel", "u:object_r:mobicore_file:s0");
set_metadata("/system/system/vendor/app/mcRegistry", "uid", 0, "gid", 0, "mode", 0755, "capabilities", 0x0, "selabel", "u:object_r:mobicore_file:s0");

Wanted output:

set_metadata("/system/system/vendor/app/mcRegistry", "uid", 0, "gid", 0, "dmode", 0755, "fmode", 0644, "capabilities", 0x0, "selabel", "u:object_r:mobicore_file:s0");

So basically if all share common uid, gid, mode, rewrite the full directory, rename its mode to dmode, save all the files common mode add it as fmode

also I am using https://github.com/cubinator/ext4/blob/master/ext4.py35.py library to check all this.

How would I do it. It's too difficult for me. I managed to rename "mode" to "dmode" with re.sub and thats about it nothing else.

EDIT: assume you can get the uid of file with {uid} and same goes for gid etc.

EDIT2: I find directories with

import glob

files = glob.glob("system" + '/**/*', recursive=True)


来源: stackexchange

问:
react native vector icons not working after export on expo
I use

react-native-vector-icons

and when I run app on emulator everything is ok
but after the export with

```<code>expo build:android -t apk
</code>```

and install on real phone all icons got hidden and not showing

答:
this you try?
react-native link react-native-vector-icons

ContentLicense: CC BY-SA 4.0

Body:
I use

react-native-vector-icons

and when I run app on emulator everything is ok
but after the export with

expo build:android -t apk

and install on real phone all icons got hidden and not showing


问:
How to update only specific fields in django model?
I want to update only specific fields in my model.
This is my models.py

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='teacher/images')
    phone = models.CharField(max_length=15)
    address = models.CharField(max_length=25)
    salary = models.DecimalField(max_digits=20, decimal_places=2)
    joindate = models.DateField(auto_now_add=True)
    status = models.BooleanField(default=True)```
</div>
</div>
</p>

<p>And this is my forms.py</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>class TeacherForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'password']

class TeacherExtraForm(forms.ModelForm):
    class Meta:
        model = models.Teacher
        fields = ['phone', 'address', 'salary', 'status', 'image']</code>```

And this is my views.py

def update_teacher(request, pk):
    teacher = models.Teacher.objects.get(id=pk)
    user = models.User.objects.get(id=teacher.user_id)
    form1 = forms.TeacherForm(instance=user)
    form2 = forms.TeacherExtraForm(instance=teacher)
    context = {
        'teacher': teacher,
        'user': user,
        'form1': form1,
        'form2': form2
    }
    if request.method == 'POST':
        form1 = forms.TeacherForm(request.POST, instance=user)
        form2 = forms.TeacherExtraForm(request.POST, instance=teacher)
        if form1.is_valid() and form2.is_valid():
            user = form1.save(commit=False)

            user.save(update_fields=['first_name', 'last_name', 'email', 'username'])
            f2 = form2.save(commit=False)
            f2.status = True
            f2.save(update_fields=['phone', 'address', 'salary', 'status'])
            return redirect('Teacher:teacher_index')
    return render(request, 'Teacher/update_teacher.html', context)```

Here I only want to update the first_name, last_name, email, username, phone, address, salary and status without affecting the password and image field. When I add the password and image field also, it works but I do not want to update password and image here.

答:
Typically in such situations, one makes two forms, one to create and one to update. Django itself for example has a UserCreateForm [Django-doc] and a UserChangeForm [Django-doc]. We thus can construct two additional forms:

```<code>class Teacher<b>Update</b>Form(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email']

class Teacher<b>Update</b>ExtraForm(forms.ModelForm):
    class Meta:
        model = models.Teacher
        fields = ['phone', 'address', 'salary', 'status']</code>```

In the view, we thus then work with these forms:

```<code>from django.shortcuts import get_object_or_404

def update_teacher(request, pk):
    teacher = get_object_or_404(models.Teacher, pk=pk)
    user = teacher.user
    if request.method == 'POST':
        form1 = forms.Teacher<b>Update</b>Form(request.POST, instance=user)
        form2 = forms.Teacher<b>Update</b>ExtraForm(request.POST, instance=teacher)
        if form1.is_valid() and form2.is_valid():
            form1.save()
            from2.instance.status = True
            form2.save()
            return redirect('Teacher:teacher_index')
    else:
        form1 = forms.Teacher<b>Update</b>Form(instance=user)
        form2 = forms.Teacher<b>Update</b>ExtraForm(instance=teacher)
    context = {
        'teacher': teacher,
        'user': user,
        'form1': form1,
        'form2': form2
    }
    return render(request, 'Teacher/update_teacher.html', context)</code>```

Body:
I want to update only specific fields in my model.
This is my models.py

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='teacher/images')
    phone = models.CharField(max_length=15)
    address = models.CharField(max_length=25)
    salary = models.DecimalField(max_digits=20, decimal_places=2)
    joindate = models.DateField(auto_now_add=True)
    status = models.BooleanField(default=True)

And this is my forms.py

class TeacherForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'password']

class TeacherExtraForm(forms.ModelForm):
    class Meta:
        model = models.Teacher
        fields = ['phone', 'address', 'salary', 'status', 'image']

And this is my views.py

def update_teacher(request, pk):
    teacher = models.Teacher.objects.get(id=pk)
    user = models.User.objects.get(id=teacher.user_id)
    form1 = forms.TeacherForm(instance=user)
    form2 = forms.TeacherExtraForm(instance=teacher)
    context = {
        'teacher': teacher,
        'user': user,
        'form1': form1,
        'form2': form2
    }
    if request.method == 'POST':
        form1 = forms.TeacherForm(request.POST, instance=user)
        form2 = forms.TeacherExtraForm(request.POST, instance=teacher)
        if form1.is_valid() and form2.is_valid():
            user = form1.save(commit=False)

            user.save(update_fields=['first_name', 'last_name', 'email', 'username'])
            f2 = form2.save(commit=False)
            f2.status = True
            f2.save(update_fields=['phone', 'address', 'salary', 'status'])
            return redirect('Teacher:teacher_index')
    return render(request, 'Teacher/update_teacher.html', context)

Here I only want to update the first_name, last_name, email, username, phone, address, salary and status without affecting the password and image field. When I add the password and image field also, it works but I do not want to update password and image here.

Body:
Typically in such situations, one makes two forms, one to create and one to update. Django itself for example has a UserCreateForm [Django-doc] and a UserChangeForm [Django-doc]. We thus can construct two additional forms:

class TeacherUpdateForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email']

class TeacherUpdateExtraForm(forms.ModelForm):
    class Meta:
        model = models.Teacher
        fields = ['phone', 'address', 'salary', 'status']

In the view, we thus then work with these forms:

from django.shortcuts import get_object_or_404

def update_teacher(request, pk):
    teacher = get_object_or_404(models.Teacher, pk=pk)
    user = teacher.user
    if request.method == 'POST':
        form1 = forms.TeacherUpdateForm(request.POST, instance=user)
        form2 = forms.TeacherUpdateExtraForm(request.POST, instance=teacher)
        if form1.is_valid() and form2.is_valid():
            form1.save()
            from2.instance.status = True
            form2.save()
            return redirect('Teacher:teacher_index')
    else:
        form1 = forms.TeacherUpdateForm(instance=user)
        form2 = forms.TeacherUpdateExtraForm(instance=teacher)
    context = {
        'teacher': teacher,
        'user': user,
        'form1': form1,
        'form2': form2
    }
    return render(request, 'Teacher/update_teacher.html', context)


问:
Bash linux loop throu file and send email
I have a file which have in every row email recipient,header and body .
So the structure is like that:

```<code>receipient|header|body

george@gmail.com,Alertheader,CheckYourData

rafal@gmail.com,GreenLight,GoWithYourProcess
</code>```

I would like to write a script which process every row and send an email to each person with header and body.

Please keep in mind that i am writing it on Informatica ETL tool (if that makes any difference)

So below script is working for sending email to 1 person from file(so file just have 1 email and nothing else),but got stuck on multiple persons and how to loop thru all those values.

```<code>echo "Please check the session log in /ciwetl/SessLogs directory.CIW-SUPPORT TEAM" | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." `cat /filelocation/emailsrc.txt`
</code>```

EDIT:
I have this working with this script :)

```<code>cat 'location/emailsrc.txt' | while IFS=, read -r line line2 || [[ -n $line ]]; do  echo $line2 | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." $line; done
</code>```

But there is another thing i didnt anticipated ....
In a body we can have commas so that would probably ruin my file.I was thinking to change delimiter in file to | .
I tried to change IFS=| but that didnt work out. Any tips ?

答:
Consider the following to include the 'header' and 'body' from the file</p>

```<code>IFS=',' while read email header body ; do
   if [ "$email" ] ; then
      mailx -s "$header" $mail <<< "$body"
   fi
done < /location/emailsrc.txt
</code>```

Body:
I have a file which have in every row email recipient,header and body .
So the structure is like that:

receipient|header|body

george@gmail.com,Alertheader,CheckYourData

rafal@gmail.com,GreenLight,GoWithYourProcess

I would like to write a script which process every row and send an email to each person with header and body.

Please keep in mind that i am writing it on Informatica ETL tool (if that makes any difference)

So below script is working for sending email to 1 person from file(so file just have 1 email and nothing else),but got stuck on multiple persons and how to loop thru all those values.

echo "Please check the session log in /ciwetl/SessLogs directory.CIW-SUPPORT TEAM" | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." `cat /filelocation/emailsrc.txt`

EDIT:
I have this working with this script :)

cat 'location/emailsrc.txt' | while IFS=, read -r line line2 || [[ -n $line ]]; do  echo $line2 | mailx -s "CIW : Workflow wf_m_LOAD_CIW_LOCATION_RT failed." $line; done

But there is another thing i didnt anticipated ....
In a body we can have commas so that would probably ruin my file.I was thinking to change delimiter in file to | .
I tried to change IFS=| but that didnt work out. Any tips ?

Body:
Consider the following to include the 'header' and 'body' from the file

IFS=',' while read email header body ; do
   if [ "$email" ] ; then
      mailx -s "$header" $mail <<< "$body"
   fi
done < /location/emailsrc.txt


问:
Splitting std::vector of size m into vector of vectors of size n
Given a vector [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
what are some possible approaches to construct [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17]], focusing primarily on readability?

At the moment, I have correctly defined the starting and ending indexes of all the subarrays, and was trying to use std::copy(cam.begin() + start, cam.begin() + end+ 1, vec.begin()); to construct a new vector.. resulting in:

```<code>terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc
</code>```

答:
Using the range-v3 library this becomes very simple, and readable:

```<code>std::vector<int> v = ...
int m = ...

auto vs = v | ranges::views::chunk(m)
            | ranges::to<std::vector<std::vector<int>>>;
</code>```

Here's a demo.

Body:
Given a vector [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
what are some possible approaches to construct [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17]], focusing primarily on readability?

At the moment, I have correctly defined the starting and ending indexes of all the subarrays, and was trying to use std::copy(cam.begin() + start, cam.begin() + end+ 1, vec.begin()); to construct a new vector.. resulting in:

terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc

Body:
Using the range-v3 library this becomes very simple, and readable:

std::vector<int> v = ...
int m = ...

auto vs = v | ranges::views::chunk(m)
            | ranges::to<std::vector<std::vector<int>>>;

Here's a demo.


问:
Maven - Java EE 6 Web Profile Javadocs
By declaring the following dependency:

```<code><dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
</dependency>
</code>```

I can use about everything I need for a Java EE 6 Project (Servlet 3.0, JPA 2, EJB, CDI, etc).
The problem is: Maven can not download the Javadocs for the dependency (or at least m2eclipse "Download JavaDoc" feature don't work), so Eclipse don't show me the Javadocs when I use the very handy code completion feature.

I've found this post specific to Servlet 3.0 API, Maven dependency for Servlet 3.0 API?.

Can anyone kindly point to a solution that works for every API? Or, can anyone please provide a dummy guide to install Java EE 6 Javadocs and link it to javaee-web-api artifact in the local repository?

答:
Assuming you have Java EE javadocs, you can install them to your local maven repository using the maven install plugin.  Look at this usage link

You would use the -Dclassifier=sources to indicate you are installing sources. See this example for this.

ContentLicense: CC BY-SA 3.0

Title: Maven - Java EE 6 Web Profile Javadocs

Body:
By declaring the following dependency:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
</dependency>

I can use about everything I need for a Java EE 6 Project (Servlet 3.0, JPA 2, EJB, CDI, etc).
The problem is: Maven can not download the Javadocs for the dependency (or at least m2eclipse "Download JavaDoc" feature don't work), so Eclipse don't show me the Javadocs when I use the very handy code completion feature.

I've found this post specific to Servlet 3.0 API, Maven dependency for Servlet 3.0 API?.

Can anyone kindly point to a solution that works for every API? Or, can anyone please provide a dummy guide to install Java EE 6 Javadocs and link it to javaee-web-api artifact in the local repository?


问:
Define functions in structs
Can we define functions in structs in C programming language?</p>

答:
You can use only function pointers in C. Assign address of real function to that pointer after struct initialization, example:

```<code>#include <stdio.h>
#include <stdlib.h>

struct unit
{
  int result;
  int (*add) (int x, int y);
};

int sumFunc(int x, int y) { return x + y; }

void *unitInit()
{
  struct unit *ptr = (struct unit*) malloc(sizeof(struct unit));
  ptr->add = &sumFunc;
  return ptr;
}

int main(int argc, char **argv)
{
  struct unit *U = unitInit();

  U->result = U->add(5, 10);

  printf("Result is %i\n", U->result);

  free(U);

  return 0;
}
</code>```

Good example of using function pointers in a struct you can find here https://github.com/AlexanderAgd/CLIST
Check header and then clist.c file.

Title: Define functions in structs

Body:
You can use only function pointers in C. Assign address of real function to that pointer after struct initialization, example:

#include <stdio.h>
#include <stdlib.h>

struct unit
{
  int result;
  int (*add) (int x, int y);
};

int sumFunc(int x, int y) { return x + y; }

void *unitInit()
{
  struct unit *ptr = (struct unit*) malloc(sizeof(struct unit));
  ptr->add = &sumFunc;
  return ptr;
}

int main(int argc, char **argv)
{
  struct unit *U = unitInit();

  U->result = U->add(5, 10);

  printf("Result is %i\n", U->result);

  free(U);

  return 0;
}

Good example of using function pointers in a struct you can find here https://github.com/AlexanderAgd/CLIST
Check header and then clist.c file.


问:
chown: changing ownership of '/var/lib/mysql/': Operation not permitted in start pods in kubernetes
When I start my mysql 5.7 pods in kubernetes v1.15.2, the logs shows like this:

```<code>2020-05-30 13:08:04+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started.
chown: changing ownership of '/var/lib/mysql/': Operation not permitted
</code>```

this is my mysql yaml define:

```<code>apiVersion: v1
kind: Service
metadata:
  name: apollo-mysql
  namespace: sre
spec:
  ports:
  - port: 3306
  selector:
    app: mysql
  clusterIP: None
---
apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: apollo-mysql
  namespace: sre
spec:
  selector:
    matchLabels:
      app: apollo-mysql
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: apollo-mysql
    spec:
      containers:
      - image: mysql:5.7
        name: mysql
        env:
          # Use secret in real usage
        - name: MYSQL_ROOT_PASSWORD
          value: gfwge4LucnXwfefewegLwAd29QqJn4
        ports:
        - containerPort: 3306
          name: mysql
        volumeMounts:
        - name: apollo-mysql-persistent-storage
          mountPath: /var/lib/mysql
      volumes:
      - name: apollo-mysql-persistent-storage
        persistentVolumeClaim:
          claimName: apollo-mysql-pv-claim
</code>```

and this is my pv define:

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-apollo-mysql-pv1
  namespace: sre
  labels:
    alicloud-pvname: apollo-mysql-data-db
spec:
  capacity:
    storage: 5Gi
  storageClassName: apollo-mysql-data-db
  mountOptions:
    - vers=4.0
    - noresvport
  accessModes:
    - ReadWriteOnce
  nfs:
    server: "192.168.64.237"
    path: "/mnt/data/apollodb/apollopv"
  persistentVolumeReclaimPolicy: Retain
</code>```

and I already change the mod to 777 like this:

```<code>chmod 777 /mnt/data/apollodb/apollopv
</code>```

so where is the problem and what should I do to fix this? I check the selinux status and it is disabled.

```<code>[miao@meowk8sslave3 apollodb]$ /usr/sbin/sestatus -v
SELinux status:                 disabled
</code>```

This is my nfs exports define:

```<code>/mnt/data/apollodb/apollopv *(rw,sync,no_subtree_check,no_root_squash)
</code>```

答:
The yaml you have provided is missing PVC, which specifies the storageClass to be mounted.

It looks like you are trying to mount an external NFS (with some cloud provider perhaps), in which case you need to have nfs-utils installed, and do mount -t nfs 192.168.64.237:/entrypoint /mnt/....

Your PV says /mnt/data/apollodb/apollopv, which should be the entrypoint to the nfs server, and not where it is going to be mounted in your filesystem.

To make this work, get yourself an nfs server (get the IP address and the entrypoint; say 192.168.64.237:/nfs), then mount it in your pod as follows:

```<code>apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: apollo-mysql
  namespace: sre
spec:
  selector:
    matchLabels:
      app: apollo-mysql
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: apollo-mysql
    spec:
      containers:
      - image: mysql:5.7
        name: mysql
        env:
          # Use secret in real usage
        - name: MYSQL_ROOT_PASSWORD
          value: gfwge4LucnXwfefewegLwAd29QqJn4
        ports:
        - containerPort: 3306
          name: mysql
        volumeMounts:
        - name: apollo-mysql-persistent-storage
          mountPath: /var/lib/mysql
      volumes:
      - name: apollo-mysql-persistent-storage
        nfs:
          server: 192.168.64.237
          path: "/nfs"
</code>```

You won't need the storage class, the PVC and the PV. Everything you need is in the pod, and externally you have the nfs server.

Body:
When I start my mysql 5.7 pods in kubernetes v1.15.2, the logs shows like this:

2020-05-30 13:08:04+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started.
chown: changing ownership of '/var/lib/mysql/': Operation not permitted

this is my mysql yaml define:

apiVersion: v1
kind: Service
metadata:
  name: apollo-mysql
  namespace: sre
spec:
  ports:
  - port: 3306
  selector:
    app: mysql
  clusterIP: None
---
apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: apollo-mysql
  namespace: sre
spec:
  selector:
    matchLabels:
      app: apollo-mysql
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: apollo-mysql
    spec:
      containers:
      - image: mysql:5.7
        name: mysql
        env:
          # Use secret in real usage
        - name: MYSQL_ROOT_PASSWORD
          value: gfwge4LucnXwfefewegLwAd29QqJn4
        ports:
        - containerPort: 3306
          name: mysql
        volumeMounts:
        - name: apollo-mysql-persistent-storage
          mountPath: /var/lib/mysql
      volumes:
      - name: apollo-mysql-persistent-storage
        persistentVolumeClaim:
          claimName: apollo-mysql-pv-claim

and this is my pv define:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-apollo-mysql-pv1
  namespace: sre
  labels:
    alicloud-pvname: apollo-mysql-data-db
spec:
  capacity:
    storage: 5Gi
  storageClassName: apollo-mysql-data-db
  mountOptions:
    - vers=4.0
    - noresvport
  accessModes:
    - ReadWriteOnce
  nfs:
    server: "192.168.64.237"
    path: "/mnt/data/apollodb/apollopv"
  persistentVolumeReclaimPolicy: Retain

and I already change the mod to 777 like this:

chmod 777 /mnt/data/apollodb/apollopv

so where is the problem and what should I do to fix this? I check the selinux status and it is disabled.

[miao@meowk8sslave3 apollodb]$ /usr/sbin/sestatus -v
SELinux status:                 disabled

This is my nfs exports define:

/mnt/data/apollodb/apollopv *(rw,sync,no_subtree_check,no_root_squash)

Body:
The yaml you have provided is missing PVC, which specifies the storageClass to be mounted.

It looks like you are trying to mount an external NFS (with some cloud provider perhaps), in which case you need to have nfs-utils installed, and do mount -t nfs 192.168.64.237:/entrypoint /mnt/....

Your PV says /mnt/data/apollodb/apollopv, which should be the entrypoint to the nfs server, and not where it is going to be mounted in your filesystem.

To make this work, get yourself an nfs server (get the IP address and the entrypoint; say 192.168.64.237:/nfs), then mount it in your pod as follows:

apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: apollo-mysql
  namespace: sre
spec:
  selector:
    matchLabels:
      app: apollo-mysql
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: apollo-mysql
    spec:
      containers:
      - image: mysql:5.7
        name: mysql
        env:
          # Use secret in real usage
        - name: MYSQL_ROOT_PASSWORD
          value: gfwge4LucnXwfefewegLwAd29QqJn4
        ports:
        - containerPort: 3306
          name: mysql
        volumeMounts:
        - name: apollo-mysql-persistent-storage
          mountPath: /var/lib/mysql
      volumes:
      - name: apollo-mysql-persistent-storage
        nfs:
          server: 192.168.64.237
          path: "/nfs"

You won't need the storage class, the PVC and the PV. Everything you need is in the pod, and externally you have the nfs server.


问:
Can help me to solve Longest Collatz sequence -14
This is my code

```<code>def Collatz(n,x,m):
    if(n%2!=0):
        n=3*n+1
        x=x+1
        Collatz(n,x,m)
    else:
        n=n/2
        x=x+1
        if(n==1):
            sumlist.append(x)
            print(sumlist)
            print(m)
            m=m+1
            if m==1000000:
                print(max(sumlist),"bye")
                exit();
            Collatz(m,0,m)
        Collatz(n,x,m)
sumlist=[]

c=2

Collatz(c,0,2)
</code>```

My code is this.But I get some errors after executing it.

```<code>1]
2
[1, 7]
3
[1, 7, 2]
4
[1, 7, 2, 5]
5
[1, 7, 2, 5, 8]
6
[1, 7, 2, 5, 8, 16]
7
[1, 7, 2, 5, 8, 16, 3]
8
[1, 7, 2, 5, 8, 16, 3, 19]
9
[1, 7, 2, 5, 8, 16, 3, 19, 6]
10
[1, 7, 2, 5, 8, 16, 3, 19, 6, 14]
11
[1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9]
12
[1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9, 9]
13.....
.....[1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9, 9, 17, 17, 4, 12, 20, 20, 7, 7, 15, 15, 10, 23, 10, 111, 18, 18, 18, 106, 5, 26, 13, 13, 21, 21, 21, 34, 8, 109, 8, 29, 16, 16, 16, 104]
47
Traceback (most recent call last):
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 61, in <module>
    Collatz(c,0,2)
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 54, in Collatz
    Collatz(m,0,m)
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 36, in Collatz
    Collatz(n,x,m)
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 56, in Collatz
</code>```

This code runs until m=47 correctly. Then it shows errors.
Can anyone help me?

答:
A short-term solution would be to manually raise Python's default recursion depth from 1000 to some higher number:

```<code>import sys
sys.setrecursionlimit(20000)

def Collatz(n,x,m):
    ...
</code>```

In the medium term you should move the code inside the if(n==1): into the main loop of your program. Iteration over m doesn't belong in the Collatz function, this is why your call stack recurses deeper and deeper and never gets cleaned up.

Body:
This is my code

def Collatz(n,x,m):
    if(n%2!=0):
        n=3*n+1
        x=x+1
        Collatz(n,x,m)
    else:
        n=n/2
        x=x+1
        if(n==1):
            sumlist.append(x)
            print(sumlist)
            print(m)
            m=m+1
            if m==1000000:
                print(max(sumlist),"bye")
                exit();
            Collatz(m,0,m)
        Collatz(n,x,m)
sumlist=[]

c=2

Collatz(c,0,2)

My code is this.But I get some errors after executing it.

1]
2
[1, 7]
3
[1, 7, 2]
4
[1, 7, 2, 5]
5
[1, 7, 2, 5, 8]
6
[1, 7, 2, 5, 8, 16]
7
[1, 7, 2, 5, 8, 16, 3]
8
[1, 7, 2, 5, 8, 16, 3, 19]
9
[1, 7, 2, 5, 8, 16, 3, 19, 6]
10
[1, 7, 2, 5, 8, 16, 3, 19, 6, 14]
11
[1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9]
12
[1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9, 9]
13.....
.....[1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9, 9, 17, 17, 4, 12, 20, 20, 7, 7, 15, 15, 10, 23, 10, 111, 18, 18, 18, 106, 5, 26, 13, 13, 21, 21, 21, 34, 8, 109, 8, 29, 16, 16, 16, 104]
47
Traceback (most recent call last):
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 61, in <module>
    Collatz(c,0,2)
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 54, in Collatz
    Collatz(m,0,m)
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 36, in Collatz
    Collatz(n,x,m)
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 56, in Collatz

This code runs until m=47 correctly. Then it shows errors.
Can anyone help me?

Body:
A short-term solution would be to manually raise Python's default recursion depth from 1000 to some higher number:

import sys
sys.setrecursionlimit(20000)

def Collatz(n,x,m):
    ...

In the medium term you should move the code inside the if(n==1): into the main loop of your program. Iteration over m doesn't belong in the Collatz function, this is why your call stack recurses deeper and deeper and never gets cleaned up.


问:
How do I create a serializer that reuses a unique key of my model?
I'm using Python 3.7, Django 2.2, the Django rest framework, and pytest.  I have the following model, in which I want to re-use an existing model if it exists by its unique key ...

class CoopTypeManager(models.Manager):

    def get_by_natural_key(self, name):
        return self.get_or_create(name=name)[0]

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False, unique=True)

    objects = CoopTypeManager()
```

<p>Then I have created the below serializer to generate this model from REST data</p>

```class CoopTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.get_or_create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `CoopType` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance
```

<p>However, when I run the below test in which I intentionally use a name that is taken</p>

```@pytest.mark.django_db
def test_coop_type_create_with_existing(self):
    """ Test coop type serizlizer model if there is already a coop type by that name """
    coop_type = CoopTypeFactory()
    serializer_data = {
        "name": coop_type.name,
    }

    serializer = CoopTypeSerializer(data=serializer_data)
    serializer.is_valid()
    print(serializer.errors)
    assert serializer.is_valid(), serializer.errors
    result = serializer.save()
    assert result.name == name
```

<p>I get the below error</p>

```python manage.py test --settings=directory.test_settings
...        ----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_serializers.py", line 46, in test_coop_type_create_with_existing
    assert serializer.is_valid(), serializer.errors
AssertionError: {'name': [ErrorDetail(string='coop type with this name already exists.', code='unique')]}
```

<p>How do I construct my serializer so that I can create my model if its unique key doesn't exist, or re-use it if it does?</p>

<p><b>Edit:</b> Here's the GitHub link ...</p>

```https://github.com/chicommons/maps/tree/master/web
```

答:
My suggestion is to not use a ModelSerializer but instead use a vanilla serializer.

```<code>class CoopTypeSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=200, required=True, allow_blank=False)

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.get_or_create(**validated_data)[0]

    def update(self, instance, validated_data):
        """
        Update and return an existing `CoopType` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance
</code>```

Body:
I'm using Python 3.7, Django 2.2, the Django rest framework, and pytest.  I have the following model, in which I want to re-use an existing model if it exists by its unique key ...

class CoopTypeManager(models.Manager):

    def get_by_natural_key(self, name):
        return self.get_or_create(name=name)[0]

class CoopType(models.Model):
    name = models.CharField(max_length=200, null=False, unique=True)

    objects = CoopTypeManager()

Then I have created the below serializer to generate this model from REST data

class CoopTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = CoopType
        fields = ['id', 'name']

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.get_or_create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `CoopType` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance

However, when I run the below test in which I intentionally use a name that is taken

@pytest.mark.django_db
def test_coop_type_create_with_existing(self):
    """ Test coop type serizlizer model if there is already a coop type by that name """
    coop_type = CoopTypeFactory()
    serializer_data = {
        "name": coop_type.name,
    }

    serializer = CoopTypeSerializer(data=serializer_data)
    serializer.is_valid()
    print(serializer.errors)
    assert serializer.is_valid(), serializer.errors
    result = serializer.save()
    assert result.name == name

I get the below error

python manage.py test --settings=directory.test_settings
...        ----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_serializers.py", line 46, in test_coop_type_create_with_existing
    assert serializer.is_valid(), serializer.errors
AssertionError: {'name': [ErrorDetail(string='coop type with this name already exists.', code='unique')]}

How do I construct my serializer so that I can create my model if its unique key doesn't exist, or re-use it if it does?

Edit: Here's the GitHub link ...

https://github.com/chicommons/maps/tree/master/web

Body:
My suggestion is to not use a ModelSerializer but instead use a vanilla serializer.

class CoopTypeSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    name = serializers.CharField(max_length=200, required=True, allow_blank=False)

    def create(self, validated_data):
        """
        Create and return a new `CoopType` instance, given the validated data.
        """
        return CoopType.objects.get_or_create(**validated_data)[0]

    def update(self, instance, validated_data):
        """
        Update and return an existing `CoopType` instance, given the validated data.
        """
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance


问:
Checking property existence of include fragment in MyBatis
Is there some way to check if a property in include fragment has been set?
Example:

```<code><include refid="myFilterLocation">
  <property name="model" value="model_name"/>
  ...
  ...
  ...
</include>
</code>```

And then when this fragment is used:

```<code><if test="....">
 AND ${model}= #{${param}.model,jdbcType=VARCHAR}
</if>
</code>```

Is there some way to test if the property is not sent?. I want not send properties if I do not want to filter in my query.

Kind regards.

答:
When the property is not defined, ${model} is not replaced at all, so you may be able to write the condition as follows.

<if test='"${model}" != "\${model}"'>
  AND ${model}= #{${param}.model,jdbcType=VARCHAR}
</if>
```

<p>Note the unusual usage of single/double quotes and the backslash before the second dollar sign.</p>

<p>(Longer explanation)</p>

<p>There are two variables <code>${model}</code> in the <code>test</code> attribute value, however the second one is <em>escaped</em> using a leading backslash.<br>
So, when the 'model' property is specified, the included if element will look as follows.  </p>

<pre class="lang-xml prettyprint-override"><code><if test='"model_name" != "${model}"'>
</code>```

The condition is a simple two strings comparison and the result is true.

Note that the backslash used to escape the variable is removed (that's how MyBatis' variable escaping works).

Now, when the 'model' property is not specified, the variable is not replaced, so the if element looks as follows after the inclusion.

<if test='"${model}" != "${model}"'>
```

As you can see, the two strings are the same and the result of the condition is false.

And OGNL requires double quotes for string literal.

If you use single quotes, NumberFormatException may be thrown (OGNL recognizes it as a char, it seems).

Body:
Is there some way to check if a property in include fragment has been set?
Example:

<include refid="myFilterLocation">
  <property name="model" value="model_name"/>
  ...
  ...
  ...
</include>

And then when this fragment is used:

<if test="....">
 AND ${model}= #{${param}.model,jdbcType=VARCHAR}
</if>

Is there some way to test if the property is not sent?. I want not send properties if I do not want to filter in my query.

Kind regards.

Body:
When the property is not defined, ${model} is not replaced at all, so you may be able to write the condition as follows.

<if test='"${model}" != "\${model}"'>
  AND ${model}= #{${param}.model,jdbcType=VARCHAR}
</if>

Note the unusual usage of single/double quotes and the backslash before the second dollar sign.

(Longer explanation)

There are two variables ${model} in the test attribute value, however the second one is escaped using a leading backslash.

So, when the 'model' property is specified, the included if element will look as follows.

<if test='"model_name" != "${model}"'>

The condition is a simple two strings comparison and the result is true.

Note that the backslash used to escape the variable is removed (that's how MyBatis' variable escaping works).

Now, when the 'model' property is not specified, the variable is not replaced, so the if element looks as follows after the inclusion.

<if test='"${model}" != "${model}"'>

As you can see, the two strings are the same and the result of the condition is false.

And OGNL requires double quotes for string literal.

If you use single quotes, NumberFormatException may be thrown (OGNL recognizes it as a char, it seems).


问:
Not making a table in Laravel 7
I have tried different ways to solve this problem, but none of them have solved the problem.This part of the code is for building a relationship in Laravel, but this code works in Laravel 5 but is error-prone in Laravel 7.

Error:
SQLSTATE[HY000]: General error: 1005 Can't create table shoplaravel.role_user (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table role_user add constraint role_user_role_id_foreign foreign key (role_id) references roles (id) on delete cascade on update cascade)

```<code>    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });
    Schema::create('permissions', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });

    Schema::create('role_user', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id');
        $table->unsignedBigInteger('user_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->primary(['role_id', 'user_id']);
    });
    Schema::create('permission_role', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id');
        $table->unsignedBigInteger('permission_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('permission_id')
            ->references('id')
            ->on('permissions')
            ->onDelete('cascade')
            ->onUpdate('cascade');
        $table->primary(['permission_id', 'role_id']);
    });
</code>```

答:
Foreign keys need to be of the exact same type as the column they're referencing.

Laravel's default user table migration uses $table->increments('id'); - an alias of $table->bigIncrements('id').

Change $table->increments('id'); to $table->bigIncrements('id'); in your roles and permissions table migrations.

More on migration columns: https://laravel.com/docs/7.x/migrations#creating-columns

Title: Not making a table in Laravel 7

Body:
I have tried different ways to solve this problem, but none of them have solved the problem.This part of the code is for building a relationship in Laravel, but this code works in Laravel 5 but is error-prone in Laravel 7.

Error:
SQLSTATE[HY000]: General error: 1005 Can't create table shoplaravel.role_user (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table role_user add constraint role_user_role_id_foreign foreign key (role_id) references roles (id) on delete cascade on update cascade)

    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });
    Schema::create('permissions', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('title')->nullable();
        $table->timestamps();
    });

    Schema::create('role_user', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id');
        $table->unsignedBigInteger('user_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->primary(['role_id', 'user_id']);
    });
    Schema::create('permission_role', function (Blueprint $table) {
        $table->unsignedBigInteger('role_id');
        $table->unsignedBigInteger('permission_id');

        $table->foreign('role_id')
            ->references('id')
            ->on('roles')
            ->onDelete('cascade')
            ->onUpdate('cascade');

        $table->foreign('permission_id')
            ->references('id')
            ->on('permissions')
            ->onDelete('cascade')
            ->onUpdate('cascade');
        $table->primary(['permission_id', 'role_id']);
    });


问:
How to move directories using jdk7
Using jdk7, I am trying to use the java.nio.file.Files class to move an empty directory, let's say Bar, into another empty directory, let's say Foo

```<code>Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
    Files.move(
        source,
        target,
        StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

After executing that code snippet, I expected that the Bar directory would be in the Foo directory (...\Foo\Bar). Instead it is not. And here's the kicker, it's been deleted as well. Also, no exceptions were thrown.

Am I doing this wrong?

NOTE

I'm looking for a jdk7-specific solution.I am also looking into the problem, but I figured I'd see if there was anyone else playing around with jdk7.

EDIT

In addition to the accepted answer, here's another solution

```<code>Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
    Files.move(
    source,
    target.resolve(source.getFileName()),
    StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

答:
I didn't realize jdk7 java.nio.file.Files is a necessity, so here is the edited solution.  Please see if it works coz I have never used the new Files class before.</p>

```<code>Path source = Paths.get("Bar");
Path target = Paths.get("Foo", "Bar");
try {
    Files.move(
        source,
        target,
        StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Title: How to move directories using jdk7

Body:
Using jdk7, I am trying to use the java.nio.file.Files class to move an empty directory, let's say Bar, into another empty directory, let's say Foo

Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
    Files.move(
        source,
        target,
        StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}

After executing that code snippet, I expected that the Bar directory would be in the Foo directory (...\Foo\Bar). Instead it is not. And here's the kicker, it's been deleted as well. Also, no exceptions were thrown.

Am I doing this wrong?

NOTE

I'm looking for a jdk7-specific solution.I am also looking into the problem, but I figured I'd see if there was anyone else playing around with jdk7.

EDIT

In addition to the accepted answer, here's another solution

Path source = Paths.get("Bar");
Path target = Paths.get("Foo");
try {
    Files.move(
    source,
    target.resolve(source.getFileName()),
    StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}

Body:
I didn't realize jdk7 java.nio.file.Files is a necessity, so here is the edited solution.  Please see if it works coz I have never used the new Files class before.

Path source = Paths.get("Bar");
Path target = Paths.get("Foo", "Bar");
try {
    Files.move(
        source,
        target,
        StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}


问:
error with clearcontent/clearcontents and keeping formulas
having trouble with the following code:

```<code>function addDelivery() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = ss.getSheetByName("Sheet7");

  var range = srcSheet.getRange("B3:L3").getValues();
  var formulas = srcSheet.getRange("B3:L3").getFormulas();
  srcSheet.insertRowBefore(6);
  srcSheet.getRange(6,2,1,11).setValues(range);
  range.clearContents();
  range.setFormulas(formulas);
</code>```

I want to clear the contents of cells B3:L3 but keep the formula in L3.

I get the error message "TypeError: range.clearContent is not a function".
I read that clearContent is a method of Range and clearContents is a method of sheet.
I've tried both, but neither work.

Please help.

Best regards
manc

答:
Perhaps this would work better:

```<code>function addDelivery() {
  var ss = SpreadsheetApp.getActive();
  var srcSheet = ss.getSheetByName("Sheet7");
  var range=srcSheet.getRange("B3:L3");
  var values = range.getValues();
  var formulas = range.getFormulas();
  srcSheet.insertRowBefore(6);
  srcSheet.getRange(6,2,1,11).setValues(values);
  range.setFormulas(formulas);
  srcSheet.getRange("B3:K3").clearContent();
</code>```

I thought about it some more and I think I'd probably do it this way:

```<code>  function addDelivery() {
  var ss = SpreadsheetApp.getActive();
  var srcSheet = ss.getSheetByName("Sheet7");
  var range = srcSheet.getRange("B3:L3");
  var values = range.getValues();
  var formula = srcSheet.getRange("L3").getFormula();
  srcSheet.insertRowBefore(6);
  srcSheet.getRange(6,2,values.length,values[0].length).setValues(values);
  srcSheet.getRange("L3").setFormula(formula);
  srcSheet.getRange("B3:K3").clearContent();
</code>```

Body:
having trouble with the following code:

function addDelivery() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var srcSheet = ss.getSheetByName("Sheet7");

  var range = srcSheet.getRange("B3:L3").getValues();
  var formulas = srcSheet.getRange("B3:L3").getFormulas();
  srcSheet.insertRowBefore(6);
  srcSheet.getRange(6,2,1,11).setValues(range);
  range.clearContents();
  range.setFormulas(formulas);

I want to clear the contents of cells B3:L3 but keep the formula in L3.

I get the error message "TypeError: range.clearContent is not a function".
I read that clearContent is a method of Range and clearContents is a method of sheet.
I've tried both, but neither work.

Please help.

Best regards
manc

Body:
Perhaps this would work better:

function addDelivery() {
  var ss = SpreadsheetApp.getActive();
  var srcSheet = ss.getSheetByName("Sheet7");
  var range=srcSheet.getRange("B3:L3");
  var values = range.getValues();
  var formulas = range.getFormulas();
  srcSheet.insertRowBefore(6);
  srcSheet.getRange(6,2,1,11).setValues(values);
  range.setFormulas(formulas);
  srcSheet.getRange("B3:K3").clearContent();

I thought about it some more and I think I'd probably do it this way:

  function addDelivery() {
  var ss = SpreadsheetApp.getActive();
  var srcSheet = ss.getSheetByName("Sheet7");
  var range = srcSheet.getRange("B3:L3");
  var values = range.getValues();
  var formula = srcSheet.getRange("L3").getFormula();
  srcSheet.insertRowBefore(6);
  srcSheet.getRange(6,2,values.length,values[0].length).setValues(values);
  srcSheet.getRange("L3").setFormula(formula);
  srcSheet.getRange("B3:K3").clearContent();


问:
How do i pass php variable to .js file to create function Chart
i done create my chart but i dont know how to pass it, i already try use ?php  but its not working.. and i already define in head like below, but when i try to pass it. the php file returning "''" like function tooltips title

```<code><script src="includes/templates/chart.js"></script>
</code>```

chart.js

```<code>
window.onload = function() {
    var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['08:00'] , //Jamnya
                datasets: [{
                    backgroundColor: 'rgba(85, 212, 226, 0.2)',
                    borderColor: '#55d4e2',
                    label: '<?php echo $dtDateChart1; ?>' ,
                    data: [600],
                    fill: true,
                    pointRadius: 5,
                    pointHoverRadius: 10,
                    showLine: true
                }]
            }, options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: 'Total Online Today',
                    position: 'top',
                    fontSize: 15,
                    fontStyle: 'bold'
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        pointStyle: 'circle'
                    }
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TIME'
                        },
                        ticks: {
                            major: {
                                fontStyle: 'bold',
                                fontColor: '#FF0000'
                            }
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TOTAL ONLINE'
                        }
                    }]
                },
                tooltips:{
                    callbacks: {
                        title: function(tooltipItem, data) {
                          return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
                        },
                        label: function(tooltipItem, data) {
                          return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                        },
                    },
                    titleFontSize: 15,
                    bodyFontSize: 15,
                    displayColors: false
                }
            }
        }
     );

     return myChart;

}
</code>```

in my php file

```<code>$out .=  '         <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';
</code>```

and this is my variable that i want to pass to my .js

```<code>         //result chart1
            @mssql_free_result($graph_query2);
            $dtDateChart1 = $dateTittleChart1;
            $convertChart1 = json_encode($datesChart1);
            $totalChart1 = json_encode($nMaxChart1);
            $labelChart1 =  $convertChart1;
</code>```

i dont know how to pass it when i already succes getelementbyid thanks you if you know something about it that i should know. i dont have a lot knowledge about javascript passing variable.

Body:
i done create my chart but i dont know how to pass it, i already try use ?php  but its not working.. and i already define in head like below, but when i try to pass it. the php file returning "''" like function tooltips title

chart.js

window.onload = function() {
    var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['08:00'] , //Jamnya
                datasets: [{
                    backgroundColor: 'rgba(85, 212, 226, 0.2)',
                    borderColor: '#55d4e2',
                    label: '<?php echo $dtDateChart1; ?>' ,
                    data: [600],
                    fill: true,
                    pointRadius: 5,
                    pointHoverRadius: 10,
                    showLine: true
                }]
            }, options: {
                responsive: true,
                maintainAspectRatio: false,
                title: {
                    display: true,
                    text: 'Total Online Today',
                    position: 'top',
                    fontSize: 15,
                    fontStyle: 'bold'
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        pointStyle: 'circle'
                    }
                },
                scales: {
                    xAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TIME'
                        },
                        ticks: {
                            major: {
                                fontStyle: 'bold',
                                fontColor: '#FF0000'
                            }
                        }
                    }],
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'TOTAL ONLINE'
                        }
                    }]
                },
                tooltips:{
                    callbacks: {
                        title: function(tooltipItem, data) {
                          return '<?php echo $dtDateChart1; ?>' +data['labels'][tooltipItem[0]['index']];
                        },
                        label: function(tooltipItem, data) {
                          return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                        },
                    },
                    titleFontSize: 15,
                    bodyFontSize: 15,
                    displayColors: false
                }
            }
        }
     );

     return myChart;

}

in my php file

$out .=  '         <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';

and this is my variable that i want to pass to my .js

         //result chart1
            @mssql_free_result($graph_query2);
            $dtDateChart1 = $dateTittleChart1;
            $convertChart1 = json_encode($datesChart1);
            $totalChart1 = json_encode($nMaxChart1);
            $labelChart1 =  $convertChart1;

i dont know how to pass it when i already succes getelementbyid thanks you if you know something about it that i should know. i dont have a lot knowledge about javascript passing variable.

Body:
You should not have php code inside js files.

What you can do instead is:

Inside the php file pass the values you need to js variables.

Then, use the global js variables or pass them as parameters to js functions.

Alternatively, instead of including the separate charts.js file, have the contents of charts.js in the php file inside a <script> tag. This way you can have php and js sideways as you did.


问:
Basic authentication for website to secure site login and API access
I'm looking at the security model of a website that's being developed. After researching the web i have found that there are several security models to secure websites i.e. Basic Auth, JWT ...

At the moment, SSL is not enabled as still in dev. Website has a login page and communicates via API's (including login and logout). On the login page, as a test, I have attempted to log in with false details, and then I have looked at the developer tools to identify the security mechanism and found the following screenshots. I think the site is using basic authentication, though I noted that the email / password is not encoded and is using a custom login form. Could someone confirm if it is basic authentication being utilised?

Developer Tools Images

[Request Header Image][2]

UPDATE:
I discovered that once the user is authenticated by email/password, I should have posted the screenshots as this is where keys are returned. In the below screenshot a bidder token and bidder secret is sent back to client. I think these are generated through crypto on backend. So I don't think its JWT, but is this a suitable way in creating keys and not sending in header but in response body?

Network tab after user logged in

Login Form Code :

```<code> {

        /* prepare ui */
        progress.classList.remove('hide');
        login_btn.innerText = 'Logging In';
        login_btn.setAttribute('disabled', true);

        /* make http request */
        var http = new XMLHttpRequest();
        var url = SERVER + '/api/bidder/login';
        var body = {
            email: email.value,
            password: password.value
        };

        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/JSON');

        http.onreadystatechange = function () { //Call a function when the state changes.
            if (http.readyState == 4 && http.status == 200) {
                var res = JSON.parse(http.responseText);

                if (res.status) {

                    localStorage.setItem("bidData", JSON.stringify(res.data));
                    window.location.href = window.location.href.replace('login.html','');

                } else {
                    Toast.show('Danger', res.message);
                }

                /* reset ui */
                progress.classList.add('hide');
                login_btn.innerText = 'Log In';
                login_btn.removeAttribute('disabled');

            }
        }
        http.send(JSON.stringify(body));

    }
</code>```

答:
Spring security is the most basic authentication in the Spring project
If you want to enable Spring security, the first thing you must add is the spring security library to your project. After adding it, you create a class to configure Spring security.

A function in the class config for Spring security.

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors()
                .and()
            .csrf()
                .disable()
            .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .authorizeRequests()
                .antMatchers("/",
                    "/api/statistical/**",
                    "/static/**",
                    "/webjars/**",
                    "/img/**",
                    "/css/**",
                    "/js/**",
                    "/api/diary/**")
                    .permitAll()
                .antMatchers("/api/auth/**")
                    .permitAll()
                .antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
                    .permitAll()
                .antMatchers(HttpMethod.GET, "/api/users/**") //, "/api/polls/**"
                    .permitAll()
                .anyRequest()
                    .authenticated();
</code>```

Body:
I'm looking at the security model of a website that's being developed. After researching the web i have found that there are several security models to secure websites i.e. Basic Auth, JWT ...

At the moment, SSL is not enabled as still in dev. Website has a login page and communicates via API's (including login and logout). On the login page, as a test, I have attempted to log in with false details, and then I have looked at the developer tools to identify the security mechanism and found the following screenshots. I think the site is using basic authentication, though I noted that the email / password is not encoded and is using a custom login form. Could someone confirm if it is basic authentication being utilised?

Developer Tools Images

[Request Header Image][2]

UPDATE:
I discovered that once the user is authenticated by email/password, I should have posted the screenshots as this is where keys are returned. In the below screenshot a bidder token and bidder secret is sent back to client. I think these are generated through crypto on backend. So I don't think its JWT, but is this a suitable way in creating keys and not sending in header but in response body?

Network tab after user logged in

Login Form Code :

 {

        /* prepare ui */
        progress.classList.remove('hide');
        login_btn.innerText = 'Logging In';
        login_btn.setAttribute('disabled', true);

        /* make http request */
        var http = new XMLHttpRequest();
        var url = SERVER + '/api/bidder/login';
        var body = {
            email: email.value,
            password: password.value
        };

        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/JSON');

        http.onreadystatechange = function () { //Call a function when the state changes.
            if (http.readyState == 4 && http.status == 200) {
                var res = JSON.parse(http.responseText);

                if (res.status) {

                    localStorage.setItem("bidData", JSON.stringify(res.data));
                    window.location.href = window.location.href.replace('login.html','');

                } else {
                    Toast.show('Danger', res.message);
                }

                /* reset ui */
                progress.classList.add('hide');
                login_btn.innerText = 'Log In';
                login_btn.removeAttribute('disabled');

            }
        }
        http.send(JSON.stringify(body));

    }

Body:
Spring security is the most basic authentication in the Spring project
If you want to enable Spring security, the first thing you must add is the spring security library to your project. After adding it, you create a class to configure Spring security.

A function in the class config for Spring security.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors()
                .and()
            .csrf()
                .disable()
            .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .authorizeRequests()
                .antMatchers("/",
                    "/api/statistical/**",
                    "/static/**",
                    "/webjars/**",
                    "/img/**",
                    "/css/**",
                    "/js/**",
                    "/api/diary/**")
                    .permitAll()
                .antMatchers("/api/auth/**")
                    .permitAll()
                .antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
                    .permitAll()
                .antMatchers(HttpMethod.GET, "/api/users/**") //, "/api/polls/**"
                    .permitAll()
                .anyRequest()
                    .authenticated();


问:
TableView ContentInset does not shrink cell width / Add horizontal padding to TableView contents
I'd like to have a UITableView which is full screen. But the content of the UITableView should have a padding on the left and right.

So I tried to set ContentInset. But now the cells are as wide as the UITableView and the UITableView scrolls horizontally.

Is there a way to say that the UITableView content's width should become narrowed by the horizontal content insets? Or do I have to add the padding to all cells and header/footer views?

I don't want to narrow the table view itself, because the scroll indicator should stay at the right side of the screen and not in the middle.
The here (How to set the width of a cell in a UITableView in grouped style) suggested solution seems to be not as generic as i'd love to, beacuse the cells and header and footer views have to know about the padding (at least 3 places to maintain instead of one)

答:
Set the layout margins of the table view. For this to work make sure your constraints in the cells are set relative to the superview margin.

```<code>tableView.layoutMargins = UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
</code>```

Body:
Set the layout margins of the table view. For this to work make sure your constraints in the cells are set relative to the superview margin.

tableView.layoutMargins = UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)


问:
cannot find module '@angular/http'?
I added the following property to my systemjs.config.js map object in my Angular 2 app:

```<code>'@angular/http': 'https://npmcdn.com/@angular/http'
</code>```

When I ctrl-click on the url it attempts to download a js file. However, when I try to import from '@angular/http' at the top of my service.ts, the compiler returns the error "Cannot find module '@angular/http'.`"

Is there an additional step that I'm missing in order for this module to be recognized and usable by my angular app? I'm using Angular version 2.0.0-rc.4.

答:
@angular/http is deprecated

try this:

```<code>import { HttpClient } from "@angular/common/http";
</code>```

in the constructor:

```<code> constructor(public http: HttpClient) { }
</code>```

Title: cannot find module '@angular/http'?

Body:
I added the following property to my systemjs.config.js map object in my Angular 2 app:

'@angular/http': 'https://npmcdn.com/@angular/http'

When I ctrl-click on the url it attempts to download a js file. However, when I try to import from '@angular/http' at the top of my service.ts, the compiler returns the error "Cannot find module '@angular/http'.`"

Is there an additional step that I'm missing in order for this module to be recognized and usable by my angular app? I'm using Angular version 2.0.0-rc.4.

Body:
@angular/http is deprecated

try this:

import { HttpClient } from "@angular/common/http";

in the constructor:

 constructor(public http: HttpClient) { }


问:
Fill an array with distanced random integers
I need an array to be filled with random integers
Those integers should be very distinct from each other i.e. must at least be 20 units of separation between each items

This is what i have tried so far :

var all = [];
var i = 0;

randomDiff();

function randomDiff() {
    var num1 = randomNumber(10, 290); //chose a first random num in the range...
    all[0] = num1; //...put it in first index of array
    do // until you have 12 items...
    {
        var temp = randomNumber(10, 290); //...you pick a temporary num
        var j;
        for (j = 0; j < all.length; j++) // for each item already in the array
        {
            if ((temp < all[i] - 10) || (temp > all[i] + 10)) // if the temporary num is different enough                                                            from others members...
            {
                all.push(temp); //then you can store it
                i++; //increment until....
                console.log(all[i]);
            }
        }
    }
    while (i < 11) // ...it is filled with 12 items in array
}
////////////Radom in int range function///////////////////////////////////////
function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}
```

but always unsuccessful, including infinite loops...

答:
Here's a solution that will always work, as long as you allow enough room in the range/separation/count you choose. And it's way more efficient than a while loop. It doesn't just keep trying until it gets it right, it actually does the math to make sure it's right the first time.

This comes at the cost of tending to lean towards certain numbers more than others (like from + (i * separation)), so take note of that.

function getSeparatedRadomInts(from, through, separation, count) {
  if(through < from) return getSeparatedRadomInts(through, from, separation, count);
  if(count == 0) return [];
  if(separation == 0) return !!console.log("Please allow enough room in the range/separation/count you choose.");

  //pick values from pool of numbers evenly stepped apart by units of separation... adding 1 to from and through if from is 0 so we can divide properly
  var smallFrom = Math.ceil((from || 1) / separation);
  var smallThrough = Math.floor((through + (from == 0)) / separation);
  var picks = randoSequence(smallFrom, smallThrough).slice(-count).sort((a, b) => a - b);
  if(picks.length < count) return !!console.log("Please allow enough room in the range/separation/count you choose.");
  for (var i = 0; i < picks.length; i++) picks[i] *= separation;

  //go through each pick and randomize with any wiggle room between the numbers above/below it... adding 1 to from and through if from is 0
  for (var i = 0; i < picks.length; i++) {
    var lowerBound = picks[i - 1] + separation || from || 1;
    var upperBound = picks[i + 1] - separation || (through + (from == 0));
    picks[i] = rando(lowerBound, upperBound);
  }

  //subtract 1 from all picks in cases where from is 0 to compensate for adding 1 earlier
  for (var i = 0; i < picks.length; i++) if(from == 0) picks[i] = picks[i] - 1;

  return picks;
}

console.log(getSeparatedRadomInts(10, 290, 20, 12));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://randojs.com/1.0.0.js"></script></code>```

To be clear, from is the minimum range value, through is the maximum range value, separation is the minimum each number must be apart from each other (a separation of 20 could result in [10, 30, 50, 70], for example), and count is how many values you want to pick.

I used randojs in this code to simplify the randomness and make it easier to read, so if you want to use this code, just remember to paste this in the head of your HTML document:

```<code><script src="https://randojs.com/1.0.0.js"></script>
</code>```

Body:
I need an array to be filled with random integers
Those integers should be very distinct from each other i.e. must at least be 20 units of separation between each items

This is what i have tried so far :

var all = [];
var i = 0;

randomDiff();

function randomDiff() {
    var num1 = randomNumber(10, 290); //chose a first random num in the range...
    all[0] = num1; //...put it in first index of array
    do // until you have 12 items...
    {
        var temp = randomNumber(10, 290); //...you pick a temporary num
        var j;
        for (j = 0; j < all.length; j++) // for each item already in the array
        {
            if ((temp < all[i] - 10) || (temp > all[i] + 10)) // if the temporary num is different enough                                                            from others members...
            {
                all.push(temp); //then you can store it
                i++; //increment until....
                console.log(all[i]);
            }
        }
    }
    while (i < 11) // ...it is filled with 12 items in array
}
////////////Radom in int range function///////////////////////////////////////
function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

but always unsuccessful, including infinite loops...

Body:
Here's a solution that will always work, as long as you allow enough room in the range/separation/count you choose. And it's way more efficient than a while loop. It doesn't just keep trying until it gets it right, it actually does the math to make sure it's right the first time.

This comes at the cost of tending to lean towards certain numbers more than others (like from + (i * separation)), so take note of that.

function getSeparatedRadomInts(from, through, separation, count) {
  if(through < from) return getSeparatedRadomInts(through, from, separation, count);
  if(count == 0) return [];
  if(separation == 0) return !!console.log("Please allow enough room in the range/separation/count you choose.");

  //pick values from pool of numbers evenly stepped apart by units of separation... adding 1 to from and through if from is 0 so we can divide properly
  var smallFrom = Math.ceil((from || 1) / separation);
  var smallThrough = Math.floor((through + (from == 0)) / separation);
  var picks = randoSequence(smallFrom, smallThrough).slice(-count).sort((a, b) => a - b);
  if(picks.length < count) return !!console.log("Please allow enough room in the range/separation/count you choose.");
  for (var i = 0; i < picks.length; i++) picks[i] *= separation;

  //go through each pick and randomize with any wiggle room between the numbers above/below it... adding 1 to from and through if from is 0
  for (var i = 0; i < picks.length; i++) {
    var lowerBound = picks[i - 1] + separation || from || 1;
    var upperBound = picks[i + 1] - separation || (through + (from == 0));
    picks[i] = rando(lowerBound, upperBound);
  }

  //subtract 1 from all picks in cases where from is 0 to compensate for adding 1 earlier
  for (var i = 0; i < picks.length; i++) if(from == 0) picks[i] = picks[i] - 1;

  return picks;
}

console.log(getSeparatedRadomInts(10, 290, 20, 12));

<script src="https://randojs.com/1.0.0.js"></script>

To be clear, from is the minimum range value, through is the maximum range value, separation is the minimum each number must be apart from each other (a separation of 20 could result in [10, 30, 50, 70], for example), and count is how many values you want to pick.

I used randojs in this code to simplify the randomness and make it easier to read, so if you want to use this code, just remember to paste this in the head of your HTML document:

<script src="https://randojs.com/1.0.0.js"></script>


问:
Any way to have a real-time preview of AVMutableComposition? If no, how does Final Cut Pro does it?
is it possible to have a real-time preview of AVMutableComposition which has some layer instructions applied to its assets?

The only class I found that connects AVMutableComposition with AVVideoComposition (holding instructions) is AVExportSession. Does it mean I must export it first to play a preview?

If so, how does apps like Final Cut Pro serve real-time preview when I edit part of the video. Do they cut the whole video into multiple chunks, export what has changed and keep change of everything else?

This sounds like a difficult problem - is there any library that would help in cutting video into small chunks to export and keeping an eye on cache invalidation?

Cheers,
M.

答:
I don't know if this is still relevant but you can always extract each frame from the video, manipulate it accordingly then render it to the screen.

If its from AVCaptureSession you can get CMSampleBuffer from the callbacks, if it's a file I think AVReader is your best bet then you can use either CoreImage or Metal to manipulate the frames and render them in real-time.


问:
Validate Regex: min/max characters, one hypen and start/finish conditions
I am trying to create a validation function for usernames.  It must be:

Min six characters / Max 16 characters

Only letters, numbers and, at the most, one hyphen

It must start with a letter and no end with a hyphen

I came up with this regular expression:

```<code>^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$
</code>```

Which does everything but the maximum number of characters.  What am I missing?

You may wonder why I am using 4 to 14: it is because the first and last characters are already defined by the other conditions, so I need the rest to be at least 4 (to make it to six) and at most 14 characters (to make it to 16).

This is a simple validation function in Python:

```<code># Username validation
import re

def validate(username):
    regex = re.compile('^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$', re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Invalid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username
</code>```

Thanks very much for any suggestion.

答:
Try (?i)^(?=[a-z].{5,15}$)[a-z0-9]*-?[a-z0-9]+$

just need to validate length in assertion

demo

Body:
I am trying to create a validation function for usernames.  It must be:

Min six characters / Max 16 characters

Only letters, numbers and, at the most, one hyphen

It must start with a letter and no end with a hyphen

I came up with this regular expression:

^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$

Which does everything but the maximum number of characters.  What am I missing?

You may wonder why I am using 4 to 14: it is because the first and last characters are already defined by the other conditions, so I need the rest to be at least 4 (to make it to six) and at most 14 characters (to make it to 16).

This is a simple validation function in Python:

# Username validation
import re

def validate(username):
    regex = re.compile('^([A-Za-z]+-?[A-Za-z0-9]{4,14}[A-Za-z0-9])$', re.I)
    match = regex.match(str(username))
    return bool(match)

print(validate("PeterParker")) #Valid username
print(validate("Peter-Parker")) #Valid username
print(validate("Peter-P-arker")) #Invalid username
print(validate("Peter")) #Invalid username
print(validate("PeterParker-")) #Invalid username
print(validate("-PeterParker")) #Invalid username
print(validate("1PeterParker")) #Invalid username
print(validate("Peter Parker")) #Invalid username
print(validate("PeterParkerSpiderMan")) #Invalid username

Thanks very much for any suggestion.


问:
Angular shuffle array elements of two ngFor loops
i am try to build Angular project ,  i have tow different API news sources . l want to display the tow API news as randomly like :

element news 1

element news 2

element news 1

element news 2

But what i have in my code below is

element news 1 loop

element news 2 loop

news.ts

```<code> news_one_array:any
 news_tow_array:any

ngOnInit() {

this.news_one()
this.news_tow()
}

async news_one() {
    this.http.get("/nodes/25/iq/0/20/xlarge")
      .pipe(timeout(5000),
        catchError(err => {
          console.log(err)
          return Observable.throw("Timeout has occurred");
        })).subscribe(data => {

          this.news_one_array = data
        })

  }

  async news_tow() {
    this.http.get("/nodes/25/iq/0/21/xlarge")
      .pipe(timeout(5000),
        catchError(err => {
          console.log(err)
          return Observable.throw("Timeout has occurred");
        })).subscribe(data => {

          this.news_tow_array = data
        })

  }
</code>```

HTML  :

```<code>// *ngfor news 1

<div *ngFor="let items of news_one_array; let i=index">
<p>{{items.title}}</p>
</div>

// *ngfor news 2
<div *ngFor="let items of news_tow_array; let i=index">
<p>{{items.title}}</p>
</div>
</code>```

output :

答:
You can use map function to combine two arrays into a single array of objects as follows.

```<code>    listA = [1, 2, 3 , 4];
    listB = ['a', 'b', 'c']
    this.combined = this.listA.map((x, i)=> {
          return {"a": x, "b": this.listB[i]}
    } );
</code>```

And then use it in the html. For uneven arrays, use *ngIf to check null/undefined.

```<code><div *ngFor="let item of combined">
    {{item.a}}
    {{item.b}}
</div>
</code>```

Body:
i am try to build Angular project ,  i have tow different API news sources . l want to display the tow API news as randomly like :

element news 1

element news 2

element news 1

element news 2

But what i have in my code below is

element news 1 loop

element news 2 loop

news.ts

 news_one_array:any
 news_tow_array:any

ngOnInit() {

this.news_one()
this.news_tow()
}

async news_one() {
    this.http.get("/nodes/25/iq/0/20/xlarge")
      .pipe(timeout(5000),
        catchError(err => {
          console.log(err)
          return Observable.throw("Timeout has occurred");
        })).subscribe(data => {

          this.news_one_array = data
        })

  }

  async news_tow() {
    this.http.get("/nodes/25/iq/0/21/xlarge")
      .pipe(timeout(5000),
        catchError(err => {
          console.log(err)
          return Observable.throw("Timeout has occurred");
        })).subscribe(data => {

          this.news_tow_array = data
        })

  }

HTML  :

// *ngfor news 1

{{items.title}}

// *ngfor news 2

{{items.title}}

output :

Body:
You can use map function to combine two arrays into a single array of objects as follows.

    listA = [1, 2, 3 , 4];
    listB = ['a', 'b', 'c']
    this.combined = this.listA.map((x, i)=> {
          return {"a": x, "b": this.listB[i]}
    } );

And then use it in the html. For uneven arrays, use *ngIf to check null/undefined.

<div *ngFor="let item of combined">
    {{item.a}}
    {{item.b}}
</div>


问:
Faster and more efficient python method for fuzzy matching substrings
I want the program to search for all occurrences of crocodile, etc with fuzzy matching i.e. If there are any spelling mistakes, it should count those words as well.

```<code>s="Difference between a crocodile and an alligator is......." #Long paragraph, >10000 words
to_search=["crocodile","insect","alligator"]

for i in range(len(to_search)):
    for j in range(len(s)):
        a = s[j:j+len(to_search[i])]
        match = difflib.SequenceMatcher(None,a,to_search[I]).ratio()
        if(match>0.9): #90% similarity
            print(a)
</code>```

So all of the following should be considered as instances of "crocodile": "crocodile","crocodil","crocodele",etc

The above method works but is too slow if the main string ("s" here) is of large size like >1million words.
Is there any way to do this that's faster than the above method**?

**(splitting the string into sub-string sized blocks and then comparing sub-string with reference word)

答:
One of the reasons it takes too long on a large body of text is that you are repeating the sliding window through the entire text multiple times, once for each words you are searching for. And a lot of the computation is on comparing your words to blocks of the same length which might contain parts of multiple words.

If you are willing to posit that you are always looking to match individual words, you could split the text into words and just compare against the words - far fewer comparisons (number of words, vs. windows starting at every position in the text), and the splitting only needs to be done once, not for every search term. Here's an example:

```<code>to_search= ["crocodile", "insect", "alligator"]
s = "Difference between a crocodile and an alligator is" #Long paragraph, >10000 words
s_words = s.replace(".", " ").split(" ") # Split on spaces, with periods removed
for search_for in to_search:
    for s_word in s_words:
        match = difflib.SequenceMatcher(None, s_word, search_for).ratio()
        if(match > 0.9):  #90% similarity
            print(s_word)
            continue      # no longer need to continue the search for this word!
</code>```

This should give you significant speedup, hope it solves your needs!

Happy Coding!

Body:
I want the program to search for all occurrences of crocodile, etc with fuzzy matching i.e. If there are any spelling mistakes, it should count those words as well.

s="Difference between a crocodile and an alligator is......." #Long paragraph, >10000 words
to_search=["crocodile","insect","alligator"]

for i in range(len(to_search)):
    for j in range(len(s)):
        a = s[j:j+len(to_search[i])]
        match = difflib.SequenceMatcher(None,a,to_search[I]).ratio()
        if(match>0.9): #90% similarity
            print(a)

So all of the following should be considered as instances of "crocodile": "crocodile","crocodil","crocodele",etc

The above method works but is too slow if the main string ("s" here) is of large size like >1million words.
Is there any way to do this that's faster than the above method**?

**(splitting the string into sub-string sized blocks and then comparing sub-string with reference word)

Body:
One of the reasons it takes too long on a large body of text is that you are repeating the sliding window through the entire text multiple times, once for each words you are searching for. And a lot of the computation is on comparing your words to blocks of the same length which might contain parts of multiple words.

If you are willing to posit that you are always looking to match individual words, you could split the text into words and just compare against the words - far fewer comparisons (number of words, vs. windows starting at every position in the text), and the splitting only needs to be done once, not for every search term. Here's an example:

to_search= ["crocodile", "insect", "alligator"]
s = "Difference between a crocodile and an alligator is" #Long paragraph, >10000 words
s_words = s.replace(".", " ").split(" ") # Split on spaces, with periods removed
for search_for in to_search:
    for s_word in s_words:
        match = difflib.SequenceMatcher(None, s_word, search_for).ratio()
        if(match > 0.9):  #90% similarity
            print(s_word)
            continue      # no longer need to continue the search for this word!

This should give you significant speedup, hope it solves your needs!

Happy Coding!


问:
Any way to produce route values instead of query arguments when submitting a form?
I have the following form.

```<code><form method="get">
    <div class="row">
        <div class="col-md-4">
            <div class="form-group">
                <select asp-for="@Model.MonthCode" asp-items="@Model.InvoiceDates" class="form-control">
                </select>
            </div>
        </div>
        <div class="col-md-4">
            <div class="form-group">
                <button type="submit" class="btn btn-success">Update</button>
            </div>
        </div>
    </div>
</form>
</code>```

I'm using the get method (instead of post) because I don't want to have to duplicate all my OnGetAsync() logic in OnPostAsync(). The two methods would do exactly the same thing. This way, I don't need OnPostAsync().

However, the downside is that the data is passed as a query argument.

```<code>https://localhost:44322/Invoices?MonthCode=24243
</code>```

And I would much prefer the URL:

```<code>https://localhost:44322/Invoices/24243
</code>```

Is there any way to have this code produce the second URL? I prefer my users don't get a description of what the arguments are.

答:
Put the route parameter name at the top of razor page .cshtml side:

```<code>@page "{MonthCode}"
</code>```

and on the backend the property can be defined as:

[BindProperty(SupportsGet=true)]
public int MonthCode { get; set; }
```

Body:
I have the following form.

<form method="get">

                <select asp-for="@Model.MonthCode" asp-items="@Model.InvoiceDates" class="form-control">
                </select>

                <button type="submit" class="btn btn-success">Update</button>

</form>

I'm using the get method (instead of post) because I don't want to have to duplicate all my OnGetAsync() logic in OnPostAsync(). The two methods would do exactly the same thing. This way, I don't need OnPostAsync().

However, the downside is that the data is passed as a query argument.

https://localhost:44322/Invoices?MonthCode=24243

And I would much prefer the URL:

https://localhost:44322/Invoices/24243

Is there any way to have this code produce the second URL? I prefer my users don't get a description of what the arguments are.

Body:
Put the route parameter name at the top of razor page .cshtml side:

@page "{MonthCode}"

and on the backend the property can be defined as:

[BindProperty(SupportsGet=true)]
public int MonthCode { get; set; }


问:
Lost a row after saving excel as txt (check with wc -l)
I have an excel file with 3 rows which I saved as txt. In the terminal, I checked the number of row of the saved txt using wc -l, and it showed 2. I opened the txt file and I can see it is still three rows...Why is that?

答:
The problem is that wc -l probably is counting \n characters (new line characters) and a file that has three lines but does not end its last line with a new line has only two new lines at all... This is common with tools (like Excel) on exporting as text files... probably if you open the file with an editor, it will notice you that the file does not end in a new line char (or that it lacks a newline on the last line) and when you close it, the editor adds it to the file.

The convention forces to end text lines with an end of line terminator (be it an ASCII CR, an ASCII LF, or a pair ASCII CR ASCII LF, depending on the operating system) but as a convention, can be followed or not.  Microsoft has always famous for driving on the left side (please pardon me, english men) and trying to establish their own conventions, so you can thing that a N lines text file can have N or N-1 line terminator chars.


问:
What is the & operating doing in this situation
In the function below, what is the meaning of the & character? I'm not aware how it's valid syntax or how this would be used normally.

Normally using &= together would do a concatenation and assignment, resulting in "Hello world". However in this "typo" the code actually compiles but the result is just an assignment of " world" to the MyStr variable.  Also if you define MyStr in the function rather than at the class level, the result is that it will not compile and interprets the & as a Type Character and fails because MyStr is a string and not of type Long.

```<code>Public Class MyClassName

    Private MyStr As String

    Public Sub New()

    End Sub

    Public Function MyFunction() As String

        MyStr = "Hello"

        MyStr& = " World"

        Return MyStr

    End Function

End Class
</code>```

答:
As you mention, the & is acting as a type character. Type characters are essentially just a shorthand for declaring the type of a variable. For example, you could use

dim value& = 100 rather than dim value as Long = 100

They are generally used when defining a value on the fly, such as when passing a value to a function:

dim result = funcThatTakesALong(100&)

You can also see in the link that you posted there are also type characters for integers (%), decimals (@), singles (!), doubles (#), and strings ($).

Edit: formatting

Body:
In the function below, what is the meaning of the & character? I'm not aware how it's valid syntax or how this would be used normally.

Normally using &= together would do a concatenation and assignment, resulting in "Hello world". However in this "typo" the code actually compiles but the result is just an assignment of " world" to the MyStr variable.  Also if you define MyStr in the function rather than at the class level, the result is that it will not compile and interprets the & as a Type Character and fails because MyStr is a string and not of type Long.

Public Class MyClassName

    Private MyStr As String

    Public Sub New()

    End Sub

    Public Function MyFunction() As String

        MyStr = "Hello"

        MyStr& = " World"

        Return MyStr

    End Function

End Class