问:
PersistentVolumeClaim is not bound: "nfs-pv-provisioning-demo"
I am setting up a kubernetes lab using one node only and learning to setup kubernetes nfs.
I am following kubernetes nfs example step by step from the following link:
https://github.com/kubernetes/examples/tree/master/staging/volumes/nfs

Trying the first section, NFS server part, executed 3 commands:

```<code>$ kubectl create -f examples/volumes/nfs/provisioner/nfs-server-gce-pv.yaml
$ kubectl create -f examples/volumes/nfs/nfs-server-rc.yaml
$ kubectl create -f examples/volumes/nfs/nfs-server-service.yaml
</code>```

I experience problem, where I see the following event:

```<code>PersistentVolumeClaim is not bound: "nfs-pv-provisioning-demo"
</code>```

Research done:

https://github.com/kubernetes/kubernetes/issues/43120

https://github.com/kubernetes/examples/pull/30

None of those links above help me to resolve issue I experience.
I have made sure it is using image 0.8.

```<code>Image:        gcr.io/google_containers/volume-nfs:0.8
</code>```

Does anyone know what does this message mean?
Clue and guidance on how to troubleshoot this issue is very much appreciated.
Thank you.

```<code>$ docker version

Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:41:23 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:42:49 2017
 OS/Arch:      linux/amd64
 Experimental: false

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-08T18:39:33Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-08T18:27:48Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}

$ kubectl get nodes
NAME          STATUS    ROLES     AGE       VERSION
lab-kube-06   Ready     master    2m        v1.8.3

$ kubectl describe nodes lab-kube-06
Name:               lab-kube-06
Roles:              master
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/hostname=lab-kube-06
                    node-role.kubernetes.io/master=
Annotations:        node.alpha.kubernetes.io/ttl=0
                    volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:             <none>
CreationTimestamp:  Thu, 16 Nov 2017 16:51:28 +0000
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  OutOfDisk        False   Thu, 16 Nov 2017 17:30:36 +0000   Thu, 16 Nov 2017 16:51:28 +0000   KubeletHasSufficientDisk     kubelet has sufficient disk space available
  MemoryPressure   False   Thu, 16 Nov 2017 17:30:36 +0000   Thu, 16 Nov 2017 16:51:28 +0000   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Thu, 16 Nov 2017 17:30:36 +0000   Thu, 16 Nov 2017 16:51:28 +0000   KubeletHasNoDiskPressure     kubelet has no disk pressure
  Ready            True    Thu, 16 Nov 2017 17:30:36 +0000   Thu, 16 Nov 2017 16:51:28 +0000   KubeletReady                 kubelet is posting ready status
Addresses:
  InternalIP:  10.0.0.6
  Hostname:    lab-kube-06
Capacity:
 cpu:     2
 memory:  8159076Ki
 pods:    110
Allocatable:
 cpu:     2
 memory:  8056676Ki
 pods:    110
System Info:
 Machine ID:                 e198b57826ab4704a6526baea5fa1d06
 System UUID:                05EF54CC-E8C8-874B-A708-BBC7BC140FF2
 Boot ID:                    3d64ad16-5603-42e9-bd34-84f6069ded5f
 Kernel Version:             3.10.0-693.el7.x86_64
 OS Image:                   Red Hat Enterprise Linux Server 7.4 (Maipo)
 Operating System:           linux
 Architecture:               amd64
 Container Runtime Version:  docker://Unknown
 Kubelet Version:            v1.8.3
 Kube-Proxy Version:         v1.8.3
ExternalID:                  lab-kube-06
Non-terminated Pods:         (7 in total)
  Namespace                  Name                                   CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ---------                  ----                                   ------------  ----------  ---------------  -------------
  kube-system                etcd-lab-kube-06                       0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-apiserver-lab-kube-06             250m (12%)    0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-controller-manager-lab-kube-06    200m (10%)    0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-dns-545bc4bfd4-gmdvn              260m (13%)    0 (0%)      110Mi (1%)       170Mi (2%)
  kube-system                kube-proxy-68w8k                       0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-scheduler-lab-kube-06             100m (5%)     0 (0%)      0 (0%)           0 (0%)
  kube-system                weave-net-7zlbg                        20m (1%)      0 (0%)      0 (0%)           0 (0%)
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ------------  ----------  ---------------  -------------
  830m (41%)    0 (0%)      110Mi (1%)       170Mi (2%)
Events:
  Type    Reason                   Age                From                     Message
  ----    ------                   ----               ----                     -------
  Normal  Starting                 39m                kubelet, lab-kube-06     Starting kubelet.
  Normal  NodeAllocatableEnforced  39m                kubelet, lab-kube-06     Updated Node Allocatable limit across pods
  Normal  NodeHasSufficientDisk    39m (x8 over 39m)  kubelet, lab-kube-06     Node lab-kube-06 status is now: NodeHasSufficientDisk
  Normal  NodeHasSufficientMemory  39m (x8 over 39m)  kubelet, lab-kube-06     Node lab-kube-06 status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    39m (x7 over 39m)  kubelet, lab-kube-06     Node lab-kube-06 status is now: NodeHasNoDiskPressure
  Normal  Starting                 38m                kube-proxy, lab-kube-06  Starting kube-proxy.

$ kubectl get pvc
NAME                       STATUS    VOLUME    CAPACITY   ACCESS MODES   STORAGECLASS   AGE
nfs-pv-provisioning-demo   Pending                                                      14s

$ kubectl get events
LAST SEEN   FIRST SEEN   COUNT     NAME                                        KIND                    SUBOBJECT   TYPE      REASON                    SOURCE                        MESSAGE
18m         18m          1         lab-kube-06.14f79f093119829a                Node                                Normal    Starting                  kubelet, lab-kube-06          Starting kubelet.
18m         18m          8         lab-kube-06.14f79f0931d0eb6e                Node                                Normal    NodeHasSufficientDisk     kubelet, lab-kube-06          Node lab-kube-06 status is now: NodeHasSufficientDisk
18m         18m          8         lab-kube-06.14f79f0931d1253e                Node                                Normal    NodeHasSufficientMemory   kubelet, lab-kube-06          Node lab-kube-06 status is now: NodeHasSufficientMemory
18m         18m          7         lab-kube-06.14f79f0931d131be                Node                                Normal    NodeHasNoDiskPressure     kubelet, lab-kube-06          Node lab-kube-06 status is now: NodeHasNoDiskPressure
18m         18m          1         lab-kube-06.14f79f0932f3f1b0                Node                                Normal    NodeAllocatableEnforced   kubelet, lab-kube-06          Updated Node Allocatable limit across pods
18m         18m          1         lab-kube-06.14f79f122a32282d                Node                                Normal    RegisteredNode            controllermanager             Node lab-kube-06 event: Registered Node lab-kube-06 in Controller
17m         17m          1         lab-kube-06.14f79f1cdfc4c3b1                Node                                Normal    Starting                  kube-proxy, lab-kube-06       Starting kube-proxy.
17m         17m          1         lab-kube-06.14f79f1d94ef1c17                Node                                Normal    RegisteredNode            controllermanager             Node lab-kube-06 event: Registered Node lab-kube-06 in Controller
14m         14m          1         lab-kube-06.14f79f4b91cf73b3                Node                                Normal    RegisteredNode            controllermanager             Node lab-kube-06 event: Registered Node lab-kube-06 in Controller
58s         11m          42        nfs-pv-provisioning-demo.14f79f766cf887f2   PersistentVolumeClaim               Normal    FailedBinding             persistentvolume-controller   no persistent volumes available for this claim and no storage class is set
14s         4m           20        nfs-server-kq44h.14f79fd21b9db5f9           Pod                                 Warning   FailedScheduling          default-scheduler             PersistentVolumeClaim is not bound: "nfs-pv-provisioning-demo"
4m          4m           1         nfs-server.14f79fd21b946027                 ReplicationController               Normal    SuccessfulCreate          replication-controller        Created pod: nfs-server-kq44h
                                       2m

$ kubectl get pods
NAME               READY     STATUS    RESTARTS   AGE
nfs-server-kq44h   0/1       Pending   0          16s

$ kubectl get pods

NAME               READY     STATUS    RESTARTS   AGE
nfs-server-kq44h   0/1       Pending   0          26s

$ kubectl get rc

NAME         DESIRED   CURRENT   READY     AGE
nfs-server   1         1         0         40s

$ kubectl describe pods nfs-server-kq44h

Name:           nfs-server-kq44h
Namespace:      default
Node:           <none>
Labels:         role=nfs-server
Annotations:    kubernetes.io/created-

by={"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"ReplicationController","namespace":"default","name":"nfs-server","uid":"5653eb53-caf0-11e7-ac02-000d3a04eb...
Status:         Pending
IP:
Created By:     ReplicationController/nfs-server
Controlled By:  ReplicationController/nfs-server
Containers:
  nfs-server:
    Image:        gcr.io/google_containers/volume-nfs:0.8
    Ports:        2049/TCP, 20048/TCP, 111/TCP
    Environment:  <none>
    Mounts:
      /exports from mypvc (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-plgv5 (ro)
Conditions:
  Type           Status
  PodScheduled   False
Volumes:
  mypvc:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  nfs-pv-provisioning-demo
    ReadOnly:   false
  default-token-plgv5:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-plgv5
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.alpha.kubernetes.io/notReady:NoExecute for 300s
                 node.alpha.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason            Age                From               Message
  ----     ------            ----               ----               -------
  Warning  FailedScheduling  39s (x22 over 5m)  default-scheduler  PersistentVolumeClaim is not bound: "nfs-pv-provisioning-demo"
</code>```

答:
Each Persistent Volume Claim (PVC) needs a Persistent Volume (PV) that it can bind to. In your example, you have only created a PVC, but not the volume itself.

A PV can either be created manually, or automatically by using a Volume class with a provisioner. Have a look at the docs of static and dynamic provisioning for more information):

There are two ways PVs may be provisioned: statically or dynamically.

Static

A cluster administrator creates a number of PVs. They carry the details of the real storage which is available for use by cluster users. [...]

Dynamic

When none of the static PVs the administrator created matches a user’s PersistentVolumeClaim, the cluster may try to dynamically provision a volume specially for the PVC. This provisioning is based on StorageClasses: the PVC must request a class and the administrator must have created and configured that class in order for dynamic provisioning to occur.

In your example, you are creating a storage class provisioner (defined in examples/volumes/nfs/provisioner/nfs-server-gce-pv.yaml) that seems to be tailored for usage within the Google cloud (which it will probably not be able to actually create PVs in your lab setup).

You can create a persistent volume manually on your own. After creating the PV, the PVC should automatically bind itself to the volume and your pods should start. Below is an example for a persistent volume that uses the node's local file system as a volume (which is probably OK for a one-node test setup):

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: someVolume
spec:
  capacity:
    storage: 200Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: /path/on/host
</code>```

For a production setup, you'll probably want to choose a different volume type at hostPath, although the volume types available to you will greatly differ depending on the environment that you're in (cloud or self-hosted/bare-metal).

Body:
I am setting up a kubernetes lab using one node only and learning to setup kubernetes nfs.
I am following kubernetes nfs example step by step from the following link:
https://github.com/kubernetes/examples/tree/master/staging/volumes/nfs

Trying the first section, NFS server part, executed 3 commands:

$ kubectl create -f examples/volumes/nfs/provisioner/nfs-server-gce-pv.yaml
$ kubectl create -f examples/volumes/nfs/nfs-server-rc.yaml
$ kubectl create -f examples/volumes/nfs/nfs-server-service.yaml

I experience problem, where I see the following event:

PersistentVolumeClaim is not bound: "nfs-pv-provisioning-demo"

Research done:

https://github.com/kubernetes/kubernetes/issues/43120

https://github.com/kubernetes/examples/pull/30

None of those links above help me to resolve issue I experience.
I have made sure it is using image 0.8.

Image:        gcr.io/google_containers/volume-nfs:0.8

Does anyone know what does this message mean?
Clue and guidance on how to troubleshoot this issue is very much appreciated.
Thank you.

$ docker version

Client:
 Version:      17.09.0-ce
 API version:  1.32
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:41:23 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.09.0-ce
 API version:  1.32 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   afdb6d4
 Built:        Tue Sep 26 22:42:49 2017
 OS/Arch:      linux/amd64
 Experimental: false

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-08T18:39:33Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"8", GitVersion:"v1.8.3", GitCommit:"f0efb3cb883751c5ffdbe6d515f3cb4fbe7b7acd", GitTreeState:"clean", BuildDate:"2017-11-08T18:27:48Z", GoVersion:"go1.8.3", Compiler:"gc", Platform:"linux/amd64"}

$ kubectl get nodes
NAME          STATUS    ROLES     AGE       VERSION
lab-kube-06   Ready     master    2m        v1.8.3

$ kubectl describe nodes lab-kube-06
Name:               lab-kube-06
Roles:              master
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/hostname=lab-kube-06
                    node-role.kubernetes.io/master=
Annotations:        node.alpha.kubernetes.io/ttl=0
                    volumes.kubernetes.io/controller-managed-attach-detach=true
Taints:             <none>
CreationTimestamp:  Thu, 16 Nov 2017 16:51:28 +0000
Conditions:
  Type             Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----             ------  -----------------                 ------------------                ------                       -------
  OutOfDisk        False   Thu, 16 Nov 2017 17:30:36 +0000   Thu, 16 Nov 2017 16:51:28 +0000   KubeletHasSufficientDisk     kubelet has sufficient disk space available
  MemoryPressure   False   Thu, 16 Nov 2017 17:30:36 +0000   Thu, 16 Nov 2017 16:51:28 +0000   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure     False   Thu, 16 Nov 2017 17:30:36 +0000   Thu, 16 Nov 2017 16:51:28 +0000   KubeletHasNoDiskPressure     kubelet has no disk pressure
  Ready            True    Thu, 16 Nov 2017 17:30:36 +0000   Thu, 16 Nov 2017 16:51:28 +0000   KubeletReady                 kubelet is posting ready status
Addresses:
  InternalIP:  10.0.0.6
  Hostname:    lab-kube-06
Capacity:
 cpu:     2
 memory:  8159076Ki
 pods:    110
Allocatable:
 cpu:     2
 memory:  8056676Ki
 pods:    110
System Info:
 Machine ID:                 e198b57826ab4704a6526baea5fa1d06
 System UUID:                05EF54CC-E8C8-874B-A708-BBC7BC140FF2
 Boot ID:                    3d64ad16-5603-42e9-bd34-84f6069ded5f
 Kernel Version:             3.10.0-693.el7.x86_64
 OS Image:                   Red Hat Enterprise Linux Server 7.4 (Maipo)
 Operating System:           linux
 Architecture:               amd64
 Container Runtime Version:  docker://Unknown
 Kubelet Version:            v1.8.3
 Kube-Proxy Version:         v1.8.3
ExternalID:                  lab-kube-06
Non-terminated Pods:         (7 in total)
  Namespace                  Name                                   CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ---------                  ----                                   ------------  ----------  ---------------  -------------
  kube-system                etcd-lab-kube-06                       0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-apiserver-lab-kube-06             250m (12%)    0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-controller-manager-lab-kube-06    200m (10%)    0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-dns-545bc4bfd4-gmdvn              260m (13%)    0 (0%)      110Mi (1%)       170Mi (2%)
  kube-system                kube-proxy-68w8k                       0 (0%)        0 (0%)      0 (0%)           0 (0%)
  kube-system                kube-scheduler-lab-kube-06             100m (5%)     0 (0%)      0 (0%)           0 (0%)
  kube-system                weave-net-7zlbg                        20m (1%)      0 (0%)      0 (0%)           0 (0%)
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  CPU Requests  CPU Limits  Memory Requests  Memory Limits
  ------------  ----------  ---------------  -------------
  830m (41%)    0 (0%)      110Mi (1%)       170Mi (2%)
Events:
  Type    Reason                   Age                From                     Message
  ----    ------                   ----               ----                     -------
  Normal  Starting                 39m                kubelet, lab-kube-06     Starting kubelet.
  Normal  NodeAllocatableEnforced  39m                kubelet, lab-kube-06     Updated Node Allocatable limit across pods
  Normal  NodeHasSufficientDisk    39m (x8 over 39m)  kubelet, lab-kube-06     Node lab-kube-06 status is now: NodeHasSufficientDisk
  Normal  NodeHasSufficientMemory  39m (x8 over 39m)  kubelet, lab-kube-06     Node lab-kube-06 status is now: NodeHasSufficientMemory
  Normal  NodeHasNoDiskPressure    39m (x7 over 39m)  kubelet, lab-kube-06     Node lab-kube-06 status is now: NodeHasNoDiskPressure
  Normal  Starting                 38m                kube-proxy, lab-kube-06  Starting kube-proxy.

$ kubectl get pvc
NAME                       STATUS    VOLUME    CAPACITY   ACCESS MODES   STORAGECLASS   AGE
nfs-pv-provisioning-demo   Pending                                                      14s

$ kubectl get events
LAST SEEN   FIRST SEEN   COUNT     NAME                                        KIND                    SUBOBJECT   TYPE      REASON                    SOURCE                        MESSAGE
18m         18m          1         lab-kube-06.14f79f093119829a                Node                                Normal    Starting                  kubelet, lab-kube-06          Starting kubelet.
18m         18m          8         lab-kube-06.14f79f0931d0eb6e                Node                                Normal    NodeHasSufficientDisk     kubelet, lab-kube-06          Node lab-kube-06 status is now: NodeHasSufficientDisk
18m         18m          8         lab-kube-06.14f79f0931d1253e                Node                                Normal    NodeHasSufficientMemory   kubelet, lab-kube-06          Node lab-kube-06 status is now: NodeHasSufficientMemory
18m         18m          7         lab-kube-06.14f79f0931d131be                Node                                Normal    NodeHasNoDiskPressure     kubelet, lab-kube-06          Node lab-kube-06 status is now: NodeHasNoDiskPressure
18m         18m          1         lab-kube-06.14f79f0932f3f1b0                Node                                Normal    NodeAllocatableEnforced   kubelet, lab-kube-06          Updated Node Allocatable limit across pods
18m         18m          1         lab-kube-06.14f79f122a32282d                Node                                Normal    RegisteredNode            controllermanager             Node lab-kube-06 event: Registered Node lab-kube-06 in Controller
17m         17m          1         lab-kube-06.14f79f1cdfc4c3b1                Node                                Normal    Starting                  kube-proxy, lab-kube-06       Starting kube-proxy.
17m         17m          1         lab-kube-06.14f79f1d94ef1c17                Node                                Normal    RegisteredNode            controllermanager             Node lab-kube-06 event: Registered Node lab-kube-06 in Controller
14m         14m          1         lab-kube-06.14f79f4b91cf73b3                Node                                Normal    RegisteredNode            controllermanager             Node lab-kube-06 event: Registered Node lab-kube-06 in Controller
58s         11m          42        nfs-pv-provisioning-demo.14f79f766cf887f2   PersistentVolumeClaim               Normal    FailedBinding             persistentvolume-controller   no persistent volumes available for this claim and no storage class is set
14s         4m           20        nfs-server-kq44h.14f79fd21b9db5f9           Pod                                 Warning   FailedScheduling          default-scheduler             PersistentVolumeClaim is not bound: "nfs-pv-provisioning-demo"
4m          4m           1         nfs-server.14f79fd21b946027                 ReplicationController               Normal    SuccessfulCreate          replication-controller        Created pod: nfs-server-kq44h
                                       2m

$ kubectl get pods
NAME               READY     STATUS    RESTARTS   AGE
nfs-server-kq44h   0/1       Pending   0          16s

$ kubectl get pods

NAME               READY     STATUS    RESTARTS   AGE
nfs-server-kq44h   0/1       Pending   0          26s

$ kubectl get rc

NAME         DESIRED   CURRENT   READY     AGE
nfs-server   1         1         0         40s

$ kubectl describe pods nfs-server-kq44h

Name:           nfs-server-kq44h
Namespace:      default
Node:           <none>
Labels:         role=nfs-server
Annotations:    kubernetes.io/created-

by={"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"ReplicationController","namespace":"default","name":"nfs-server","uid":"5653eb53-caf0-11e7-ac02-000d3a04eb...
Status:         Pending
IP:
Created By:     ReplicationController/nfs-server
Controlled By:  ReplicationController/nfs-server
Containers:
  nfs-server:
    Image:        gcr.io/google_containers/volume-nfs:0.8
    Ports:        2049/TCP, 20048/TCP, 111/TCP
    Environment:  <none>
    Mounts:
      /exports from mypvc (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-plgv5 (ro)
Conditions:
  Type           Status
  PodScheduled   False
Volumes:
  mypvc:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  nfs-pv-provisioning-demo
    ReadOnly:   false
  default-token-plgv5:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-plgv5
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.alpha.kubernetes.io/notReady:NoExecute for 300s
                 node.alpha.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason            Age                From               Message
  ----     ------            ----               ----               -------
  Warning  FailedScheduling  39s (x22 over 5m)  default-scheduler  PersistentVolumeClaim is not bound: "nfs-pv-provisioning-demo"

Body:
Each Persistent Volume Claim (PVC) needs a Persistent Volume (PV) that it can bind to. In your example, you have only created a PVC, but not the volume itself.

A PV can either be created manually, or automatically by using a Volume class with a provisioner. Have a look at the docs of static and dynamic provisioning for more information):

There are two ways PVs may be provisioned: statically or dynamically.

Static

A cluster administrator creates a number of PVs. They carry the details of the real storage which is available for use by cluster users. [...]

Dynamic

When none of the static PVs the administrator created matches a user’s PersistentVolumeClaim, the cluster may try to dynamically provision a volume specially for the PVC. This provisioning is based on StorageClasses: the PVC must request a class and the administrator must have created and configured that class in order for dynamic provisioning to occur.

In your example, you are creating a storage class provisioner (defined in examples/volumes/nfs/provisioner/nfs-server-gce-pv.yaml) that seems to be tailored for usage within the Google cloud (which it will probably not be able to actually create PVs in your lab setup).

You can create a persistent volume manually on your own. After creating the PV, the PVC should automatically bind itself to the volume and your pods should start. Below is an example for a persistent volume that uses the node's local file system as a volume (which is probably OK for a one-node test setup):

apiVersion: v1
kind: PersistentVolume
metadata:
  name: someVolume
spec:
  capacity:
    storage: 200Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: /path/on/host

For a production setup, you'll probably want to choose a different volume type at hostPath, although the volume types available to you will greatly differ depending on the environment that you're in (cloud or self-hosted/bare-metal).


来源: stackexchange

问:
OCR ID document reader AccessIS OCR315
I know that this is very specific question, but ... I have problem with reader OCR315 from company AccessIS on Windows 10 Professional 64x. On Windows 7 Home 86x everything works fine. I'm using reader with ASPS for reading passports with rules and sending data on keyboard. I try to switch logging on and message bellow appears after passport reading :

CHIDInterface::GetDeviceViaInterface - Unable to open device handle (The process cannot access the file because it is being used by another process.)

Any ideas, have somebody same issue ?

答:
The issue you are facing is very likely a permissions conflict or COM port manipulation issue.
Similar to what happens when you try to CHGPORT while a program has an active connection to the device.</p>

ContentLicense: CC BY-SA 3.0

Title: OCR ID document reader AccessIS OCR315


问:
Rebol calc-workdays not working on Red
I trying to execute this script https://www.mail-archive.com/rebol-bounce@rebol.com/msg01222.html in Red but I can't see why I got

calc-workdays now/date 3-feb-2007 [1-feb-2007]

*** Script Error: > operator is missing an argument

*** Where: do

*** Stack: print calc-workdays

```<code>    found?: func [
        "Returns TRUE if value is not NONE."
        value
    ][
        not none? :value
    ]

    calc-workdays: func [
        "Return number of workdays between two dates, excluding holidays"
        date1 [date!] "Start date"
        date2 [date!] "End date"
        holidays [block!] "Block of dates to exclude (holidays, etc.)"
        /non "Return number of non-work days (weekend + holidays) between 2 dates"
        /local days day1 day2 diff param
    ][
        days: copy []
        set [day1 day2] sort reduce [date1 date2]
        diff: day2 - day1
        param: pick [[> 5 union][< 6 exclude]] either found? non [1][2]
        loop diff [
            day1: day1 + 1
            if do param/1 day1/weekday param/2 [append days day1]
        ]
        return length? do param/3 days holidays
    ]
</code>```

答:
Rebol2 seems to allow you to pass a WORD! to DO, and evaluate it.  If the word happens to be a variable holding an ANY-FUNCTION!, it will be run...and if it's an infix "OP!" then it will be run as if it were not infix.

```<code>>> do quote > 1 2
== false

>> do quote < 1 2
== true
</code>```

Red sort of does this also, but DO is not variadic.  It can run 0 arity functions only:

```<code>>> foo: does [print "hi"]

>> do quote foo
hi

>> bar: func [x] [print x]

>> do quote bar "hi"
*** Script Error: bar is missing its x argument
</code>```

The script in question was attempting to use this feature.  But it could be done with ordinary COMPOSE or REDUCE.  So change:

```<code>if do param/1 day1/weekday param/2 [append days day1]
</code>```

To:

```<code>if do reduce [day1/weekday param/1 param/2] [append days day1]
</code>```

That will build a block of code where the > or < operator is in the middle, and execute it normally without relying on this WORD!-dispatch or infix-dropping behavior of DO.

Similarly, change:

```<code>return length? do param/3 days holidays
</code>```

To:

```<code>return length? do reduce [param/3 days holidays]
</code>```

With those changes, and removing the found? (it's not necessary) then it appears to work.

Title: Rebol calc-workdays not working on Red

Body:
I trying to execute this script https://www.mail-archive.com/rebol-bounce@rebol.com/msg01222.html in Red but I can't see why I got

calc-workdays now/date 3-feb-2007 [1-feb-2007]

*** Script Error: > operator is missing an argument

*** Where: do

*** Stack: print calc-workdays

    found?: func [
        "Returns TRUE if value is not NONE."
        value
    ][
        not none? :value
    ]

    calc-workdays: func [
        "Return number of workdays between two dates, excluding holidays"
        date1 [date!] "Start date"
        date2 [date!] "End date"
        holidays [block!] "Block of dates to exclude (holidays, etc.)"
        /non "Return number of non-work days (weekend + holidays) between 2 dates"
        /local days day1 day2 diff param
    ][
        days: copy []
        set [day1 day2] sort reduce [date1 date2]
        diff: day2 - day1
        param: pick [[> 5 union][< 6 exclude]] either found? non [1][2]
        loop diff [
            day1: day1 + 1
            if do param/1 day1/weekday param/2 [append days day1]
        ]
        return length? do param/3 days holidays
    ]

Body:
Rebol2 seems to allow you to pass a WORD! to DO, and evaluate it.  If the word happens to be a variable holding an ANY-FUNCTION!, it will be run...and if it's an infix "OP!" then it will be run as if it were not infix.

>> do quote > 1 2
== false

>> do quote < 1 2
== true

Red sort of does this also, but DO is not variadic.  It can run 0 arity functions only:

>> foo: does [print "hi"]

>> do quote foo
hi

>> bar: func [x] [print x]

>> do quote bar "hi"
*** Script Error: bar is missing its x argument

The script in question was attempting to use this feature.  But it could be done with ordinary COMPOSE or REDUCE.  So change:

if do param/1 day1/weekday param/2 [append days day1]

To:

if do reduce [day1/weekday param/1 param/2] [append days day1]

That will build a block of code where the > or < operator is in the middle, and execute it normally without relying on this WORD!-dispatch or infix-dropping behavior of DO.

Similarly, change:

return length? do param/3 days holidays

To:

return length? do reduce [param/3 days holidays]

With those changes, and removing the found? (it's not necessary) then it appears to work.


问:
3-Tier BizTalk Architecture Possible?
According to this BizTalk documentation, the HTTP receive adapter must be in the application (middle) layer. This means BizTalk is limited to a 2-tier architecture, which for modern enterprises is a pretty big limitation.

Is the reverse proxy suggestion that Microsoft recommends (on the link above) the common solution to this problem? Has anyone used any other configuration to use the HTTP receive adapter in the web/perimeter layer and been able to negotiate messages through an application layer?

If the reverse proxy method was used, were existing proxy's in the enterprise used or were dedicated proxy's configured for the solution?

答:
Keep in mind, the "n-tier" thing is pretty much meaningless.  An app can be as many tiers as you want to count.

However, in 99.9% of cases, there is no reason to put the BizTalk HTTP host or any other endpoint on the perimeter network.

Depending on local polity, shops will do either port forwarding or inbound proxy (reverse proxy isn't really a thing either ;).

There are absolutely no limits in BizTalk for way to accomplish this.  How depends entirely on what your network team allows or prefers.

Title: 3-Tier BizTalk Architecture Possible?


问:
No Reverse Match error in Django
New to Django and stuck on this error. My template was rendering correctly. The only change I made was adding a '1/0' in my views.py file to simulate a breakpoint. And now the template will not render when I remove it.

urls.py

```<code>from django.conf.urls import url
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.views import login, logout
from app.views import send_morsel, start_hunt, MorselList, MorselDetailView,\
register, create_morsel, HomePageView, FAQPageView, AboutPageView,\
newsletter_signup, edit_morsel

app_name = 'app'
urlpatterns = [
    url(r'^$', HomePageView.as_view(), name='home'),
    url(r'^morsels/$', MorselList.as_view(), name='morsel_list'),
    url(r'^morsels/send/$', send_morsel, name='morsel_send'),
    url(r'^morsels/(?P<morsel_id>[0-9])/start_hunt/$', start_hunt, name='start_hunt'),
    url(r'^register/', register, name='register'),
    url(r'^faq/$', FAQPageView.as_view(), name='faq'),
    url(r'^about/$', AboutPageView.as_view(), name='about'),
    url(r'^morsels/create/$', create_morsel, name="create_morsel"),
    url(r'^morsels/(?P<morsel_id>[0-9])/edit/$', edit_morsel, name='edit_morsel'),
    url(r'^morsels/(?P<pk>[0-9])/display/$', MorselDetailView.as_view(), name='morsel_detail'),
    url(r'^newsletter_signup/$', newsletter_signup, name='newsletter_signup')
]
</code>```

morsel_list.html

```<code>{% extends "app/base.html" %}
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
{% block content %}
    <h2>Morsels</h2>
    {% if user.is_authenticated %}
        <p>hello</p>
        <p>welcome {{ user.username }}</p>
        <p><a href="/logout">Logout</a></p>
    {% else %}
        <p><a href="/login">Login</a></p>
        <p><a href="/app/register">Register</a></p>
    {% endif %}
    <ul>
        {% for morsel in object_list %}
            <li>{{ morsel.name }}
                <a href="{%url 'app:morsel_detail' morsel.id%}">View</a>
                <a href="{%url 'app:edit_morsel' morsel.id %}">Edit</a>
                <a href="{%url 'app:start_hunt' morsel.id%}">Send! </a>
            </li>
        {% endfor %}
    </ul>
    {% if messages %}
        {% for msg in messages %}
            {% bootstrap_alert msg.message alert_type=msg.level_tag %}
        {% endfor %}
    {% endif %}
{% endblock %}
</code>```

Really not sure what to do here.

relevant block from views.py:

```<code>def edit_morsel(request, morsel_id=None):
    if request.method == 'POST':
        extra = int(request.session['extra'])
        form = MorselCreationForm(request.POST)
        formset = formset_factory(QuestionAnswerCreationForm, extra=extra)(request.POST)
        if form.is_valid() and formset.is_valid():
            name = form.cleaned_data["name"]
            start_time = form.cleaned_data["start_time"]
            end_time = form.cleaned_data["end_time"]
            welcome_text = form.cleaned_data["welcome_text"]
            completed_text = form.cleaned_data["completed_text"]
            public_enabled = form.cleaned_data["public_enabled"]
            m = Morsel(
                name=name,
                start_time = start_time,
                end_time = end_time,
                welcome_text = welcome_text,
                completed_text = completed_text,
                public_enabled = public_enabled
            )
            m.save()
            # this order is important to be able to access the relations
            for form in formset:
                question_text = form.cleaned_data["question_text"]
                q = Question(
                    question_text=question_text,
                    morsel = m
                )
                answer = Answer(question=q)
                q.answer.answer_text = form.cleaned_data["answer_text"]
                q.save()
    morsel = get_object_or_404(Morsel.objects.prefetch_related('questions'), pk=morsel_id)
    form = MorselCreationForm(initial={
        "start_time" : morsel.start_time,
        "end_time" : morsel.end_time,
        "name" : morsel.name,
        "welcome_text" : morsel.welcome_text,
        "completed_text" : morsel.completed_text,
        "public_enabled" : morsel.public_enabled
    })
    initial_formset_values = [{"question_text":question.question_text,"answer_text":question.answer.answer_text} \
    for question in morsel.questions.select_related("answer").all()]
    formset = formset_factory(QuestionAnswerCreationForm, extra=1, max_num=len(morsel.questions.all()))(initial=initial_formset_values)
    return render(request, 'app/edit_morsel.html', {'form':form, 'formset':formset})
</code>```

Traceback:

```<code>Environment:

Request Method: GET
Request URL: http://localhost:8000/app/morsels/

Django Version: 1.11.6
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'app.apps.AppConfig',
 'django_extensions',
 'twilio',
 'debug_toolbar',
 'bootstrap3',
 'sass_processor']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware']

Template error:
In template /Users/kiniadit/code/morsels/app/templates/app/base.html, error at line 12
   Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$']   2 : <html><head>
   3 :         <meta charset="utf-8">
   4 :         <meta name="viewport" content="width=device-width, initial-scale=1">
   5 :         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">s
   6 :
   7 :         <!-- Custom links -->
   8 :          <link href="{% static 'app/css/style.css' %}" rel="stylesheet" type="text/css" />
   9 :         <body>
   10 :         <nav class="navbar navbar-expand-md navbar-dark bg-success">
   11 :           <div class="container">
   12 :             <a  class="navbar-brand" href="/"><img sr c="{% static 'app/images/logo.png' %}"></a>
   13 :             <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar2SupportedContent" aria-controls="navbar2SupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button>
   14 :             <div class="collapse navbar-collapse text-center justify-content-end" id="navbar2SupportedContent">
   15 :               <ul class="navbar-nav">
   16 :                 <li class="nav-item">
   17 :                   <a class="nav-link text-white" href="{% url 'app:about' %}">About</a>
   18 :                 </li>
   19 :                 <li class="nav-item">
   20 :                   <a class="nav-link text-white" href="{% url 'app:faq' %}">FAQ</a>
   21 :                 </li>
   22 :               </ul>

Traceback:

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  215.                 response = response.render()

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in render
  107.             self.content = self.rendered_content

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in rendered_content
  84.         content = template.render(context, self._request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  207.                     return self._render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
  107.     return self.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
  107.     return self.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  216.                     nodelist.append(node.render_annotated(context))

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  458.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/base.py" in reverse
  91.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
  497.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /app/morsels/
Exception Value: Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$']
</code>```

答:
Your regex matches a single digit, so it works for pk=9 but not pk=10. Add a + so that it matches multiple digits.

```<code>url(r'^morsels/(?P<pk>[0-9]+)/display/$', MorselDetailView.as_view(), name='morsel_detail'),
</code>```

You’ll need to fix your other URL patterns that use [0-9] as well.

Title: No Reverse Match error in Django

Body:
New to Django and stuck on this error. My template was rendering correctly. The only change I made was adding a '1/0' in my views.py file to simulate a breakpoint. And now the template will not render when I remove it.

urls.py

from django.conf.urls import url
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.views import login, logout
from app.views import send_morsel, start_hunt, MorselList, MorselDetailView,\
register, create_morsel, HomePageView, FAQPageView, AboutPageView,\
newsletter_signup, edit_morsel

app_name = 'app'
urlpatterns = [
    url(r'^$', HomePageView.as_view(), name='home'),
    url(r'^morsels/$', MorselList.as_view(), name='morsel_list'),
    url(r'^morsels/send/$', send_morsel, name='morsel_send'),
    url(r'^morsels/(?P<morsel_id>[0-9])/start_hunt/$', start_hunt, name='start_hunt'),
    url(r'^register/', register, name='register'),
    url(r'^faq/$', FAQPageView.as_view(), name='faq'),
    url(r'^about/$', AboutPageView.as_view(), name='about'),
    url(r'^morsels/create/$', create_morsel, name="create_morsel"),
    url(r'^morsels/(?P<morsel_id>[0-9])/edit/$', edit_morsel, name='edit_morsel'),
    url(r'^morsels/(?P<pk>[0-9])/display/$', MorselDetailView.as_view(), name='morsel_detail'),
    url(r'^newsletter_signup/$', newsletter_signup, name='newsletter_signup')
]

morsel_list.html

{% extends "app/base.html" %}
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
{% block content %}

Morsels

    {% if user.is_authenticated %}

hello

welcome {{ user.username }}

Logout

    {% else %}

Login

Register

    {% endif %}

        {% for morsel in object_list %}

{{ morsel.name }}
                View
                Edit
                Send!

        {% endfor %}

    {% if messages %}
        {% for msg in messages %}
            {% bootstrap_alert msg.message alert_type=msg.level_tag %}
        {% endfor %}
    {% endif %}
{% endblock %}

Really not sure what to do here.

relevant block from views.py:

def edit_morsel(request, morsel_id=None):
    if request.method == 'POST':
        extra = int(request.session['extra'])
        form = MorselCreationForm(request.POST)
        formset = formset_factory(QuestionAnswerCreationForm, extra=extra)(request.POST)
        if form.is_valid() and formset.is_valid():
            name = form.cleaned_data["name"]
            start_time = form.cleaned_data["start_time"]
            end_time = form.cleaned_data["end_time"]
            welcome_text = form.cleaned_data["welcome_text"]
            completed_text = form.cleaned_data["completed_text"]
            public_enabled = form.cleaned_data["public_enabled"]
            m = Morsel(
                name=name,
                start_time = start_time,
                end_time = end_time,
                welcome_text = welcome_text,
                completed_text = completed_text,
                public_enabled = public_enabled
            )
            m.save()
            # this order is important to be able to access the relations
            for form in formset:
                question_text = form.cleaned_data["question_text"]
                q = Question(
                    question_text=question_text,
                    morsel = m
                )
                answer = Answer(question=q)
                q.answer.answer_text = form.cleaned_data["answer_text"]
                q.save()
    morsel = get_object_or_404(Morsel.objects.prefetch_related('questions'), pk=morsel_id)
    form = MorselCreationForm(initial={
        "start_time" : morsel.start_time,
        "end_time" : morsel.end_time,
        "name" : morsel.name,
        "welcome_text" : morsel.welcome_text,
        "completed_text" : morsel.completed_text,
        "public_enabled" : morsel.public_enabled
    })
    initial_formset_values = [{"question_text":question.question_text,"answer_text":question.answer.answer_text} \
    for question in morsel.questions.select_related("answer").all()]
    formset = formset_factory(QuestionAnswerCreationForm, extra=1, max_num=len(morsel.questions.all()))(initial=initial_formset_values)
    return render(request, 'app/edit_morsel.html', {'form':form, 'formset':formset})

Traceback:

Environment:

Request Method: GET
Request URL: http://localhost:8000/app/morsels/

Django Version: 1.11.6
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'app.apps.AppConfig',
 'django_extensions',
 'twilio',
 'debug_toolbar',
 'bootstrap3',
 'sass_processor']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware']

Template error:
In template /Users/kiniadit/code/morsels/app/templates/app/base.html, error at line 12
   Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$']   2 :
   3 :         <meta charset="utf-8">
   4 :         <meta name="viewport" content="width=device-width, initial-scale=1">
   5 :         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">s
   6 :
   7 :
   8 :          <link href="{% static 'app/css/style.css' %}" rel="stylesheet" type="text/css" />
   9 :
   10 :
   11 :

   12 :
   13 :             <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbar2SupportedContent" aria-controls="navbar2SupportedContent" aria-expanded="false" aria-label="Toggle navigation">  </button>
   14 :

   15 :

   16 :

   17 :                   About
   18 :

   19 :

   20 :                   FAQ
   21 :

   22 :

Traceback:

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  215.                 response = response.render()

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in render
  107.             self.content = self.rendered_content

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/response.py" in rendered_content
  84.         content = template.render(context, self._request)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  207.                     return self._render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
  107.     return self.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render
  107.     return self.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  216.                     nodelist.append(node.render_annotated(context))

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  458.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/base.py" in reverse
  91.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "/Users/kiniadit/code/morsels/env/lib/python3.6/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
  497.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /app/morsels/
Exception Value: Reverse for 'morsel_detail' with arguments '(10,)' not found. 1 pattern(s) tried: ['app/morsels/(?P<pk>[0-9])/display/$']

Body:
Your regex matches a single digit, so it works for pk=9 but not pk=10. Add a + so that it matches multiple digits.

url(r'^morsels/(?P<pk>[0-9]+)/display/$', MorselDetailView.as_view(), name='morsel_detail'),

You’ll need to fix your other URL patterns that use [0-9] as well.


问:
.htaccess doesn't redirect properly from one website to another website
I want to redirect temporarily from one URL to another URL using .htaccess

Example :

When browse from URL www.example.com, Then I want to redirect www.another-example.com. This is working good.

But don't want to redirect anywhere if browse like as www.example.com/other/path

But it is always redirecting to http://www.another-example.com if i browse like www.example.com/other/path other path.

Here is my .htaccess code

```<code><IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule    ^$   app/      [L]
  RewriteRule    (.*) app/$1    [L]
  Redirect 302 "/" "http://www.another-example.com"
</IfModule>
</code>```

How can I do it by modifying my .htaccess code?

答:
Don't use Redirect directive as it doesn't support regex and exact matching.

Use all mod_rewrite rules as in:

```<code><IfModule mod_rewrite.c>
  RewriteEngine on

  RewriteRule ^/?$ http://www.another-example.com [L,R=301]

  RewriteRule    ^$   app/      [L]

  RewriteRule    (.*) app/$1    [L]
</IfModule>
</code>```

^/?$ matches only landing page for current domain.

Make sure to clear your browser cache or use a different browser when testing this change.

Body:
I want to redirect temporarily from one URL to another URL using .htaccess

Example :

When browse from URL www.example.com, Then I want to redirect www.another-example.com. This is working good.

But don't want to redirect anywhere if browse like as www.example.com/other/path

But it is always redirecting to http://www.another-example.com if i browse like www.example.com/other/path other path.

Here is my .htaccess code

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule    ^$   app/      [L]
  RewriteRule    (.*) app/$1    [L]
  Redirect 302 "/" "http://www.another-example.com"
</IfModule>

How can I do it by modifying my .htaccess code?

Body:
Don't use Redirect directive as it doesn't support regex and exact matching.

Use all mod_rewrite rules as in:

<IfModule mod_rewrite.c>
  RewriteEngine on

  RewriteRule ^/?$ http://www.another-example.com [L,R=301]

  RewriteRule    ^$   app/      [L]

  RewriteRule    (.*) app/$1    [L]
</IfModule>

^/?$ matches only landing page for current domain.

Make sure to clear your browser cache or use a different browser when testing this change.


问:
Excel VBA - Evaluate Function Returning #NAME? Error
So I wrote a VBA code to calculate the number of blanks, non-blanks and total entries under each header for some input data. I want to add a code that copies and pastes the values from one sheet to another, dedupes the values, gives me the unique list of values under each header, number of unique values, and the number of times those unique values are occurring under the header.

Blanks: I used the countblank function earlier, but it would skip certain empty fields, so I changed it to sumproduct(len(Range)=0)*1).
Non-Blanks: I wrote a similar function and tried to calculate the above.

It turns out VBA is unable to process the Sumproduct function. Here are the approaches I have tried:

```<code> 1. Application.WorksheetFunction.Sumproduct(...)
 2. ..Number.. = "=Sumproduct(...)"
 3. ..Number.. = Evaluate("Sumproduct(...)")
 4. ..Number.. = Worksheet.Evaluate("Sumproduct(...)")
</code>```

Below is the code for the macro, I am writing the code on the Input_File, i.e., the Input worksheet.

```<code>Sub Dedupe()
ThisWorkbook.Worksheets("Control_Totals").Cells.ClearContents

Dim lRow As Long
Dim lCol As Long
Dim i As Long
Dim j As Long
Dim Input_File As Worksheet
Dim Output_File As Worksheet
Dim Dedup_File As Worksheet
Dim Col_Let As String
Dim Rng As String
Dim blank As String
Dim non_blank As String

Set Input_File = ThisWorkbook.Worksheets("Input")
Set Output_File = ThisWorkbook.Worksheets("Control_Totals")
Set Dedup_File = ThisWorkbook.Worksheets("Deduped")

With Output_File
        .Cells(1, 1) = "Field_Name"
        .Cells(1, 2) = "Blanks"
        .Cells(1, 3) = "Non-Blanks"
        .Cells(1, 4) = "Total"
End With

'Finding the last row among all entries, including the blank ones
lRow = Input_File.Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

MsgBox "Last Row: " & lRow

'Finding the last column header/field
lCol = Input_File.Cells.Find(What:="*", _
                  LookAt:=xlPart, _
                  LookIn:=xlFormulas, _
                  SearchOrder:=xlByColumns, _
                  SearchDirection:=xlPrevious, _
                  MatchCase:=False).Column

MsgBox "Last Column: " & lCol

i = 1

'Finding the number of blank and non-blank entries for all the fields
Do While i < lCol + 1
Col_Let = ColumnLetter(i)
Rng = "Input!" & "Col_Let" & "2" & ":" & "lRow"

    Output_File.Cells(i + 1, 1) = Input_File.Cells(1, i)

         blank = "SumProduct((Len(Rng) = 0) * 1)"
         non_blank = "SumProduct((Len(Rng) > 0) * 1)"

    Output_File.Cells(i + 1, 2).Value = Evaluate(blank)
    Output_File.Cells(i + 1, 3).Value = Evaluate(non_blank)
    Output_File.Cells(i + 1, 4) = lRow - 1

    'Deduping the data under the headers
    j = 0
    For j = 1 To lRow
    Dedup_File.Cells(j, i).Value = Input_File.Cells(j, i).Value
    j = j + 1
    Next
    Dedup_File.Range(Cells(1, i), Cells(lRow, i)).RemoveDuplicates Columns:=1, _
    Header:=xlYes

        i = i + 1

Loop

End Sub
</code>```

答:
I want to add a code that copies and pastes the values from one sheet to another, dedupes the values, gives me the unique list of values under each header, number of unique values, and the number of times those unique values are occurring under the header.

What you have just described there is a PivotTable, with the field of interest in both the Rows area and in the Values area as a Count.

Body:
So I wrote a VBA code to calculate the number of blanks, non-blanks and total entries under each header for some input data. I want to add a code that copies and pastes the values from one sheet to another, dedupes the values, gives me the unique list of values under each header, number of unique values, and the number of times those unique values are occurring under the header.

Blanks: I used the countblank function earlier, but it would skip certain empty fields, so I changed it to sumproduct(len(Range)=0)*1).
Non-Blanks: I wrote a similar function and tried to calculate the above.

It turns out VBA is unable to process the Sumproduct function. Here are the approaches I have tried:

 1. Application.WorksheetFunction.Sumproduct(...)
 2. ..Number.. = "=Sumproduct(...)"
 3. ..Number.. = Evaluate("Sumproduct(...)")
 4. ..Number.. = Worksheet.Evaluate("Sumproduct(...)")

Below is the code for the macro, I am writing the code on the Input_File, i.e., the Input worksheet.

Sub Dedupe()
ThisWorkbook.Worksheets("Control_Totals").Cells.ClearContents

Dim lRow As Long
Dim lCol As Long
Dim i As Long
Dim j As Long
Dim Input_File As Worksheet
Dim Output_File As Worksheet
Dim Dedup_File As Worksheet
Dim Col_Let As String
Dim Rng As String
Dim blank As String
Dim non_blank As String

Set Input_File = ThisWorkbook.Worksheets("Input")
Set Output_File = ThisWorkbook.Worksheets("Control_Totals")
Set Dedup_File = ThisWorkbook.Worksheets("Deduped")

With Output_File
        .Cells(1, 1) = "Field_Name"
        .Cells(1, 2) = "Blanks"
        .Cells(1, 3) = "Non-Blanks"
        .Cells(1, 4) = "Total"
End With

'Finding the last row among all entries, including the blank ones
lRow = Input_File.Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

MsgBox "Last Row: " & lRow

'Finding the last column header/field
lCol = Input_File.Cells.Find(What:="*", _
                  LookAt:=xlPart, _
                  LookIn:=xlFormulas, _
                  SearchOrder:=xlByColumns, _
                  SearchDirection:=xlPrevious, _
                  MatchCase:=False).Column

MsgBox "Last Column: " & lCol

i = 1

'Finding the number of blank and non-blank entries for all the fields
Do While i < lCol + 1
Col_Let = ColumnLetter(i)
Rng = "Input!" & "Col_Let" & "2" & ":" & "lRow"

    Output_File.Cells(i + 1, 1) = Input_File.Cells(1, i)

         blank = "SumProduct((Len(Rng) = 0) * 1)"
         non_blank = "SumProduct((Len(Rng) > 0) * 1)"

    Output_File.Cells(i + 1, 2).Value = Evaluate(blank)
    Output_File.Cells(i + 1, 3).Value = Evaluate(non_blank)
    Output_File.Cells(i + 1, 4) = lRow - 1

    'Deduping the data under the headers
    j = 0
    For j = 1 To lRow
    Dedup_File.Cells(j, i).Value = Input_File.Cells(j, i).Value
    j = j + 1
    Next
    Dedup_File.Range(Cells(1, i), Cells(lRow, i)).RemoveDuplicates Columns:=1, _
    Header:=xlYes

        i = i + 1

Loop

End Sub


问:
pass userData from callback-begin to callback-end
How to appropriately cache userData that is generated from user's callbackBegin() and send it to user's callbackEnd().

Simple version  (No userData - demo)

I want to create a complex database that support callback.  For MCVE, let's say it is MyArray.

Here is a simple array class that supports callback but no userData.

```<code>#include <iostream>
template<class Derived>class MyArray{           //library - I design it.
    public: void push_back(int s){
        static_cast<Derived*>(this)->callbackBegin(s);
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s);
    }
    //other fields / functions
};
class Callback : public MyArray<Callback>{      //user's class
    public: void callbackBegin(int s){
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s){
        std::cout<<"callbackEnd"<<std::endl;
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd
    return 0;
}
</code>```

It works correctly.

The next step : I want to pass some userData from Callback::callbackBegin() to Callback::callbackEnd().

For example, userData is a clock time when Callback::callbackBegin() is called.

My poor solution (void*& userdata : demo)

Here is my attempt to implement it :-

```<code>#include <iostream>
#include <time.h>
template<class Derived>class MyArray{
    public: void push_back(int s){
        void* userData=nullptr;                                 //#
        static_cast<Derived*>(this)->callbackBegin(s,userData); //# ugly
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s,userData);   //# ugly
    }
};
class Callback : public MyArray<Callback>{
    public: void callbackBegin(int s,void*& userData){          //#
        userData=new clock_t(clock());                          //# danger
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s,void*& userData){            //#
        clock_t* userDataTyped=static_cast<clock_t*>(userData);
        clock_t clock2=clock();
        clock_t different=clock2 - (*userDataTyped);
        std::cout<<"callbackEnd time(second)="
                 <<((float)different)/CLOCKS_PER_SEC<<std::endl;
        delete userDataTyped;                                   //# danger
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd time(second)=8.5e-05
    return 0;
}
</code>```

It also works correctly, but I believe it is a bad design (at various #) :-

new/delete in 2 places : potential memory leaking.

Strong pointer is preferred, but I don't know how to.

static_cast<clock_t*>(userData) is code-smell, at least for me.

(minor issue) an extra ugly parameter void*&

Question: What are design patterns / C++ magic to avoid such issues, while make MyArray concise, easy to use, maintainable (i.e. not much worse than the Simple version)?

Other notes:

In real cases, <5% of user's callback classes need userData.

Thus, I feel very reluctant to add void&* as an extra parameter.

Clarify: (edited) The minority cases usually need different types of userData e.g. Callback1 need clock_t,  Callback2 need std::string, etc.

Proposed solution should restrain from using std::function<> or virtual function, because the performance is a major concern here.

Thank.

答:
std::any would allow you to hold clock_t (or any other) object and do away with the void* pointers, however that's a C++17 concept and not yet widely available (although there are implementations such as boost::any).

In the meantime, your code may benefit from a little composition over inheritance, as array and callback are conceptually pretty different and don't seem to belong in the same inheritance hierarchy. So, preferring composition, the code might look something like:

```<code>template<class T> struct ICallback
{
    virtual void callbackBegin(int s, std::unique_ptr<T>& p) = 0;
    virtual void callbackEnd(int s, std::unique_ptr<T>& p) = 0;
};

template<class T> class MyArray
{
public:
    MyArray(std::shared_ptr<ICallback<T>> cb) { callback = cb; }
    void push_back(int s)
    {
        callback->callbackBegin(s, usrDataPtr);
        //do something about array
        callback->callbackEnd(s, usrDataPtr);
    }
protected:
    std::shared_ptr<ICallback<T>> callback;
    std::unique_ptr<T> usrDataPtr;
};

class ClockCallback : public ICallback<clock_t>
{
public:
    void callbackBegin(int s, std::unique_ptr<clock_t>& c){
        c = std::make_unique<clock_t>(clock());
        std::cout << "callbackBegin" << std::endl;
    }
    void callbackEnd(int s, std::unique_ptr<clock_t>& c){
        clock_t clock2 = clock();
        clock_t different = clock2 - (*c);
        std::cout << "callbackEnd time(second)="
            << ((float)different) / CLOCKS_PER_SEC << std::endl;
    }
};

int main() {
    std::shared_ptr<ClockCallback> c = std::make_shared<ClockCallback>();
    MyArray<clock_t> ma(c);
    ma.push_back(7);

    return 0;
}
</code>```

Body:
How to appropriately cache userData that is generated from user's callbackBegin() and send it to user's callbackEnd().

Simple version  (No userData - demo)

I want to create a complex database that support callback.  For MCVE, let's say it is MyArray.

Here is a simple array class that supports callback but no userData.

#include <iostream>
template<class Derived>class MyArray{           //library - I design it.
    public: void push_back(int s){
        static_cast<Derived*>(this)->callbackBegin(s);
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s);
    }
    //other fields / functions
};
class Callback : public MyArray<Callback>{      //user's class
    public: void callbackBegin(int s){
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s){
        std::cout<<"callbackEnd"<<std::endl;
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd
    return 0;
}

It works correctly.

The next step : I want to pass some userData from Callback::callbackBegin() to Callback::callbackEnd().

For example, userData is a clock time when Callback::callbackBegin() is called.

My poor solution (void*& userdata : demo)

Here is my attempt to implement it :-

#include <iostream>
#include <time.h>
template<class Derived>class MyArray{
    public: void push_back(int s){
        void* userData=nullptr;                                 //#
        static_cast<Derived*>(this)->callbackBegin(s,userData); //# ugly
        //do something about array
        static_cast<Derived*>(this)->callbackEnd(s,userData);   //# ugly
    }
};
class Callback : public MyArray<Callback>{
    public: void callbackBegin(int s,void*& userData){          //#
        userData=new clock_t(clock());                          //# danger
        std::cout<<"callbackBegin"<<std::endl;
    }
    public: void callbackEnd(int s,void*& userData){            //#
        clock_t* userDataTyped=static_cast<clock_t*>(userData);
        clock_t clock2=clock();
        clock_t different=clock2 - (*userDataTyped);
        std::cout<<"callbackEnd time(second)="
                 <<((float)different)/CLOCKS_PER_SEC<<std::endl;
        delete userDataTyped;                                   //# danger
    }
};
int main() {
    Callback c;
    c.push_back(5); //print: callbackBegin callbackEnd time(second)=8.5e-05
    return 0;
}

It also works correctly, but I believe it is a bad design (at various #) :-

new/delete in 2 places : potential memory leaking.

Strong pointer is preferred, but I don't know how to.

static_cast<clock_t*>(userData) is code-smell, at least for me.

(minor issue) an extra ugly parameter void*&

Question: What are design patterns / C++ magic to avoid such issues, while make MyArray concise, easy to use, maintainable (i.e. not much worse than the Simple version)?

Other notes:

In real cases, <5% of user's callback classes need userData.

Thus, I feel very reluctant to add void&* as an extra parameter.

Clarify: (edited) The minority cases usually need different types of userData e.g. Callback1 need clock_t,  Callback2 need std::string, etc.

Proposed solution should restrain from using std::function<> or virtual function, because the performance is a major concern here.

Thank.

Body:
std::any would allow you to hold clock_t (or any other) object and do away with the void* pointers, however that's a C++17 concept and not yet widely available (although there are implementations such as boost::any).

In the meantime, your code may benefit from a little composition over inheritance, as array and callback are conceptually pretty different and don't seem to belong in the same inheritance hierarchy. So, preferring composition, the code might look something like:

template<class T> struct ICallback
{
    virtual void callbackBegin(int s, std::unique_ptr<T>& p) = 0;
    virtual void callbackEnd(int s, std::unique_ptr<T>& p) = 0;
};

template<class T> class MyArray
{
public:
    MyArray(std::shared_ptr<ICallback<T>> cb) { callback = cb; }
    void push_back(int s)
    {
        callback->callbackBegin(s, usrDataPtr);
        //do something about array
        callback->callbackEnd(s, usrDataPtr);
    }
protected:
    std::shared_ptr<ICallback<T>> callback;
    std::unique_ptr<T> usrDataPtr;
};

class ClockCallback : public ICallback<clock_t>
{
public:
    void callbackBegin(int s, std::unique_ptr<clock_t>& c){
        c = std::make_unique<clock_t>(clock());
        std::cout << "callbackBegin" << std::endl;
    }
    void callbackEnd(int s, std::unique_ptr<clock_t>& c){
        clock_t clock2 = clock();
        clock_t different = clock2 - (*c);
        std::cout << "callbackEnd time(second)="
            << ((float)different) / CLOCKS_PER_SEC << std::endl;
    }
};

int main() {
    std::shared_ptr<ClockCallback> c = std::make_shared<ClockCallback>();
    MyArray<clock_t> ma(c);
    ma.push_back(7);

    return 0;
}


问:
Searching in mongoDb (using mongooseJS) by several criteria
For example, I've got a Schema

```<code>let UserSchema = new Schema({

username: { type: String, required: true, unique: true },
name: { type: String, required: true },
surname: { type: String, required: true },
....
....
</code>```

Is it possible to search for users by name, username, surname simultaneously? I mean, if we input "Paul" - we get an array of users including users with username containing "Paul", name "Paul" and surname< which may contain "Paul".

How to do this using queries in Mongoose(how the construction for this kind of search looks like) Thanks for attention.

答:
The basic syntax around Mongoose queries is nicely documented.

And, yes, you can use any number of fields in a search condition. There is a bunch of logical operators available to combine your filters with. And for case-insensitive "contains" queries you'd need to use $regex like so:

```<code>var userName = "Paul";
var User = mongoose.model('User', UserSchema);
User.find({
    $or:
    [
        { "username": { $regex: userName, $options: 'i' } },
        { "name": { $regex: userName, $options: 'i' } },
        { "surname": { $regex: userName, $options: 'i' } }
    ]
},
function (err, docs) {
    /* do something with your results */
});
</code>```

Body:
For example, I've got a Schema

let UserSchema = new Schema({

username: { type: String, required: true, unique: true },
name: { type: String, required: true },
surname: { type: String, required: true },
....
....

Is it possible to search for users by name, username, surname simultaneously? I mean, if we input "Paul" - we get an array of users including users with username containing "Paul", name "Paul" and surname< which may contain "Paul".

How to do this using queries in Mongoose(how the construction for this kind of search looks like) Thanks for attention.

Body:
The basic syntax around Mongoose queries is nicely documented.

And, yes, you can use any number of fields in a search condition. There is a bunch of logical operators available to combine your filters with. And for case-insensitive "contains" queries you'd need to use $regex like so:

var userName = "Paul";
var User = mongoose.model('User', UserSchema);
User.find({
    $or:
    [
        { "username": { $regex: userName, $options: 'i' } },
        { "name": { $regex: userName, $options: 'i' } },
        { "surname": { $regex: userName, $options: 'i' } }
    ]
},
function (err, docs) {
    /* do something with your results */
});


问:
MD5 hash decryption when knowing part of input
Is it possible to decrypt an MD5 hash if you have part of the original text? Like:

```<code>Text     : hi how are you?
MD5 hash : 31a015d54f92382d2cee35eb2f0cc556
</code>```

MD5 hashes can't be decrypted, but if I know part of the text like hi how are, does that help?

答:
Is it possible to decrypt an MD5 hash if you have part of the original text?

Given an exhaustive key search (brute-force) attack is applied then theoretically the answer is yes, because knowing a digestive algorithm's partial input helps determine its complete original input by:

reducing key space.

reducing false positives (collisions).

Theoretically, because cost (time) relates to key space and reduction does not necessarily result in manageable size. However, ability to dismiss collisions increases likeliness to discern actual input (which would not be possible otherwise).

Related.

Body:
Is it possible to decrypt an MD5 hash if you have part of the original text? Like:

Text     : hi how are you?
MD5 hash : 31a015d54f92382d2cee35eb2f0cc556

MD5 hashes can't be decrypted, but if I know part of the text like hi how are, does that help?


问:
How to specify Docker private registry credentials in Docker configuration File?
I am creating Docker container of nodejs application. Below is the sample of my Docker configuration file

```<code>FROM node:6.11
WORKDIR /usr/src/app
COPY package.json .
npm install
copy . /usr/src/app
EXPOSE 80
CMD [ "npm", "start" ]
</code>```

This will download the node image from Docker hub and then it will create Docker image as per the configuration.

For security reasons I don't want to download nodejs image from Docker hub, Instead I want to use my private repository to download nodejs image.

As I have setup private repository I am not sure how to specify registry credentials in DockerFile.

Can anyone help me with this?

答:
By default, docker pulls all images from Dockerhub. If you want to pull an image from another registry, you have to prefix the image name with the registry URL. Check the official docker pull documentation.

In your case, you have 2 options:

The first is to specify explicitly the registry inside the Dockerfile as such:

```<code>FROM <registry>:<port>/node:6.11
WORKDIR /usr/src/app
</code>```

Once you build, the image will be downloaded from the private registry. Make sure that you are logged in to the registry before building using the docker login command.

Alternatively, if you don't want to change the docker file. Pull the image from the private registry using docker pull <registry>:<port>/node:6.11 and then force docker build to use this image by tagging it with only node:6.11

```<code>docker tag <registry>:<port>/node:6.11 node:6.11
</code>```

Body:
I am creating Docker container of nodejs application. Below is the sample of my Docker configuration file

FROM node:6.11
WORKDIR /usr/src/app
COPY package.json .
npm install
copy . /usr/src/app
EXPOSE 80
CMD [ "npm", "start" ]

This will download the node image from Docker hub and then it will create Docker image as per the configuration.

For security reasons I don't want to download nodejs image from Docker hub, Instead I want to use my private repository to download nodejs image.

As I have setup private repository I am not sure how to specify registry credentials in DockerFile.

Can anyone help me with this?

Body:
By default, docker pulls all images from Dockerhub. If you want to pull an image from another registry, you have to prefix the image name with the registry URL. Check the official docker pull documentation.

In your case, you have 2 options:

The first is to specify explicitly the registry inside the Dockerfile as such:

FROM <registry>:<port>/node:6.11
WORKDIR /usr/src/app

Once you build, the image will be downloaded from the private registry. Make sure that you are logged in to the registry before building using the docker login command.

Alternatively, if you don't want to change the docker file. Pull the image from the private registry using docker pull <registry>:<port>/node:6.11 and then force docker build to use this image by tagging it with only node:6.11

docker tag <registry>:<port>/node:6.11 node:6.11


问:
how to initialize diff date formats in spring config xml with constructor injection
I have two diff POJOs(Bean Classes) and i need to have diff date format for each bean. Do i need to initialize the SimpleDateFormat twice with diff Ids so that my two POJOs can use the two date formats?</p>

```<code><bean id="dateFormatEmployee" class="java.text.SimpleDateFormat">
    <constructor-arg value="mm-dd-yy"></constructor-arg>
    <constructor-arg value="true" />
</bean>
<bean id="dateFormatUser" class="java.text.SimpleDateFormat">
    <constructor-arg value="dd-mm-yyyy"></constructor-arg>
    <constructor-arg value="true" />
</bean>
<bean id="employee" class="com.kranti.springcore.Employee">
    <constructor-arg name="dob">
        <bean factory-bean="dateFormatEmployee" factory-method="parse">
            <constructor-arg value="12-20-90"></constructor-arg>
        </bean>
    </constructor-arg>
</bean>
<bean id="user" class="com.kranti.springcore.User">
    <constructor-arg name="dob">
        <bean factory-bean="dateFormatUser" factory-method="parse">
            <constructor-arg value="20-12-1995"></constructor-arg>
        </bean>
    </constructor-arg>
</bean>
</code>```

答:
SimpleDateFormat is not a thread safe class and should not be created as a singleton - here is why. As a workaround try putting these formats in a properties file. Inject these formats as necessary in to your code and use it when instantiating the SimpleDateFormat class.

Your properties file could look like:

```<code>date.format.user=dd-mm-yyyy
date.format.employee=mm-dd-yy
</code>```

Lets say you have a service beans which handles employees and users

```<code>@Component
public class Employee {

    @Value("${date.format.employee}")
    private String dateFormat; // this will end up with the value mm-dd-yy

    public void doStuff() {
        // your service code here
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        // do something with simpleDateFormat
    }

}

@Component
public class User {

    @Value("${date.format.user}")
    private String dateFormat; // this will end up with the value dd-mm-yyyy

    public void doStuff() {
        // your service code here
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        // do something with simpleDateFormat
    }

}
</code>```

Body:
I have two diff POJOs(Bean Classes) and i need to have diff date format for each bean. Do i need to initialize the SimpleDateFormat twice with diff Ids so that my two POJOs can use the two date formats?

<bean id="dateFormatEmployee" class="java.text.SimpleDateFormat">
    <constructor-arg value="mm-dd-yy"></constructor-arg>
    <constructor-arg value="true" />
</bean>
<bean id="dateFormatUser" class="java.text.SimpleDateFormat">
    <constructor-arg value="dd-mm-yyyy"></constructor-arg>
    <constructor-arg value="true" />
</bean>
<bean id="employee" class="com.kranti.springcore.Employee">
    <constructor-arg name="dob">
        <bean factory-bean="dateFormatEmployee" factory-method="parse">
            <constructor-arg value="12-20-90"></constructor-arg>
        </bean>
    </constructor-arg>
</bean>
<bean id="user" class="com.kranti.springcore.User">
    <constructor-arg name="dob">
        <bean factory-bean="dateFormatUser" factory-method="parse">
            <constructor-arg value="20-12-1995"></constructor-arg>
        </bean>
    </constructor-arg>
</bean>

Body:
SimpleDateFormat is not a thread safe class and should not be created as a singleton - here is why. As a workaround try putting these formats in a properties file. Inject these formats as necessary in to your code and use it when instantiating the SimpleDateFormat class.

Your properties file could look like:

date.format.user=dd-mm-yyyy
date.format.employee=mm-dd-yy

Lets say you have a service beans which handles employees and users

@Component
public class Employee {

    @Value("${date.format.employee}")
    private String dateFormat; // this will end up with the value mm-dd-yy

    public void doStuff() {
        // your service code here
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        // do something with simpleDateFormat
    }

}

@Component
public class User {

    @Value("${date.format.user}")
    private String dateFormat; // this will end up with the value dd-mm-yyyy

    public void doStuff() {
        // your service code here
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        // do something with simpleDateFormat
    }

}


问:
Angular2 FormGroup in FormArray validation
I have the following model:

```<code>export interface Content {
  lang: string;
  title: string;
}
</code>```

I need to validate a contents FormArray of this parent FormGroup:

```<code>this.formBuilder.group({
  defaultLang: ['', Validators.required],
  contents: this.formBuilder.array([], Validators.minLength(1))
});
</code>```

For each Content in my contents FormArray, I validate the model with the following content FormGroup:

```<code>this.formBuilder.group({
  lang: ['', Validators.required],
  title: ['', Validators.required]
});
</code>```

For now, I add the following content FormGroup to my contents FormArray to validate each Content:

```<code>(<FormArray>parentFormGroup.controls['contents'])
    .push(this.contentFormGroup);
</code>```

But with this approach I can't validate these rules:

If one of the Content fields are filled up then content validation occurs (which means adding the content FormGroup to the contents FormArray)

If none of the content fields are filled up then no content validation occurs (which means removing the content FormGroup of the contents FormArray if present)

If lang of a Content is the defaultLang of the parent FormGroup, then the content is required.

Questions

Is there a work around of adding/removing the content FormGroup of the contents FormArray just with validators?

Is there a way to do it with Angular native validators only?

Do I need to create a custom validator? If yes, do you have great example to do so with FormArray?

答:
You can add validator to the group like below</p>

```<code> this.group = this.formBuilder.group({
        lang: ['', Validators.required],
        title: ['', Validators.required]
    });

    this.group.setValidators([
        this.titleRequiredValidator(),
    ]);

    private titleRequiredValidator(): ValidatorFn {
        return (group: FormGroup): { [key: string]: any } => {
        const langControl = group.controls.lang;
        const titleControl = group.controls.title;

        if (langControl.value !== '' && titleControl.value == '')) {
            const error = { required: true };
            titleControl.setErrors(error);
            return error;
        }
        else {
            titleControl.setErrors(null);
            return null;
        }
    };
}
</code>```

Body:
I have the following model:

export interface Content {
  lang: string;
  title: string;
}

I need to validate a contents FormArray of this parent FormGroup:

this.formBuilder.group({
  defaultLang: ['', Validators.required],
  contents: this.formBuilder.array([], Validators.minLength(1))
});

For each Content in my contents FormArray, I validate the model with the following content FormGroup:

this.formBuilder.group({
  lang: ['', Validators.required],
  title: ['', Validators.required]
});

For now, I add the following content FormGroup to my contents FormArray to validate each Content:

(<FormArray>parentFormGroup.controls['contents'])
    .push(this.contentFormGroup);

But with this approach I can't validate these rules:

If one of the Content fields are filled up then content validation occurs (which means adding the content FormGroup to the contents FormArray)

If none of the content fields are filled up then no content validation occurs (which means removing the content FormGroup of the contents FormArray if present)

If lang of a Content is the defaultLang of the parent FormGroup, then the content is required.

Questions

Is there a work around of adding/removing the content FormGroup of the contents FormArray just with validators?

Is there a way to do it with Angular native validators only?

Do I need to create a custom validator? If yes, do you have great example to do so with FormArray?

Body:
You can add validator to the group like below

 this.group = this.formBuilder.group({
        lang: ['', Validators.required],
        title: ['', Validators.required]
    });

    this.group.setValidators([
        this.titleRequiredValidator(),
    ]);

    private titleRequiredValidator(): ValidatorFn {
        return (group: FormGroup): { [key: string]: any } => {
        const langControl = group.controls.lang;
        const titleControl = group.controls.title;

        if (langControl.value !== '' && titleControl.value == '')) {
            const error = { required: true };
            titleControl.setErrors(error);
            return error;
        }
        else {
            titleControl.setErrors(null);
            return null;
        }
    };
}


问:
Error compiling CPP application. "error: 'posix_memalign' was not declared in this scope"
I'm trying to compile a CPP application (an open source project) in the latest cygwin64 environment using g++ 6.4.0 and I get the following error:

error: 'posix_memalign' was not declared in this scope

now posix_memlign can be found in stdlib.h if you compile the most simple CPP "hello world" application there wouldn't be a problem calling posix_memlign.

The make file of the project report the following setup for the compilation

g++ -DHAVE_CONFIG_H -I. -Wall -Wnon-virtual-dtor -I. -I./include -g -O3 -std=c++0x -g -O3 -std=c++0x -MT lib/rectangular_binary_matrix.lo -MD -MP -MF lib/.deps/rectangular_binary_matrix.Tpo -c lib/rectangular_binary_matrix.cc  -DDLL_EXPORT -DPIC -o lib/.libs/rectangular_binary_matrix.o

so it doesn't look like it override the default include path. Any ideas?

p.s.
I was able to build the code on Linux (Redhat) without a problem.

答:
posix_memalign is not part of the C Standard Library or the C++ Standard
library and the cygwin GCC compilers do not provide it, although other
compilers may do so, including GCC compilers from other builders.

You might consider using instead the C Standard function aligned_alloc, if you feel comfortable to edit your project source. It is provided in <cstdlib> for C++ compilation in cygwin g++ 6.4.0

Later

I do see the function in C:\cygwin64\usr\include\stdlib.h...

The fact that you can find the function declaration in the header file
does not mean that the compiler can see it after preprocessing. The same
source header may be used by many builders, exposing different
declarations to the compiler depending on the builder's settings of implementor
macros. In this case, the declaration is concealed from your compiler by
the fact that __POSIX_VISIBLE >= 200112 is false. Identifiers beginning __ are reserved for implementors.
See the explanation of this macro
and note the comment:

```<code> * The following private macros are used throughout the headers to control
 * which symbols should be exposed.  They are for internal use only, as
 * indicated by the leading double underscore, and must never be used outside
 * of these headers.
</code>```

Body:
posix_memalign is not part of the C Standard Library or the C++ Standard
library and the cygwin GCC compilers do not provide it, although other
compilers may do so, including GCC compilers from other builders.

You might consider using instead the C Standard function aligned_alloc, if you feel comfortable to edit your project source. It is provided in <cstdlib> for C++ compilation in cygwin g++ 6.4.0

Later

I do see the function in C:\cygwin64\usr\include\stdlib.h...

The fact that you can find the function declaration in the header file
does not mean that the compiler can see it after preprocessing. The same
source header may be used by many builders, exposing different
declarations to the compiler depending on the builder's settings of implementor
macros. In this case, the declaration is concealed from your compiler by
the fact that __POSIX_VISIBLE >= 200112 is false. Identifiers beginning __ are reserved for implementors.
See the explanation of this macro
and note the comment:

 * The following private macros are used throughout the headers to control
 * which symbols should be exposed.  They are for internal use only, as
 * indicated by the leading double underscore, and must never be used outside
 * of these headers.


问:
Where on EC2/ElasticBeanstalk AWS_ACCESS_KEY_ID is stored?
To perform some action on Cognito on my dev environment I need to have: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY so I set them as environment variables. On the staging server I didn't set it and app works, so I assume it should be added automatically by EB or EC2 or anything else. Where can I find it and change?</p>

答:
You do not want to store credentials on your instance. Instead use IAM roles.

For Elastic Beanstalk look into Instance Profiles and Service Roles. This link will help you put everything inplace.

An instance profile is a container for an AWS Identity and Access
  Management (IAM) role that you can use to pass role information to an
  EC2 instance when the instance starts. When you launch an environment
  in the AWS Elastic Beanstalk environment management console, the
  console creates a default instance profile, called
  aws-elasticbeanstalk-ec2-role, and assigns managed policies with
  default permissions to it.

Using Elastic Beanstalk with AWS Identity and Access Management


问:
Incorrect stacktrace by rethrow
I rethrow an exception with "throw;", but the stacktrace is incorrect:

```<code>static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}
</code>```

The right stacktrace should be:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12
</code>```

But I get:

```<code>System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15
</code>```

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.

答:
I think this is less a case of stack trace changing and more to do with the way the line number for the stack trace is determined. Trying it out in Visual Studio 2010, the behaviour is similar to what you would expect from the MSDN documentation: "throw ex;" rebuilds the stack trace from the point of this statement, "throw;" leaves the stack trace as it as, except that where ever the exception is rethrown, the line number is the location of the rethrow and not the call the exception came through.

So with "throw;" the method call tree is left unaltered, but the line numbers may change.

I've come across this a few times, and it may be by design and just not documented fully. I can understand why they may have done this as the rethrow location is very useful to know, and if your methods are simple enough the original source would usually be obvious anyway.

As many other people have said, it usually best to not catch the exception unless you really have to, and/or you are going to deal with it at that point.

Interesting side note: Visual Studio 2010 won't even let me build the code as presented in the question as it picks up the divide by zero error at compile time.

Title: Incorrect stacktrace by rethrow

Body:
I rethrow an exception with "throw;", but the stacktrace is incorrect:

static void Main(string[] args) {
    try {
        try {
            throw new Exception("Test"); //Line 12
        }
        catch (Exception ex) {
            throw; //Line 15
        }
    }
    catch (Exception ex) {
        System.Diagnostics.Debug.Write(ex.ToString());
    }
    Console.ReadKey();
}

The right stacktrace should be:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 12

But I get:

System.Exception: Test
   at ConsoleApplication1.Program.Main(String[] args) in Program.cs:Line 15

But line 15 is the position of the "throw;". I have tested this with .NET 3.5.