问:
Why can't find osd pod in kubernetes after deploying rook-ceph?
Tried to install rook-ceph on kubernetes as this guide:

https://rook.io/docs/rook/v1.3/ceph-quickstart.html

```<code>git clone --single-branch --branch release-1.3 https://github.com/rook/rook.git
cd rook/cluster/examples/kubernetes/ceph
kubectl create -f common.yaml
kubectl create -f operator.yaml
kubectl create -f cluster.yaml
</code>```

When I check all the pods

```<code>$ kubectl -n rook-ceph get pod
NAME                                            READY   STATUS    RESTARTS   AGE
csi-cephfsplugin-9c2z9                          3/3     Running   0          23m
csi-cephfsplugin-provisioner-7678bcfc46-s67hq   5/5     Running   0          23m
csi-cephfsplugin-provisioner-7678bcfc46-sfljd   5/5     Running   0          23m
csi-cephfsplugin-smmlf                          3/3     Running   0          23m
csi-rbdplugin-provisioner-fbd45b7c8-dnwsq       6/6     Running   0          23m
csi-rbdplugin-provisioner-fbd45b7c8-rp85z       6/6     Running   0          23m
csi-rbdplugin-s67lw                             3/3     Running   0          23m
csi-rbdplugin-zq4k5                             3/3     Running   0          23m
rook-ceph-mon-a-canary-954dc5cd9-5q8tk          1/1     Running   0          2m9s
rook-ceph-mon-b-canary-b9d6f5594-mcqwc          1/1     Running   0          2m9s
rook-ceph-mon-c-canary-78b48dbfb7-z2t7d         0/1     Pending   0          2m8s
rook-ceph-operator-757d6db48d-x27lm             1/1     Running   0          25m
rook-ceph-tools-75f575489-znbbz                 1/1     Running   0          7m45s
rook-discover-gq489                             1/1     Running   0          24m
rook-discover-p9zlg                             1/1     Running   0          24m
</code>```

```<code>$ kubectl -n rook-ceph get pod -l app=rook-ceph-osd-prepare
No resources found in rook-ceph namespace.
</code>```

Do some other operation

```<code>$ kubectl taint nodes $(hostname) node-role.kubernetes.io/master:NoSchedule-
$ kubectl -n rook-ceph-system delete pods rook-ceph-operator-757d6db48d-x27lm
</code>```

Create file system

```<code>$ kubectl create -f filesystem.yaml
</code>```

Check again

```<code>$ kubectl get pods -n rook-ceph -o wide
NAME                                              READY   STATUS     RESTARTS   AGE    IP             NODE     NOMINATED NODE   READINESS GATES
csi-cephfsplugin-9c2z9                            3/3     Running    0          135m   192.168.0.53   kube3    <none>           <none>
csi-cephfsplugin-provisioner-7678bcfc46-s67hq     5/5     Running    0          135m   10.1.2.6       kube3    <none>           <none>
csi-cephfsplugin-provisioner-7678bcfc46-sfljd     5/5     Running    0          135m   10.1.2.5       kube3    <none>           <none>
csi-cephfsplugin-smmlf                            3/3     Running    0          135m   192.168.0.52   kube2    <none>           <none>
csi-rbdplugin-provisioner-fbd45b7c8-dnwsq         6/6     Running    0          135m   10.1.1.6       kube2    <none>           <none>
csi-rbdplugin-provisioner-fbd45b7c8-rp85z         6/6     Running    0          135m   10.1.1.5       kube2    <none>           <none>
csi-rbdplugin-s67lw                               3/3     Running    0          135m   192.168.0.52   kube2    <none>           <none>
csi-rbdplugin-zq4k5                               3/3     Running    0          135m   192.168.0.53   kube3    <none>           <none>
rook-ceph-crashcollector-kube2-6d95bb9c-r5w7p     0/1     Init:0/2   0          110m   <none>         kube2    <none>           <none>
rook-ceph-crashcollector-kube3-644c849bdb-9hcvg   0/1     Init:0/2   0          110m   <none>         kube3    <none>           <none>
rook-ceph-mon-a-canary-954dc5cd9-6ccbh            1/1     Running    0          75s    10.1.2.130     kube3    <none>           <none>
rook-ceph-mon-b-canary-b9d6f5594-k85w5            1/1     Running    0          74s    10.1.1.74      kube2    <none>           <none>
rook-ceph-mon-c-canary-78b48dbfb7-kfzzx           0/1     Pending    0          73s    <none>         <none>   <none>           <none>
rook-ceph-operator-757d6db48d-nlh84               1/1     Running    0          110m   10.1.2.28      kube3    <none>           <none>
rook-ceph-tools-75f575489-znbbz                   1/1     Running    0          119m   10.1.1.14      kube2    <none>           <none>
rook-discover-gq489                               1/1     Running    0          135m   10.1.1.3       kube2    <none>           <none>
rook-discover-p9zlg                               1/1     Running    0          135m   10.1.2.4       kube3    <none>           <none>
</code>```

Can't see pod as rook-ceph-osd-.

And rook-ceph-mon-c-canary-78b48dbfb7-kfzzx pod is always Pending.

If install toolbox as

https://rook.io/docs/rook/v1.3/ceph-toolbox.html

```<code>$ kubectl create -f toolbox.yaml
$ kubectl -n rook-ceph exec -it $(kubectl -n rook-ceph get pod -l "app=rook-ceph-tools" -o jsonpath='{.items[0].metadata.name}') bash
</code>```

Inside the container, check the ceph status

```<code>[root@rook-ceph-tools-75f575489-znbbz /]# ceph -s
unable to get monitor info from DNS SRV with service name: ceph-mon
[errno 2] error connecting to the cluster
</code>```

It's running on Ubuntu 16.04.6.

Deploy again

```<code>$ kubectl -n rook-ceph get pod -o wide
NAME                                            READY   STATUS    RESTARTS   AGE     IP             NODE     NOMINATED NODE   READINESS GATES
csi-cephfsplugin-4tww8                          3/3     Running   0          3m38s   192.168.0.52   kube2    <none>           <none>
csi-cephfsplugin-dbbfb                          3/3     Running   0          3m38s   192.168.0.53   kube3    <none>           <none>
csi-cephfsplugin-provisioner-7678bcfc46-8kt96   5/5     Running   0          3m37s   10.1.2.6       kube3    <none>           <none>
csi-cephfsplugin-provisioner-7678bcfc46-kq6vv   5/5     Running   0          3m38s   10.1.1.6       kube2    <none>           <none>
csi-rbdplugin-4qrqn                             3/3     Running   0          3m39s   192.168.0.53   kube3    <none>           <none>
csi-rbdplugin-dqx9z                             3/3     Running   0          3m39s   192.168.0.52   kube2    <none>           <none>
csi-rbdplugin-provisioner-fbd45b7c8-7f57t       6/6     Running   0          3m39s   10.1.2.5       kube3    <none>           <none>
csi-rbdplugin-provisioner-fbd45b7c8-9zwhb       6/6     Running   0          3m39s   10.1.1.5       kube2    <none>           <none>
rook-ceph-mon-a-canary-954dc5cd9-rgqpg          1/1     Running   0          2m40s   10.1.1.7       kube2    <none>           <none>
rook-ceph-mon-b-canary-b9d6f5594-n2pwc          1/1     Running   0          2m35s   10.1.2.8       kube3    <none>           <none>
rook-ceph-mon-c-canary-78b48dbfb7-fv46f         0/1     Pending   0          2m30s   <none>         <none>   <none>           <none>
rook-ceph-operator-757d6db48d-2m25g             1/1     Running   0          6m27s   10.1.2.3       kube3    <none>           <none>
rook-discover-lpsht                             1/1     Running   0          5m15s   10.1.1.3       kube2    <none>           <none>
rook-discover-v4l77                             1/1     Running   0          5m15s   10.1.2.4       kube3    <none>           <none>
</code>```

Describe pending pod

```<code>$ kubectl describe pod rook-ceph-mon-c-canary-78b48dbfb7-fv46f -n rook-ceph
Name:           rook-ceph-mon-c-canary-78b48dbfb7-fv46f
Namespace:      rook-ceph
Priority:       0
Node:           <none>
Labels:         app=rook-ceph-mon
                ceph_daemon_id=c
                mon=c
                mon_canary=true
                mon_cluster=rook-ceph
                pod-template-hash=78b48dbfb7
                rook_cluster=rook-ceph
Annotations:    <none>
Status:         Pending
IP:
IPs:            <none>
Controlled By:  ReplicaSet/rook-ceph-mon-c-canary-78b48dbfb7
Containers:
  mon:
    Image:      rook/ceph:v1.3.4
    Port:       6789/TCP
    Host Port:  0/TCP
    Command:
      /tini
    Args:
      --
      sleep
      3600
    Environment:
      CONTAINER_IMAGE:                ceph/ceph:v14.2.9
      POD_NAME:                       rook-ceph-mon-c-canary-78b48dbfb7-fv46f (v1:metadata.name)
      POD_NAMESPACE:                  rook-ceph (v1:metadata.namespace)
      NODE_NAME:                       (v1:spec.nodeName)
      POD_MEMORY_LIMIT:               node allocatable (limits.memory)
      POD_MEMORY_REQUEST:             0 (requests.memory)
      POD_CPU_LIMIT:                  node allocatable (limits.cpu)
      POD_CPU_REQUEST:                0 (requests.cpu)
      ROOK_CEPH_MON_HOST:             <set to the key 'mon_host' in secret 'rook-ceph-config'>             Optional: false
      ROOK_CEPH_MON_INITIAL_MEMBERS:  <set to the key 'mon_initial_members' in secret 'rook-ceph-config'>  Optional: false
      ROOK_POD_IP:                     (v1:status.podIP)
    Mounts:
      /etc/ceph from rook-config-override (ro)
      /etc/ceph/keyring-store/ from rook-ceph-mons-keyring (ro)
      /var/lib/ceph/crash from rook-ceph-crash (rw)
      /var/lib/ceph/mon/ceph-c from ceph-daemon-data (rw)
      /var/log/ceph from rook-ceph-log (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-65xtn (ro)
Conditions:
  Type           Status
  PodScheduled   False
Volumes:
  rook-config-override:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      rook-config-override
    Optional:  false
  rook-ceph-mons-keyring:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  rook-ceph-mons-keyring
    Optional:    false
  rook-ceph-log:
    Type:          HostPath (bare host directory volume)
    Path:          /var/lib/rook/rook-ceph/log
    HostPathType:
  rook-ceph-crash:
    Type:          HostPath (bare host directory volume)
    Path:          /var/lib/rook/rook-ceph/crash
    HostPathType:
  ceph-daemon-data:
    Type:          HostPath (bare host directory volume)
    Path:          /var/lib/rook/mon-c/data
    HostPathType:
  default-token-65xtn:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-65xtn
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason            Age                From               Message
  ----     ------            ----               ----               -------
  Warning  FailedScheduling  22s (x3 over 84s)  default-scheduler  0/3 nodes are available: 1 node(s) had taint {node-role.kubernetes.io/master: }, that the pod didn't tolerate, 2 node(s) didn't match pod affinity/anti-affinity, 2 node(s) didn't satisfy existing pods anti-affinity rules.
</code>```

Test mount

Create a nginx.yaml file

```<code>$ kubectl -n rook-ceph get pod
NAME                                            READY   STATUS    RESTARTS   AGE
csi-cephfsplugin-9c2z9                          3/3     Running   0          23m
csi-cephfsplugin-provisioner-7678bcfc46-s67hq   5/5     Running   0          23m
csi-cephfsplugin-provisioner-7678bcfc46-sfljd   5/5     Running   0          23m
csi-cephfsplugin-smmlf                          3/3     Running   0          23m
csi-rbdplugin-provisioner-fbd45b7c8-dnwsq       6/6     Running   0          23m
csi-rbdplugin-provisioner-fbd45b7c8-rp85z       6/6     Running   0          23m
csi-rbdplugin-s67lw                             3/3     Running   0          23m
csi-rbdplugin-zq4k5                             3/3     Running   0          23m
rook-ceph-mon-a-canary-954dc5cd9-5q8tk          1/1     Running   0          2m9s
rook-ceph-mon-b-canary-b9d6f5594-mcqwc          1/1     Running   0          2m9s
rook-ceph-mon-c-canary-78b48dbfb7-z2t7d         0/1     Pending   0          2m8s
rook-ceph-operator-757d6db48d-x27lm             1/1     Running   0          25m
rook-ceph-tools-75f575489-znbbz                 1/1     Running   0          7m45s
rook-discover-gq489                             1/1     Running   0          24m
rook-discover-p9zlg                             1/1     Running   0          24m
</code>```0

Deploy it and describe the pod detail

```<code>$ kubectl -n rook-ceph get pod
NAME                                            READY   STATUS    RESTARTS   AGE
csi-cephfsplugin-9c2z9                          3/3     Running   0          23m
csi-cephfsplugin-provisioner-7678bcfc46-s67hq   5/5     Running   0          23m
csi-cephfsplugin-provisioner-7678bcfc46-sfljd   5/5     Running   0          23m
csi-cephfsplugin-smmlf                          3/3     Running   0          23m
csi-rbdplugin-provisioner-fbd45b7c8-dnwsq       6/6     Running   0          23m
csi-rbdplugin-provisioner-fbd45b7c8-rp85z       6/6     Running   0          23m
csi-rbdplugin-s67lw                             3/3     Running   0          23m
csi-rbdplugin-zq4k5                             3/3     Running   0          23m
rook-ceph-mon-a-canary-954dc5cd9-5q8tk          1/1     Running   0          2m9s
rook-ceph-mon-b-canary-b9d6f5594-mcqwc          1/1     Running   0          2m9s
rook-ceph-mon-c-canary-78b48dbfb7-z2t7d         0/1     Pending   0          2m8s
rook-ceph-operator-757d6db48d-x27lm             1/1     Running   0          25m
rook-ceph-tools-75f575489-znbbz                 1/1     Running   0          7m45s
rook-discover-gq489                             1/1     Running   0          24m
rook-discover-p9zlg                             1/1     Running   0          24m
</code>```1

答:
rook-ceph-mon-x pods have following affinity:

```<code>spec:
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchLabels:
            app: rook-ceph-mon
        topologyKey: kubernetes.io/hostname
</code>```

which doesn't allow for running 2 rook-ceph-mon pods on the same node.
Since you seem to have 3 nodes: 1 master and 2 workers, 2 pods get created, one on kube2 and one on kube3 node. kube1 is master node tainted as unschedulable so rook-ceph-mon-c cannot be scheduled there.

To solve it you can:

add one more worker node

remove NoSchedule taint with kubectl taint nodes kube1 key:NoSchedule-

change mon count to lower value

Body:
Tried to install rook-ceph on kubernetes as this guide:

https://rook.io/docs/rook/v1.3/ceph-quickstart.html

git clone --single-branch --branch release-1.3 https://github.com/rook/rook.git
cd rook/cluster/examples/kubernetes/ceph
kubectl create -f common.yaml
kubectl create -f operator.yaml
kubectl create -f cluster.yaml

When I check all the pods

$ kubectl -n rook-ceph get pod
NAME                                            READY   STATUS    RESTARTS   AGE
csi-cephfsplugin-9c2z9                          3/3     Running   0          23m
csi-cephfsplugin-provisioner-7678bcfc46-s67hq   5/5     Running   0          23m
csi-cephfsplugin-provisioner-7678bcfc46-sfljd   5/5     Running   0          23m
csi-cephfsplugin-smmlf                          3/3     Running   0          23m
csi-rbdplugin-provisioner-fbd45b7c8-dnwsq       6/6     Running   0          23m
csi-rbdplugin-provisioner-fbd45b7c8-rp85z       6/6     Running   0          23m
csi-rbdplugin-s67lw                             3/3     Running   0          23m
csi-rbdplugin-zq4k5                             3/3     Running   0          23m
rook-ceph-mon-a-canary-954dc5cd9-5q8tk          1/1     Running   0          2m9s
rook-ceph-mon-b-canary-b9d6f5594-mcqwc          1/1     Running   0          2m9s
rook-ceph-mon-c-canary-78b48dbfb7-z2t7d         0/1     Pending   0          2m8s
rook-ceph-operator-757d6db48d-x27lm             1/1     Running   0          25m
rook-ceph-tools-75f575489-znbbz                 1/1     Running   0          7m45s
rook-discover-gq489                             1/1     Running   0          24m
rook-discover-p9zlg                             1/1     Running   0          24m

$ kubectl -n rook-ceph get pod -l app=rook-ceph-osd-prepare
No resources found in rook-ceph namespace.

Do some other operation

$ kubectl taint nodes $(hostname) node-role.kubernetes.io/master:NoSchedule-
$ kubectl -n rook-ceph-system delete pods rook-ceph-operator-757d6db48d-x27lm

Create file system

$ kubectl create -f filesystem.yaml

Check again

$ kubectl get pods -n rook-ceph -o wide
NAME                                              READY   STATUS     RESTARTS   AGE    IP             NODE     NOMINATED NODE   READINESS GATES
csi-cephfsplugin-9c2z9                            3/3     Running    0          135m   192.168.0.53   kube3    <none>           <none>
csi-cephfsplugin-provisioner-7678bcfc46-s67hq     5/5     Running    0          135m   10.1.2.6       kube3    <none>           <none>
csi-cephfsplugin-provisioner-7678bcfc46-sfljd     5/5     Running    0          135m   10.1.2.5       kube3    <none>           <none>
csi-cephfsplugin-smmlf                            3/3     Running    0          135m   192.168.0.52   kube2    <none>           <none>
csi-rbdplugin-provisioner-fbd45b7c8-dnwsq         6/6     Running    0          135m   10.1.1.6       kube2    <none>           <none>
csi-rbdplugin-provisioner-fbd45b7c8-rp85z         6/6     Running    0          135m   10.1.1.5       kube2    <none>           <none>
csi-rbdplugin-s67lw                               3/3     Running    0          135m   192.168.0.52   kube2    <none>           <none>
csi-rbdplugin-zq4k5                               3/3     Running    0          135m   192.168.0.53   kube3    <none>           <none>
rook-ceph-crashcollector-kube2-6d95bb9c-r5w7p     0/1     Init:0/2   0          110m   <none>         kube2    <none>           <none>
rook-ceph-crashcollector-kube3-644c849bdb-9hcvg   0/1     Init:0/2   0          110m   <none>         kube3    <none>           <none>
rook-ceph-mon-a-canary-954dc5cd9-6ccbh            1/1     Running    0          75s    10.1.2.130     kube3    <none>           <none>
rook-ceph-mon-b-canary-b9d6f5594-k85w5            1/1     Running    0          74s    10.1.1.74      kube2    <none>           <none>
rook-ceph-mon-c-canary-78b48dbfb7-kfzzx           0/1     Pending    0          73s    <none>         <none>   <none>           <none>
rook-ceph-operator-757d6db48d-nlh84               1/1     Running    0          110m   10.1.2.28      kube3    <none>           <none>
rook-ceph-tools-75f575489-znbbz                   1/1     Running    0          119m   10.1.1.14      kube2    <none>           <none>
rook-discover-gq489                               1/1     Running    0          135m   10.1.1.3       kube2    <none>           <none>
rook-discover-p9zlg                               1/1     Running    0          135m   10.1.2.4       kube3    <none>           <none>

Can't see pod as rook-ceph-osd-.

And rook-ceph-mon-c-canary-78b48dbfb7-kfzzx pod is always Pending.

If install toolbox as

https://rook.io/docs/rook/v1.3/ceph-toolbox.html

$ kubectl create -f toolbox.yaml
$ kubectl -n rook-ceph exec -it $(kubectl -n rook-ceph get pod -l "app=rook-ceph-tools" -o jsonpath='{.items[0].metadata.name}') bash

Inside the container, check the ceph status

[root@rook-ceph-tools-75f575489-znbbz /]# ceph -s
unable to get monitor info from DNS SRV with service name: ceph-mon
[errno 2] error connecting to the cluster

It's running on Ubuntu 16.04.6.

Deploy again

$ kubectl -n rook-ceph get pod -o wide
NAME                                            READY   STATUS    RESTARTS   AGE     IP             NODE     NOMINATED NODE   READINESS GATES
csi-cephfsplugin-4tww8                          3/3     Running   0          3m38s   192.168.0.52   kube2    <none>           <none>
csi-cephfsplugin-dbbfb                          3/3     Running   0          3m38s   192.168.0.53   kube3    <none>           <none>
csi-cephfsplugin-provisioner-7678bcfc46-8kt96   5/5     Running   0          3m37s   10.1.2.6       kube3    <none>           <none>
csi-cephfsplugin-provisioner-7678bcfc46-kq6vv   5/5     Running   0          3m38s   10.1.1.6       kube2    <none>           <none>
csi-rbdplugin-4qrqn                             3/3     Running   0          3m39s   192.168.0.53   kube3    <none>           <none>
csi-rbdplugin-dqx9z                             3/3     Running   0          3m39s   192.168.0.52   kube2    <none>           <none>
csi-rbdplugin-provisioner-fbd45b7c8-7f57t       6/6     Running   0          3m39s   10.1.2.5       kube3    <none>           <none>
csi-rbdplugin-provisioner-fbd45b7c8-9zwhb       6/6     Running   0          3m39s   10.1.1.5       kube2    <none>           <none>
rook-ceph-mon-a-canary-954dc5cd9-rgqpg          1/1     Running   0          2m40s   10.1.1.7       kube2    <none>           <none>
rook-ceph-mon-b-canary-b9d6f5594-n2pwc          1/1     Running   0          2m35s   10.1.2.8       kube3    <none>           <none>
rook-ceph-mon-c-canary-78b48dbfb7-fv46f         0/1     Pending   0          2m30s   <none>         <none>   <none>           <none>
rook-ceph-operator-757d6db48d-2m25g             1/1     Running   0          6m27s   10.1.2.3       kube3    <none>           <none>
rook-discover-lpsht                             1/1     Running   0          5m15s   10.1.1.3       kube2    <none>           <none>
rook-discover-v4l77                             1/1     Running   0          5m15s   10.1.2.4       kube3    <none>           <none>

Describe pending pod

$ kubectl describe pod rook-ceph-mon-c-canary-78b48dbfb7-fv46f -n rook-ceph
Name:           rook-ceph-mon-c-canary-78b48dbfb7-fv46f
Namespace:      rook-ceph
Priority:       0
Node:           <none>
Labels:         app=rook-ceph-mon
                ceph_daemon_id=c
                mon=c
                mon_canary=true
                mon_cluster=rook-ceph
                pod-template-hash=78b48dbfb7
                rook_cluster=rook-ceph
Annotations:    <none>
Status:         Pending
IP:
IPs:            <none>
Controlled By:  ReplicaSet/rook-ceph-mon-c-canary-78b48dbfb7
Containers:
  mon:
    Image:      rook/ceph:v1.3.4
    Port:       6789/TCP
    Host Port:  0/TCP
    Command:
      /tini
    Args:
      --
      sleep
      3600
    Environment:
      CONTAINER_IMAGE:                ceph/ceph:v14.2.9
      POD_NAME:                       rook-ceph-mon-c-canary-78b48dbfb7-fv46f (v1:metadata.name)
      POD_NAMESPACE:                  rook-ceph (v1:metadata.namespace)
      NODE_NAME:                       (v1:spec.nodeName)
      POD_MEMORY_LIMIT:               node allocatable (limits.memory)
      POD_MEMORY_REQUEST:             0 (requests.memory)
      POD_CPU_LIMIT:                  node allocatable (limits.cpu)
      POD_CPU_REQUEST:                0 (requests.cpu)
      ROOK_CEPH_MON_HOST:             <set to the key 'mon_host' in secret 'rook-ceph-config'>             Optional: false
      ROOK_CEPH_MON_INITIAL_MEMBERS:  <set to the key 'mon_initial_members' in secret 'rook-ceph-config'>  Optional: false
      ROOK_POD_IP:                     (v1:status.podIP)
    Mounts:
      /etc/ceph from rook-config-override (ro)
      /etc/ceph/keyring-store/ from rook-ceph-mons-keyring (ro)
      /var/lib/ceph/crash from rook-ceph-crash (rw)
      /var/lib/ceph/mon/ceph-c from ceph-daemon-data (rw)
      /var/log/ceph from rook-ceph-log (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-65xtn (ro)
Conditions:
  Type           Status
  PodScheduled   False
Volumes:
  rook-config-override:
    Type:      ConfigMap (a volume populated by a ConfigMap)
    Name:      rook-config-override
    Optional:  false
  rook-ceph-mons-keyring:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  rook-ceph-mons-keyring
    Optional:    false
  rook-ceph-log:
    Type:          HostPath (bare host directory volume)
    Path:          /var/lib/rook/rook-ceph/log
    HostPathType:
  rook-ceph-crash:
    Type:          HostPath (bare host directory volume)
    Path:          /var/lib/rook/rook-ceph/crash
    HostPathType:
  ceph-daemon-data:
    Type:          HostPath (bare host directory volume)
    Path:          /var/lib/rook/mon-c/data
    HostPathType:
  default-token-65xtn:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-65xtn
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason            Age                From               Message
  ----     ------            ----               ----               -------
  Warning  FailedScheduling  22s (x3 over 84s)  default-scheduler  0/3 nodes are available: 1 node(s) had taint {node-role.kubernetes.io/master: }, that the pod didn't tolerate, 2 node(s) didn't match pod affinity/anti-affinity, 2 node(s) didn't satisfy existing pods anti-affinity rules.

Test mount

Create a nginx.yaml file

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx:1.7.9
    ports:
    - containerPort: 80
    volumeMounts:
    - name: www
      mountPath: /usr/share/nginx/html
  volumes:
  - name: www
    flexVolume:
      driver: ceph.rook.io/rook
      fsType: ceph
      options:
        fsName: myfs
        clusterNamespace: rook-ceph

Deploy it and describe the pod detail

...
Events:
  Type     Reason       Age                    From               Message
  ----     ------       ----                   ----               -------
  Normal   Scheduled    9m28s                  default-scheduler  Successfully assigned default/nginx to kube2
  Warning  FailedMount  9m28s                  kubelet, kube2     Unable to attach or mount volumes: unmounted volumes=[www default-token-fnb28], unattached volumes=[www default-token-fnb28]: failed to get Plugin from volumeSpec for volume "www" err=no volume plugin matched
  Warning  FailedMount  6m14s (x2 over 6m38s)  kubelet, kube2     Unable to attach or mount volumes: unmounted volumes=[www], unattached volumes=[default-token-fnb28 www]: failed to get Plugin from volumeSpec for volume "www" err=no volume plugin matched
  Warning  FailedMount  4m6s (x23 over 9m13s)  kubelet, kube2     Unable to attach or mount volumes: unmounted volumes=[www], unattached volumes=[www default-token-fnb28]: failed to get Plugin from volumeSpec for volume "www" err=no volume plugin matched

Body:
rook-ceph-mon-x pods have following affinity:

spec:
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchLabels:
            app: rook-ceph-mon
        topologyKey: kubernetes.io/hostname

which doesn't allow for running 2 rook-ceph-mon pods on the same node.
Since you seem to have 3 nodes: 1 master and 2 workers, 2 pods get created, one on kube2 and one on kube3 node. kube1 is master node tainted as unschedulable so rook-ceph-mon-c cannot be scheduled there.

To solve it you can:

add one more worker node

remove NoSchedule taint with kubectl taint nodes kube1 key:NoSchedule-

change mon count to lower value


来源: stackexchange

问:
JSONObject etc instantiation crashing
I am trying to learn how to use JSON and writing a simple program however whenever I instantiate a JSON Object it crashes.
What am I missing if I receive this error when trying to instantiate a JSONObject or JSONArray. I have added http://sourceforge.net/projects/json-lib/files/ this JSON library to the build path. Is there anything I am missing?

The error message is as follows:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at jsonexp.JSONexp.<init>(JSONexp.java:36)
    at jsonexp.JSONexp.main(JSONexp.java:55)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
</code>```

I have learned that this sort of error occurs when the library being used depends on another library.

I do not know how to deal with this problem and would very much appreciate some help.

Thanks.

答:
You're forgetting the jar that contains the class NestableRuntimeException.

Based on the package of that exception, it is an Apache Commons library and you must go to Apache Commons and download the Apache Commons Lang library. Download the commons-lang-x.y-bin.(tar.gz|bin) archive, get the jar from the archive and add it to your project or java classpath.

ContentLicense: CC BY-SA 3.0

Title: JSONObject etc instantiation crashing

Body:
I am trying to learn how to use JSON and writing a simple program however whenever I instantiate a JSON Object it crashes.
What am I missing if I receive this error when trying to instantiate a JSONObject or JSONArray. I have added http://sourceforge.net/projects/json-lib/files/ this JSON library to the build path. Is there anything I am missing?

The error message is as follows:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at jsonexp.JSONexp.<init>(JSONexp.java:36)
    at jsonexp.JSONexp.main(JSONexp.java:55)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException

I have learned that this sort of error occurs when the library being used depends on another library.

I do not know how to deal with this problem and would very much appreciate some help.

Thanks.


问:
Starting minikube in a Linux box requires authentication with Google Container Registry, why?
I am currently learning Kubernetes and I am playing with minikube tool. I have decided to install the tool in a VirtualBox instance that runs ubuntu/xenial64. I have created this instance using Vagrant and connected the instance through ssh.
I have installed minikube in accordance to the tool documentation - https://minikube.sigs.k8s.io/docs/start/.
When I run:
$ minikube start,
it failed with the following message:

```<code>$ minikube start
  minikube v1.11.0 on Ubuntu 16.04 (vbox/amd64)
✨  Using the docker driver based on existing profile
  Starting control plane node minikube in cluster minikube
  Pulling base image ...
  Unfortunately, could not download the base image gcr.io/k8s-minikube/kicbase:v0.0.10
❗  In order to use the fall back image, you need to log in to the github packages registry
  Please visit the following link for documentation around this:
    https://help.github.com/en/packages/using-github-packages-with-your-projects-ecosystem/configuring-docker-for-use-with-github-packages#authenticating-to-github-packages

  Please either authenticate to the registry or use --base-image flag to use a different registry.
</code>```

For some reason, in order to download minikube base image, it requires to authenticate to the gcr.io registry (Google Container Registry). The minikube documentation does mention nothing about this requirement. I am wondering why it happened. My understanding is it should not be mandatory to have a gsr account in order to use minikube. What am I doing wrong?
And what is the kicbase container (KIC) that minikube depends on?
I appreciate any help on this problem. Thank you.

答: It's not requesting you to login to gcr.io. It's falling back to use github registry for the image. And github require at least read permission to pull images. https://github.com/kubernetes/minikube/pull/8225</p>

ContentLicense: CC BY-SA 4.0

Body:
I am currently learning Kubernetes and I am playing with minikube tool. I have decided to install the tool in a VirtualBox instance that runs ubuntu/xenial64. I have created this instance using Vagrant and connected the instance through ssh.
I have installed minikube in accordance to the tool documentation - https://minikube.sigs.k8s.io/docs/start/.
When I run:
$ minikube start,
it failed with the following message:

$ minikube start
  minikube v1.11.0 on Ubuntu 16.04 (vbox/amd64)
✨  Using the docker driver based on existing profile
  Starting control plane node minikube in cluster minikube
  Pulling base image ...
  Unfortunately, could not download the base image gcr.io/k8s-minikube/kicbase:v0.0.10
❗  In order to use the fall back image, you need to log in to the github packages registry
  Please visit the following link for documentation around this:
    https://help.github.com/en/packages/using-github-packages-with-your-projects-ecosystem/configuring-docker-for-use-with-github-packages#authenticating-to-github-packages

  Please either authenticate to the registry or use --base-image flag to use a different registry.

For some reason, in order to download minikube base image, it requires to authenticate to the gcr.io registry (Google Container Registry). The minikube documentation does mention nothing about this requirement. I am wondering why it happened. My understanding is it should not be mandatory to have a gsr account in order to use minikube. What am I doing wrong?
And what is the kicbase container (KIC) that minikube depends on?
I appreciate any help on this problem. Thank you.


问:
printing variable inside a def, inside a class
I am new to object oriented programming, what I want to do basically is print a variable inside a def which is in its turn inside a class, I think there's probably a very simple answer but I just can't figure it out, thanks for the assistance, here's my code:

```<code>class test():
    def test2():
        x = 12
print(test.test2.x)
</code>```

this gives me the following error:

```<code>Traceback (most recent call last):
  File "/home/vandeventer/x.py", line 4, in <module>
    print(test.test2.x)
AttributeError: 'function' object has no attribute 'x'
</code>```

when I try:

```<code>class test():
    def test2():
        x = 12
print(test.x)
</code>```

I get:

```<code>Traceback (most recent call last):
  File "/home/vandeventer/x.py", line 4, in <module>
    print(test.x)
AttributeError: type object 'test' has no attribute 'x'
</code>```

答:
If you want to print that value you could also use a return statement and the self parameter.

```<code>    class test():
        def test2(self):
            x = 12
            return x

     test = test()
     print(test.test2())
</code>```

I do not know if this fully answers your questions but it is a way to print your x.

Body:
I am new to object oriented programming, what I want to do basically is print a variable inside a def which is in its turn inside a class, I think there's probably a very simple answer but I just can't figure it out, thanks for the assistance, here's my code:

class test():
    def test2():
        x = 12
print(test.test2.x)

this gives me the following error:

Traceback (most recent call last):
  File "/home/vandeventer/x.py", line 4, in <module>
    print(test.test2.x)
AttributeError: 'function' object has no attribute 'x'

when I try:

class test():
    def test2():
        x = 12
print(test.x)

I get:

Traceback (most recent call last):
  File "/home/vandeventer/x.py", line 4, in <module>
    print(test.x)
AttributeError: type object 'test' has no attribute 'x'

Body:
If you want to print that value you could also use a return statement and the self parameter.

    class test():
        def test2(self):
            x = 12
            return x

     test = test()
     print(test.test2())

I do not know if this fully answers your questions but it is a way to print your x.


问:
How to filter the div as we search in search box?
I made a page with 9 cards. The card is with the class name "card". I want to get the card when I type the letters. I want this to be filtered on the basis of p tag that consist "First project", "Second project" and so on for seven more.

function search() {
  let input = document.getElementById('.searchbar').value
  input = input.toLowerCase();
  let x = document.querySelector('.card p');

  for (i = 0; i < x.length; i++) {
    if (!x[i].innerHTML.toLowerCase().includes(input)) {
      x[i].style.display = "none";
    } else {
      x[i].style.display = "list-item";
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">

  <h3 class="first">Page Heading <span class="span-text">Secondary Text</span></h3>
  <form class='searchbox'>
    <input class="searchbar" type="text" onkeyup="search()" placeholder="Search.." name="search">
  </form>

  <section class="cards">
    <div class="card">
      <div class="card-box">700 x 400</div>
      <p style="color:blue; font-size:1.5rem;">First Project</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.
      </p>
    </div>

    <div class="card">
      <div class="card-box">700 x 400</div>
      <p style="color:blue; font-size:1.5rem;">Second Project</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.
      </p>
    </div>
    //and seven more of same "card" class
</div></code>```

I am not able to filter it when I type in the search box. Kindly guide on what is wrong and what I can do  to display the card that I searched.

答:
Changed your getElementById() to querySelector() since you used css class selector to select searchbox.

Changed your querySelector() to querySelectorAll() since you want to select multiple card p elements.

Changed the search() function name to filter() since it was conflicting with the name attribute of the searchbox which was also search. Alternatively you can bind the event handler in JavaScript. Declaring event handlers inline is considered bad practice by many developers.

Last I changed the search logic so it filters the cards based on the title alone since you had 2 p elements in each card. Also hidden the card element instead of the p elements. I added the title class the the title p to use it as a selector.

function filter() {
  let input = document.querySelector('.searchbar').value //<-- Changed to querySelector
  input = input.toLowerCase();
  let cards = document.querySelectorAll('.card'); //<-- Changed to querySelectorAll with '.card' selector.

  //loop over cards and compare search with title.
  cards.forEach((el) => {
    let title = el.querySelector('.title').textContent.toLowerCase();
    el.style.display = title.includes(input) ? "list-item" : "none";
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">

  <h3 class="first">Page Heading <span class="span-text">Secondary Text</span></h3>
  <form class='searchbox'>
    <input class="searchbar" type="text" onkeyup="filter()" placeholder="Search.." name="search">
  </form>

  <section class="cards">
    <div class="card">
      <div class="card-box">700 x 400</div>
      <p class="title" style="color:blue; font-size:1.5rem;">First Project</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.
      </p>
    </div>

    <div class="card">
      <div class="card-box">700 x 400</div>
      <p class="title" style="color:blue; font-size:1.5rem;">Second Project</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.
      </p>
    </div>
    //and seven more of same "card" class
  </section>
</div></code>```

Body:
I made a page with 9 cards. The card is with the class name "card". I want to get the card when I type the letters. I want this to be filtered on the basis of p tag that consist "First project", "Second project" and so on for seven more.

function search() {
  let input = document.getElementById('.searchbar').value
  input = input.toLowerCase();
  let x = document.querySelector('.card p');

  for (i = 0; i < x.length; i++) {
    if (!x[i].innerHTML.toLowerCase().includes(input)) {
      x[i].style.display = "none";
    } else {
      x[i].style.display = "list-item";
    }
  }
}

Page Heading Secondary Text

  <form class='searchbox'>
    <input class="searchbar" type="text" onkeyup="search()" placeholder="Search.." name="search">
  </form>

700 x 400

First Project

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.

700 x 400

Second Project

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.

    //and seven more of same "card" class

I am not able to filter it when I type in the search box. Kindly guide on what is wrong and what I can do  to display the card that I searched.

Body:
Changed your getElementById() to querySelector() since you used css class selector to select searchbox.

Changed your querySelector() to querySelectorAll() since you want to select multiple card p elements.

Changed the search() function name to filter() since it was conflicting with the name attribute of the searchbox which was also search. Alternatively you can bind the event handler in JavaScript. Declaring event handlers inline is considered bad practice by many developers.

Last I changed the search logic so it filters the cards based on the title alone since you had 2 p elements in each card. Also hidden the card element instead of the p elements. I added the title class the the title p to use it as a selector.

function filter() {
  let input = document.querySelector('.searchbar').value //<-- Changed to querySelector
  input = input.toLowerCase();
  let cards = document.querySelectorAll('.card'); //<-- Changed to querySelectorAll with '.card' selector.

  //loop over cards and compare search with title.
  cards.forEach((el) => {
    let title = el.querySelector('.title').textContent.toLowerCase();
    el.style.display = title.includes(input) ? "list-item" : "none";
  });
}

<div class="main">

  <h3 class="first">Page Heading <span class="span-text">Secondary Text</span></h3>
  <form class='searchbox'>
    <input class="searchbar" type="text" onkeyup="filter()" placeholder="Search.." name="search">
  </form>

  <section class="cards">
    <div class="card">
      <div class="card-box">700 x 400</div>
      <p class="title" style="color:blue; font-size:1.5rem;">First Project</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.
      </p>
    </div>

    <div class="card">
      <div class="card-box">700 x 400</div>
      <p class="title" style="color:blue; font-size:1.5rem;">Second Project</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.
      </p>
    </div>
    //and seven more of same "card" class
  </section>
</div>


问:
JQUERY: How to change the input value by clicking a button with a generic JQuery
I'm not an expert in JQuery but I'm trying to get a value from a button - when the user click a button and the input field will change the value.

But, I can have many buttons.. (In same cases, more than 100) for this reason I want to know if it's possible to get the value from the clicked button with a "generic" JQuery - to avoid a big JQuery with a $('#answer').val() for each button..

https://jsfiddle.net/Ldy01wb2/1/

HTML:

```<code><input type="button" id ='one' value="A">
<input type="button" id ='two' value="B">
<br><br>
Hidden: <input type="text" id="answer" value="">
</code>```

JQUERY: (what I want)

```<code>$(':button').click(function(){
    $('#answer').val = $(':button').val ;
});
</code>```

JQUERY: (works.. but if I have 100, I need 100 functions.. and I'm trying to get a generic solution for all buttons)

```<code>$('#one').click(function(){
    $('#answer').val("A") ;
});

$('#two').click(function(){
    $('#answer').val("B") ;
});
</code>```

答:
Please give a class to the button and get the value based on class

$('.mybutton').click(function(){
    $('#myInput').val($(this).val()) ;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="mybutton" id='one' value="A">
<input type="button" class="mybutton" id='two' value="B">
<br><br>
Hidden: <input type="text" id="myInput" value=""></code>```

Body:
I'm not an expert in JQuery but I'm trying to get a value from a button - when the user click a button and the input field will change the value.

But, I can have many buttons.. (In same cases, more than 100) for this reason I want to know if it's possible to get the value from the clicked button with a "generic" JQuery - to avoid a big JQuery with a $('#answer').val() for each button..

https://jsfiddle.net/Ldy01wb2/1/

HTML:

<input type="button" id ='one' value="A">
<input type="button" id ='two' value="B">

Hidden: <input type="text" id="answer" value="">

JQUERY: (what I want)

$(':button').click(function(){
    $('#answer').val = $(':button').val ;
});

JQUERY: (works.. but if I have 100, I need 100 functions.. and I'm trying to get a generic solution for all buttons)

$('#one').click(function(){
    $('#answer').val("A") ;
});

$('#two').click(function(){
    $('#answer').val("B") ;
});

Body:
Please give a class to the button and get the value based on class

$('.mybutton').click(function(){
    $('#myInput').val($(this).val()) ;
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="mybutton" id='one' value="A">
<input type="button" class="mybutton" id='two' value="B">
<br><br>
Hidden: <input type="text" id="myInput" value="">


问:
How to create a sparse matrix in MATLAB given the locations of non-zero elements
I need to create matrix in MATLAB with the following requirement. Given a vector v, for example, [1,2,2,1,3,5,1], I need to form a matrix:

```<code>[1 0 0 1 0 0 1;
 0 1 1 0 0 0 0;
 0 0 0 0 1 0 0;
 0 0 0 0 0 0 0;
 0 0 0 0 0 1 0]
</code>```

i.e. the matrix's ith column contains only one non-zero element (a single 1) at row v[i]. How can I avoid a loop and do this in an efficient way?

答:
This is very similar to the step required in creating a target vector in Neural Network Assignment (Week 5- Handwritten Digit Recognition from Andrew NG ML course). We had to create a vector of 10 X 1 size for a single training output say ith output of y. If the ith training output in y is 2, the vectorized ith output was [0 1 0 0 0 0 0 0 0 0]'.
So, For 5000 training examples, we required 5000 vectors.

Without much ado, The code is :

```<code>
>> v =  [1,2,2,1,3,5,1];
>> v_vec = (1:5)==v';
>> v_vec
v_vec =

  1  0  0  0  0
  0  1  0  0  0
  0  1  0  0  0
  1  0  0  0  0
  0  0  1  0  0
  0  0  0  0  1
  1  0  0  0  0

>> v_vec'
ans =

  1  0  0  1  0  0  1
  0  1  1  0  0  0  0
  0  0  0  0  1  0  0
  0  0  0  0  0  0  0
  0  0  0  0  0  1  0

</code>```

v_vec' is the desired output.
A useful link : https://www.ee.columbia.edu/~marios/matlab/Matlab%20Tricks.pdf

Body:
I need to create matrix in MATLAB with the following requirement. Given a vector v, for example, [1,2,2,1,3,5,1], I need to form a matrix:

[1 0 0 1 0 0 1;
 0 1 1 0 0 0 0;
 0 0 0 0 1 0 0;
 0 0 0 0 0 0 0;
 0 0 0 0 0 1 0]

i.e. the matrix's ith column contains only one non-zero element (a single 1) at row v[i]. How can I avoid a loop and do this in an efficient way?

Body:
This is very similar to the step required in creating a target vector in Neural Network Assignment (Week 5- Handwritten Digit Recognition from Andrew NG ML course). We had to create a vector of 10 X 1 size for a single training output say ith output of y. If the ith training output in y is 2, the vectorized ith output was [0 1 0 0 0 0 0 0 0 0]'.
So, For 5000 training examples, we required 5000 vectors.

Without much ado, The code is :

>> v =  [1,2,2,1,3,5,1];
>> v_vec = (1:5)==v';
>> v_vec
v_vec =

  1  0  0  0  0
  0  1  0  0  0
  0  1  0  0  0
  1  0  0  0  0
  0  0  1  0  0
  0  0  0  0  1
  1  0  0  0  0

>> v_vec'
ans =

  1  0  0  1  0  0  1
  0  1  1  0  0  0  0
  0  0  0  0  1  0  0
  0  0  0  0  0  0  0
  0  0  0  0  0  1  0

v_vec' is the desired output.
A useful link : https://www.ee.columbia.edu/~marios/matlab/Matlab%20Tricks.pdf


问:
Oracle if value to be inserted in foreign key is -1, insert null instead
I have a xml script I'm reading from to populate my database with data. One of the nodes in the xml file don't have a idDirector field (the nodes are movies) and so the xml reads a -1  as idDirector and then my stored procedure tries to insert -1 into the fk field and this makes my database returna constraint error : director -1 doesn't exist in Director table. How can I make it so it inserts null instead and make my fk field nullable?

```<code>CREATE TABLE Film (
    PRIMARY KEY (idFilm),
    FOREIGN KEY (idDirector) REFERENCES Director
);
</code>```

Thank you

答:
Looks like CASE to me, e.g.

```<code>insert into film (id_film, id_director)
select id_film,
       case when id_director = -1 then null
            else id_director
       end
from ...
</code>```

Will it work? Yes:

```<code>SQL> create table director (id number primary key);

Table created.

SQL> create table film (id number primary key, id_director number references director);

Table created.

SQL> insert into director values (100);

1 row created.
</code>```

Inserting -1 fails:

```<code>SQL> insert into film (id, id_director) values (1, -1);
insert into film (id, id_director) values (1, -1)
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C0065885) violated - parent key not
found
</code>```

Inserting NULL works:

```<code>SQL> insert into film (id, id_director) values (1, null);

1 row created.

SQL>
</code>```

Body:
I have a xml script I'm reading from to populate my database with data. One of the nodes in the xml file don't have a idDirector field (the nodes are movies) and so the xml reads a -1  as idDirector and then my stored procedure tries to insert -1 into the fk field and this makes my database returna constraint error : director -1 doesn't exist in Director table. How can I make it so it inserts null instead and make my fk field nullable?

CREATE TABLE Film (
    PRIMARY KEY (idFilm),
    FOREIGN KEY (idDirector) REFERENCES Director
);

Thank you

Body:
Looks like CASE to me, e.g.

insert into film (id_film, id_director)
select id_film,
       case when id_director = -1 then null
            else id_director
       end
from ...

Will it work? Yes:

SQL> create table director (id number primary key);

Table created.

SQL> create table film (id number primary key, id_director number references director);

Table created.

SQL> insert into director values (100);

1 row created.

Inserting -1 fails:

SQL> insert into film (id, id_director) values (1, -1);
insert into film (id, id_director) values (1, -1)
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C0065885) violated - parent key not
found

Inserting NULL works:

SQL> insert into film (id, id_director) values (1, null);

1 row created.

SQL>


答:
Use a class to query instead of ID.

```<code>$('.button').click(function(){
    $('#answer').val($(this).val());
});
</code>```

You can also use $('input:button').click(function() without using a class

Title: JQUERY: How to change the input value by clicking a button with a generic JQuery

Body:
Use a class to query instead of ID.

$('.button').click(function(){
    $('#answer').val($(this).val());
});

You can also use $('input:button').click(function() without using a class


问:
stdout and need to flush it C++
I have some C++ code that uses cout statements for debug purposes and for some reason I can't get all the data to print unless I do a std::cout.flush(); at the end.

I don't quite understand why this flush operation is needed.

Anyone have any insight?

答:
It is the right behavior. You probably use std::endl that add \n and flush the buffer. http://www.cplusplus.com/reference/ostream/endl/

You need to flush the stream, if you want to see the output.

Title: stdout and need to flush it C++


问:
Git merge feature on develop branch to another already existing develop branch
I have a git repo (inherited) and branch lets call "develop" (well A for the rest of the question). That branch has 2 more branches where it is the parent called "B" and "C" where customer specific changes happen. However that branch (A labeled below) is roughly 1 year old so B and C have diverged. I’m working on breaking out the customer specific features and rejoining the changes back into A so we have a common ancestor but not there yet. We do feature branches workflow so I created a new branch off "B" (which is customer1 in this case) called D.

```<code>A -> B
    -> D
  -> C
</code>```

I did 100's of commits working on the new feature and did a 'git co B && git merge D' which in this case happen to be 100% new files (well except for the .gitignore) for branch B. I did not squash and my git log now looks like

```<code>*   250f8fd4 - (origin/B, origin/HEAD, B) Add new files for project X (3 days ago) <me>
|\
| * f8a1a83e - (origin/D, D) cleaning up before merge (3 days ago) <me>
* | 84bc9cb5 - cleaning up before merge (3 days ago) <me>
|/
* 08510627 - variablize and not hardcode value (3 days ago) <me>
</code>```

Then I git pushed, and verified everything worked. I now want those same files to be in branch C. Since these are 100% new files and I can just copy them from B to C but I don‘t want to have merge conflicts in the future when I do collapse all the branches back into A.

Running 'git merge 250f8fd4' results in ALL changes since B diverged from A being applied to C (including overwriting customer specific files and changes) and generates thousands of merge conflicts. I use git merge --abort to undo it.

```<code>$ git cherry-pick 250f8fd4
error: commit 250f8fd4e41c069eb1a2861855a4db30a1fba658 is a merge but no -m option was given.
fatal: cherry-pick failed
</code>```

fails, so lets try telling it which side

```<code>$ git cherry-pick -m 1 250f8fd4
On branch C
Your branch is up to date with 'origin/C'.

You are currently cherry-picking commit 250f8fd4.

nothing to commit, working tree clean
The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

    git commit --allow-empty

Otherwise, please use 'git reset'
</code>```

Regardless if i use -m 1 or -m 2 it always results in empty commit.

How do i do this the "git" way and get my feature changes into multiple NON master/develop branches? I guess I also haven‘t tried merging from D into C but I don‘t think that would work either.

答:
git hinted it in the cherry-pick error message : commit 250f8fd4 is just the merge commit ; the actual changes are contained in 84bc9cb5 and f8a1a83e.

There are only two commits, you can cherry-pick them easily :

```<code>git cherry-pick 84bc9cb5 f8a1a83e
</code>```

If there were more commits, or if you wanted a more systematic way to select a bunch of commits and replay them on top of C, you can use the --onto option of git rebase :

```<code># this will rebase :
#  - on top of commit C (--onto C)
#  - commits starting from 08510627 (this commit will *not* be included)
#  - up to 250f8fd4 (included)
git rebase --onto C 08510627 250f8fd4

# once the rebase is completed, you can update branch C to this new commit :
git branch -f C
git checkout C

# or :
git checkout C
git merge --ff-only <rebased-commit>
</code>```

Body:
I have a git repo (inherited) and branch lets call "develop" (well A for the rest of the question). That branch has 2 more branches where it is the parent called "B" and "C" where customer specific changes happen. However that branch (A labeled below) is roughly 1 year old so B and C have diverged. I’m working on breaking out the customer specific features and rejoining the changes back into A so we have a common ancestor but not there yet. We do feature branches workflow so I created a new branch off "B" (which is customer1 in this case) called D.

A -> B
    -> D
  -> C

I did 100's of commits working on the new feature and did a 'git co B && git merge D' which in this case happen to be 100% new files (well except for the .gitignore) for branch B. I did not squash and my git log now looks like

*   250f8fd4 - (origin/B, origin/HEAD, B) Add new files for project X (3 days ago) <me>
|\
| * f8a1a83e - (origin/D, D) cleaning up before merge (3 days ago) <me>
* | 84bc9cb5 - cleaning up before merge (3 days ago) <me>
|/
* 08510627 - variablize and not hardcode value (3 days ago) <me>

Then I git pushed, and verified everything worked. I now want those same files to be in branch C. Since these are 100% new files and I can just copy them from B to C but I don‘t want to have merge conflicts in the future when I do collapse all the branches back into A.

Running 'git merge 250f8fd4' results in ALL changes since B diverged from A being applied to C (including overwriting customer specific files and changes) and generates thousands of merge conflicts. I use git merge --abort to undo it.

$ git cherry-pick 250f8fd4
error: commit 250f8fd4e41c069eb1a2861855a4db30a1fba658 is a merge but no -m option was given.
fatal: cherry-pick failed

fails, so lets try telling it which side

$ git cherry-pick -m 1 250f8fd4
On branch C
Your branch is up to date with 'origin/C'.

You are currently cherry-picking commit 250f8fd4.

nothing to commit, working tree clean
The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

    git commit --allow-empty

Otherwise, please use 'git reset'

Regardless if i use -m 1 or -m 2 it always results in empty commit.

How do i do this the "git" way and get my feature changes into multiple NON master/develop branches? I guess I also haven‘t tried merging from D into C but I don‘t think that would work either.

Body:
git hinted it in the cherry-pick error message : commit 250f8fd4 is just the merge commit ; the actual changes are contained in 84bc9cb5 and f8a1a83e.

There are only two commits, you can cherry-pick them easily :

git cherry-pick 84bc9cb5 f8a1a83e

If there were more commits, or if you wanted a more systematic way to select a bunch of commits and replay them on top of C, you can use the --onto option of git rebase :

# this will rebase :
#  - on top of commit C (--onto C)
#  - commits starting from 08510627 (this commit will *not* be included)
#  - up to 250f8fd4 (included)
git rebase --onto C 08510627 250f8fd4

# once the rebase is completed, you can update branch C to this new commit :
git branch -f C
git checkout C

# or :
git checkout C
git merge --ff-only <rebased-commit>


问:
Storing multiple ndarrays to a list
During each iteration of for loop some results get stored in a ndarray which look like this,

```<code>testpredict=[[1.1],
             [2.344],
             [3.00]]
</code>```

I want to store the above results in a list variable during each iteration.
Something like...

```<code>list[i]= testpredict
</code>```

My final list should look like this:

```<code>final_list=[
            [[1.1], [2.344], [3.00]],
            [[4.03130], [4.55914], [4.46367]],
            .......
           ]
</code>```

how can I do this correctly?

答:
```<code># declared outside the iteration loop
new_list = []

# inside the loop
new_list = new_list.append(testpredict.tolist())
</code>```

<p>'list' is a built-in type. Avoid using it as a variable name, as a best practice.</p>

Title: Storing multiple ndarrays to a list

Body:
During each iteration of for loop some results get stored in a ndarray which look like this,

testpredict=[[1.1],
             [2.344],
             [3.00]]

I want to store the above results in a list variable during each iteration.
Something like...

list[i]= testpredict

My final list should look like this:

final_list=[
            [[1.1], [2.344], [3.00]],
            [[4.03130], [4.55914], [4.46367]],
            .......
           ]

how can I do this correctly?

Body:
# declared outside the iteration loop
new_list = []

# inside the loop
new_list = new_list.append(testpredict.tolist())

'list' is a built-in type. Avoid using it as a variable name, as a best practice.


问:
JavaScript: Overriding alert()
Has anyone got any experience with overriding the alert() function in JavaScript?

Which browsers support this?

Which browser-versions support this?

What are the dangers in overriding the function?

答:
I have faced a requirement to show a default message along with the actual alert messages. This is how I managed to do it.

```<code>
    const actualAlertFunc = window.alert;
    window.alert = function(msg) {
         actualAlertFunc('some default message '+ msg);
    }
</code>```

I have tested it on chrome.
I am not sure whether its a good practise, but it serves the purpose.

ContentLicense: CC BY-SA 2.5

Title: JavaScript: Overriding alert()

Body:
I have faced a requirement to show a default message along with the actual alert messages. This is how I managed to do it.

    const actualAlertFunc = window.alert;
    window.alert = function(msg) {
         actualAlertFunc('some default message '+ msg);
    }

I have tested it on chrome.
I am not sure whether its a good practise, but it serves the purpose.


问:
Factoring out repetitive ItemsControl.ItemsPanel XAML code to a resource
I have some ItemsControl.ItemsPanel repetitive XAML sections that I'd like to factor out to a Windows.resource. I've made an attempt at it for RegionD but I get a incompatible type error message. Any help would be appreciated.

```<code><Window x:Class="PrismDemo.Views.ShellWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:prism="http://prismlibrary.com/"
    prism:ViewModelLocator.AutoWireViewModel="True"
    Title="{Binding Title}" Height="150" Width="325" >

<Window.Resources>
    <ItemsControl x:Key="IC" >
        <ItemsControl.ItemsPanel >
            <ItemsPanelTemplate>
                <Grid IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</Window.Resources>

<Grid ShowGridLines="True">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <ContentControl Grid.Row="0"  prism:RegionManager.RegionName="RegionA" />
    <ContentControl Grid.Row="0"  prism:RegionManager.RegionName="RegionB" />
    <ItemsControl Grid.Row="1"  prism:RegionManager.RegionName="RegionC" >
        <ItemsControl.ItemsPanel >
            <ItemsPanelTemplate>
                <Grid IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
    <ItemsControl x:Name="{StaticResource IC}" Grid.Row="2"  prism:RegionManager.RegionName="RegionD" />
</Grid>
</code>```

答:
create a Style with Setter for ItemsPanel:

```<code><Style x:Key="IC" TargetType="{x:Type ItemsControl}">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <Grid IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

then apply Style to each ItemsControl:

```<code><ItemsControl Style="{StaticResource IC}" Grid.Row="1"  prism:RegionManager.RegionName="RegionC" />
<ItemsControl Style="{StaticResource IC}" Grid.Row="2"  prism:RegionManager.RegionName="RegionD" />
</code>```

Body:
I have some ItemsControl.ItemsPanel repetitive XAML sections that I'd like to factor out to a Windows.resource. I've made an attempt at it for RegionD but I get a incompatible type error message. Any help would be appreciated.

<Window x:Class="PrismDemo.Views.ShellWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:prism="http://prismlibrary.com/"
    prism:ViewModelLocator.AutoWireViewModel="True"
    Title="{Binding Title}" Height="150" Width="325" >

<Window.Resources>
    <ItemsControl x:Key="IC" >
        <ItemsControl.ItemsPanel >
            <ItemsPanelTemplate>
                <Grid IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</Window.Resources>

<Grid ShowGridLines="True">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <ContentControl Grid.Row="0"  prism:RegionManager.RegionName="RegionA" />
    <ContentControl Grid.Row="0"  prism:RegionManager.RegionName="RegionB" />
    <ItemsControl Grid.Row="1"  prism:RegionManager.RegionName="RegionC" >
        <ItemsControl.ItemsPanel >
            <ItemsPanelTemplate>
                <Grid IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
    <ItemsControl x:Name="{StaticResource IC}" Grid.Row="2"  prism:RegionManager.RegionName="RegionD" />
</Grid>

Body:
create a Style with Setter for ItemsPanel:

<Style x:Key="IC" TargetType="{x:Type ItemsControl}">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <Grid IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
</Style>

then apply Style to each ItemsControl:

<ItemsControl Style="{StaticResource IC}" Grid.Row="1"  prism:RegionManager.RegionName="RegionC" />
<ItemsControl Style="{StaticResource IC}" Grid.Row="2"  prism:RegionManager.RegionName="RegionD" />


问:
Entity Framework related entities generate unnecessary joins of the same table
I am running into issue of EF Core 3.1 generating multiple INNER JOINs to the same table even though it has enough information to avoid it.

Simplified model with mapping :

```<code>internal class PRecord
{
    public int Id { get; private set; }
    public string Name { get; private set; }

    public PImport Import { get; private set; }

    private PRecord()
    {
    }

    internal PRecord(string name)
    {
        Name = name;
    }

    public class PRecordDbMapping : IEntityTypeConfiguration<PRecord>
    {
        public void Configure(EntityTypeBuilder<PRecord> builder)
        {
            builder.ToTable("p_records");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<long>("PImportId").HasColumnName("p_import_id");

            builder.HasOne(x => x.Import).WithMany(x => x.Records).HasForeignKey("PImportId").IsRequired();
        }
    }
}

internal class PImport
{
    public long Id { get; private set; }
    public PSource Source { get; private set; }

    public IEnumerable<PRecord> Records { get; private set; }

    private PImport()
    {
    }

    internal PImport(PSource source)
    {
        Source = source;
    }

    public class PImportDbMapping : IEntityTypeConfiguration<PImport>
    {
        public void Configure(EntityTypeBuilder<PImport> builder)
        {
            builder.ToTable("p_imports");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<int>("PSourceId").HasColumnName("p_source_id");

            builder.HasOne(x => x.Source).WithMany(x => x.Imports).HasForeignKey("PSourceId").IsRequired();
        }
    }
}

internal class PSource
{
    public int Id { get; private set; }
    public PImport CurrentImport { get; private set; }

    public IEnumerable<PImport> Imports { get; private set; }

    private PSource()
    {
    }

    internal PSource(int id)
    {
        Id = id;
    }

    public class PSourceDbMapping : IEntityTypeConfiguration<PSource>
    {
        public void Configure(EntityTypeBuilder<PSource> builder)
        {
            builder.ToTable("p_sources");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<long>("CurrentPImportId").HasColumnName("current_p_import_id");

            builder.HasOne(x => x.CurrentImport).WithOne().HasForeignKey<PEPSource>("CurrentPImportId");
        }
    }
}
</code>```

I tried multiple variants of the following, but with slight variations I always get the same problem in SQL :

```<code>var query = ctx.PRecords
               .Where(x => x.Name.Contains("bla"))
               .Where(x => x.Import.Source.CurrentImport == x.Import)
               .Select(x => new { Record = x, Source = x.Import.Source });

SELECT
    [p].[id], [p].[name], [p].[p_import_id], [p1].[id], [p1].[current_p_import_id]
FROM [p_records] AS [p]
INNER JOIN [p_source_imports] AS [p0] ON [p].[p_import_id] = [p0].[id]
INNER JOIN [p_sources] AS [p1] ON [p0].[p_source_id] = [p1].[id]
INNER JOIN [p_source_imports] AS [p2] ON [p1].[current_p_import_id] = [p2].[id]
WHERE (CHARINDEX(N'bla', [p].[name]) > 0) AND ([p2].[id] = [p0].[id])
</code>```

I am able to generate the SQL I want with the following code :

```<code>var query = ctx.PSources
               .Where(x => x.CurrentImport != null)
               .SelectMany(x => x.CurrentImport.Records, (x, y) => new { Record = y, Source = x })
               .Where(x => x.Record.Name.Contains("bla"));
</code>```

The issue with this one is that I want to move the .Where(x => x.Record.Name.Contains("bla")) into extension method. And in this query I have to apply it on the anonymous type.

So I have two questions :

Can the first query be salvaged to generate reasonable SQL, while still returning IQueryable<PRecord> or if not possible a queryable of some non-anonymous type ?

If (1) cannot be achieved reasonably, can I achieve the moving of the WHERE condition on the Name to some extension method anyway?

EDIT: specified EF Core 3.1 as the verswion used

EDIT: the accepted solution is enough for my case. Completely clean solution might not be possible in the current version of EF Core. As I was browsing github issues for EF Core it seems the SQL generator might have restrictions that cause the more straightforward queries to use unnecessary 'JOIN's.

So the query I went with is :

```<code>var query = ctx.PSources
               .Where(x => x.CurrentImport != null)
               .SelectMany(x => x.CurrentImport.Records, (x, y) => new SourceRecordPair() { Record = y, Source = x })
               .Where(x => x.Record.Name.Contains("bla"));
</code>```

答:
Can the first query be salvaged to generate reasonable SQL, while still returning IQueryable<PRecord> or if not possible a queryable of some non-anonymous type ?

Yes, by breaking the encapsulation and accessing directly the shadow FK property (with EF.Property method) inside the query. Error prone (you need to know/keep in sync the property name string), but can be used as workaround until gets fixed by EF Core (because it's current EF Core defect):

```<code>.Where(x => EF.Property<long?>(x.Import.Source, "CurrentPImportId") == x.Import.Id)
</code>```

If (1) cannot be achieved reasonably, can I achieve the moving of the WHERE condition on the Name to some extension method anyway?

Yes. But you have to create two extension methods - one normal and one generic with expression argument for extracting the "source", e.g.

```<code>public static IQueryable<PRecord> FilterRecords(this IQueryable<PRecord> source)
    => source.FilterRecords(x => x);

public static IQueryable<T> FilterRecords<T>(this IQueryable<T> source, Expression<Func<T, PRecord>> recordSelector)
    => source.Where(recordSelector.Apply(
            x => x.Name.Contains("blah") // actual filter goes here
        ));
</code>```

Now you can use the non generic method with your first query

```<code>var query = ctx.PRecords
    .FilterRecords() // <--
    .Where(x => EF.Property<long?>(x.Import.Source, "CurrentPImportId") == x.Import.Id) // from (1)
    .Select(x => new { Record = x, Source = x.Import.Source });
</code>```

and the generic method with your second query

```<code>var query = ctx.PSources
    .Where(x => x.CurrentImport != null)
    .SelectMany(x => x.CurrentImport.Records, (x, y) => new { Record = y, Source = x })
    .FilterRecords(x => x.Record); // <--
</code>```

Note that the generic method works with any type of T, and also the T is inferred by the compiler, so you can use it with both anonymous and concrete type projections.

The first method will simply call the second passing "self selector" (x => x), and the actual implementation will be in the second method. With the following detail - you need a small helper utility for composing expressions, so the Apply method here is from my own ExpressionUtils helper class which I use in many expression related answers:

```<code>public static partial class ExpressionUtils
{
    public static Expression<Func<TOuter, TResult>> Apply<TOuter, TInner, TResult>(this Expression<Func<TOuter, TInner>> outer, Expression<Func<TInner, TResult>> inner)
        => Expression.Lambda<Func<TOuter, TResult>>(inner.Body.ReplaceParameter(inner.Parameters[0], outer.Body), outer.Parameters);

    public static Expression<Func<TOuter, TResult>> ApplyTo<TInner, TResult, TOuter>(this Expression<Func<TInner, TResult>> inner, Expression<Func<TOuter, TInner>> outer)
        => outer.Apply(inner);

    public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
        => new ParameterReplacer { source = source, target = target }.Visit(expression);

    class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression source;
        public Expression target;
        protected override Expression VisitParameter(ParameterExpression node)
            => node == source ? target : node;
    }
}
</code>```

Body:
I am running into issue of EF Core 3.1 generating multiple INNER JOINs to the same table even though it has enough information to avoid it.

Simplified model with mapping :

internal class PRecord
{
    public int Id { get; private set; }
    public string Name { get; private set; }

    public PImport Import { get; private set; }

    private PRecord()
    {
    }

    internal PRecord(string name)
    {
        Name = name;
    }

    public class PRecordDbMapping : IEntityTypeConfiguration<PRecord>
    {
        public void Configure(EntityTypeBuilder<PRecord> builder)
        {
            builder.ToTable("p_records");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<long>("PImportId").HasColumnName("p_import_id");

            builder.HasOne(x => x.Import).WithMany(x => x.Records).HasForeignKey("PImportId").IsRequired();
        }
    }
}

internal class PImport
{
    public long Id { get; private set; }
    public PSource Source { get; private set; }

    public IEnumerable<PRecord> Records { get; private set; }

    private PImport()
    {
    }

    internal PImport(PSource source)
    {
        Source = source;
    }

    public class PImportDbMapping : IEntityTypeConfiguration<PImport>
    {
        public void Configure(EntityTypeBuilder<PImport> builder)
        {
            builder.ToTable("p_imports");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<int>("PSourceId").HasColumnName("p_source_id");

            builder.HasOne(x => x.Source).WithMany(x => x.Imports).HasForeignKey("PSourceId").IsRequired();
        }
    }
}

internal class PSource
{
    public int Id { get; private set; }
    public PImport CurrentImport { get; private set; }

    public IEnumerable<PImport> Imports { get; private set; }

    private PSource()
    {
    }

    internal PSource(int id)
    {
        Id = id;
    }

    public class PSourceDbMapping : IEntityTypeConfiguration<PSource>
    {
        public void Configure(EntityTypeBuilder<PSource> builder)
        {
            builder.ToTable("p_sources");
            builder.HasKey(x => x.Id);

            builder.Property(x => x.Id).HasColumnName("id");
            builder.Property<long>("CurrentPImportId").HasColumnName("current_p_import_id");

            builder.HasOne(x => x.CurrentImport).WithOne().HasForeignKey<PEPSource>("CurrentPImportId");
        }
    }
}

I tried multiple variants of the following, but with slight variations I always get the same problem in SQL :

var query = ctx.PRecords
               .Where(x => x.Name.Contains("bla"))
               .Where(x => x.Import.Source.CurrentImport == x.Import)
               .Select(x => new { Record = x, Source = x.Import.Source });

SELECT
    [p].[id], [p].[name], [p].[p_import_id], [p1].[id], [p1].[current_p_import_id]
FROM [p_records] AS [p]
INNER JOIN [p_source_imports] AS [p0] ON [p].[p_import_id] = [p0].[id]
INNER JOIN [p_sources] AS [p1] ON [p0].[p_source_id] = [p1].[id]
INNER JOIN [p_source_imports] AS [p2] ON [p1].[current_p_import_id] = [p2].[id]
WHERE (CHARINDEX(N'bla', [p].[name]) > 0) AND ([p2].[id] = [p0].[id])

I am able to generate the SQL I want with the following code :

var query = ctx.PSources
               .Where(x => x.CurrentImport != null)
               .SelectMany(x => x.CurrentImport.Records, (x, y) => new { Record = y, Source = x })
               .Where(x => x.Record.Name.Contains("bla"));

The issue with this one is that I want to move the .Where(x => x.Record.Name.Contains("bla")) into extension method. And in this query I have to apply it on the anonymous type.

So I have two questions :

Can the first query be salvaged to generate reasonable SQL, while still returning IQueryable<PRecord> or if not possible a queryable of some non-anonymous type ?

If (1) cannot be achieved reasonably, can I achieve the moving of the WHERE condition on the Name to some extension method anyway?

EDIT: specified EF Core 3.1 as the verswion used

EDIT: the accepted solution is enough for my case. Completely clean solution might not be possible in the current version of EF Core. As I was browsing github issues for EF Core it seems the SQL generator might have restrictions that cause the more straightforward queries to use unnecessary 'JOIN's.

So the query I went with is :

var query = ctx.PSources
               .Where(x => x.CurrentImport != null)
               .SelectMany(x => x.CurrentImport.Records, (x, y) => new SourceRecordPair() { Record = y, Source = x })
               .Where(x => x.Record.Name.Contains("bla"));

Body:
Can the first query be salvaged to generate reasonable SQL, while still returning IQueryable<PRecord> or if not possible a queryable of some non-anonymous type ?

Yes, by breaking the encapsulation and accessing directly the shadow FK property (with EF.Property method) inside the query. Error prone (you need to know/keep in sync the property name string), but can be used as workaround until gets fixed by EF Core (because it's current EF Core defect):

.Where(x => EF.Property<long?>(x.Import.Source, "CurrentPImportId") == x.Import.Id)

If (1) cannot be achieved reasonably, can I achieve the moving of the WHERE condition on the Name to some extension method anyway?

Yes. But you have to create two extension methods - one normal and one generic with expression argument for extracting the "source", e.g.

public static IQueryable<PRecord> FilterRecords(this IQueryable<PRecord> source)
    => source.FilterRecords(x => x);

public static IQueryable<T> FilterRecords<T>(this IQueryable<T> source, Expression<Func<T, PRecord>> recordSelector)
    => source.Where(recordSelector.Apply(
            x => x.Name.Contains("blah") // actual filter goes here
        ));

Now you can use the non generic method with your first query

var query = ctx.PRecords
    .FilterRecords() // <--
    .Where(x => EF.Property<long?>(x.Import.Source, "CurrentPImportId") == x.Import.Id) // from (1)
    .Select(x => new { Record = x, Source = x.Import.Source });

and the generic method with your second query

var query = ctx.PSources
    .Where(x => x.CurrentImport != null)
    .SelectMany(x => x.CurrentImport.Records, (x, y) => new { Record = y, Source = x })
    .FilterRecords(x => x.Record); // <--

Note that the generic method works with any type of T, and also the T is inferred by the compiler, so you can use it with both anonymous and concrete type projections.

The first method will simply call the second passing "self selector" (x => x), and the actual implementation will be in the second method. With the following detail - you need a small helper utility for composing expressions, so the Apply method here is from my own ExpressionUtils helper class which I use in many expression related answers:

public static partial class ExpressionUtils
{
    public static Expression<Func<TOuter, TResult>> Apply<TOuter, TInner, TResult>(this Expression<Func<TOuter, TInner>> outer, Expression<Func<TInner, TResult>> inner)
        => Expression.Lambda<Func<TOuter, TResult>>(inner.Body.ReplaceParameter(inner.Parameters[0], outer.Body), outer.Parameters);

    public static Expression<Func<TOuter, TResult>> ApplyTo<TInner, TResult, TOuter>(this Expression<Func<TInner, TResult>> inner, Expression<Func<TOuter, TInner>> outer)
        => outer.Apply(inner);

    public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
        => new ParameterReplacer { source = source, target = target }.Visit(expression);

    class ParameterReplacer : ExpressionVisitor
    {
        public ParameterExpression source;
        public Expression target;
        protected override Expression VisitParameter(ParameterExpression node)
            => node == source ? target : node;
    }
}


问:
Django Web Application, Facebook login
I am building a basic social media web application and I would like my only login point to be via facebook login. After doing a fare amount of research, I have seen multiple third party authorization frameworks that plug in with facebook, but I was wondering if there were any opinions on what the best foot forward would be.

Additionally, how would I go about still being able to use sessions/cookies within Django if I use fb login?

All answers are appreciated!

答: You can use SocialAuth (https://github.com/python-social-auth/social-app-django), this app allows you to let users log in via many common SocialMedia-accounts, e.g. facebook. Upon login, the app will create a user in your database, which you can then use as if the user logged in with a local account. Therefore, the session will still be handled by django, fb only sends you some information about the user (e.g. first- and lastname, email, etc. [configurable in your settings.py])</p>

Title: Django Web Application, Facebook login


问:
How to implements a button tag to form_for helper?
I need implements a helper that creates <button>...</button> tag, I need to do some similar to this:

```<code><%= form_for(some_var) do |f| %>
  <%= f.submit '+' %>
<% end %>
</code>```

The helper should work like this:

```<code><%= f.button '+' %>
# Returns
<button type="submit">+</button>
</code>```

I saw https://github.com/rails/rails/blob/master/actionpack/lib/action_view/helpers/form_tag_helper.rb#L458 but this isn't implemented in Rails 3.0.7.

What I need to do to implements this helper in my application?

答:
I had implemented a similar helper method in one of my applications earlier. I needed the button tag with an image on the button and a class of its own. You can pass either a string which is the text that is displayed on the button or the object itself. It looks like this:

```<code>def submit_button(object)
    image   = "#{image_tag('/images/icons/tick.png', :alt => '')}"

    if object.is_a?(String)
      value = "#{image}#{object}"
    else
      name  = object.class.to_s.titlecase
      value = object.new_record? ? "#{image} Save #{name} Information" : "#{image} Update #{name} Information"
    end

    content_tag :button, :type => :submit, :class => 'button positive' do
      content_tag(:image, '/images/icons/tick.png', :alt => '')
      value
    end
  end
</code>```

Then you call this in the form <%= submit_button @admission %>

It looks like this:

Body:
I need implements a helper that creates <button>...</button> tag, I need to do some similar to this:

<%= form_for(some_var) do |f| %>
  <%= f.submit '+' %>
<% end %>

The helper should work like this:

<%= f.button '+' %>
# Returns
<button type="submit">+</button>

I saw https://github.com/rails/rails/blob/master/actionpack/lib/action_view/helpers/form_tag_helper.rb#L458 but this isn't implemented in Rails 3.0.7.

What I need to do to implements this helper in my application?

Body:
I had implemented a similar helper method in one of my applications earlier. I needed the button tag with an image on the button and a class of its own. You can pass either a string which is the text that is displayed on the button or the object itself. It looks like this:

def submit_button(object)
    image   = "#{image_tag('/images/icons/tick.png', :alt => '')}"

    if object.is_a?(String)
      value = "#{image}#{object}"
    else
      name  = object.class.to_s.titlecase
      value = object.new_record? ? "#{image} Save #{name} Information" : "#{image} Update #{name} Information"
    end

    content_tag :button, :type => :submit, :class => 'button positive' do
      content_tag(:image, '/images/icons/tick.png', :alt => '')
      value
    end
  end

Then you call this in the form <%= submit_button @admission %>

It looks like this:


问:
Angular material creating a form inside mat-table
I need to create a form inside a mat-table (the mat table is inside a stepper which is inside a mat-dialog). As of right now I created a table and inside the td tag I used mat-form field with mat-input inside but my input seems to be disabled as I can't use it.

html code for the step which holds the table:

```<code>
<mat-step [stepControl]="contactsFormGroup">
        <ng-template matStepLabel>Contacts</ng-template>
        <div
          fxLayout="column"
          fxLayoutAlign="center Center"
          fxLayoutGap="20px"
          class="form-wrapper-add-contacts"
          [formGroup]="contactsFormGroup"
        >
          <div class="add-contacts-table-wrapper">
            <table
              mat-table
              [dataSource]="contactsFormGroup.get('contactsArray').value"
              formArrayName="contactsArray"
            >
              <ng-container matColumnDef="indexPos">
                <th mat-header-cell *matHeaderCellDef>No.</th>
                <td mat-cell *matCellDef="let element; let i = index">
                  {{ i + 1 + "." }}
                </td>
              </ng-container>

              <ng-container matColumnDef="firstName">
                <th mat-header-cell *matHeaderCellDef>First Name</th>
                <td
                  mat-cell
                  *matCellDef="let element; let i = index"
                  formGroupName="{{ i }}"
                >
                  <mat-form-field appearance="fill">
                    <mat-label>First Name</mat-label>
                    <input
                      matInput
                      placeholder="First Name"
                      autocorrect="off"
                      autocapitalize="off"
                      spellcheck="off"
                      type="text"
                      formControlName="contactFirstName"
                      required
                    />
                  </mat-form-field>
                </td>
              </ng-container>

              <ng-container matColumnDef="lastName">
                <th mat-header-cell *matHeaderCellDef>Last Name</th>
                <td
                  mat-cell
                  *matCellDef="let element; let i = index"
                  formGroupName="{{ i }}"
                >
                  <mat-form-field appearance="fill">
                    <mat-label>Last Name</mat-label>
                    <input
                      matInput
                      placeholder="Last Name"
                      autocorrect="off"
                      autocapitalize="off"
                      spellcheck="off"
                      type="text"
                      formControlName="contactLastName"
                      required
                    />
                  </mat-form-field>
                </td>
              </ng-container>

              <ng-container matColumnDef="email">
                <th mat-header-cell *matHeaderCellDef>Email</th>
                <td
                  mat-cell
                  *matCellDef="let element; let i = index"
                  formGroupName="{{ i }}"
                >
                  <mat-form-field appearance="fill">
                    <mat-label>Email</mat-label>
                    <input
                      matInput
                      placeholder="Email"
                      autocorrect="off"
                      autocapitalize="off"
                      spellcheck="off"
                      type="text"
                      formControlName="contactEmail"
                      required
                    />
                  </mat-form-field>
                </td>
              </ng-container>

              <ng-container matColumnDef="phone">
                <th mat-header-cell *matHeaderCellDef>Phone</th>
                <td
                  mat-cell
                  *matCellDef="let element; let i = index"
                  formGroupName="{{ i }}"
                >
                  <mat-form-field appearance="fill">
                    <mat-label>Phone</mat-label>
                    <input
                      matInput
                      placeholder="Phone"
                      autocorrect="off"
                      autocapitalize="off"
                      spellcheck="off"
                      type="text"
                      formControlName="contactPhone"
                      required
                    />
                  </mat-form-field>
                </td>
              </ng-container>

              <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
              <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
            </table>
          </div>

          <div class="previous-button-wrapper">
            <button mat-button matStepperPrevious type="button">
              Back
            </button>
          </div>
        </div>
      </mat-step>
</code>```

ts code for the form group:

```<code>contactsFormGroup: FormGroup = this.fb.group({
    contactsArray: this.fb.array([this.fb.group({
      contactFirstName: ['', [Validators.required, Validators.maxLength(200)]],
      contactLastName: ['', [Validators.required, Validators.maxLength(200)]],
      contactEmail: ['', [Validators.required, Validators.email, Validators.maxLength(200)]],
      contactPhone: ['', [Validators.required, Validators.maxLength(15)]]
    }, { updateOn: 'blur' })])
  }, { updateOn: 'blur' });
</code>```

a picture of the table as of right now: form - table

答:
Got it to work, Changed this:

```<code>[dataSource]="contactsFormGroup.get('contactsArray').value
</code>```

to:

```<code>[dataSource]=contactsFormGroup.get('contactsArray').controls
</code>```

Body:
I need to create a form inside a mat-table (the mat table is inside a stepper which is inside a mat-dialog). As of right now I created a table and inside the td tag I used mat-form field with mat-input inside but my input seems to be disabled as I can't use it.

html code for the step which holds the table:

<mat-step [stepControl]="contactsFormGroup">
        <ng-template matStepLabel>Contacts</ng-template>

              <ng-container matColumnDef="indexPos">
                No.

                  {{ i + 1 + "." }}

              </ng-container>

              <ng-container matColumnDef="firstName">
                First Name

                  <mat-form-field appearance="fill">
                    <mat-label>First Name</mat-label>
                    <input
                      matInput
                      placeholder="First Name"
                      autocorrect="off"
                      autocapitalize="off"
                      spellcheck="off"
                      type="text"
                      formControlName="contactFirstName"
                      required
                    />
                  </mat-form-field>

              </ng-container>

              <ng-container matColumnDef="lastName">
                Last Name

                  <mat-form-field appearance="fill">
                    <mat-label>Last Name</mat-label>
                    <input
                      matInput
                      placeholder="Last Name"
                      autocorrect="off"
                      autocapitalize="off"
                      spellcheck="off"
                      type="text"
                      formControlName="contactLastName"
                      required
                    />
                  </mat-form-field>

              </ng-container>

              <ng-container matColumnDef="email">
                Email

                  <mat-form-field appearance="fill">
                    <mat-label>Email</mat-label>
                    <input
                      matInput
                      placeholder="Email"
                      autocorrect="off"
                      autocapitalize="off"
                      spellcheck="off"
                      type="text"
                      formControlName="contactEmail"
                      required
                    />
                  </mat-form-field>

              </ng-container>

              <ng-container matColumnDef="phone">
                Phone

                  <mat-form-field appearance="fill">
                    <mat-label>Phone</mat-label>
                    <input
                      matInput
                      placeholder="Phone"
                      autocorrect="off"
                      autocapitalize="off"
                      spellcheck="off"
                      type="text"
                      formControlName="contactPhone"
                      required
                    />
                  </mat-form-field>

              </ng-container>

            <button mat-button matStepperPrevious type="button">
              Back
            </button>

      </mat-step>

ts code for the form group:

contactsFormGroup: FormGroup = this.fb.group({
    contactsArray: this.fb.array([this.fb.group({
      contactFirstName: ['', [Validators.required, Validators.maxLength(200)]],
      contactLastName: ['', [Validators.required, Validators.maxLength(200)]],
      contactEmail: ['', [Validators.required, Validators.email, Validators.maxLength(200)]],
      contactPhone: ['', [Validators.required, Validators.maxLength(15)]]
    }, { updateOn: 'blur' })])
  }, { updateOn: 'blur' });

a picture of the table as of right now: form - table

Body:
Got it to work, Changed this:

[dataSource]="contactsFormGroup.get('contactsArray').value

to:

[dataSource]=contactsFormGroup.get('contactsArray').controls