问:
How to run a simple php hello world application using Kubernetes
I'm trying to deploy and run a simple PHP application that will only show a Hello World message through my Kubernetes cluster which is only a master node cluster, unfortunately, I can't do that.

I'm describing my project structure -
I have a root project directory called kubernetes-test and under that directory, I have 3 yaml files and one directory called code under that directory I have a PHP file called index.php

hello-world-service.yaml:

```<code>apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    tier: backend
spec:
  selector:
    app: nginx
    tier: backend
  type: NodePort
  ports:
  - nodePort: 30500
    port: 80
    targetPort: 80
</code>```

nginx-deployment.yaml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    tier: backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
      tier: backend
  template:
    metadata:
      labels:
        app: nginx
        tier: backend
    spec:
      volumes:
      - name: code
        hostPath:
          path: /code
      - name: config
        configMap:
          name: nginx-config
          items:
          - key: config
            path: site.conf
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
        volumeMounts:
        - name: code
          mountPath: /var/www/html
        - name: config
          mountPath: /etc/nginx/conf.d
</code>```

php-deployment.yaml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: php
  labels:
    tier: backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: php
      tier: backend
  template:
    metadata:
      labels:
        app: php
        tier: backend
    spec:
      volumes:
      - name: code
        hostPath:
          path: /code
      containers:
      - name: php
        image: php:7-fpm
        volumeMounts:
        - name: code
          mountPath: /var/www/html
</code>```

code/index.php

```<code><?php
  echo 'Hello World';
</code>```

Above all those things I've found through the internet.

When I ran this command kubectl get pods
then the status is showing ContainerCreating forever for the Nginx deployment like this

```<code>NAME                    READY   STATUS              RESTARTS   AGE
nginx-64c9df788f-jxwzx   0/1     ContainerCreating    0          12h
php-55f974bb4-qvv9x      1/1     Running              0          25s
</code>```

Command: kubectl describe pod nginx-64c9df788f-jxwzx

Output:

```<code>Name:           nginx-64c9df788f-jxwzx
Namespace:      default
Priority:       0
Node:           bablu-node/192.168.43.123
Start Time:     Mon, 11 May 2020 03:20:58 +0600
Labels:         app=nginx
                pod-template-hash=64c9df788f
                tier=backend
Annotations:    <none>
Status:         Pending
IP:
IPs:            <none>
Controlled By:  ReplicaSet/nginx-64c9df788f
Containers:
  nginx:
    Container ID:
    Image:          nginx
    Image ID:
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /etc/nginx/conf.d from config (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-l2zp2 (ro)
      /var/www/html from code (rw)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  code:
    Type:          HostPath (bare host directory volume)
    Path:          /code
    HostPathType:
  config:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      nginx-config
    Optional:  false
  default-token-l2zp2:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-l2zp2
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason       Age                    From                 Message
  ----     ------       ----                   ----                 -------
  Warning  FailedMount  31m (x14 over 147m)    kubelet, bablu-node  Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[default-token-l2zp2 code config]: timed out waiting for the condition
  Warning  FailedMount  16m (x82 over 167m)    kubelet, bablu-node  MountVolume.SetUp failed for volume "config" : configmap "nginx-config" not found
  Warning  FailedMount  6m53s (x44 over 165m)  kubelet, bablu-node  Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[code config default-token-l2zp2]: timed out waiting for the condition
  Warning  FailedMount  2m23s (x10 over 163m)  kubelet, bablu-node  Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[config default-token-l2zp2 code]: timed out waiting for the condition
</code>```

Command: kubectl get events -n default

Output:

```<code>LAST SEEN   TYPE      REASON              OBJECT                       MESSAGE
18m         Warning   FailedMount         pod/nginx-64c9df788f-jxwzx   MountVolume.SetUp failed for volume "config" : configmap "nginx-config" not found
8m45s       Warning   FailedMount         pod/nginx-64c9df788f-jxwzx   Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[code config default-token-l2zp2]: timed out waiting for the condition
4m15s       Warning   FailedMount         pod/nginx-64c9df788f-jxwzx   Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[config default-token-l2zp2 code]: timed out waiting for the condition
33m         Warning   FailedMount         pod/nginx-64c9df788f-jxwzx   Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[default-token-l2zp2 code config]: timed out waiting for the condition
18m         Normal    Scheduled           pod/php-55f974bb4-qvv9x      Successfully assigned default/php-55f974bb4-qvv9x to bablu-node
18m         Normal    Pulled              pod/php-55f974bb4-qvv9x      Container image "php:7-fpm" already present on machine
18m         Normal    Created             pod/php-55f974bb4-qvv9x      Created container php
18m         Normal    Started             pod/php-55f974bb4-qvv9x      Started container php
18m         Normal    SuccessfulCreate    replicaset/php-55f974bb4     Created pod: php-55f974bb4-qvv9x
18m         Normal    ScalingReplicaSet   deployment/php               Scaled up replica set php-55f974bb4 to 1
</code>```

Can anyone please help me?
Thanks in advance!!

答:
I ran your environment and here are the main issues I found:

First of all, you don't have the nginx-config deployed, but this would be only your first issue and easily addressable (more on the example below).

The second (and on my opinion the main) issue, is the usage of HostPath:

As I explained here HostPath requires that the container process run as root.

php-fpm runs as www-data therefore he cannot use the mount files at /code if this folder is mounted through hostPath.

From here our options now are:

Bake the php file inside the image (or as a configmap) and run both nginx and php in the same pod (sharing an emptydir folder), more about this process in this guide: PHP-FPM, Nginx, Kubernetes, and Docker - while in one hand it involves creating a new Docker image, on the other hand it spare you of configuring a storage provisioner if you don't already have one.

Use an external storage to mount the file in a Persistent Volume downloading the php file from an external repository. This approach requires nginx and php to run on the same node - because storage is RWO, meaning that can be mount as read-write on only one node. Since your setup is on a single node, I'll use this approach on this example.

I tried to reproduce as close as your example, but I had to do some changes.
Here are the files:

cm-nginx.yaml:

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
  labels:
    tier: backend
data:
  config : |
    server {
      index index.php index.html;
      error_log  /var/log/nginx/error.log;
      access_log /var/log/nginx/access.log;

      root /code;

      location / {
          try_files $uri $uri/ /index.php?$query_string;
      }

      location ~ \.php$ {
          try_files $uri =404;
          fastcgi_split_path_info ^(.+\.php)(/.+)$;
          fastcgi_pass php:9000;
          fastcgi_index index.php;
          include fastcgi_params;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          fastcgi_param PATH_INFO $fastcgi_path_info;
        }
    }
</code>```

root /code is pointing the directory where to look for index.php

fastcgi_pass php:9000 pointing to the service called php service listening on port 9000.

Storage:

This is mutable depending on the storage type you are using. Minikube comes with storage provider and storageclass configured out of the box. And although minikube storage provider is called minikube-hostpath it's a CSI that will not require root access on container level to run.

That being said, here is the pvc.yaml:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: code
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
  storageClassName: standard
</code>```

Note that standard is the name of the dynamic storage provider built in minikube. What we are doing here is to create a PVC called code for our app to run.

php.yaml:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: php
  labels:
    tier: backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: php
      tier: backend
  template:
    metadata:
      labels:
        app: php
        tier: backend
    spec:
      volumes:
      - name: code
        persistentVolumeClaim:
          claimName: code
      containers:
      - name: php
        image: php:7-fpm
        volumeMounts:
        - name: code
          mountPath: /code
      initContainers:
      - name: install
        image: busybox
        volumeMounts:
        - name: code
          mountPath: /code
        command:
        - wget
        - "-O"
        - "/code/index.php"
        - https://raw.githubusercontent.com/videofalls/demo/master/index.php
</code>```

here we are using a busybox initContainer to wget this php file (which is identical to the one you are using) and save it inside the mounted volume /code.

PHP service svc-php.yaml:

```<code>apiVersion: v1
kind: Service
metadata:
  name: php
  labels:
    tier: backend
spec:
  selector:
    app: php
    tier: backend
  ports:
  - protocol: TCP
    port: 9000
</code>```

The Nginx deployment nginx.yaml:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    tier: backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
      tier: backend
  template:
    metadata:
      labels:
        app: nginx
        tier: backend
    spec:
      volumes:
      - name: code
        persistentVolumeClaim:
          claimName: code
      - name: config
        configMap:
          name: nginx-config
          items:
          - key: config
            path: site.conf
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
        volumeMounts:
        - name: code
          mountPath: /code
        - name: config
          mountPath: /etc/nginx/conf.d
</code>```

The key points here, is the mount of the PVC called code on mountPath /code and the configmap we created being monted as a file called site.conf inside the folder /etc/nginx/conf.d

The Nginx service svc-nginx.yaml:

```<code>apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    tier: backend
spec:
  type: NodePort
  selector:
    app: nginx
    tier: backend
  ports:
  - protocol: TCP
    port: 80
</code>```

I'm using NodePort to ease the output test.

Reproduction:

Let's create the files: first the configmap and pvc, since they are required for the pods to start correctly, then the services and deployments:

```<code>$ ls
cm-nginx.yaml  nginx.yaml  php.yaml  pvc.yaml  svc-nginx.yaml  svc-php.yaml

$ kubectl apply -f cm-nginx.yaml
configmap/nginx-config created

$ kubectl apply -f pvc.yaml
persistentvolumeclaim/code created

$ kubectl get cm
NAME           DATA   AGE
nginx-config   1      52s

$ kubectl get pvc
NAME   STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
code   Bound    pvc-b63559a0-a306-46f2-942b-0a063bc4ab6b   1Gi        RWO            standard       17s

$ kubectl apply -f svc-php.yaml
service/php created

$ kubectl apply -f svc-nginx.yaml
service/nginx created

$ kubectl apply -f php.yaml
deployment.apps/php created

$ kubectl get pods
NAME                   READY   STATUS    RESTARTS   AGE
php-69d5c956ff-8tjfn   1/1     Running   0          5s

$ kubectl apply -f nginx.yaml
deployment.apps/nginx created

$ kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6854dcb7db-75zxt   1/1     Running   0          4s
php-69d5c956ff-8tjfn     1/1     Running   0          22s

$ kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
nginx        NodePort    10.107.16.212   <none>        80:31017/TCP   41s
php          ClusterIP   10.97.237.214   <none>        9000/TCP       44s

$ minikube service nginx --url
http://172.17.0.2:31017

$ curl -i http://172.17.0.2:31017
HTTP/1.1 200 OK
Server: nginx/1.7.9
Date: Thu, 28 May 2020 19:04:48 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/7.4.6

Demo Test
</code>```

Here we can see the curl returned 200 OK from nginx server, powered by PHP 7 and the content of the index.php file.

I hope it helps you have a clearer understanding of this scenario.

If you have any question, let me know in the comments.

Body:
I'm trying to deploy and run a simple PHP application that will only show a Hello World message through my Kubernetes cluster which is only a master node cluster, unfortunately, I can't do that.

I'm describing my project structure -
I have a root project directory called kubernetes-test and under that directory, I have 3 yaml files and one directory called code under that directory I have a PHP file called index.php

hello-world-service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    tier: backend
spec:
  selector:
    app: nginx
    tier: backend
  type: NodePort
  ports:
  - nodePort: 30500
    port: 80
    targetPort: 80

nginx-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    tier: backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
      tier: backend
  template:
    metadata:
      labels:
        app: nginx
        tier: backend
    spec:
      volumes:
      - name: code
        hostPath:
          path: /code
      - name: config
        configMap:
          name: nginx-config
          items:
          - key: config
            path: site.conf
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
        volumeMounts:
        - name: code
          mountPath: /var/www/html
        - name: config
          mountPath: /etc/nginx/conf.d

php-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: php
  labels:
    tier: backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: php
      tier: backend
  template:
    metadata:
      labels:
        app: php
        tier: backend
    spec:
      volumes:
      - name: code
        hostPath:
          path: /code
      containers:
      - name: php
        image: php:7-fpm
        volumeMounts:
        - name: code
          mountPath: /var/www/html

code/index.php

<?php
  echo 'Hello World';

Above all those things I've found through the internet.

When I ran this command kubectl get pods
then the status is showing ContainerCreating forever for the Nginx deployment like this

NAME                    READY   STATUS              RESTARTS   AGE
nginx-64c9df788f-jxwzx   0/1     ContainerCreating    0          12h
php-55f974bb4-qvv9x      1/1     Running              0          25s

Command: kubectl describe pod nginx-64c9df788f-jxwzx

Output:

Name:           nginx-64c9df788f-jxwzx
Namespace:      default
Priority:       0
Node:           bablu-node/192.168.43.123
Start Time:     Mon, 11 May 2020 03:20:58 +0600
Labels:         app=nginx
                pod-template-hash=64c9df788f
                tier=backend
Annotations:    <none>
Status:         Pending
IP:
IPs:            <none>
Controlled By:  ReplicaSet/nginx-64c9df788f
Containers:
  nginx:
    Container ID:
    Image:          nginx
    Image ID:
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /etc/nginx/conf.d from config (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-l2zp2 (ro)
      /var/www/html from code (rw)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  code:
    Type:          HostPath (bare host directory volume)
    Path:          /code
    HostPathType:
  config:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      nginx-config
    Optional:  false
  default-token-l2zp2:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-l2zp2
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason       Age                    From                 Message
  ----     ------       ----                   ----                 -------
  Warning  FailedMount  31m (x14 over 147m)    kubelet, bablu-node  Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[default-token-l2zp2 code config]: timed out waiting for the condition
  Warning  FailedMount  16m (x82 over 167m)    kubelet, bablu-node  MountVolume.SetUp failed for volume "config" : configmap "nginx-config" not found
  Warning  FailedMount  6m53s (x44 over 165m)  kubelet, bablu-node  Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[code config default-token-l2zp2]: timed out waiting for the condition
  Warning  FailedMount  2m23s (x10 over 163m)  kubelet, bablu-node  Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[config default-token-l2zp2 code]: timed out waiting for the condition

Command: kubectl get events -n default

Output:

LAST SEEN   TYPE      REASON              OBJECT                       MESSAGE
18m         Warning   FailedMount         pod/nginx-64c9df788f-jxwzx   MountVolume.SetUp failed for volume "config" : configmap "nginx-config" not found
8m45s       Warning   FailedMount         pod/nginx-64c9df788f-jxwzx   Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[code config default-token-l2zp2]: timed out waiting for the condition
4m15s       Warning   FailedMount         pod/nginx-64c9df788f-jxwzx   Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[config default-token-l2zp2 code]: timed out waiting for the condition
33m         Warning   FailedMount         pod/nginx-64c9df788f-jxwzx   Unable to attach or mount volumes: unmounted volumes=[config], unattached volumes=[default-token-l2zp2 code config]: timed out waiting for the condition
18m         Normal    Scheduled           pod/php-55f974bb4-qvv9x      Successfully assigned default/php-55f974bb4-qvv9x to bablu-node
18m         Normal    Pulled              pod/php-55f974bb4-qvv9x      Container image "php:7-fpm" already present on machine
18m         Normal    Created             pod/php-55f974bb4-qvv9x      Created container php
18m         Normal    Started             pod/php-55f974bb4-qvv9x      Started container php
18m         Normal    SuccessfulCreate    replicaset/php-55f974bb4     Created pod: php-55f974bb4-qvv9x
18m         Normal    ScalingReplicaSet   deployment/php               Scaled up replica set php-55f974bb4 to 1

Can anyone please help me?
Thanks in advance!!

Body:
I ran your environment and here are the main issues I found:

First of all, you don't have the nginx-config deployed, but this would be only your first issue and easily addressable (more on the example below).

The second (and on my opinion the main) issue, is the usage of HostPath:

As I explained here HostPath requires that the container process run as root.

php-fpm runs as www-data therefore he cannot use the mount files at /code if this folder is mounted through hostPath.

From here our options now are:

Bake the php file inside the image (or as a configmap) and run both nginx and php in the same pod (sharing an emptydir folder), more about this process in this guide: PHP-FPM, Nginx, Kubernetes, and Docker - while in one hand it involves creating a new Docker image, on the other hand it spare you of configuring a storage provisioner if you don't already have one.

Use an external storage to mount the file in a Persistent Volume downloading the php file from an external repository. This approach requires nginx and php to run on the same node - because storage is RWO, meaning that can be mount as read-write on only one node. Since your setup is on a single node, I'll use this approach on this example.

I tried to reproduce as close as your example, but I had to do some changes.
Here are the files:

cm-nginx.yaml:

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
  labels:
    tier: backend
data:
  config : |
    server {
      index index.php index.html;
      error_log  /var/log/nginx/error.log;
      access_log /var/log/nginx/access.log;

      root /code;

      location / {
          try_files $uri $uri/ /index.php?$query_string;
      }

      location ~ \.php$ {
          try_files $uri =404;
          fastcgi_split_path_info ^(.+\.php)(/.+)$;
          fastcgi_pass php:9000;
          fastcgi_index index.php;
          include fastcgi_params;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          fastcgi_param PATH_INFO $fastcgi_path_info;
        }
    }

root /code is pointing the directory where to look for index.php

fastcgi_pass php:9000 pointing to the service called php service listening on port 9000.

Storage:

This is mutable depending on the storage type you are using. Minikube comes with storage provider and storageclass configured out of the box. And although minikube storage provider is called minikube-hostpath it's a CSI that will not require root access on container level to run.

That being said, here is the pvc.yaml:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: code
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
  storageClassName: standard

Note that standard is the name of the dynamic storage provider built in minikube. What we are doing here is to create a PVC called code for our app to run.

php.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: php
  labels:
    tier: backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: php
      tier: backend
  template:
    metadata:
      labels:
        app: php
        tier: backend
    spec:
      volumes:
      - name: code
        persistentVolumeClaim:
          claimName: code
      containers:
      - name: php
        image: php:7-fpm
        volumeMounts:
        - name: code
          mountPath: /code
      initContainers:
      - name: install
        image: busybox
        volumeMounts:
        - name: code
          mountPath: /code
        command:
        - wget
        - "-O"
        - "/code/index.php"
        - https://raw.githubusercontent.com/videofalls/demo/master/index.php

here we are using a busybox initContainer to wget this php file (which is identical to the one you are using) and save it inside the mounted volume /code.

PHP service svc-php.yaml:

apiVersion: v1
kind: Service
metadata:
  name: php
  labels:
    tier: backend
spec:
  selector:
    app: php
    tier: backend
  ports:
  - protocol: TCP
    port: 9000

The Nginx deployment nginx.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    tier: backend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
      tier: backend
  template:
    metadata:
      labels:
        app: nginx
        tier: backend
    spec:
      volumes:
      - name: code
        persistentVolumeClaim:
          claimName: code
      - name: config
        configMap:
          name: nginx-config
          items:
          - key: config
            path: site.conf
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
        volumeMounts:
        - name: code
          mountPath: /code
        - name: config
          mountPath: /etc/nginx/conf.d

The key points here, is the mount of the PVC called code on mountPath /code and the configmap we created being monted as a file called site.conf inside the folder /etc/nginx/conf.d

The Nginx service svc-nginx.yaml:

apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    tier: backend
spec:
  type: NodePort
  selector:
    app: nginx
    tier: backend
  ports:
  - protocol: TCP
    port: 80

I'm using NodePort to ease the output test.

Reproduction:

Let's create the files: first the configmap and pvc, since they are required for the pods to start correctly, then the services and deployments:

$ ls
cm-nginx.yaml  nginx.yaml  php.yaml  pvc.yaml  svc-nginx.yaml  svc-php.yaml

$ kubectl apply -f cm-nginx.yaml
configmap/nginx-config created

$ kubectl apply -f pvc.yaml
persistentvolumeclaim/code created

$ kubectl get cm
NAME           DATA   AGE
nginx-config   1      52s

$ kubectl get pvc
NAME   STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   AGE
code   Bound    pvc-b63559a0-a306-46f2-942b-0a063bc4ab6b   1Gi        RWO            standard       17s

$ kubectl apply -f svc-php.yaml
service/php created

$ kubectl apply -f svc-nginx.yaml
service/nginx created

$ kubectl apply -f php.yaml
deployment.apps/php created

$ kubectl get pods
NAME                   READY   STATUS    RESTARTS   AGE
php-69d5c956ff-8tjfn   1/1     Running   0          5s

$ kubectl apply -f nginx.yaml
deployment.apps/nginx created

$ kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-6854dcb7db-75zxt   1/1     Running   0          4s
php-69d5c956ff-8tjfn     1/1     Running   0          22s

$ kubectl get svc
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
nginx        NodePort    10.107.16.212   <none>        80:31017/TCP   41s
php          ClusterIP   10.97.237.214   <none>        9000/TCP       44s

$ minikube service nginx --url
http://172.17.0.2:31017

$ curl -i http://172.17.0.2:31017
HTTP/1.1 200 OK
Server: nginx/1.7.9
Date: Thu, 28 May 2020 19:04:48 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/7.4.6

Demo Test

Here we can see the curl returned 200 OK from nginx server, powered by PHP 7 and the content of the index.php file.

I hope it helps you have a clearer understanding of this scenario.

If you have any question, let me know in the comments.


来源: stackexchange

问:
Install dotnet ef success but when call it hit error
Error: A fatal error occurred. The required library libhostfxr.so could not be found. If this is a self-contained application, that library should exist in [/home/alanee/.dotnet/tools/.store/dotnet-ef/3.1.3/dotnet-ef/3.1.3/tools/netcoreapp3.1/any/]. If this is a framework-dependent application, install the runtime in the global location [/usr/share/dotnet] or use the DOTNET_ROOT environment variable to specify the runtime location or register the runtime location in [/etc/dotnet/install_location].

The .NET Core runtime can be found at: - https://aka.ms/dotnet-core-applaunch?missing_runtime=true&arch=x64&rid=ubuntu.20.04-x64

My current dotnet info is: .NET Core SDK (reflecting any global.json): Version: 3.1.201 Commit: b1768b4ae7

Runtime Environment: OS Name: ubuntu OS Version: 20.04 OS Platform: Linux RID: linux-x64 Base Path: /snap/dotnet-sdk/69/sdk/3.1.201/

Host (useful for support): Version: 3.1.3 Commit: 4a9f85e9f8

.NET Core SDKs installed: 3.1.201 [/snap/dotnet-sdk/69/sdk]

.NET Core runtimes installed: Microsoft.AspNetCore.App 3.1.3 [/snap/dotnet-sdk/69/shared/Microsoft.AspNetCore.App] Microsoft.NETCore.App 3.1.3 [/snap/dotnet-sdk/69/shared/Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs: https://aka.ms/dotnet-download

答:
make the configuration below and use the latest version of dotnet-ef:</p>

```<code>export PATH="$PATH:$HOME/.dotnet/tools"
export DOTNET_ROOT=/snap/dotnet-sdk/current
export MSBuildSDKsPath=$DOTNET_ROOT/sdk/$(${DOTNET_ROOT}/dotnet --version)/Sdks
export PATH="${PATH}:${DOTNET_ROOT}"
export PATH="$PATH:$HOME/.dotnet/tools"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
make the configuration below and use the latest version of dotnet-ef:

export PATH="$PATH:$HOME/.dotnet/tools"
export DOTNET_ROOT=/snap/dotnet-sdk/current
export MSBuildSDKsPath=$DOTNET_ROOT/sdk/$(${DOTNET_ROOT}/dotnet --version)/Sdks
export PATH="${PATH}:${DOTNET_ROOT}"
export PATH="$PATH:$HOME/.dotnet/tools"


问:
Using WebSockets... Efficiently?
I've read pretty much every guide and tutorial I can find on WebSockets, but not one of them has covered how to use them efficiently. </p>

<p>Does anyone have any sort of guide on how to do this? I'm concerned about the amount of bandwidth a single connection can take up, especially when applications have hundrends of connections opened. </p>

答:
The efficiency in WebSocket depends on the implementation and architecture of the webserver that handles them. WebSocket is a very efficient protocol with only 2 byte (!) overhead, compare to the all different HTTP header fields and HTTP cookies that is sent in every Ajax request.

Usually an efficient webserver for websockets should be event driven (see the examples below). In opposite, the traditional way to implement web servers have been to spawn a new thread per request. But threads allocate much memory e.g. 256MB per thread. So if you have 1GB memory on your server you can't handle very many requests concurrently. But if your server is event-driven your memory usage will be almost constant, since new threads aren't created. See also Technically why is processes in Erlang more efficient than OS threads?

You can send any data in your WebSockets. JSON is efficient if the client is a web browser, or maybe typed arrays. If your client is a custom application, you can use Protocol Buffers. See also Google Wave Client-Server Protocol Whitepaper

You can implement efficient websocket servers using Twisted (Python) or Netty (Java). Play Framework is an efficient web framework for Java and Scala implemented on Netty. Another efficient alternative is Yaws web server (Erlang) or Node.js + Socket.io (JavaScript).

As an application developer, the less data you send the more efficient (less traffic) and the less load on your server.

ContentLicense: CC BY-SA 3.0

Title: Using WebSockets... Efficiently?

Body:
I've read pretty much every guide and tutorial I can find on WebSockets, but not one of them has covered how to use them efficiently.

Does anyone have any sort of guide on how to do this? I'm concerned about the amount of bandwidth a single connection can take up, especially when applications have hundrends of connections opened.


问:
How to highlight SQL keywords using a regular expression?
I would like to highlight SQL keywords that occur within a string in a syntax highlighter. Here are the rules I would like to have:

Match the keywords SELECT and FROM (others will be added, but we'll start here). Must be all-caps

Must be contained in a string -- either starting with ' or "

The first word in that string (ignoring whitespace preceding it) should be one of the keywords.

This of course is not comprehensive (can ignore escapes within a string), but I'd like to start here.

Here are a few examples:

SELECT * FROM main -- will not match (not in a string)

"SELECT name FROM main" -- will match

"

      SELECT name FROM main" -- will match

"""Here is a SQL statement:

SELECT * FROM main""" -- no, string does not start with a keyword (SELECT...).

The only way I thought to do it in a single regex would be with a negative lookbehind...but then it would not be fixed width, as we don't know when the string starts. Something like:

(?<=["']\s*(SELECT)\s*)(SELECT|FROM)

But this of course won't work:

Would something like this be possible to do in a single regex?

答:
Just tested the regexp bellow:

If you need to add other commands the thing may get a little trick, because some keywords doesn't apply. Eg: ALTER TABLE mytable or UPDATE  SET col = val;. For these scenarios you will need to create subgroups and the regexp may become slow.

Best regards!


问:
Replace image in reveal.js
Suppose I have two very similar images I want to display in succession (say first is a photo and the second one the same photo with some area highlighted). I'd like to avoid a transition animation and just have the second image replace the first image. Is this possible with reveal.js?

Setting data-transition="none" doesn't work very well because the previous slide still retains its animation.

答:
reveal.js 4.0 introduces a new r-stack class that makes it easier to stack elements on top of each other.

```

<p>The above example fades in images on top of each other. If you want to only show one image at a time you'll need to use slightly different fragment settings.</p>

<pre class="lang-html prettyprint-override"><code><div class="r-stack">
  <img class="fragment current-visible" src="...">
  <img class="fragment current-visible" src="...">
  <img class="fragment" src="...">
</div>
</code>```

You can see examples of how this works in the reveal.js docs https://revealjs.com/layout/#stack

Title: Replace image in reveal.js

Body:
reveal.js 4.0 introduces a new r-stack class that makes it easier to stack elements on top of each other.

<div class="r-stack">
  <img class="fragment" src="https://placekitten.com/450/300" width="450" height="300">
  <img class="fragment" src="https://placekitten.com/300/450" width="300" height="450">
  <img class="fragment" src="https://placekitten.com/400/400" width="400" height="400">
</div>

The above example fades in images on top of each other. If you want to only show one image at a time you'll need to use slightly different fragment settings.

<div class="r-stack">
  <img class="fragment current-visible" src="...">
  <img class="fragment current-visible" src="...">
  <img class="fragment" src="...">
</div>

You can see examples of how this works in the reveal.js docs https://revealjs.com/layout/#stack


问:
Why does turtle open an even smaller screen when the canvas is small?
I'm trying to draw on a small 200x200 screen using turtle, however the drawing doesn't pop up as full size, it opens a smaller window and I have to scroll up/down, left/right (just a bit) to see the whole drawing. I don't have this problem with larger windows. How do I prevent this?

```<code>import turtle
import random

height, width = 200, 200
screen = turtle.Screen()
screen.setup(width, height)
screen.setworldcoordinates(0, 0, width, height)

t = turtle.Turtle()
t.speed(1)

for _ in range(5):
    t.penup()
    t.goto(random.randint(20, width-20), random.randint(0, height-40))
    t.pendown()
    t.circle(20)
</code>```

edit: screenshot, I want the actual size window instead of the scrolls

答:
Using small windows in turtle is a can of worms.  If @TheOneMusic's simple solution (+1) is good enough for your purposes, go for it!  On my system, your setworldcoordinates() call gets rid of the scroll bars, so I don't even see the issue.  So, another approximate solution might be to upgrade to current Python and tkinter.

However, neither is an exact solution.  If we add code to draw a 200 x 200 box around our drawing area:

```<code>t.penup()
t.color('red')
t.goto(0, 0)  # because of setworldcoordinates()
t.pendown()
for _ in range(4):
    t.forward(200)
    t.left(90)
</code>```

We get the box skewed:

To solve this problem more precisely, involves uglier code:

```<code>from turtle import Screen, Turtle
from random import randint

TRUE_WIDTH, TRUE_HEIGHT = 200, 200

CURSOR_SIZE = 20  # for drawing frame around edge
RADIUS = 20
CHROME = 14  # magic number possibly derivable from tkinter

width, height = TRUE_WIDTH + CHROME, TRUE_HEIGHT + CHROME # needs to be slightly larger than 200 target

offset_x = CHROME / -2 + 2
offset_y = CHROME / 2 - 2

screen = Screen()
screen.setup(width, height)
screen.screensize(width/2, height/2)  # backing store needs to be smaller than window
screen.setworldcoordinates(0, 0, TRUE_WIDTH, TRUE_HEIGHT)

# Draw red frame around edge to "prove" drawing area
frame = Turtle(shape='square', visible=False)
frame.shapesize(TRUE_HEIGHT / CURSOR_SIZE, TRUE_WIDTH / CURSOR_SIZE)  # 200 x 200 frame
frame.color('red', 'white')
frame.penup()
frame.goto(TRUE_WIDTH/2 + offset_x, TRUE_HEIGHT/2 + offset_y)
frame.stamp()

turtle = Turtle()
turtle.speed('fastest')  # because I have no patience

for _ in range(5):
    turtle.penup()
    turtle.goto(randint(RADIUS, TRUE_WIDTH - RADIUS) + offset_x, randint(0, TRUE_HEIGHT - RADIUS*2) + offset_y)
    turtle.pendown()
    turtle.circle(RADIUS)

screen.exitonclick()
</code>```

But this sort of detail work could easily be undone by a future release of turtle and/or tkinter.  If you can live with turtle's default window, life gets easier.

Body:
I'm trying to draw on a small 200x200 screen using turtle, however the drawing doesn't pop up as full size, it opens a smaller window and I have to scroll up/down, left/right (just a bit) to see the whole drawing. I don't have this problem with larger windows. How do I prevent this?

import turtle
import random

height, width = 200, 200
screen = turtle.Screen()
screen.setup(width, height)
screen.setworldcoordinates(0, 0, width, height)

t = turtle.Turtle()
t.speed(1)

for _ in range(5):
    t.penup()
    t.goto(random.randint(20, width-20), random.randint(0, height-40))
    t.pendown()
    t.circle(20)

edit: screenshot, I want the actual size window instead of the scrolls

Body:
Using small windows in turtle is a can of worms.  If @TheOneMusic's simple solution (+1) is good enough for your purposes, go for it!  On my system, your setworldcoordinates() call gets rid of the scroll bars, so I don't even see the issue.  So, another approximate solution might be to upgrade to current Python and tkinter.

However, neither is an exact solution.  If we add code to draw a 200 x 200 box around our drawing area:

t.penup()
t.color('red')
t.goto(0, 0)  # because of setworldcoordinates()
t.pendown()
for _ in range(4):
    t.forward(200)
    t.left(90)

We get the box skewed:

To solve this problem more precisely, involves uglier code:

from turtle import Screen, Turtle
from random import randint

TRUE_WIDTH, TRUE_HEIGHT = 200, 200

CURSOR_SIZE = 20  # for drawing frame around edge
RADIUS = 20
CHROME = 14  # magic number possibly derivable from tkinter

width, height = TRUE_WIDTH + CHROME, TRUE_HEIGHT + CHROME # needs to be slightly larger than 200 target

offset_x = CHROME / -2 + 2
offset_y = CHROME / 2 - 2

screen = Screen()
screen.setup(width, height)
screen.screensize(width/2, height/2)  # backing store needs to be smaller than window
screen.setworldcoordinates(0, 0, TRUE_WIDTH, TRUE_HEIGHT)

# Draw red frame around edge to "prove" drawing area
frame = Turtle(shape='square', visible=False)
frame.shapesize(TRUE_HEIGHT / CURSOR_SIZE, TRUE_WIDTH / CURSOR_SIZE)  # 200 x 200 frame
frame.color('red', 'white')
frame.penup()
frame.goto(TRUE_WIDTH/2 + offset_x, TRUE_HEIGHT/2 + offset_y)
frame.stamp()

turtle = Turtle()
turtle.speed('fastest')  # because I have no patience

for _ in range(5):
    turtle.penup()
    turtle.goto(randint(RADIUS, TRUE_WIDTH - RADIUS) + offset_x, randint(0, TRUE_HEIGHT - RADIUS*2) + offset_y)
    turtle.pendown()
    turtle.circle(RADIUS)

screen.exitonclick()

But this sort of detail work could easily be undone by a future release of turtle and/or tkinter.  If you can live with turtle's default window, life gets easier.


问:
How to use an asset in Android Ui?
I am new to Android Studio. While working on front end its sometimes easy to take some parts as png file and place it on the particular position instead of recreating it in xml  file. I am confused can we use png all the time ? I am worried about memory space . Like the app contains 50 pages and in each page I use 1-2 assets . I don't want my app to have more than 40mb. What will be the best way to do? Can we store the image as a URL and retrieve it whenever we use. What's the drawback in that way?</p>

答:
So many questions :)

I am confused can we use png all the time ?

Use what's best for your picture. For a photo, a JPEG will probably do better. But if you wish, you can use PNG all the time, yes.

I don't want my app to have more than 40mb.

Check and see. Depends on how big your images are; we can't tell.

What will be the best way to do?

Not enough information to tell you that. In general, there's nothing wrong with using images in assets.

Can we store the image as a URL and retrieve it whenever we use.

Yes.

What's the drawback in that way?

You'll need to get some server space somewhere. Also, there will be a loading latency. Also, your app won't be usable while disconnected from the Internet.

While working on front end its sometimes easy to take some parts as png file and place it on the particular position instead of recreating it in xml file.

That's the part that is confusing to me. Android XML layouts usually contain interactive elements, ones that the user can interact with. Images, on the other hand, tend to be static. What kind of XML is there out there that you think you can replace by an image?

Title: How to use an asset in Android Ui?


问:
What does the CPU Limit mean for App Engine instances?
I created a site on App Engine and chose the smallest F1 instance class which according to the docs has a CPU Limit of 600 MHz.

I limited the app to 1 instance only as a test and let it run several days then checked the CPU utilization on the dashboard. Here's part of the chart:

As you can see the utilization which is given in Megacycles/sec which I assume equals to one MHz is between like 700 and 1500.

The app uses one F1 instance only, runs without problems, there are no quota errors, but then what does the 600 Mhz CPU limit mean if the utilization is usually above it?

答:
Megacycles/sec is not MHz in this graph. As explained in Interface QuotaService:

Measures the duration that the current request has spent so far
  processing the request within the App Engine sandbox. Note that time
  spent in API calls will not be added to this value. The unit the
  duration is measured is Megacycles. If all instructions were to be
  executed sequentially on a standard 1.2 GHz 64-bit x86 CPU, 1200
  megacycles would equate to one second physical time elapsed.

In App Engine Flex, you get an entire CPU core from the machine you are renting out, but in App Engine Standard, it shows the Megacycles since it uses a sandbox.

Note that there is a feature request in the issue tracker on adding CPU% metric under gae_app for App Engine standard and I have relayed your concern about it to the Cloud App Engine product team. However, there is no guarantee of the implementation and ETA at this time. I recommend to star the ticket so that you would receive updates about it.


问:
how may I concatenate the columns in this script in MySQL?
Below is a SQL query that i am using to concatenate columns in SQL Server. How may I concatenate the same in MySQL?</p>

```<code> SELECT Name, STRING_AGG(school,',') AS School
,STRING_AGG(class,',') AS Class
,STRING_AGG(description,',') AS Description
,MIN(start_date) AS Start_date
,MAX(end_date) AS End_date FROM source_table GROUP BY Name
</code>```

答:
The equivalent function in MySQL is group_concat():

```<code>SELECT Name, GROUP_CONCAT(school) AS Schools,
       GROUP_CONCAT(class) AS Classes,
       GROUP_CONCAT(description) AS Descriptions,
       MIN(start_date) AS Start_date,
       MAX(end_date) AS End_date
FROM source_table
GROUP BY Name;
</code>```

The default separate is a comma, so there is no need to explicitly provide it.

Body:
Below is a SQL query that i am using to concatenate columns in SQL Server. How may I concatenate the same in MySQL?

 SELECT Name, STRING_AGG(school,',') AS School
,STRING_AGG(class,',') AS Class
,STRING_AGG(description,',') AS Description
,MIN(start_date) AS Start_date
,MAX(end_date) AS End_date FROM source_table GROUP BY Name

Body:
The equivalent function in MySQL is group_concat():

SELECT Name, GROUP_CONCAT(school) AS Schools,
       GROUP_CONCAT(class) AS Classes,
       GROUP_CONCAT(description) AS Descriptions,
       MIN(start_date) AS Start_date,
       MAX(end_date) AS End_date
FROM source_table
GROUP BY Name;

The default separate is a comma, so there is no need to explicitly provide it.


问:
SwiftUI - Animate path shape stroke drawing
Is there a way to animate the stroke drawing of a path whenever its destination point changes?

Here is a snippet of my code:

```<code>struct JourneyMapLineView: View {
    @Binding var rects: [CGRect]

    var body: some View {
        rects.count != 0 ?
            JourneyMapLineShape(startRect: rects[0], endRect: rects[rects.count-1])
                .stroke(Color.red), lineWidth: 8)
                .animation(.easeInOut(duration: 0.3)) //<-- Is not working
        : nil
    }
}

struct JourneyMapLineShape: Shape {
    var startRect: CGRect
    var endRect: CGRect

    func path(in _: CGRect) -> Path {
        var path = Path()

        path.move(to: startRect.origin)
        path.addLine(to: endRect.origin)

        return path
    }
}
</code>```

Currently, as you can see, there is no animation by changing the value of endRect:

I have already looked at some similar questions, it seems that this is a new case,.

Thank you so much!

答:
Update: Xcode 13.4 / iOS 15.5

The .animation has deprecated, so corrected part is

```<code>Route(points: self.vm.points, head: self.vm.lastPoint)
    .stroke(style: StrokeStyle(lineWidth: 8, lineCap: .round, lineJoin: .miter, miterLimit: 0, dash: [], dashPhase: 0))
    .foregroundColor(.red)
    .animation(.linear(duration: 0.5), value: self.vm.lastPoint) // << here !!
</code>```

Test module is here

Original

Here is a demo of possible solution. Tested with Xcode 11.4 / iOS 13.4

```<code>// Route shape animating head point
struct Route: Shape {
    var points: [CGPoint]
    var head: CGPoint

    // make route animatable head position only
    var animatableData: AnimatablePair<CGFloat, CGFloat> {
        get { AnimatablePair(head.x, head.y) }
        set {
            head.x = newValue.first
            head.y = newValue.second
        }
    }

    func path(in rect: CGRect) -> Path {
        Path { path in
            guard points.count > 1 else { return }
            path.move(to: points.first!)
            _ = points.dropFirst().dropLast().map { path.addLine(to: $0) }
            path.addLine(to: head)
        }
    }
}

// Route view model holding all points and notifying when last one changed
class RouteVM: ObservableObject {
    var points = [CGPoint.zero] {
        didSet {
            self.lastPoint = points.last ?? CGPoint.zero
        }
    }
    @Published var lastPoint = CGPoint.zero
}

struct DemoRouteView: View {
    @ObservedObject var vm = RouteVM()

    var body: some View {
        GeometryReader { gp in
            ZStack { // area
                Rectangle().fill(Color.white)
                    .gesture(DragGesture(minimumDistance: 0).onEnded { value in
                        self.vm.points.append(value.location) // read coordinates in area
                    })

                Circle().fill(Color.blue).frame(width: 20)
                    .position(self.vm.points.first!) // show initial point

                // draw route when head changed, animating
                Route(points: self.vm.points, head: self.vm.lastPoint)
                    .stroke(style: StrokeStyle(lineWidth: 8, lineCap: .round, lineJoin: .miter, miterLimit: 0, dash: [], dashPhase: 0))
                    .foregroundColor(.red)
                    .animation(.linear(duration: 0.5))
            }
            .onAppear {
                let area = gp.frame(in: .global)
                // just initail point at the bottom of screen
                self.vm.points = [CGPoint(x: area.midX, y: area.maxY)]
            }
        }.edgesIgnoringSafeArea(.all)
    }
}
</code>```

Body:
Is there a way to animate the stroke drawing of a path whenever its destination point changes?

Here is a snippet of my code:

struct JourneyMapLineView: View {
    @Binding var rects: [CGRect]

    var body: some View {
        rects.count != 0 ?
            JourneyMapLineShape(startRect: rects[0], endRect: rects[rects.count-1])
                .stroke(Color.red), lineWidth: 8)
                .animation(.easeInOut(duration: 0.3)) //<-- Is not working
        : nil
    }
}

struct JourneyMapLineShape: Shape {
    var startRect: CGRect
    var endRect: CGRect

    func path(in _: CGRect) -> Path {
        var path = Path()

        path.move(to: startRect.origin)
        path.addLine(to: endRect.origin)

        return path
    }
}

Currently, as you can see, there is no animation by changing the value of endRect:

I have already looked at some similar questions, it seems that this is a new case,.

Thank you so much!

Body:
Update: Xcode 13.4 / iOS 15.5

The .animation has deprecated, so corrected part is

Route(points: self.vm.points, head: self.vm.lastPoint)
    .stroke(style: StrokeStyle(lineWidth: 8, lineCap: .round, lineJoin: .miter, miterLimit: 0, dash: [], dashPhase: 0))
    .foregroundColor(.red)
    .animation(.linear(duration: 0.5), value: self.vm.lastPoint) // << here !!

Test module is here

Original

Here is a demo of possible solution. Tested with Xcode 11.4 / iOS 13.4

// Route shape animating head point
struct Route: Shape {
    var points: [CGPoint]
    var head: CGPoint

    // make route animatable head position only
    var animatableData: AnimatablePair<CGFloat, CGFloat> {
        get { AnimatablePair(head.x, head.y) }
        set {
            head.x = newValue.first
            head.y = newValue.second
        }
    }

    func path(in rect: CGRect) -> Path {
        Path { path in
            guard points.count > 1 else { return }
            path.move(to: points.first!)
            _ = points.dropFirst().dropLast().map { path.addLine(to: $0) }
            path.addLine(to: head)
        }
    }
}

// Route view model holding all points and notifying when last one changed
class RouteVM: ObservableObject {
    var points = [CGPoint.zero] {
        didSet {
            self.lastPoint = points.last ?? CGPoint.zero
        }
    }
    @Published var lastPoint = CGPoint.zero
}

struct DemoRouteView: View {
    @ObservedObject var vm = RouteVM()

    var body: some View {
        GeometryReader { gp in
            ZStack { // area
                Rectangle().fill(Color.white)
                    .gesture(DragGesture(minimumDistance: 0).onEnded { value in
                        self.vm.points.append(value.location) // read coordinates in area
                    })

                Circle().fill(Color.blue).frame(width: 20)
                    .position(self.vm.points.first!) // show initial point

                // draw route when head changed, animating
                Route(points: self.vm.points, head: self.vm.lastPoint)
                    .stroke(style: StrokeStyle(lineWidth: 8, lineCap: .round, lineJoin: .miter, miterLimit: 0, dash: [], dashPhase: 0))
                    .foregroundColor(.red)
                    .animation(.linear(duration: 0.5))
            }
            .onAppear {
                let area = gp.frame(in: .global)
                // just initail point at the bottom of screen
                self.vm.points = [CGPoint(x: area.midX, y: area.maxY)]
            }
        }.edgesIgnoringSafeArea(.all)
    }
}


问:
ag-grid : setting rowHeight manually
I am trying to set the row height of ag-grid like below

```<code><ag-grid-angular  style="height: 130px;"  [rowData]="rows"  [columnDefs]="columns" [getRowHeight]="getRowHeight">
</code>```

and in ts file

```<code>getRowHeight = 5;
</code>```

I also changed it to 5px but it is not reflecting. any other way to do the same.

I am doing it in angular8

I also added the snapshot it looks like after I made it 20px

答:
getRowHeight is the callback function but why can't you just use the property rowHeight on the grid object itself. Like this:

```<code><ag-grid-angular  style="height: 130px;"  [rowData]="rows"  [columnDefs]="columns" [rowHeight]="rowHeight">
</code>```

And then in your component:

rowHeight = 5

Edit 1:

You can also set autoheight for your rows - then the row height will be adapted according to the provided data:

In your template: <ag-grid-angular [defaultColDef]="defaultColDef" ...(all the other options)... >
In your component:

```<code>this.defaultColDef = {
      flex: 1,
      autoHeight: true,
};
</code>```

The default value is 25 (pixels)

Title: ag-grid : setting rowHeight manually

Body:
I am trying to set the row height of ag-grid like below

<ag-grid-angular  style="height: 130px;"  [rowData]="rows"  [columnDefs]="columns" [getRowHeight]="getRowHeight">

and in ts file

getRowHeight = 5;

I also changed it to 5px but it is not reflecting. any other way to do the same.

I am doing it in angular8

I also added the snapshot it looks like after I made it 20px

Body:
getRowHeight is the callback function but why can't you just use the property rowHeight on the grid object itself. Like this:

<ag-grid-angular  style="height: 130px;"  [rowData]="rows"  [columnDefs]="columns" [rowHeight]="rowHeight">

And then in your component:

rowHeight = 5

Edit 1:

You can also set autoheight for your rows - then the row height will be adapted according to the provided data:

In your template: <ag-grid-angular [defaultColDef]="defaultColDef" ...(all the other options)... >
In your component:

this.defaultColDef = {
      flex: 1,
      autoHeight: true,
};

The default value is 25 (pixels)


问:
Draft-JS Mention Plugin - Change Mentions Object K/V
Switched our Rich Text Editor over to Draft-JS but am having an issue with the mentions plugin.

The mentions plugin expects an array of objects such as below.

```<code>const mentions = [
  {
    name: 'Matthew Russell',
    link: 'https://twitter.com/mrussell247',
    avatar: 'https://pbs.twimg.com/profile_images/517863945/mattsailing_400x400.jpg',
  }
]
</code>```

My issue is that I'd like to to search on name, but insert the value when selected

```<code>const mentions = [
  {
    name: 'Matthew Russell',
    link: 'https://twitter.com/mrussell247',
    avatar: 'https://pbs.twimg.com/profile_images/517863945/mattsailing_400x400.jpg',
    value: "mr5058"
  }
]
</code>```

For example, when the user searches and selects "Matthew Russel", "mr5058" gets inserted into the text field. Does anyone know of a work around or solution to this?

答:
You can achieve this thing by using mentionComponent property of createMentionPlugin.  Sample Code below:

```<code> const mentionPlugin = createMentionPlugin({
  mentionTrigger: "@",
  mentionComponent: FileMentionComponent
});
</code>```

Where my FileMentionComponent is:

```<code>export default function FileMentionComponent
({  mention: { name,link,value},
  children
}) {
  return (
    <>
       <span>{value}</span>
       <span style={{ display: "none" }}>{children}</span>
    </>

  );
}
</code>```

See the official Docs of this plugin: https://www.draft-js-plugins.com/plugin/mention
 and search for "Custom Mention Component Example"

Cheers

Body:
Switched our Rich Text Editor over to Draft-JS but am having an issue with the mentions plugin.

The mentions plugin expects an array of objects such as below.

const mentions = [
  {
    name: 'Matthew Russell',
    link: 'https://twitter.com/mrussell247',
    avatar: 'https://pbs.twimg.com/profile_images/517863945/mattsailing_400x400.jpg',
  }
]

My issue is that I'd like to to search on name, but insert the value when selected

const mentions = [
  {
    name: 'Matthew Russell',
    link: 'https://twitter.com/mrussell247',
    avatar: 'https://pbs.twimg.com/profile_images/517863945/mattsailing_400x400.jpg',
    value: "mr5058"
  }
]

For example, when the user searches and selects "Matthew Russel", "mr5058" gets inserted into the text field. Does anyone know of a work around or solution to this?

Body:
You can achieve this thing by using mentionComponent property of createMentionPlugin.  Sample Code below:

 const mentionPlugin = createMentionPlugin({
  mentionTrigger: "@",
  mentionComponent: FileMentionComponent
});

Where my FileMentionComponent is:

export default function FileMentionComponent
({  mention: { name,link,value},
  children
}) {
  return (
    <>
       <span>{value}</span>
       <span style={{ display: "none" }}>{children}</span>
    </>

  );
}

See the official Docs of this plugin: https://www.draft-js-plugins.com/plugin/mention
 and search for "Custom Mention Component Example"

Cheers


问:
How can I change the date format?
I'm using the library react-native-masked-text to get the user birthday already formatted, and I need this to be in "DD/MM/YYYY" format for the user so I can show in that way in other screens. BUT I also need to get the value in "yyyy-MM-dd" format to send it to a API. How can I get the two formats?

The code is below:

```<code>  <View>
    <Label>Your birth date</Label>

    <TextInputMask
        type={'datetime'}
        options={{ format: 'DD/MM/YYYY' }}
        value={birthDate}
        onChange={value => this.setState({birthDate: value })}
    />
 </View>
</code>```

答:
You can set the new format on State:

<View>
  Your birth date

  <TextInputMask
      type={'datetime'}
      options={{ format: 'DD/MM/YYYY' }}
      value={birthDate}
      onChange={value => {
        const date = value.split('/');
        const birthDateAnotherFormat = date[2] + '/' + date[1] + '/' + date[0];

        this.setState({
          birthDate: value,
          birthDateAnotherFormat
        });
      }}
  />
</View>
```

Title: How can I change the date format?

Body:
I'm using the library react-native-masked-text to get the user birthday already formatted, and I need this to be in "DD/MM/YYYY" format for the user so I can show in that way in other screens. BUT I also need to get the value in "yyyy-MM-dd" format to send it to a API. How can I get the two formats?

The code is below:

  <View>
    Your birth date

    <TextInputMask
        type={'datetime'}
        options={{ format: 'DD/MM/YYYY' }}
        value={birthDate}
        onChange={value => this.setState({birthDate: value })}
    />
 </View>

Body:
You can set the new format on State:

<View>
  <Label>Your birth date</Label>

  <TextInputMask
      type={'datetime'}
      options={{ format: 'DD/MM/YYYY' }}
      value={birthDate}
      onChange={value => {
        const date = value.split('/');
        const birthDateAnotherFormat = date[2] + '/' + date[1] + '/' + date[0];

        this.setState({
          birthDate: value,
          birthDateAnotherFormat
        });
      }}
  />
</View>


问:
How can I compare two matrixes for similarity using Python?
Python 3:
How can I compare two matrices of similar shape to one another?

For example, lets say we have matrix x:

```<code>1 0 1
0 0 1
1 1 0
</code>```

I would like to compare this to matrix y:

```<code>1 0 1
0 0 1
1 1 1
</code>```

Which would give me a score, for example, 8/9 as 8/9 of the items were the same, with the exception of that last digit that went from 0 to 1. The matrices I am dealing with are much larger, but their dimensions are consistent for comparison.

There must be a library of some sort that can do this. Any thoughts?

答:
You can do this easily with numpy arrays.

```<code>import numpy as np

a = np.array([
    [1, 0, 1],
    [0, 0, 1],
    [1, 1, 0],
])

b = np.array([
    [1, 0, 1],
    [0, 0, 1],
    [1, 1, 1],
])

print(np.sum(a == b) / a.size)
</code>```

Gives back 0.889.

Body:
Python 3:
How can I compare two matrices of similar shape to one another?

For example, lets say we have matrix x:

1 0 1
0 0 1
1 1 0

I would like to compare this to matrix y:

1 0 1
0 0 1
1 1 1

Which would give me a score, for example, 8/9 as 8/9 of the items were the same, with the exception of that last digit that went from 0 to 1. The matrices I am dealing with are much larger, but their dimensions are consistent for comparison.

There must be a library of some sort that can do this. Any thoughts?

Body:
You can do this easily with numpy arrays.

import numpy as np

a = np.array([
    [1, 0, 1],
    [0, 0, 1],
    [1, 1, 0],
])

b = np.array([
    [1, 0, 1],
    [0, 0, 1],
    [1, 1, 1],
])

print(np.sum(a == b) / a.size)

Gives back 0.889.


问:
Share operation result between Keras metrics
I have a (time-expensive) operation that multiple metrics have in common. What would be the best way to share the operation result between the metrics avoiding the overhead of recalculating it each time?</p>

答:
You should create a special class to override tf.keras.callback.Callback() (thus implement your own callback class) and calculate the metrics that you need by overriding the method on_epoch_end().

Then, you can calculate some of your metrics, say, on the validation set, and you thus manually ensure that if you calculate for example TP + FP, you do use this sum to calculate the precision (TP / (TP + FP)) rather than recalculating it.

Manually doing so ensures no additional/superfluous computations are made.


问:
Constraining generic function arguments to generic interface type
In Typescript I have a generic interface representing a type I want to pass to a function.

```<code>//foo must be an object {}, not a number or string or boolean or array
interface MyInterface<T extends {[key: string]: any}> {
  foo: T
}
</code>```

So I make my function generic but TS doesn't infer the constraint from my interface

```<code>const myGenericFn: <T, U extends MyInterface<T>>(bar: U) => void = (bar) => {
  //Why is T not constrained to {[key: string]: any}?
  //Shouldn't the constraint be inferred from MyInterface<T>?
  // Or be an error since T doesn't extend {[key: string]: any}?

  //bar.foo is T but T does not extend {[key: string]: any}!
  const baz = bar.foo

}

//No error! Should be constrained to {foo: {[key: string]: any}} but accepts {foo: string}!
myGenericFn({foo: "bar"})
</code>```

The only way I can see to make this work is to repeat the constraint on T like so

```<code>const myGenericFnNotDRY: <T extends {[key: string]: any}, U extends MyInterface<T>>(bar: U) => void = (bar) => {
  //Not DRY, I have to repeat my generic constraint everywhere I want to use MyInterface within a generic fn!

  //bar.foo now correctly extends {[key: string]: any}
  const baz = bar.foo
}

//Errors as expected, string not assignable to {[key: string]: any}
myGenericFnNotDRY({foo: "bar"})
</code>```

This seems like quite a big hole in TS -- it's silently dropping the type constraint without telling me. That could easily lead to very difficult to track bugs. I'm likely missing some fundamental concept here.

TS Playground for above code

Why doesn't TS infer the constraint on T from MyInterface? How do I type my function so that T is properly constrained to the constraint specific on MyInterface?

答:
I would suggest doing one of two things:

```<code>// Solution 1: use conditional types to make sure you can never pass a "foo"
// that is not a Record<string, unknown>
interface MyInterface1<T> {
  foo: T extends Record<string, unknown> ? T : never;
}

const myGenericFn1: <T>(bar: MyInterface1<T>) => void = (bar) => {
  // ...
}

// Yaaaay! Error! I mean shit
myGenericFn1({ foo: "bar" });

// No error here though, just to check
myGenericFn1({ foo: { something: "somewhere" } });

// Solution 2: Use type parameter constraint using unknown rather than any
//
// This solution though has the same drawback you didn't like in your original
// post - you need to repeat the constraint in front of your function
interface MyInterface2<T extends Record<string, unknown>> {
  foo: T;
}

const myGenericFn2: <T extends Record<string, unknown>>(bar: MyInterface2<T>) => void = (bar) => {
  // ...
}

// Yaaaay! Error! I mean shit
myGenericFn2({ foo: "bar" });

// No error here though, just to check
myGenericFn1({ foo: { something: "somewhere" } });
</code>```

The TypeScript playground is here.

Body:
In Typescript I have a generic interface representing a type I want to pass to a function.

//foo must be an object {}, not a number or string or boolean or array
interface MyInterface<T extends {[key: string]: any}> {
  foo: T
}

So I make my function generic but TS doesn't infer the constraint from my interface

const myGenericFn: <T, U extends MyInterface<T>>(bar: U) => void = (bar) => {
  //Why is T not constrained to {[key: string]: any}?
  //Shouldn't the constraint be inferred from MyInterface<T>?
  // Or be an error since T doesn't extend {[key: string]: any}?

  //bar.foo is T but T does not extend {[key: string]: any}!
  const baz = bar.foo

}

//No error! Should be constrained to {foo: {[key: string]: any}} but accepts {foo: string}!
myGenericFn({foo: "bar"})

The only way I can see to make this work is to repeat the constraint on T like so

const myGenericFnNotDRY: <T extends {[key: string]: any}, U extends MyInterface<T>>(bar: U) => void = (bar) => {
  //Not DRY, I have to repeat my generic constraint everywhere I want to use MyInterface within a generic fn!

  //bar.foo now correctly extends {[key: string]: any}
  const baz = bar.foo
}

//Errors as expected, string not assignable to {[key: string]: any}
myGenericFnNotDRY({foo: "bar"})

This seems like quite a big hole in TS -- it's silently dropping the type constraint without telling me. That could easily lead to very difficult to track bugs. I'm likely missing some fundamental concept here.

<a href="https://www.typescriptlang.org/play/#code/PTBmHtwAgWwVwM4BcoCMCmUCGA7K5UArdAYxQG8BfAGih3BSzrhgwCd8Pk2BLHAc05pIAG3S4hWNmywBPALAAoPknRtQWEpgCysgJI5V6zegA8AFSjoAHqpwATBFHIBtANbpZALijc+-AF0fXFlKAD5nJSgoCHAfcyVKJSUScBxkWFkAcXQcNR4SADEcHwtaAFUrW1zHKF0DIw0tCzCwgApUKR9ygEooAF4IgDdwHnsBqA6pPsHIxWiQAHUAC1koHidLehRU9KQZPnRxpGhXD29fff8g7BxQgH4oKKgQAGVl8DgRexwAchQkMtMLtuFgVGhMHxQGo2EcYmxwDA6vpDGommZzGF7s8QFAAPIcDC3KzScBcPhaKCWezgdAIP4oGx2cZnTw+PwCG4hSjYxTJeYvYCdNgAOli602aDgKGptKc2yqzOc7jZl14nOCd0oAEIngKQShOgAvCbCsWQflJPmKEAAOWgMLJuven2+EKgBoOeWOp1iPlZFw5gU1oUoUsYJC0AAckE5yH61f4dUoYNlcvkijg2uQYpAfAAiYX5qCUHr8g2ZHJ5XiZ+1IAAiACUAJqlSxMmpxlWBq4a26hCqKzvIhpokwtdrC7ozYajcb9SbCmdzBbAOtQJvN2h6KDLLBDTAnKCwqPiFCpqD8dM1j1pUHg9AHtiyADuQNhUB3L9wAOgiB0KKNCYUAvjwgJ8Ngl7XgUMQ4Nq-Krma4r0C+t7SKQSAiGsHYOF25zsr2wb9la0QVsappSOa4CJPyIAAKKkmwThYE4NinmQRy0EGdAMNgCAIDw-A4FgqBiFAR4BgR6pEdyKZptWBTFHWm7ZgmhZSPmpZAA" rel="nofollow noreferrer">TS Playground for above code

Why doesn't TS infer the constraint on T from MyInterface? How do I type my function so that T is properly constrained to the constraint specific on MyInterface?

Body:
I would suggest doing one of two things:

// Solution 1: use conditional types to make sure you can never pass a "foo"
// that is not a Record<string, unknown>
interface MyInterface1<T> {
  foo: T extends Record<string, unknown> ? T : never;
}

const myGenericFn1: <T>(bar: MyInterface1<T>) => void = (bar) => {
  // ...
}

// Yaaaay! Error! I mean shit
myGenericFn1({ foo: "bar" });

// No error here though, just to check
myGenericFn1({ foo: { something: "somewhere" } });

// Solution 2: Use type parameter constraint using unknown rather than any
//
// This solution though has the same drawback you didn't like in your original
// post - you need to repeat the constraint in front of your function
interface MyInterface2<T extends Record<string, unknown>> {
  foo: T;
}

const myGenericFn2: <T extends Record<string, unknown>>(bar: MyInterface2<T>) => void = (bar) => {
  // ...
}

// Yaaaay! Error! I mean shit
myGenericFn2({ foo: "bar" });

// No error here though, just to check
myGenericFn1({ foo: { something: "somewhere" } });

The TypeScript playground is <a href="https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=33&pc=51#code/PTAEGUHsBsFcBcCWkB2oCMAuUsDOBTUAY1QBNElUBDaUeATwAd9c7JQBbKga0N1gBOhepFjEqaFPgBu%20AaEZVcrKqABEAM0iQ1AWABQIOgAsq8UIlYpI51QCV8JAaQA8ueAMQoA5gBocKNzWAO4oAHwGXvByGlREhACy9ACSKNECsfHoLgAqYaAA3gagoFqQ2Dmg%20AAe0SikrA5Oru6ePv6wgSHhoAD8oJXYUrICANwGAL4GBiQo7pz0AOL4Up5EAGIoWKC5YQAUAEZUAthJqemZ%20Nl5AJSgALz50pCIpA%20gh8d3j4XFoEYAOiBk2mhjAAE0qFCqPQAISgACiAgEkAE8OSnHwElAuGMFAMHCWKzkiA2Wz2BVK2mwaiOAjUoAmN3G%20gMRgAcuw5Cj5MY5IR4MZRN5jP4AFZ4czwdhEPlEbgEomrUmbdAUqnlQo4yAcfCCrzeGm4HX4YJ8oQMiaM5mgoxQOCUNAAJmwAFUCHQmIRFAIqLr0sRUK0qFEcLgDQEgpBQqBfYK5CZsRJ6GywKmBnjWMaHcg0ILhcZQKZWPGcX7CKRfcEjvLQCIxORSCgAOTmaCIXgWND1%20SoxDeLw0dOMSDzAC0ddEoCk%20De0tj%20GYZhMhFmwdDXlKKLSoEgGknglKnSIjsiaRicUSKXPGUvTtyVVqKwaoCaqJaHgNHS60fC%20SK%20glGUFQslMrL6Gu5iEssypki6OyVDUdQvm%20zhuJ%207SRt0YT7HSpzXhcd67N8TwvG89wfHSJG-IB-xgECAIguBRiQtCcKIsiqLopi2K4vi%20jQcSaybE66rAeodKWjazFgJyVScby-ImAW4qSmwxBygqAlKiSZJqpS4mUsa-p4j4Romma-KWtaoxAA" rel="nofollow noreferrer">here.


问:
Difference between two date strings in java
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

```<code>public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }
</code>```

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

```<code>try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.

答: Your condition diff<3 || diff>3 is equivalent to diff != 3 and diff is expressed in milliseconds. This expression will never be true.</p>

Body:
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.


问:
Unable To Connect to SQL Server Express Database from One PC To Another
I have 2 PC's on my at-home network and when I use this Microsoft connect utility trick to test database connection, I can connect to the database in SQL Server Express on the PC that SQL Server Express is installed on with no problem.

But when I using the same utility trick on the other PC and try to test the same database connection, I get an error

Test connection failed because of an error in initializing provider. [DBNETLIB][ConnectionOpen server does not exist or access denied

I have Norton Security Suite on the PC where SQL Server Express is installed on, and added a rule to open port 1433 and even disabled "Smart Firewall" and get the same error. I even added a DB user (Used in .UDL utility shown below) with all rights, same error. Any ideas on a way to fix this?

答:
By default SQL Express doesn't have TCP/IP enabled, and by default listens on a dynamic port when it is enabled.  You can use SQL Server Configuration Manager to both enable TCP/IP and disable dynamic ports and configure SQL Server to listen on port 1433.

And once you do you can connect with just the hostname.  No port number or \SQLEXPRESS required.


问:
How to deploy full-stack app to heroku or netlify? Which files are necessary?
I have a full-stack app that runs great on LocalHost, but once it gets deployed to the web (either Heroku or netlify), the app stops working properly. My question is what are the necessary changes I need to make in order for the backend to work properly and continue working with the API in order to update the frontend, etc. I've already tried changing the port on express:

```<code>const PORT = process.env.PORT || 5000;
app.listen(PORT, "0.0.0.0", err => {
  if (err) {
    console.error(err)
  } else {
    console.log(`Running on port ${PORT}`)
</code>```

}
})

Do I need to add my own .env file for the port, or does heroku do it automatically? Thanks in advance!

答:
if you are going to use netlify you can only host static files which means if you are going to do that you might need to seperate your backend from your frontend code wise
host the backend in heroku
and your frontend on netlify
also you need a procfile to tell heroku what to do with your app if you are going to build react with your backend in the same server hope this help people who are wondering about netlify/heroku deployment</p>

Body:
I have a full-stack app that runs great on LocalHost, but once it gets deployed to the web (either Heroku or netlify), the app stops working properly. My question is what are the necessary changes I need to make in order for the backend to work properly and continue working with the API in order to update the frontend, etc. I've already tried changing the port on express:

const PORT = process.env.PORT || 5000;
app.listen(PORT, "0.0.0.0", err => {
  if (err) {
    console.error(err)
  } else {
    console.log(`Running on port ${PORT}`)

}
})

Do I need to add my own .env file for the port, or does heroku do it automatically? Thanks in advance!


问:
How to calculate difference between two dates (number of days) in Pine Script?
How to calculate difference between two dates (number of days)?</p>

Body:
You can use the timestamp() function:

//@version=4
study("")
days = (timestamp(2020, 05, 28, 00, 00) - timestamp(2020, 05, 26, 12, 00)) / (24 * 60 * 60 * 1000)
plot(days)


问:
How to check for the multiple dots and stop to enter multiple dot using javascript?
I am having a input type text.

```<code><input type="text" class="checkForDot" />
</code>```

What i am trying to do is, when a user enters numbers into the box then find for the "." in the field, if it contains more then one ".", then prevent it to enter another "." in the text field.

my jquery code is:

```<code> $(".checkForDot").on("keyup", function (event) {
      CheckForDot($(this).val());
   });

function CheckForDot(value) {
     if (value != null || value != '') {
         var str = value.toString();
         if (str.indexOf('.', str.indexOf('.') + 1) != -1) {
             console.log("ok");
               }
            }
        }
</code>```

It is working fine, if two "." enters into the text box, but how to prevent to enter multiple "." in the text field?

If any other approach better than this please tell.

答:
If you are looking to make a field that only allows for numbers, you should consider using an input of type="number" as they will only allow for valid number characters to by added to its value. In some cases, it might even bring a different visual keyboard to ease of filling, wich is better for accessibility and UX. The number input field will, by default allow for mutliple dots, wich is annoying and is a bit harder to prevent than in a text field so it's a case of figuring wether accessibility and your UX is more important than adding a few extra lines of Javascript.

A lot of people will tell you that it is bad practice to limit keyboard actions, and they are right. when you do a preventDefault() on everything but numbers and ".", you disable tabing through form fields, the browser alt menu, any ctrl shortcuts, anything that happens within the browser.

This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting, as long as the pasted value is a valid number. It will allow to add "." withing the body of the number.

The only behavior that can't be prevented is if the user press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because of the way the number field handles its value. Wen the user types a dot at the end of a number like "13.", javascript can only retreive "13" when looking at its value as long as no decimal number have been placed. If the user typed a dot again, the value of "13.." would not be a valid number and therefore javascript woudl retreive "". This ensure you eighter get a valid number or nothing at all. In my solution, if a value returns "" without the press of backspace, delete or cut, it gets rolled back to the last valid value, wich in my example was "13", obtained from the typed value "13.". Preventing this behavior seems practically impossible and isn't a deal breaker as you get ensured your field value is always a valid, single dot number.

let lastValidInputValue;
let selectedDot = false;

const onKeypress = (e) => {
  if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
  selectedDot = false;
};

const onInput = (e) => {
  if (e.target.value !== "") {
    lastValidInputValue = e.target.value;
  } else if (e.inputType.match(/delete/g)) {
    lastValidInputValue = "";
  } else {
    e.target.value = lastValidInputValue;
  }
};

 const onSelect = (e) => {
   selectedDot = (window.getSelection().toString().indexOf(".") > -1)? true : false;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="myNumber" name="myNumber" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)"></code>```

You can find very detailed comments and extra bits in this Codepen

Body:
I am having a input type text.

<input type="text" class="checkForDot" />

What i am trying to do is, when a user enters numbers into the box then find for the "." in the field, if it contains more then one ".", then prevent it to enter another "." in the text field.

my jquery code is:

 $(".checkForDot").on("keyup", function (event) {
      CheckForDot($(this).val());
   });

function CheckForDot(value) {
     if (value != null || value != '') {
         var str = value.toString();
         if (str.indexOf('.', str.indexOf('.') + 1) != -1) {
             console.log("ok");
               }
            }
        }

It is working fine, if two "." enters into the text box, but how to prevent to enter multiple "." in the text field?

If any other approach better than this please tell.

Body:
If you are looking to make a field that only allows for numbers, you should consider using an input of type="number" as they will only allow for valid number characters to by added to its value. In some cases, it might even bring a different visual keyboard to ease of filling, wich is better for accessibility and UX. The number input field will, by default allow for mutliple dots, wich is annoying and is a bit harder to prevent than in a text field so it's a case of figuring wether accessibility and your UX is more important than adding a few extra lines of Javascript.

A lot of people will tell you that it is bad practice to limit keyboard actions, and they are right. when you do a preventDefault() on everything but numbers and ".", you disable tabing through form fields, the browser alt menu, any ctrl shortcuts, anything that happens within the browser.

This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting, as long as the pasted value is a valid number. It will allow to add "." withing the body of the number.

The only behavior that can't be prevented is if the user press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because of the way the number field handles its value. Wen the user types a dot at the end of a number like "13.", javascript can only retreive "13" when looking at its value as long as no decimal number have been placed. If the user typed a dot again, the value of "13.." would not be a valid number and therefore javascript woudl retreive "". This ensure you eighter get a valid number or nothing at all. In my solution, if a value returns "" without the press of backspace, delete or cut, it gets rolled back to the last valid value, wich in my example was "13", obtained from the typed value "13.". Preventing this behavior seems practically impossible and isn't a deal breaker as you get ensured your field value is always a valid, single dot number.

let lastValidInputValue;
let selectedDot = false;

const onKeypress = (e) => {
  if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
  selectedDot = false;
};

const onInput = (e) => {
  if (e.target.value !== "") {
    lastValidInputValue = e.target.value;
  } else if (e.inputType.match(/delete/g)) {
    lastValidInputValue = "";
  } else {
    e.target.value = lastValidInputValue;
  }
};

 const onSelect = (e) => {
   selectedDot = (window.getSelection().toString().indexOf(".") > -1)? true : false;
 }

<input type="number" id="myNumber" name="myNumber" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">

You can find very detailed comments and extra bits in this Codepen


问:
Boostrap container overflow and not responsive (always displayed two columns)
I have created a form with two columns. But when I decrease the browser width, two columns are preserved even when their content overflows. I have tried to change the code to plain DIV with container class, specify cols count, set width but it resists.

Here is the codepen: https://codesandbox.io/s/stoic-goldberg-4ugt6

and the source code of the parent container:

```<code><div class="container flex-wrap pt-3 w-75 ml-auto mr-auto mt-auto mb-5">
  <div class="row">
    <div class="col">
      <b-card>
        <SeriesForm />
      </b-card>
    </div>
    <div class="col">
      <b-card :header="captions[1]">
        <SeriesForm :group="forms[1]" />
      </b-card>
    </div>
  </div>
  <div class="row">
    <div class="col text-center p-4">
      <b-button>Analyse</b-button>
    </div>
  </div>
</div>
</code>```

How can I make it two columns when there is enough space and single column otherwise?

答:
I have added attribute to your  tags

If you will expand the screen then u will get the initial format.

Body:
I have created a form with two columns. But when I decrease the browser width, two columns are preserved even when their content overflows. I have tried to change the code to plain DIV with container class, specify cols count, set width but it resists.

Here is the codepen: https://codesandbox.io/s/stoic-goldberg-4ugt6

and the source code of the parent container:

        <SeriesForm />

        <SeriesForm :group="forms[1]" />

      Analyse

How can I make it two columns when there is enough space and single column otherwise?


问:
Why there is no supported iterators for some STL containers (Stack, Queue, Priority Queue)?
Across all types of iterators, why there is no supported pattern for stack, queue and priority_queue STL containers ?

```<code>#include <iostream>
#include <stack>
#include <algorithm>

int main(){

    std::stack<int> values;
    std::stack<int> valuesCopy;

    values.push(98);
    values.push(11);
    values.push(14);
    values.push(17);
    values.push(20);

    std::for_each( /* How can i manage this in a alternative way */,
                      [&](int value) mutable throw() -> void{ /* Process */ ;} );

    std::copy(/* Same for this */,std::back_inserter(valuesCopy));

    return 0;
}
</code>```

答:
The three are not classic containers, but rather container adaptors. They do not need to support the iteration. A quote from the "C++ Programming Language" book:

Container adaptors provide specialized access to underlying
  containers.

They are:

intended to be used only through their specialized interfaces. In particular, the STL
  container adaptors do not offer direct access to their underlying container. They do not offer iterators or subscripting.

Body:
Across all types of iterators, why there is no supported pattern for stack, queue and priority_queue STL containers ?

#include <iostream>
#include <stack>
#include <algorithm>

int main(){

    std::stack<int> values;
    std::stack<int> valuesCopy;

    values.push(98);
    values.push(11);
    values.push(14);
    values.push(17);
    values.push(20);

    std::for_each( /* How can i manage this in a alternative way */,
                      [&](int value) mutable throw() -> void{ /* Process */ ;} );

    std::copy(/* Same for this */,std::back_inserter(valuesCopy));

    return 0;
}


问:
How to traverse a nested XML structure using templates
I am new to XSL and in the process of picking this up from scratch to solve a problem.

I have a source XML file that contains the following structure:-

```<code><root>
  <Header>

  </Header>

  <DetailRecord>
    <CustomerNumber>1</CustomerNumber>
    <DetailSubRecord>
      <Address>London</Address>
    </DetailSubRecord>
    <DetailSubRecord>
      <Address>Hull</Address>
    </DetailSubRecord>

  </DetailRecord>

  <DetailRecord>
    <CustomerNumber>2</CustomerNumber>
    <DetailSubRecord>
      <Address>Birmingham</Address>
    </DetailSubRecord>
    <DetailSubRecord>
      <Address>Manchester</Address>
    </DetailSubRecord>

  </DetailRecord>
  <Footer>

  </Footer>

</root>
</code>```

where there are mutiple <DetailRecord>s each with multiple <DetailSubRecord>s.

I have managed to put together an XSL that outputs a single nested set of multiple DetailRecords to a flat file but I haven't been able to puzzle out how to refer to the 2nd nested level of address records in the XSL...

Here is my XSL so far:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:strip-space elements="*"/>
  <xsl:output method="text"/>
  <xsl:variable name="spaces" select="' '"/>
  <xsl:variable name="newline">
    <xsl:text>
</xsl:text>
  </xsl:variable>
  <xsl:template match="/">
    <xsl:value-of select="root/Header/HeaderField"/>
    <xsl:copy-of select="$newline"/>
    <xsl:for-each select="root/DetailRecord">
      <xsl:value-of select="CustomerNumber"/>
      <xsl:copy-of select="$newline"/>
    </xsl:for-each>
    Trailer - recordCount - <xsl:value-of select="count(root/DetailRecord)"/>
  </xsl:template>
</xsl:stylesheet>
</code>```

答:
Here you have a simple example on how to (literally) apply templates to your situation. Because you wasnt so clear about the required output, I've invented one.

XSLT 1.0 tested under Saxon 6.5.5

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:strip-space elements="*"/>
    <xsl:output method="text"/>

    <xsl:variable name="spaces" select="' '"/>
    <xsl:variable name="nl">
        <xsl:text>
</xsl:text>
    </xsl:variable>

    <xsl:template match="/root">
        <xsl:apply-templates select="DetailRecord"/>
        <xsl:apply-templates select="Footer"/>
    </xsl:template>

    <xsl:template match="DetailRecord">
        <xsl:value-of select="concat(
            'Customer ',
            CustomerNumber, $nl)"
            />
        <xsl:apply-templates select="DetailSubRecord"/>
        <xsl:value-of select="concat(
            'Address Count:',
            count(DetailSubRecord),$nl,$nl
            )"
          />
    </xsl:template>

    <xsl:template match="DetailSubRecord">
        <xsl:value-of select="concat('-',Address,$nl)"/>
    </xsl:template>

    <xsl:template match="Footer">
        <xsl:value-of select="concat(
            'Customer Count:',
            count(preceding-sibling::DetailRecord),$nl
            )"
            />
    </xsl:template>

</xsl:stylesheet>
</code>```

Applied on your input gets:

```<code>Customer 1
-London
-Hull
Address Count:2

Customer 2
-Birmingham
-Manchester
Address Count:2

Customer Count:2
</code>```

Body:
I am new to XSL and in the process of picking this up from scratch to solve a problem.

I have a source XML file that contains the following structure:-

<root>

  <DetailRecord>
    <CustomerNumber>1</CustomerNumber>
    <DetailSubRecord>
      <Address>London</Address>
    </DetailSubRecord>
    <DetailSubRecord>
      <Address>Hull</Address>
    </DetailSubRecord>

  </DetailRecord>

  <DetailRecord>
    <CustomerNumber>2</CustomerNumber>
    <DetailSubRecord>
      <Address>Birmingham</Address>
    </DetailSubRecord>
    <DetailSubRecord>
      <Address>Manchester</Address>
    </DetailSubRecord>

  </DetailRecord>

</root>

where there are mutiple <DetailRecord>s each with multiple <DetailSubRecord>s.

I have managed to put together an XSL that outputs a single nested set of multiple DetailRecords to a flat file but I haven't been able to puzzle out how to refer to the 2nd nested level of address records in the XSL...

Here is my XSL so far:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:strip-space elements="*"/>
  <xsl:output method="text"/>
  <xsl:variable name="spaces" select="' '"/>
  <xsl:variable name="newline">
    <xsl:text>
</xsl:text>
  </xsl:variable>
  <xsl:template match="/">
    <xsl:value-of select="root/Header/HeaderField"/>
    <xsl:copy-of select="$newline"/>
    <xsl:for-each select="root/DetailRecord">
      <xsl:value-of select="CustomerNumber"/>
      <xsl:copy-of select="$newline"/>
    </xsl:for-each>
    Trailer - recordCount - <xsl:value-of select="count(root/DetailRecord)"/>
  </xsl:template>
</xsl:stylesheet>

Body:
Here you have a simple example on how to (literally) apply templates to your situation. Because you wasnt so clear about the required output, I've invented one.

XSLT 1.0 tested under Saxon 6.5.5

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:strip-space elements="*"/>
    <xsl:output method="text"/>

    <xsl:variable name="spaces" select="' '"/>
    <xsl:variable name="nl">
        <xsl:text>&#10;</xsl:text>
    </xsl:variable>

    <xsl:template match="/root">
        <xsl:apply-templates select="DetailRecord"/>
        <xsl:apply-templates select="Footer"/>
    </xsl:template>

    <xsl:template match="DetailRecord">
        <xsl:value-of select="concat(
            'Customer ',
            CustomerNumber, $nl)"
            />
        <xsl:apply-templates select="DetailSubRecord"/>
        <xsl:value-of select="concat(
            'Address Count:',
            count(DetailSubRecord),$nl,$nl
            )"
          />
    </xsl:template>

    <xsl:template match="DetailSubRecord">
        <xsl:value-of select="concat('-',Address,$nl)"/>
    </xsl:template>

    <xsl:template match="Footer">
        <xsl:value-of select="concat(
            'Customer Count:',
            count(preceding-sibling::DetailRecord),$nl
            )"
            />
    </xsl:template>

</xsl:stylesheet>

Applied on your input gets:

Customer 1
-London
-Hull
Address Count:2

Customer 2
-Birmingham
-Manchester
Address Count:2

Customer Count:2


问:
Cannot open Selenium Jar file from CMD. Path or ClassPath issue?
I'm trying to launch:

```<code>java -jar selenium-server-standalone-2.14.0.jar -role hub
</code>```

from my Command Prompt but output was as below:

```<code>C:\Program Files (x86)>java -jar selenium-server-standalone-2.14.0.jar -role hub

Unable to access jarfile selenium-server-standalone-2.14.0.jar
</code>```

C:\Program Files (x86) is where the jar file is located.

I've put C:\Program Files (x86) in my PATH and CLASSPATH and it still won't work.

答:
Go to desired location in command prompt and enter the below command.
java -jar ./selenium-server-standalone-3.141.59.jar

That means if you save the .jar file in "C:\Eclipse\jar" location then the command should be:
C:\Eclipse\jar>java -jar ./selenium-server-standalone-3.141.59.jar

Body:
I'm trying to launch:

java -jar selenium-server-standalone-2.14.0.jar -role hub

from my Command Prompt but output was as below:

C:\Program Files (x86)>java -jar selenium-server-standalone-2.14.0.jar -role hub

Unable to access jarfile selenium-server-standalone-2.14.0.jar

C:\Program Files (x86) is where the jar file is located.

I've put C:\Program Files (x86) in my PATH and CLASSPATH and it still won't work.