text:
Q: Interactive plotting in Pycharm debug console through matplotlib I have a python script I'm trying to debug and I'm using Pycharm Community Edition version 2016.3.2.
What I'd like to do is make some plots in the debug console (which I activate by setting a breakpoint and starting the debugger), but the problem is that the plot simply doesn't show up.
Some code to get a reproducible example of my problem is provided on the official matplotlib documentation here, in particular this bit of code:
import matplotlib.pyplot as plt
plt.ion()
plt.plot([1.6, 2.7])

What I find strange is that if I open a new python console from inside pycharm, when executing this code pycharm pops up a new window showing the plot, but this doesn't happen if I paste the same code in the "debug" console.
In both cases, I get the following output in the console

I found a potentially related post here, but frankly I can't tell if the two problems reduce to the same issue.

A: *

*Tested in python 3.8.12, matplotlib 3.4.3, PyCharm 2021.2.3 (Professional Edition)

*In PyCharm Create a Pure Python Project

*

*File New Project... Pure Python

*

*Finish the project setup

*Create a new python file:

*

*

*After the package imports, specify an interactive backend

*

*mpl.use('Qt5Agg')

*mpl.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib as mpl
# mpl.use('Qt5Agg')  # interactive mode works with this, pick one
mpl.use('TkAgg')  # interactive mode works with this, pick one

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)

fig1, ax1 = plt.subplots()

ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
ax1.axis('equal')

plt.show()

Debug Console

*

*The script also works with debug, but the plot shows and then goes away as the debugger closes, so an extra line is included to prevent the debugger from closing the plot window.


text: Q: Why images and icons don't load when converting .py to .exe with pyinstaller? I'm trying to convert a Python program to exe using pyinstaller, the program has 1 icon and 1 png picture, so when I convert it with pyinstaller, everything works perfectly except the pictures are not loading, it gives me this error: Failed to obtain/convert traceback!, but when I copy-paste the two pics in the same folder as the exe, it loads!, however, I just want to avoid that, is it possible to package it all including pictures? Note: I tried using --onefile and --windowed as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kubernetes DNS works where kube-dns pod working, if scale kubedns pod nothing is working Kubernetes version (use kubectl version):
Client Version: version.Info{Major:"1", Minor:"4", GitVersion:"v1.4.0", GitCommit:"87d9d8d7bc5aa35041a8ddfe3d4b367381112f89", GitTreeState:"clean", BuildDate:"2016-12-12T21:10:52Z", GoVersion:"go1.6.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"4", GitVersion:"v1.4.0", GitCommit:"87d9d8d7bc5aa35041a8ddfe3d4b367381112f89", GitTreeState:"clean", BuildDate:"2016-12-12T21:10:52Z", GoVersion:"go1.6.2", Compiler:"gc", Platform:"linux/amd64"}

Environment:
AWS, using VPC, all master and 2 nodes under same subnet
RHEL 7.2
Kernel (e.g. uname -a): Linux master.example.com 3.10.0-514.6.2.el7.x86_64 #1 SMP Fri Feb 17 19:21:31 EST 2017 x86_64 x86_64 x86_64 GNU/Linux
Install tools: Install kubernetes as per Redhat guideline using flannel Network
flannel-config.json
{
"Network": "10.20.0.0/16",
"SubnetLen": 24,
"Backend": {
"Type": "vxlan",
"VNI": 1
}
}
Kubernetes Cluster Network : 10.254.0.0/16

Others:
What happened:
We have kubernetes cluster setup with following setup
Master: ip-10-52-2-56.ap-northeast-2.compute.internal
Node1: ip-10-52-2-59.ap-northeast-2.compute.internal
Node2: ip-10-52-2-54.ap-northeast-2.compute.internal

Master config details:
[root@master ~]# egrep -v '^#|^$' /etc/etcd/etcd.conf
ETCD_NAME=default
ETCD_DATA_DIR="/var/lib/etcd/default.etcd"
ETCD_LISTEN_PEER_URLS="http://localhost:2380"
ETCD_LISTEN_CLIENT_URLS="http://0.0.0.0:2379"
ETCD_ADVERTISE_CLIENT_URLS="http://0.0.0.0:2379"
[root@master ~]# egrep -v '^#|^$' /etc/kubernetes/config
KUBE_LOGTOSTDERR="--logtostderr=true"
KUBE_LOG_LEVEL="--v=0"
KUBE_ALLOW_PRIV="--allow-privileged=false"
KUBE_MASTER="--master=http://ip-10-52-2-56.ap-northeast-2.compute.internal:8080"
[root@master ~]# egrep -v '^#|^$' /etc/kubernetes/apiserver
KUBE_API_ADDRESS="--address=0.0.0.0"
KUBE_ETCD_SERVERS="--etcd_servers=http://ip-10-52-2-56.ap-northeast-2.compute.internal:2379"
KUBE_SERVICE_ADDRESSES="--service-cluster-ip-range=10.254.0.0/16"
KUBE_ADMISSION_CONTROL="--admission-control=NamespaceLifecycle,NamespaceExists,LimitRanger,SecurityContextDeny,ServiceAccount,ResourceQuota"
KUBE_API_ARGS="--service_account_key_file=/serviceaccount.key""
[root@master ~]# egrep -v '^#|^$' /etc/sysconfig/flanneld
FLANNEL_ETCD="http://ip-10-52-2-56.ap-northeast-2.compute.internal:2379"
FLANNEL_ETCD_KEY="/coreos.com/network"
FLANNEL_OPTIONS="eth0"

Node1/Node2 config details are same as follows:
[root@ip-10-52-2-59 ec2-user]# egrep -v '^$|^#' /etc/kubernetes/config
KUBE_LOGTOSTDERR="--logtostderr=true"
KUBE_LOG_LEVEL="--v=0"
KUBE_ALLOW_PRIV="--allow-privileged=false"
KUBE_MASTER="--master=http://ip-10-52-2-56.ap-northeast-2.compute.internal:8080"
[root@ip-10-52-2-59 ec2-user]# egrep -v '^#|^$' /etc/kubernetes/kubelet
KUBELET_ADDRESS="--address=0.0.0.0"
KUBELET_HOSTNAME="--hostname-override=ip-10-52-2-59.ap-northeast-2.compute.internal"
KUBELET_API_SERVER="--api-servers=http://ip-10-52-2-56.ap-northeast-2.compute.internal:8080"
KUBELET_POD_INFRA_CONTAINER="--pod-infra-container-image=registry.access.redhat.com/rhel7/pod-infrastructure:latest"
KUBELET_ARGS="--cluster-dns=10.254.0.2 --cluster-domain=cluster.local"
[root@ip-10-52-2-59 ec2-user]# grep KUBE_PROXY_ARGS /etc/kubernetes/proxy
KUBE_PROXY_ARGS=""
[root@ip-10-52-2-59 ec2-user]# egrep -v '^#|^$' /etc/sysconfig/flanneld
FLANNEL_ETCD="http://ip-10-52-2-56.ap-northeast-2.compute.internal:2379"
FLANNEL_ETCD_KEY="/coreos.com/network"
FLANNEL_OPTIONS="eth0"

Running kube dns as below configuration:
apiVersion: v1
kind: Service
metadata:
name: kube-dns
namespace: kube-system
labels:
k8s-app: kube-dns
kubernetes.io/cluster-service: "true"
kubernetes.io/name: "KubeDNS"
spec:
selector:
k8s-app: kube-dns
clusterIP: 10.254.0.2
ports:

name: dns
port: 53
protocol: UDP
name: dns-tcp
port: 53
protocol: TCP
apiVersion: v1
kind: ReplicationController
metadata:
labels:
k8s-app: kube-dns
kubernetes.io/cluster-service: "true"
version: v20
name: kube-dns-v20
namespace: kube-system
spec:
replicas: 1
selector:
k8s-app: kube-dns
version: v20
template:
metadata:
labels:
k8s-app: kube-dns
kubernetes.io/cluster-service: "true"
version: v20
spec:
containers:
-
args:
- "--domain=cluster.local"
- "--kube-master-url=http://ip-10-52-2-56.ap-northeast-2.compute.internal:8080"
- "--dns-port=10053"
image: "gcr.io/google_containers/kubedns-amd64:1.9"
livenessProbe:
failureThreshold: 5
httpGet:
path: /healthz
port: 8080
scheme: HTTP
initialDelaySeconds: 60
successThreshold: 1
timeoutSeconds: 5
name: kubedns
ports:
-
containerPort: 10053
name: dns-local
protocol: UDP
-
containerPort: 10053
name: dns-tcp-local
protocol: TCP
readinessProbe:
httpGet:
path: /readiness
port: 8081
scheme: HTTP
initialDelaySeconds: 30
timeoutSeconds: 5
resources:
limits:
cpu: 100m
memory: 500Mi
requests:
cpu: 100m
memory: 500Mi
-
args:
- "--cache-size=1000"
- "--no-resolv"
- "--server=127.0.0.1#10053"
image: "gcr.io/google_containers/kube-dnsmasq-amd64:1.4"
name: dnsmasq
ports:
-
containerPort: 53
name: dns
protocol: UDP
-
containerPort: 53
name: dns-tcp
protocol: TCP
-
args:
- "-cmd=nslookup kubernetes.default.svc.cluster.local 127.0.0.1 >/dev/null && nslookup kubernetes.default.svc.cluster.local 127.0.0.1:10053 >/dev/null"
- "-port=8080"
- "-quiet"
image: "gcr.io/google_containers/exechealthz-amd64:1.2"
name: healthz
ports:
-
containerPort: 8080
protocol: TCP
resources:
limits:
cpu: 10m
memory: 20Mi
requests:
cpu: 10m
memory: 20Mi
dnsPolicy: Default

What happen:
Kubernetes DNS works where kube-dns pod working, if scale kubedns pod nothing is working anywhere (nodes).
In below one dns pod is running on node1 and response also coming from node1 busybox pod but node2 busybox pod nslookup not responded.
image1
Now below two dns pods are running on node1 and node2 and you can see NO response coming from none of busybox pod from both node
image2
below some other observation ....
DNS pod most of the time taking 172.17 IP series if i scale more than 4 pod then in node 2 dns pod taking 10.20 series IP.
Interesting part Node2 pods started with 10.20 series IP.
but Node1 pods started with 172.17 series IP.
Some of iptable-save output for both nodes.
[root@ip-10-52-2-54 ec2-user]# iptables-save | grep DNAT
-A KUBE-SEP-3M72SO5X7J6X6TX6 -p tcp -m comment --comment "default/prometheus:prometheus" -m tcp -j DNAT --to-destination 172.17.0.8:9090
-A KUBE-SEP-7SLC3EUJVX23N2X4 -p tcp -m comment --comment "default/zookeeper:" -m tcp -j DNAT --to-destination 172.17.0.4:2181
-A KUBE-SEP-D4NTKJJ3YXXGJARZ -p udp -m comment --comment "kube-system/kube-dns:dns" -m udp -j DNAT --to-destination 172.17.0.10:53
-A KUBE-SEP-EN24FH2N7PLAR6AW -p tcp -m comment --comment "default/kafkacluster:" -m tcp -j DNAT --to-destination 172.17.0.2:9092
-A KUBE-SEP-LCDAFU4UXQHVDQT6 -p tcp -m comment --comment "default/kubernetes:https" -m recent --set --name KUBE-SEP-LCDAFU4UXQHVDQT6 --mask 255.255.255.255 --rsource -m tcp -j DNAT --to-destination 10.52.2.56:6443
-A KUBE-SEP-MX63IHIHS5ZB4347 -p tcp -m comment --comment "default/nodejs4promethus-scraping:" -m tcp -j DNAT --to-destination 172.17.0.6:3000
-A KUBE-SEP-NOI5B75N7ZJAIPJR -p tcp -m comment --comment "default/mongodb-prometheus-exporter:" -m tcp -j DNAT --to-destination 172.17.0.12:9001
-A KUBE-SEP-O6UDQQL3MHGYTSH5 -p tcp -m comment --comment "default/producer:" -m tcp -j DNAT --to-destination 172.17.0.3:8125
-A KUBE-SEP-QO4SWWCV7NMMGPBN -p tcp -m comment --comment "default/kafka-prometheus-jmx:" -m tcp -j DNAT --to-destination 172.17.0.2:7071
-A KUBE-SEP-SVCEI2UVU246H7MW -p tcp -m comment --comment "default/mongodb:" -m tcp -j DNAT --to-destination 172.17.0.12:27017
-A KUBE-SEP-Y4XH6F2KQCY7WQBG -p tcp -m comment --comment "kube-system/kube-dns:dns-tcp" -m tcp -j DNAT --to-destination 172.17.0.10:53
-A KUBE-SEP-ZXXWX3EF7T3W7UNY -p tcp -m comment --comment "default/grafana:" -m tcp -j DNAT --to-destination 172.17.0.9:3000

[root@ip-10-52-2-54 ec2-user]# iptables-save | grep 53
-A KUBE-SEP-D4NTKJJ3YXXGJARZ -p udp -m comment --comment "kube-system/kube-dns:dns" -m udp -j DNAT --to-destination 172.17.0.10:53
-A KUBE-SEP-Y4XH6F2KQCY7WQBG -p tcp -m comment --comment "kube-system/kube-dns:dns-tcp" -m tcp -j DNAT --to-destination 172.17.0.10:53
-A KUBE-SERVICES -d 10.254.0.2/32 -p udp -m comment --comment "kube-system/kube-dns:dns cluster IP" -m udp --dport 53 -j KUBE-SVC-TCOU7JCQXEZGVUNU
-A KUBE-SERVICES -d 10.254.0.2/32 -p tcp -m comment --comment "kube-system/kube-dns:dns-tcp cluster IP" -m tcp --dport 53 -j KUBE-SVC-ERIFXISQEP7F7OF4

---------

[root@ip-10-52-2-59 ec2-user]# iptables-save | grep DNAT
-A KUBE-SEP-3M72SO5X7J6X6TX6 -p tcp -m comment --comment "default/prometheus:prometheus" -m tcp -j DNAT --to-destination 172.17.0.8:9090
-A KUBE-SEP-7SLC3EUJVX23N2X4 -p tcp -m comment --comment "default/zookeeper:" -m tcp -j DNAT --to-destination 172.17.0.4:2181
-A KUBE-SEP-D4NTKJJ3YXXGJARZ -p udp -m comment --comment "kube-system/kube-dns:dns" -m udp -j DNAT --to-destination 172.17.0.10:53
-A KUBE-SEP-EN24FH2N7PLAR6AW -p tcp -m comment --comment "default/kafkacluster:" -m tcp -j DNAT --to-destination 172.17.0.2:9092
-A KUBE-SEP-LCDAFU4UXQHVDQT6 -p tcp -m comment --comment "default/kubernetes:https" -m recent --set --name KUBE-SEP-LCDAFU4UXQHVDQT6 --mask 255.255.255.255 --rsource -m tcp -j DNAT --to-destination 10.52.2.56:6443
-A KUBE-SEP-MX63IHIHS5ZB4347 -p tcp -m comment --comment "default/nodejs4promethus-scraping:" -m tcp -j DNAT --to-destination 172.17.0.6:3000
-A KUBE-SEP-NOI5B75N7ZJAIPJR -p tcp -m comment --comment "default/mongodb-prometheus-exporter:" -m tcp -j DNAT --to-destination 172.17.0.12:9001
-A KUBE-SEP-O6UDQQL3MHGYTSH5 -p tcp -m comment --comment "default/producer:" -m tcp -j DNAT --to-destination 172.17.0.3:8125
-A KUBE-SEP-QO4SWWCV7NMMGPBN -p tcp -m comment --comment "default/kafka-prometheus-jmx:" -m tcp -j DNAT --to-destination 172.17.0.2:7071
-A KUBE-SEP-SVCEI2UVU246H7MW -p tcp -m comment --comment "default/mongodb:" -m tcp -j DNAT --to-destination 172.17.0.12:27017
-A KUBE-SEP-Y4XH6F2KQCY7WQBG -p tcp -m comment --comment "kube-system/kube-dns:dns-tcp" -m tcp -j DNAT --to-destination 172.17.0.10:53
-A KUBE-SEP-ZXXWX3EF7T3W7UNY -p tcp -m comment --comment "default/grafana:" -m tcp -j DNAT --to-destination 172.17.0.9:3000

[root@ip-10-52-2-59 ec2-user]# iptables-save | grep 53

-A KUBE-SEP-D4NTKJJ3YXXGJARZ -p udp -m comment --comment "kube-system/kube-dns:dns" -m udp -j DNAT --to-destination 172.17.0.10:53
-A KUBE-SEP-Y4XH6F2KQCY7WQBG -p tcp -m comment --comment "kube-system/kube-dns:dns-tcp" -m tcp -j DNAT --to-destination 172.17.0.10:53
-A KUBE-SERVICES -d 10.254.0.2/32 -p tcp -m comment --comment "kube-system/kube-dns:dns-tcp cluster IP" -m tcp --dport 53 -j KUBE-SVC-ERIFXISQEP7F7OF4
-A KUBE-SERVICES -d 10.254.0.2/32 -p udp -m comment --comment "kube-system/kube-dns:dns cluster IP" -m udp --dport 53 -j KUBE-SVC-TCOU7JCQXEZGVUNU

Restarted below serviced on both node

    for SERVICES in flanneld docker kube-proxy.service kubelet.service; do
    systemctl stop $SERVICES
    systemctl start $SERVICES
    done

Node1: ifconfig

    [root@ip-10-52-2-59 ec2-user]# ifconfig
    docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet 172.17.0.1  netmask 255.255.0.0  broadcast 0.0.0.0
            inet6 fe80::42:2dff:fe01:c0b0  prefixlen 64  scopeid 0x20<link>
            ether 02:42:2d:01:c0:b0  txqueuelen 0  (Ethernet)
            RX packets 1718522  bytes 154898857 (147.7 MiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 1704874  bytes 2186333188 (2.0 GiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9001
            inet 10.52.2.59  netmask 255.255.255.224  broadcast 10.52.2.63
            inet6 fe80::91:9aff:fe7e:20a7  prefixlen 64  scopeid 0x20<link>
            ether 02:91:9a:7e:20:a7  txqueuelen 1000  (Ethernet)
            RX packets 2604083  bytes 2208387383 (2.0 GiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 1974861  bytes 593497458 (566.0 MiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
            inet 127.0.0.1  netmask 255.0.0.0
            inet6 ::1  prefixlen 128  scopeid 0x10<host>
            loop  txqueuelen 1  (Local Loopback)
            RX packets 80  bytes 7140 (6.9 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 80  bytes 7140 (6.9 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    veth01225a6: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::1034:a8ff:fe79:aba3  prefixlen 64  scopeid 0x20<link>
            ether 12:34:a8:79:ab:a3  txqueuelen 0  (Ethernet)
            RX packets 1017  bytes 100422 (98.0 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 1869  bytes 145519 (142.1 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    veth3079eb6: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::90c2:62ff:fe84:fb53  prefixlen 64  scopeid 0x20<link>
            ether 92:c2:62:84:fb:53  txqueuelen 0  (Ethernet)
            RX packets 4891  bytes 714845 (698.0 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 5127  bytes 829516 (810.0 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    veth3be8c1f: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::c8a5:64ff:fe15:be95  prefixlen 64  scopeid 0x20<link>
            ether ca:a5:64:15:be:95  txqueuelen 0  (Ethernet)
            RX packets 210  bytes 27750 (27.0 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 307  bytes 35118 (34.2 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    veth559a1ab: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::100b:23ff:fe60:3752  prefixlen 64  scopeid 0x20<link>
            ether 12:0b:23:60:37:52  txqueuelen 0  (Ethernet)
            RX packets 14926  bytes 1931413 (1.8 MiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 14375  bytes 19695295 (18.7 MiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    veth5c05729: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::cca1:4ff:fe5d:14cd  prefixlen 64  scopeid 0x20<link>
            ether ce:a1:04:5d:14:cd  txqueuelen 0  (Ethernet)
            RX packets 455  bytes 797963 (779.2 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 681  bytes 83904 (81.9 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    veth85ba9a9: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::74ca:90ff:feae:6f4d  prefixlen 64  scopeid 0x20<link>
            ether 76:ca:90:ae:6f:4d  txqueuelen 0  (Ethernet)
            RX packets 19  bytes 1404 (1.3 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 66  bytes 4568 (4.4 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    vetha069d16: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::accd:eeff:fe21:6eda  prefixlen 64  scopeid 0x20<link>
            ether ae:cd:ee:21:6e:da  txqueuelen 0  (Ethernet)
            RX packets 3566  bytes 7353788 (7.0 MiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 2560  bytes 278400 (271.8 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    vetha58e4af: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::6cd2:16ff:fee2:aa59  prefixlen 64  scopeid 0x20<link>
            ether 6e:d2:16:e2:aa:59  txqueuelen 0  (Ethernet)
            RX packets 779  bytes 62585 (61.1 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 1014  bytes 109417 (106.8 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    vethb7bbef5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::5ce6:6fff:fe31:c3e  prefixlen 64  scopeid 0x20<link>
            ether 5e:e6:6f:31:0c:3e  txqueuelen 0  (Ethernet)
            RX packets 589  bytes 55654 (54.3 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 573  bytes 74014 (72.2 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    vethbda3e0a: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::9c0a:f2ff:fea5:23a2  prefixlen 64  scopeid 0x20<link>
            ether 9e:0a:f2:a5:23:a2  txqueuelen 0  (Ethernet)
            RX packets 490  bytes 47064 (45.9 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 645  bytes 77464 (75.6 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    vethfc65cc3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet6 fe80::b854:dcff:feb4:f4ba  prefixlen 64  scopeid 0x20<link>
            ether ba:54:dc:b4:f4:ba  txqueuelen 0  (Ethernet)
            RX packets 503  bytes 508251 (496.3 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 565  bytes 73145 (71.4 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    Node2 - ifconfig

    [root@ip-10-52-2-54 ec2-user]# ifconfig
    docker0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 8951
            inet 10.20.48.1  netmask 255.255.255.0  broadcast 0.0.0.0
            inet6 fe80::42:87ff:fe39:2ef0  prefixlen 64  scopeid 0x20<link>
            ether 02:42:87:39:2e:f0  txqueuelen 0  (Ethernet)
            RX packets 269123  bytes 22165441 (21.1 MiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 419870  bytes 149980299 (143.0 MiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9001
            inet 10.52.2.54  netmask 255.255.255.224  broadcast 10.52.2.63
            inet6 fe80::9a:d8ff:fed3:4cf5  prefixlen 64  scopeid 0x20<link>
            ether 02:9a:d8:d3:4c:f5  txqueuelen 1000  (Ethernet)
            RX packets 1517512  bytes 938147149 (894.6 MiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 1425156  bytes 1265738472 (1.1 GiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    flannel.1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 8951
            inet 10.20.48.0  netmask 255.255.0.0  broadcast 0.0.0.0
            ether 06:69:bf:c6:8a:12  txqueuelen 0  (Ethernet)
            RX packets 0  bytes 0 (0.0 B)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 0  bytes 0 (0.0 B)
            TX errors 0  dropped 1 overruns 0  carrier 0  collisions 0

    lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
            inet 127.0.0.1  netmask 255.0.0.0
            inet6 ::1  prefixlen 128  scopeid 0x10<host>
            loop  txqueuelen 1  (Local Loopback)
            RX packets 106  bytes 8792 (8.5 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 106  bytes 8792 (8.5 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

    veth9f05785: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 8951
            inet6 fe80::d81e:d3ff:fe5e:bade  prefixlen 64  scopeid 0x20<link>
            ether da:1e:d3:5e:ba:de  txqueuelen 0  (Ethernet)
            RX packets 31  bytes 2458 (2.4 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 37  bytes 4454 (4.3 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

little confused with two ifconfig output

A: check flanneld process on node-1, flannel.1 interface is missing from node-1, check /var/log/message and also compare both node flannel config file -- /etc/sysconfig/flannel

A: It looks like flannel is not running properly on node2. You should check the logs and configs as already pointed out by Pawan.
Also, you seem to be using an older version of Kubernetes. The current version is 1.5 and I'd recommend to use this version.
The bare metal setup guides found in the net tend to get outdated pretty fast, even the official Kubernetes guides.
I'd recommend to not use any of these guides anymore and instead use a (semi) automated deployment solution, like kargo (Ansible based) or kops (only AWS, Go based). If you do not want to use these automatic solutions, you could try to use kubeadm, which is currently in alpha state but may already work good enough for you.


text:
Q: Can't Access Subdomain Start Page I have moved a website to a new webhost, strato.se, and I can't access a subdomain start page.
Strangely, I can access some pages on the subdomain; but not the homepage.
Take a look here: https://www.wpsoftdev.com/product/wpsoftdev-wordpress-navigation-menu-accordion-and-blog-categories-accordion/
In the description for the product I have put:
You can see live previews here: http://wpsoftdev-wcpca-demo.wpsoftdev.com/navigation-menu-demos/ , http://wpsoftdev-wcpca-demo.wpsoftdev.com/blog-with-demos/ ,  http://wpsoftdev-wcpca-demo.wpsoftdev.com/ .
The first two links there are accessible, but trying to access http://wpsoftdev-wcpca-demo.wpsoftdev.com/ leads to the parent site start page.
Does anyone know why this happens and if it can be fixed?
I don't know where to begin troubleshooting this.
Edit: I just saw that while it didn't work in Firefox, it worked in Chrome; and after clearing the cache in my Firefox it now works.


text:
Q: FtpWebRequest could not found in Portable Class Library I am trying to upload a file on ftp web server. I could not found FtpWebRequest class in windows phone so, I am trying it by adding new project of Portable Class Library. I have added following code
 public void GetDataUsingDataContract(byte[] fileByte)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential("uname", "pass");

        // Copy the contents of the file to the request stream.
       // StreamReader sourceStream = new StreamReader("testfile.txt");
        byte[] fileContents = fileByte;//Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        //sourceStream.Close();
        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();
    }

But there is also a same issue i.e. I could not found FtpWebResponse class. Is it supported in portable class library?

A: I guess you already have the answer, the FTPWebRequest / FTPWebResponse are not available in the portable subset of .NET.
This subset is composed of APIs that you can find on all frameworks (Silverlight, XBox, Windows Phone 7/8, .Net x.y etc ...)
If you cannot find an api within a native framework (for instance Windows Phone) you will not find it in the portable library subset.
If you want to use ftp on windows phone, I guess you will have to find a 3rd party api like OpenNETCF FTP that was built for the compact framework.
https://ftp.codeplex.com/

A: I don't know if you have considered Xamarin, but the implementation you are looking for is available at System.Net.FtpWebRequest.


text:
Q: What's the difference between these two requirejs modules? Sorry if this seems an odd question, but I'm just start learning requirejs and some advanced javascript.
Both these modules work, so question is: what's the difference and why should I prefer the first/second way?
// First way
define(['handlebars', 'backbone.marionette'],
    function() {
        console.log(Handlebars, Backbone.Marionette); // Ok
    }
);

// Another way
define(['handlebars', 'backbone.marionette'],
    function(Handlebars, BackboneMarionette) {
        console.log(Handlebars, BackboneMarionette); // Ok
    }
);

A: define(['handlebars', 'backbone.marionette'],
    function() {
        console.log(Handlebars, Backbone.Marionette); // Ok
    }
);

the only reason this one works is you have handlebars and marionette existing in the window namespace already. So Handlebars, Backbone.Marionette are global values that exist outside your function definition. I.E :
console.log(Handlebars, Backbone.Marionette); // ok
define(['handlebars', 'backbone.marionette'],
    function() {
        console.log(Handlebars, Backbone.Marionette); // Ok
    }
);


text:
Q: updatelayeredwindow not working i tried to use UpdateLayeredWindow for all day, but it failed to work :(, i put the code in OnCreate and load a png file (created by photoshop) with CImage.
int CMainWindow::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
    SetWindowLong(this->m_hWnd, GWL_STYLE, 0);
    SetWindowLong(this->m_hWnd, GWL_EXSTYLE, 0);
    SetWindowLong(this->m_hWnd, GWL_EXSTYLE, GetWindowLong(this->m_hWnd, GWL_EXSTYLE) | WS_EX_LAYERED);
    this->SetMenu(NULL);
    ::SetWindowPos(this->m_hWnd, HWND_TOP, 50, 50, 652, 492, SWP_SHOWWINDOW);

    CBitmap imageBitmap, *oldBitmap;
    CDC *dcWindow, dcMem;
    CRect wRect;
    CPoint wPos;
    CSize wSize;
    HBITMAP hbmp;
    BLENDFUNCTION bFunc;

    m_Image.Load(_T("Img/BG_Blue.png"));
    GetWindowRect(&wRect);
    dcWindow = GetWindowDC();
    imageBitmap.CreateCompatibleBitmap(dcWindow, wRect.Width(), wRect.Height());
    dcMem.CreateCompatibleDC(dcWindow);
    oldBitmap = dcMem.SelectObject(&imageBitmap);
    m_Image.Draw(dcMem.m_hDC, 0, 0, wRect.Width(), wRect.Height(), 0, 0, wRect.Width(), wRect.Height());
    wPos.x = 0; wPos.y = 0;
    wSize.cx = wRect.left; wSize.cy = wRect.bottom;
    bFunc.SourceConstantAlpha = 125;
    bFunc.BlendFlags = 0;
    bFunc.BlendOp = AC_SRC_OVER;
    bFunc.AlphaFormat = AC_SRC_ALPHA;
    UpdateLayeredWindow(dcWindow, &wPos, &wSize, &dcMem, &wPos, 0, &bFunc, ULW_ALPHA);
    //BitBlt(dcWindow->m_hDC, 0, 0, wRect.Width(), wRect.Height(), dcMem.m_hDC, 0, 0, SRCCOPY);
    DWORD error = GetLastError();
    dcMem.SelectObject(oldBitmap);
    return 0;
}

the function returned with 1 , but nothing appeared on the screen, only an icon on the starup menu indicating the program is running. I am wondering if there is something wrong with the png file ... can anyone help ?

A: dcWindow should be the Device Context of the screen not the window. So initialize it like so: dcWindow->Attach(::GetDC(NULL)) instead of dcWindow = GetWindowDC();


text:
Q: ASUS Q200E boots straight into BIOS I have an ASUS Q200E running Win8 and it is booting straight into the BIOS. While there, the internal HDD can't be seen, and I also can't boot to a Linux installation from a USB drive. It's running an American Megatrends BIOS. There is no POST screen, no message, no BSOD, etc.
Anybody know what's going on?

A: I have the same model computer and after updating the bios I had the same problem. The solution for me was to disable the secure boot feature then everything worked fine again.

A: When you view the boot order in BIOS, is the hard drive listed at all? If not, I would turn the laptop off and reset the hard drive. It would also be a good idea to take the hard drive out and plug it into an external hard drive. Then you could try to connect it to a different computer which would let you know if it's dead.


text:
Q: Every array of enum implements IEnumerable. How do I work around this? It appears that, in .NET, "array of enum" is not a strongly-typed concept. MyEnum[] is considered to implement not just IEnumerable<MyEnum>, but also IEnumerable<YourEnum>. (I didn't believe it at first either.)
// Returns true:
typeof(IEnumerable<DayOfWeek>).IsAssignableFrom(typeof(AttributeTargets[]))

// Outputs "3":
var listOfLists = new List<object> {
    new[] { AttributeTargets.All },
    new[] { ConsoleColor.Blue },
    new[] { PlatformID.Xbox, PlatformID.MacOSX }
};
Console.WriteLine(listOfLists.OfType<IEnumerable<DayOfWeek>>().Count());

So when I go looking through a list for everything that implements IEnumerable<T>, I'm getting the T[]s and the List<T>s and the iterator-generated IEnumerable<T>s, but I'm also getting the SomethingElse[]s that I do not want.
What's the easiest way to find out whether a given Type (as with IsAssignableFrom above) or a given instance (as with OfType<T> above) really and truly implements, say, IEnumerable<DayOfWeek>?

I gave Mr. Skeet the green checkmark, but once I got his code into Visual Studio, ReSharper suggested a more concise version. Use whichever version you prefer.
public static IEnumerable<IEnumerable<T>> OfSequenceType<T>
    (this IEnumerable source) where T : struct
{
    return from sequence in source.OfType<IEnumerable<T>>()
           let type = sequence.GetType()
           where !type.IsArray || type.GetElementType() == typeof (T)
           select sequence;
}

A: I believe this is basically due to section 8.7 of ECMA 335.
Basically we're looking at the assignable-to relationship between the two array-of-enum types. As far as I can tell, 8.7.2 is applicable:

A location type T is compatible-with a location type U if and only if one of the following holds.

*

*T and U are not managed pointer types and T is compatible-with U according to the definition in §8.7.1.

So we look to 8.7.1 and find bullet 5:

T is a zero-based rank-1 array V[], and U is a zero-based rank-1 array W[], and V is array-element-compatible-with W.

So now we're interested in whether the two enum types have an array-element-compatible-with relationship... That then leads to:

A signature type T is array-element-compatible-with a signature type U if and only if T has underlying type V and U has underlying type W and either:

*

*V is compatible-with W; or

*V and W have the same reduced type.

Now the underlying type of an enum is defined by this:

The underlying type of a type T is the following:

*

*If T is an enumeration type, then its underlying type is the underlying type declared in the enumeration's definition.

*[Irrelevant to us]

So in the case of, say:
enum Foo : int {}
enum Bar : int {}

the underlying types of both are int.
Now we can go back to our array-element-compatible-with definition, and see that both V and W are int. A type is compatible-with itself due to the first bullet of 8.7.1:

A signature type T is compatible-with a signature type U if and only if at least one of the following holds.

*

*T is identical to U.

Therefore, the arrays are compatible.
They're also compatible with an array of the underlying type itself:
enum Foo {}
...
object x = new int[10];
Foo[] y = (Foo[]) x; // No exception

Note that x has to be declared as object here to persuade the C# compiler that this might be legal - otherwise it follows the rules of the C# language, which aren't quite so forgiving...

Now as for your second question:

What's the easiest way to find out whether a given Type (as with IsAssignableFrom above) or a given instance (as with OfType above) really and truly implements, say, IEnumerable?

You could just special case arrays, as they behave a little oddly. Frankly that's probably the easiest approach. I tried using Type.GetInterfaceMap but that gives a problem too:

Unhandled Exception: System.ArgumentException: Interface maps for generic interf
  aces on arrays cannot be retrived.

(Yes, the typo at the end is really in the error message. Can't be bothered to raise a Connect issue for that though...)
I strongly suspect that special-casing is the way forward... for example, assuming that you know you're dealing with a value type (covariance of reference type arrays is a separate matter...)
public static IEnumerable<IEnumerable<T>> OfSequenceType<T>
    (this IEnumerable source) where T : struct
{
    // Nullity check elided...
    foreach (object x in source)
    {
        IEnumerable<T> sequence = x as IEnumerable<T>;
        if (sequence == null)
        {
            continue;
        }
        // Work around odd value type array variance
        Type type = sequence.GetType();
        if (type.IsArray && type.GetElementType() != typeof(T))
        {
            continue;
        }
        yield return sequence;
    }
}

A: I tried this:
var listOfLists = new List<object> {
    new[] { AttributeTargets.All },
    new[] { ConsoleColor.Blue },
    new[] { PlatformID.Xbox, PlatformID.MacOSX },
    new[] { DayOfWeek.Friday, DayOfWeek.Saturday }
};
Console.WriteLine(listOfLists.Where(obj => obj.GetType() == typeof(DayOfWeek[])).Count());

I got 1 as a result. I'm still searching to see how you can use IEnumerable< DayOfWeek > in the query


text:
Q: How to combine a hidden/functional scrollbar with parallax elements? I have a problem with a parallax page.

*

*the scrollbar is hidden (by pushing it to the side with inner&outer divs and "right: -17px;")

*got some parallax div elements which should float over the page with different speed
The code for the hidden scrollbar separately works and also the code for the the parallax elements separately does work.
My Problem: I tried to combine these codes but only the hidden scrollbar works. I haven't figured out the problem ... Maybe the js code of the parallax cannot work with the "inner div" hidden scrollbar? The "inner div" have to be a kinda . If I give the body a height of for example 3000px, then the parallax does work, but then I get a 2nd scrollbar.
I'd prefer to solve this without using 3rd party libraries.

var elementOne = document.querySelector("#elementOne");
    var elementTwo = document.querySelector("#elementTwo");
    var elementThree = document.querySelector("#elementThree");

    function setTranslate(xPos, yPos, el)
    {
      el.style.transform = "translate3d(" + xPos + ", " + yPos + "px, 0)";
    }

    window.addEventListener("DOMContentLoaded", scrollLoop, false);

    var xScrollPosition;
    var yScrollPosition;

    function scrollLoop()
    {
      xScrollPosition = window.scrollX;
      yScrollPosition = window.scrollY;

      setTranslate(0, yScrollPosition * -0.2, elementOne);
      setTranslate(0, yScrollPosition * -1.5, elementTwo);
      setTranslate(0, yScrollPosition * .5, elementThree);

      requestAnimationFrame(scrollLoop);
    }
*
    {
      margin: 0px;
      padding: 0px;
      font-family: Arial;
    }
    #outer
    {
   height: 100%;
      width: 100%;
      overflow: hidden;
      position: absolute;
    }
    #inner
    {
      top: 0px;
   right: -17px;
      bottom: 0px;
      left: 0px;
   position: absolute;
      overflow-x: hidden;
    }
    #frame_1
    {
      top: 0px;
      height: 100%;
      width: 100%;
      position: absolute;
      background-image: linear-gradient(-225deg, #22E1FF 0%, #1D8FE1 48%, #625EB1 100%);
    }
    #frame_2
    {
      top: 100%;
      height: 100%;
      width: 100%;
      position: absolute;
      background-image: linear-gradient(-225deg, #D4FFEC 0%, #57F2CC 48%, #4596FB 100%);
    }
    #frame_3
    {
      top: 200%;
      height: 100%;
      width: 100%;
      position: absolute;
      background-image: linear-gradient(-225deg, #473B7B 0%, #3584A7 51%, #30D2BE 100%);
    }
    #elementOne
    {
      width: 400px;
      height: 300px;
      top: 150%;
      left: 50%;
      position: fixed;
      z-index: 10;
      background-image: linear-gradient(-225deg, #22E1FF 0%, #1D8FE1 48%, #625EB1 100%);
      opacity: .75;
    }
    #elementTwo
    {
      width: 300px;
      height: 300px;
      top: 350%;
      left: 55%;
      position: fixed;
      z-index: 8;
      background-image: linear-gradient(-225deg, #D4FFEC 0%, #57F2CC 48%, #4596FB 100%);
      opacity: .75;
    }
    #elementThree
    {
      width: 300px;
      height: 300px;
      top: 50%;
      left: 25%;
      position: fixed;
      z-index: 9;
      background-image: linear-gradient(-225deg, #473B7B 0%, #3584A7 51%, #30D2BE 100%);
      opacity: .75;
    }
<!DOCTYPE html>

        <meta charset="UTF-8"/>


text:
Q: Zend validate multi-select value There is a multiselect element in form. It's needed to validate how many items are selected in it (min and max count).
The trouble is that when the element can have multiple values, then each value is validated separately.
I tried to set isArray to false to validate the value with my custom validator ArraySize, but new problem appeared: the whole array-value is passed to InArray validator and the validation fails. So I had to turn it off by setting registerInArrayValidator to false.
Now I can validate the value for number of selected values but can not validate for their correspondence to provided options.
Is there a way to solve the problem without creating one more custom validator?

A: Note: I have assume this is Zend 1.
The only way I could see to do this was to extend Multiselect and use a custom isValid. This way you can see the full array of values and not just one value at a time.
Below is my custom Multiselect class
<?php
/**
 * My_MinMaxMultiselect
 */
class My_MinMaxMultiselect extends Zend_Form_Element_Multiselect
{
    /**
     * Validate element contains the correct number of
     * selected items. Check value against minValue/maxValue
     *
     * @param mixed $value
     * @param mixed $context
     * @return boolean
     */
    public function isValid($value, $context = null)
    {
        // Call Parent first to cause chain and setValue
        $parentValid = parent::isValid($value, $context);

        $valid = true;

        if ((('' === $value) || (null === $value))
            && !$this->isRequired()
            && $this->getAllowEmpty()
        ) {
            return $valid;
        }

        // Get All Values
        $minValue = $this->getMinValue();
        $maxValue = $this->getMaxValue();

        $count = 0;
        if (is_array($value)) {
            $count = count($value);
        }

        if ($minValue && $count < $minValue) {
            $valid = false;
            $this->addError('The number of selected items must be greater than or equal to ' . $minValue);
        }

        if ($maxValue && $count > $maxValue) {
            $valid = false;
            $this->addError('The number of selected items must be less than or equal to ' . $maxValue);
        }

        return ($parentValid && $valid);
    }

    /**
     * Get the Minimum number of selected values
     *
     * @access public
     * @return int
     */
    public function getMinValue()
    {
        return $this->getAttrib('min_value');
    }

    /**
     * Get the Maximum number of selected values
     *
     * @access public
     * @return int
     */
    public function getMaxValue()
    {
        return $this->getAttrib('max_value');
    }

    /**
     * Set the Minimum number of selected Values
     *
     * @param int $minValue
     * @return $this
     * @throws Bad_Exception
     * @throws Zend_Form_Exception
     */
    public function setMinValue($minValue)
    {
        if (is_int($minValue)) {
            if ($minValue > 0) {
                $this->setAttrib('min_value', $minValue);
            }

            return $this;
        } else {
            throw new Bad_Exception ('Invalid value supplied to setMinValue');
        }
    }

    /**
     * Set the Maximum number of selected values
     *
     * @param int $maxValue
     * @return $this
     * @throws Bad_Exception
     * @throws Zend_Form_Exception
     */
    public function setMaxValue($maxValue)
    {
        if (is_int($maxValue)) {
            if ($maxValue > 0) {
                $this->setAttrib('max_value', $maxValue);
            }

            return $this;
        } else {
            throw new Bad_Exception ('Invalid value supplied to setMaxValue');
        }
    }

    /**
     * Retrieve error messages and perform translation and value substitution.
     * Overridden to avoid errors from above being output once per value
     *
     * @return array
     */
    protected function _getErrorMessages()
    {
        $translator = $this->getTranslator();
        $messages = $this->getErrorMessages();
        $value = $this->getValue();
        foreach ($messages as $key => $message) {
            if (null !== $translator) {
                $message = $translator->translate($message);
            }
            if (($this->isArray() || is_array($value))
                && !empty($value)
            ) {
                $aggregateMessages = array();
                foreach ($value as $val) {
                    $aggregateMessages[] = str_replace('%value%', $val, $message);
                }
                // Add additional array unique to avoid the same error for all values
                $messages[$key] = implode($this->getErrorMessageSeparator(), array_unique($aggregateMessages));
            } else {
                $messages[$key] = str_replace('%value%', $value, $message);
            }
        }

        return $messages;
    }
}

To use this in the form where the User must select exactly 3 options:
    $favouriteSports = new MinMaxMultiselect('favourite_sports');
    $favouriteSports
        ->addMultiOptions(array(
            'Football',
            'Cricket',
            'Golf',
            'Squash',
            'Rugby'
        ))
        ->setRequired()
        ->setLabel('Favourite Sports')
        ->setMinValue(3)
        ->setMaxValue(3);

A: While it's nice when you can squeeze by without needing to write a custom validator, there is nothing wrong with writing one when you need to do something slightly out of the ordinary.
This sounds like one of those cases.


text:
Q: No ID parameter in model save controller when saving after edit I've written a model object and I cannot edit and save an existing object, a new object is always created. I can create and delete, but editing doesn't work. I'm pretty sure that this is because the "profile_id" parameter isn't in the request when I save the object.
The interesting thing is that the "profile_id" parameter is in the request when I edit an object, it's just not getting passed to my save controller. $profile_id is always 0. Here's the code in my save controller.
$profileId = (int) $this->getRequest()->getParam('profile_id');
        $profile = $this->_profileFactory->create();
        if ($profileId) {
            $profile->load($profileId);
        }
        $this->_coreRegistry->register('profile', $profile);
        return $profile;


text: Q: Identifying duals and second duals in Banach spaces Suppose $X$ is a Banach space, and $E$ is a closed subspace of $X^{*}$. Can we find $F$ a closed subspace of $X$ such that $F^{**}$ can be (naturally) identified with $E^{*}$? Does it make a difference if $E$ is finite codimensional in $X^{*}$?


text:
Q: Finding solution to zeta function of $4$ using Euler's solution to the Basel problem I recently read and immediately loved Euler's solution to the Basel problem. In essence, he took the polynomial on the LHS of the below equation and equated it to the infinite product of its factors by noting that the polynomial is just $\frac{sin(x)}{x}$, and that $sin(x)$ has roots at integer multiples of $\pi$.
$$1 - \frac{x^2}{3!} + \frac{x^4}{5!} -... = (1-\frac{x^2}{\pi^2})(1-\frac{x^2}{4 \pi^2})...$$
You can then expand and equate the $x^2$ term to find the solution to the zeta function of $2$. This part makes sense to me, but the article then stated that he further expanded the product to find (in theory) all even values of the zeta function.
I was trying to do this myself to find the solution to the zeta function of $4$, but have thus far been unsuccessful. I tried expanding further on the RHS, but didn't end up with inverse fourth power terms like I wanted. I also tried multiplying both sides by the infinite product $(1+\frac{x^2}{\pi^2})(1+\frac{x^2}{4 \pi^2})...$ to get the desired RHS, but the LHS seemed to get quite messy in the process.
I would greatly appreciate some help!

A: Hint:
Well, you know this much:
$$\frac{\sin(x)}x=\left(1-\frac{x^2}{1^2\pi^2}\right)\left(1-\frac{x^2}{2^2\pi^2}\right)\dots$$
From that, you should be able to deduce the following:
$$\frac{\sin(ix)}{ix}=\left(1+\frac{x^2}{1^2\pi^2}\right)\left(1+\frac{x^2}{2^2\pi^2}\right)\dots$$
And multiply them together, you have
$$\frac{\sin(x)}x\frac{\sin(ix)}{ix}=\left(1-\frac{x^4}{1^4\pi^4}\right)\left(1-\frac{x^4}{2^4\pi^4}\right)\dots$$

A: One way to do that would be to partially multiply out the product up to the term $x^{4}$ and compare it to the $x^{4}$ in $\frac{\sin\left(\pi x\right)}{\pi x}$
If you begin to multiply and collect the terms in the fashion of
$\sum_{j>i>0}^{} \frac{1}{i^{2}j^{2}}$,
Then you have the following equality;
\begin{equation}
2\sum_{j>i>0}^{} \frac{1}{i^{2}j^{2}}=\sum_{n>0}^{} \frac{1}{n^{2}}^{2}-\sum_{n>0}^{} \frac{1}{n^{4}}
\end{equation}
From there, it is possible to find $\zeta(4)$ if you know $\zeta(2)$ and the coefficient of $x^{4}$ in $\frac{\sin\left(\pi x\right)}{\pi x}$

A: I actually don't know how to do it with sum and product expansions, but, I do know how to do it with contour integration! here's a detailed page I wrote about it: Link.


text:
Q: How to make the radio button to change depending to the modal answer in react-native I have the following code which is the main page and does have a ratio button:
          <Text
            style={{
              fontSize: 16,
              marginTop: 10,
              color: "#00357B",
              fontWeight: "bold",
            }}
          >
            1. Select your recording option:
          </Text>
        </View>
        <View>
          <RadioGroup
            radioButtons={radioButtons}
            onPress={onPressRadioButton}
            layout="row"
            style={{ marginBottom: 10 }}
          />
        </View>
      </View>

Below in the same page I do the section of the modal where the original modal is the CategoryModal and is imported from another file:
   <Modal
        transparent={true}
        animationType="fade"
        visible={isModalVisible}
        nRequestClose={() => changeModalVisible(false)}
      >
        <CategoryModal
          changeModalVisible={changeModalVisible}
          setData={setData}
          headerText="Header Text"
          descriptionText="Description Text"
        />
      </Modal>

The Category Modal file looks like that:
  closeModal = (bool, data) => {
    props.changeModalVisible(bool, data);
    props.setData(data);
  };
  return (
    <TouchableOpacity disabled={true} style={styles.container}>
      <View style={styles.modal}>
        <View style={styles.textView}>
          <Text style={[styles.text, { fontSize: 20 }]}>
            {props.headerText}
          </Text>
          <Text style={[styles.text, { fontWeight: "light" }]}>
            {props.descriptionText}
          </Text>
        </View>
      </View>
      <View style={styles.buttonsView}>
        <TouchableOpacity
          style={styles.touchableOpacity}
          onPress={() => closeModal(false, "Cancel")}
        >
          <Text style={[styles.text, { color: "blue" }]}>Cancel</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.touchableOpacity}
          onPress={() => closeModal(false, "Proceed")}
        >
          <Text style={[styles.text, { color: "blue" }]}> Proceed</Text>
        </TouchableOpacity>
      </View>
    </TouchableOpacity>
  );
};

And overall I am trying to implement the function for the ratio button to change depending to the modal answer that looks like that :
    if (valueDropdown2 != null && recordedWord) {
      changeModalVisible(true);
      warningModalCategory = true;
      const chooseData = await new Promise((resolve) => {
        setData(resolve);
      });

      if (chooseData == "Proceed") {
        setRadioButtons(radioButtonsArray);
        setValueDropdown1(null);
        setIsFocusDropdown1(false);
        setValueDropdown2(null);
        setIsFocusDropdown2(false);
        radioButtonsArray.forEach((button) => {
          if (button.selected) {
            selectedOptionRadioButton = button.value;
          }
        });
      } else {
        radioButtonsArray.forEach((button) => {
          if (button.value === "one-word") {
            selectedOptionRadioButton = button.value;
          }
        });
      }
    } else {
      setRadioButtons(radioButtonsArray);
      setValueDropdown1(null);
      setIsFocusDropdown1(false);
      setValueDropdown2(null);
      setIsFocusDropdown2(false);
      radioButtonsArray.forEach((button) => {
        if (button.selected) {
          selectedOptionRadioButton = button.value;
        }
      });
    }
  }


text:
Q: Ignore duplicate key upon insert with PDO Is there a generic way to INSERT IGNORE with PDO that will work on all database drivers?
If not, is it fair to assume the following would work:
try {
    $stmt = $db->prepare("INSERT INTO link_table (id1, id2) VALUES (:id1, :id2)");
    $stmt->execute(array( ':id1' => $id1, ':id2' => $id2 ));
}
catch (PDOException $ex) {
    // Thanks to comment by Mike:

    // Re-throw exception if it wasn't a constraint violation.
    if ($ex->getCode() != 23000)
        throw $ex;
}

A: AFAIK  no there is not a generic version that will work with all database drivers.  INSERT IGNORE and INSERT...ON DUPLICATE KEY UPDATE are specific to MySQL.
Checking for an existing record by selecting it first, or deleting an existing record and re-inserting are both prone to problems, including race conditions and possible foreign key constraint violations or cascading deletes.
I think your approach is probably the safest.  You can always check the error code if you want to determine the cause of the exception - see:
http://docstore.mik.ua/orelly/java-ent/jenut/ch08_06.htm
I think you might want to check for code 23000.

A: Your code would probably work, but there are other things that can go wrong while executing a PDO statement. You will want to check if you really receive a constraint violation, and even if it's not a different kind (for example, you could also receive a foreign key violation when inserting a pair of values that doesn't have corresponding rows in one of the referenced tables). AFAIK, there is no cross-DBMS way to achieve this though.
For DBMSes that support transactions (Oracle, SQL Server, PostgreSQL, MySQL to some extent, ...), here's a different approach:

*

*start transaction

*delete all rows that match the row to be inserted (deleting zero or one rows)

*insert

*commit


text:
Q: How to make a scenario that depends on another scenario using cucumber, selenium and java I am learning cucumber through some tutorials and there is something that I don't know how to do.. I need to make a scenario that depends on another scenario (for example log out scenario I have to be logged in first before logging out) so what should I do? should I write steps of login at log out scenario (at the feature file) or there is a way to call the whole log in scenario at the log out scenario
also I need to know should I set up driver before each scenario and quit the driver after each scenario?

A: There is no support for creating a scenario that depends on another scenario in Cucumber-JVM. I think still is supported in the Ruby implementation in Cucumber. It is, however, a practice that is dangerous. The support for calling a scenario from another scenario will not be supported in future versions of Cucumber.
That said, how do you solve your problem when you want to reuse functionality? You mention logout, how do you handle that when many scenarios requires the state to be logged out for a user?
The solution is to implement the functionality in a helper method or helper class that each step that requires a user to be logged out calls.
This allow each scenario to be independent of all other scenarios. This in turn will allow you to run the scenarios in a random order. I don't think the execution order for the scenarios is guaranteed. I definitely know that it is discussed to have the JUnit runner to run scenarios in a random order just to enforce the habit of not having scenarios depend on other scenarios.
Your other question, how to set up WebDriver before a scenario and how to tear it down, is solved using the Before and After hooks in Cucumber. When using them, be careful not to import the JUnit version of Before and After.

A: Take a look into cucumber hooks, this allows you to set up global 'before' and 'after' steps, which will run for every scenario without having to specify them in your feature files.
Because they run for every scenario, they're ideal for something like initialising the driver at the start of each test. It may be suitable for running your logon, but if there's a chance you'll have a scenario which doesn't involve logging on then it wouldn't be the way to go (alternative further down). The same applies for the after scenario, which is where you could perform the log off and shut down your driver. As an example:
/**
 * Before each scenario, initialise webDriver.
 */
@Before
public void beforeScenario() {
    this.application.initialiseWebDriver();
}

/**
 * After each scenario, quit the web driver.
 */
@After
public void afterScenario() {
    this.log.trace("afterScenario");
        this.application.quitBrowser();
    }

In my example, I'm simply starting the driver in the before scenario, and closing it in the after, But in theory these before and after methods could contain anything, you just need to have them in your step definitions class and annotate them with the '@Before' and '@After' tags as shown.
As well as these, you can also have multiple before and after tags which you can call by tagging the scenario. As an example:
/**
 * Something to do after certain scenarios.
 */
@After("@doAfterMethod")
public void afterMethod() {
    this.application.afterThing();
}

You can set up something like this in your step defs, and as standard it won't run. However, you can tag your scenario with '@doAfterMethod' and it will run for the tagged scenarios, which makes this good for a common scenario that you will need at the end of tests, but not all of them. The same would work for methods to run before a scenario, just change the '@After' to '@Before'.
Bear in mind that if you do use these, the global Before and After (so in this example the driver initialisation and quitting) will always be the first and last things to run, with any other before/afters in between them and the scenario.
Further Reading:
https://github.com/cucumber/cucumber/wiki/Hooks
https://zsoltfabok.com/blog/2012/09/cucumber-jvm-hooks/

A: You can set test dependency with qaf bdd. You can use dependsOnMethods or dependsOnGroups in scenario meta-data to set dependency same as in TestNG, because qaf-BDD is TestNG BDD implementation.


text:
Q: Translation of sentences
The US death toll from the coronavirus climbed to 12 on Thursday, with all but one of the victims in the north-western US state of Washington.

What does it mean: 11 dead in Washington Or just 1 one dead there?

A: It means 11 died there.
It can be parsed as follows.
All (12) but one (-1) of the victims in (so the total = 11 are in) the north-western US state of Washington.
All of the peaches on the tree but (not) the one I picked yesterday were eaten by bats last night.


text:
Q: bit.ly - API Stat Tracking I am not sure if this is the correct forum for this question, but I'm not sure where else to ask it.
bit.ly provides stats for links that are generated through their site. However, it does not seem to create stats for links generated through their API.
Can someone tell if me there is a way to see the stats associated with a link generated through the API?
Thank you!

A: You need to use the API as an authenticated user so the links appear in your dashboard. Stats are tracked for API links, you just need to know how to get to them.
If you want the stats for a specific bit.ly link regardless of creator, you can add a + to the URL - this link to StackOverflow (http://bit.ly/3UaZQr) has stats at http://bit.ly/3UaZQr+.

A: I'm seeing the same thing. I can view the history for a link, say this one: http://bit.ly/info/t3XJe - and the shortening attribution is correct, but this link (created via the API) does not show up in my history.
I'm shortening the link via api.bit.ly using an account login and api key. The response is correct (from bit.ly), the link is shortened, but the only links that show up in my recent RSS feed or on the bit.ly home page are those created via the web interface.

A: When calling the /shorten action of the REST API, you have to add a &history=1 parameter to tell bit.ly to add the URL to the web history for the authenticated user.
For example:
http://api.bit.ly/shorten?version=2.0.1&longUrl=http://cnn.com&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&history=1

Clickable version of above link


text:
Q: Got an error message Syntax Error in ansible-playbook ERROR! Syntax Error while loading YAML.
  did not find expected key
The error appears to have been in '/etc/ansible/main.yml': line 73, column 50, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: Ensure IP forwarding is disabled
  shell: "sysctl net.ipv4.ip_forward ; grep "net\.ipv4\.ip_forward" /etc/sysctl.conf /etc/sysctl.d/*"
                                             ^ here

We could be wrong, but this one looks like it might be an issue with
unbalanced quotes.  If starting a value with a quote, make sure the
line ends with the same set of quotes.  For instance this arbitrary
example:
I using grep with "" into shell module in ansible playbook and got an ERROR message as follow "ERROR! Syntax Error while loading YAML."
- name: Ensure IP forwarding is disabled
  shell: "sysctl net.ipv4.ip_forward ; grep "net\.ipv4\.ip_forward" /etc/sysctl.conf /etc/sysctl.d/*"
  register: CIS_3.1.1
  ignore_errors: True

A: That configuration file for ansible is in the YAML format and in YAML a scalar that represents a string can be in multiple formats:

*

*plain: no quotes, has restrictions on the start character and internal character sequences, no escapes

*single quoted: can contain double quotes, no escapes except for repeating single quotes

*double quoted: backslash escapes in string, in string double quotes need to be escaped

*literal: newlines are preserved, no escapes

*folded: newlines are converted to spaces, no escapes

You are using double quoted style, and in that you would need to escape the internal double quotes (") and backslashes (\). That gets ugly and unreadble real soon. It is much more useful to use literal style in such cases:
- name: Ensure IP forwarding is disabled
  shell: |-
    sysctl net.ipv4.ip_forward ; grep "net\.ipv4\.ip_forward" /etc/sysctl.conf /etc/sysctl.d/*

I.e. you put |- (the minus is to strip the final newline of the following line), then put the line without starting or end quotes, indented, on the next line.


text:
Q: Speed gains: Converting 2D array to 1D array I initially had a 2D array. The results were taking time to get back the results. So, I converted the 2D array into 1D array but still there is not much improvement in speed of my program.
Here is my code:
for( counter1=0; counter1< size ; ++counter1)
    {
       y=buffer[counter1];
       x=buffer[counter1+1];

       IndexEntries index= OneDTable[x*256+y];

    SingleTableEntries NewNextState=NewSingleTable[Next*blocksize+index];

    Next=NewNextState.Next_State;
    if(NewNextState.accept[index.serialnumber]=='1' )
    {
        return 1;
    }

}
In my code above: OneDTable is a 1D array generated from a 2D array of 256 * 256 elements.
NewSingleTable is a 1D array generated from a 2D array of blocksize* (Total Next Elements).
Actually , I was expecting large speed gains after converting into 1D arrays. Is this the right way to extract value from a 1D array or certain improvements can be done to the above code?
More Details:
Both 2D arrays are of structure type:
Structure type of IndexEntries consists of:
          int
          int

Structure type of NewSingleTable consists of:
          int
          vector<char>

A: You could gain something changing from a vector of vector to a plain vector. E.g. from:
std::vector<std::vector<my_struct>> table(total_rows,
                                          std::vector<my_struct>(total_columns,
                                                                 my_struct()));

// do something with table[row][column]...

to
std::vector<my_struct> table(total_rows * total_columns);

// do something with table[row * total_columns + column]...

This because a vector of vector is not really a matrix and you lose data locality.
Changing from:
my_struct table[total_rows][total_columns];

to
my_struct table[total_rows * total_columns];

is worthless since the memory layout between the two is (usually) precisely the same.
The only difference is the semantic type of the array and the fact that you now have to implement the 2D element lookup yourself (of course changing from table[row * 256 + column] to table[row << 8 + column] is useless since any decent compiler will automatically perform this "optimization").
The 1D array could be a bit faster when you have to perform an operation on every element. This because of the simpler for loop:
for (unsigned row(0); row < total_rows; ++row)
  for (unsigned column(0); column < total_columns; ++column)
    // do something with table[row][column]

const unsigned stop(total_rows * total_columns);
for (unsigned i(0); i < stop; ++i)
  // do something with table[i]

but this isn't your case.
As laune said in is comment, copying a NewSingleTable just to extract a couple of integers is bad:
SingleTableEntries NewNextState=NewSingleTable[Next*blocksize+index];

From your example it seems that a const reference should be enough:
...
const SingleTableEntries &NewNextState(NewSingleTable[Next * blocksize + index]);

if (NewNextState.accept[index.serialnumber] == '1' )
  return 1;

Next = NewNextState.Next_State;
...


text:
Q: String concatenation with constants in ruby 2.7.2 I'm trying to concatenate a constant into a string but I'm getting syntax error, unexpected unary+, expecting end' (SyntaxError)`
This is an example of what I have to do:
NAME = "Jane"
def a_function
   s = 'Hi' + NAME +' !'
   puts s
end

I know you can do "Hi #{NAME}!" but in my case the string has to be with single quotes.
How can I achieve this?

A: You are missing a space between + and ' !'.
This is a special case of confusing Ruby, because a single expression like +x is actually a valid unary expression meaning just x, the same way as +1 means 1.
Because of this it's likely Ruby is interpreting your expression a + b +c, as a + b c, which is invalid, and hence the error.
The fix:
s = 'Hi ' + NAME + ' !'
                  ^------ Note the space here!


text:
Q: Representing a graph with an unknown number of nodes? For the last few days I cannot think about how to represent a given graph in a text file into an adjacency matrix without knowing the number of vertices in the graph beforehand.
The input file has vertices defined as Strings and a pair of consecutive lines representing an edge between both vertices. For example:
VertexA
VertexB
VertexC
VertexD

There is an edge from VertexA -> VertexB and VertexC -> VertexD in the above example. Directed, weights are arbitrarily 1.
I would like to implement this in it's own class which doesn't parse the file directly and instead has only a method which adds a directed between a given source and destination vertex. For example:
// adds a directed edge from vertex1 -> vertex2
addEdgeBetweenVertices(String vertex1, String vertex2);

In this method so far I have made a HashMap and if either vertex is not in the map, add it with it's own unique index. (The key being the name of the vertex and the value being its index.)
How can I construct this adjacency matrix using such a method, while maintaining this edge information, but without knowing the number of vertices ( |V| ) prior?
I was thinking an ArrayList of ArrayLists but I can't wrap my head around this.

A: You can use ArrayList of ArrayList and your idea is perfect that you can map the Strings with unique Integer ids and then directly add the corresponding vertex to the list.
The problem with Adjacency Matrix is that you need to know the maximum limit of the vertexes. Adjacency Matrix is not memory efficient and also not feasible for dynamic operations. So here Adjacency List comes into the picture. I have written a small code to demonstrate the creation of Adjacency List and also how to add new Vertex or and Edge.
import java.util.ArrayList;
import java.util.HashMap;

public class AdjacencyListDemo {

    static int availableId=0;                            //Represents the available id for mapping
    static HashMap<String,Integer> mapping;              //To store the String-Integer mapping for Vertexes
    static ArrayList<ArrayList<Integer>> adjacencyList;

    public static void main(String args[])
    {
        adjacencyList = new ArrayList<ArrayList<Integer>>();

        mapping  = new HashMap<String,Integer>();

        String sampleVertexes[] = {"Vertex1","Vertex2","Vertex3","Vertex4"};

        for(String vertex : sampleVertexes)
            addNewVertex(vertex);

        addEdgeBetween("Vertex1","Vertex2");
        addEdgeBetween("Vertex3","Vertex4");

        System.out.println("Old List: ");
        printList();

        //Add New Vertex if required
        addNewVertex("Vertex5");

        addEdgeBetween("Vertex5","Vertex1");
        addEdgeBetween("Vertex2","Vertex1");
        addEdgeBetween("Vertex3","Vertex2");
        addEdgeBetween("Vertex5","Vertex2");

        System.out.println("\n\nNew List: ");
        printList();

    }

    private static void printList()
    {
        for(String vertex : mapping.keySet()) {
            int index = mapping.get(vertex);
            System.out.println(vertex+" ID: "+index+" List: "+adjacencyList.get(index));
        }
    }
    private static void addEdgeBetween(String vertex1, String vertex2) {
        //get both indexes
        int index1 = mapping.get(vertex1);
        int index2 = mapping.get(vertex2);

        //add index2 into the arraylist of index1
        adjacencyList.get(index1).add(index2);
    }

    private static void addNewVertex(String vertex) {

        if(!mapping.containsKey(vertex))
        {
            //assign available ID
            mapping.put(vertex,availableId);
            availableId++;                                   //make increment in available id
            adjacencyList.add(new ArrayList<Integer>());     //Add an Empty ArrayList
        }
    }
}

Output :
Old List:
Vertex2 ID: 1 List: []
Vertex3 ID: 2 List: [3]
Vertex1 ID: 0 List: [1]
Vertex4 ID: 3 List: []

New List:
Vertex2 ID: 1 List: [0]
Vertex3 ID: 2 List: [3, 1]
Vertex1 ID: 0 List: [1]
Vertex4 ID: 3 List: []
Vertex5 ID: 4 List: [0, 1]

A: I would say that both the Map and the ArrayList of ArrayLists can be part or a solution. Use the Map<String,int> to obtain the unique id for each vertex string, as you already described. Then something like this might work (sorry just more or less Java)
HashMap<String,Integer> map;
ArrayList< ArrayList<Boolean> > adjacency;

addEdgeBetweenVertices(String vertex1, String vertex2) {
  Integer idx1 = (map.containsValue(vertex1)) ? map.get(vertex1) : map.put(vertex1,getNextIndex());
  Integer idx2 = (map.containsValue(vertex1)) ? map.get(vertex2) : map.put(vertex2,getNextIndex());

  adjacency[idx1].set(idx2,true);
}

A: If you don't need to use that adjacency matrix after most of calls to addEdgeBetweenVertices, then you can add data about your edges to some array. And just before you want to use it call Build (or Rebuild) member function of your class (you will need to add this one). Which will actually build your adjacency matrix.


text:
Q: Vuex error: "Do not mutate vuex store state outside mutation handlers." I have a button on my website that performs the following action:
this.$store.commit('SET_THREAD_UPDATE', thread)

'thread' is an object consisting of multiple properties and objects and when the function is called there might be only a small change within an object of 'thread' or one of its properties.
'SET_THREAD_UPDATE' is a Vuex mutation and the only one of many that causes problems even though I am not doing anything differently.
const state = {
    threadUpdate: {}
}

const mutations = {
    SET_THREAD_UPDATE (state, userObj) {
        state.threadUpdate = userObj
    }
}

When the button that triggers the commit is pressed the first time, everything works like expected. But then, from the second time forward I get two errors and the commit doesn't do anything:
[Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] Do not mutate vuex store state outside mutation handlers." (found in <Root>)

Error: "[vuex] Do not mutate vuex store state outside mutation handlers."

I can't figure out the error. It doesn't make sense because I am using a mutation to change the state. Ideas anyone? Thanks!

A: Solution to the problem was to use JSON instead of regular JS objects. Not sure why though.


text:
Q: How to get reference of already running AWS EC2 instance in my CDK stack/app? I want to add an Alert to the CPU usage metric of an already running EC2 instance using AWS Cloud Development Kit (CDK). The version of CDK I'm using is 2.60.0. But I found no solution in the sample examples or on google searches.
Below is the Stack I've tried. It uses the existing VPC but creates a new EC2 instance instead of referring to existing ones.
class CloudwatchHighCpuUsageAlertStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        vpc = ec2.Vpc.from_lookup(self, "MyVPC", vpc_id="vpc-xyz")  # Uses existing VPC

        instance = ec2.Instance(  # Creates new Instance instead of getting one with Instance ID (i-abc)
            self,
            id="i-abc",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ec2.MachineImage.latest_amazon_linux(),
            vpc=vpc,
        )


text:
Q: Whenever I run this function from its script it doesn't work correctly, but when I move it to main it works just fine. Why is this happening? I'm trying to write a function that gives an approximation of pi based off of a recursive algorithm. When I wrote the function in main it worked perfectly, but when I moved it back to its own script it kept giving back a false answer. What am I doing wrong?
This is the function in its own script "liuhui.py"
import math

def pi_LiuHui(epsilon):
    M = 1
    error = 1
    sides = 6.0
    aN = 2.59808

    while error > epsilon and error < 20:
        m = math.sqrt(((M / 2) ** 2) + (1 - math.sqrt(1 - ((M ** 2) / 4))) ** 2)
        sides = sides * 2.0
        apoth = math.sqrt(1 - (m / 2) ** 2)
        aTri = (m * apoth) / 2
        a2N = aTri * sides
        error = a2N - aN
        aN = a2N
        M = m

    return a2N

This is the function call in main.py
import math

from liuhui import pi_LiuHui

print(pi_LiuHui(0.0001))

The output for this is 3.401919999999999. However, this is the function when written in main.py
import math

epsilon = 0.0001
M = 1
error = 1
sides = 6.0
aN = 2.59808

while error > epsilon and error < 20:
    m = math.sqrt(((M/2)**2) + (1 - math.sqrt(1 - ((M**2)/4)))**2)
    sides = sides * 2.0
    apoth = math.sqrt(1 - (m/2)**2)
    aTri = (m * apoth)/2
    a2N = aTri * sides
    error = a2N - aN
    aN = a2N
    M = m

print(a2N)

This outputs 3.1415838921483186, which is correct. Is there a way to make the function behave this way in the other script?


text:
Q: `super` with a class and its metaclass The signature is: super([type[, object-or-type]]). And its doc says:

If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true (this is useful for classmethods).

According to the doc, if someone wants super(metatype, type), the second argument is a type, so issubclass(type, metatype) must be true. But my test program shows it can be false:
#!/usr/bin/env python3

class M0(type):
    def wtf(self):
        print('M0')

class M1(M0):
    def wtf(self):
        print('M1')

class C0(metaclass=M1):
    @classmethod
    def wtf(cls):
        assert issubclass(C0, M1) == False
        super(M1, C0).wtf()

C0.wtf()

Is this guaranteed or undefined?


text:
Q: display multiple xml node into datagridview using c# I have xml file, i displayed the first node within form in c#, this node have attribute is called 'id', now i want to display all nodes that have attribute is called 'father' its value equal to id value.
xml file:
<?xml version="1.0" encoding="UTF-8"?>
<tree>
   <grand name ="aaa" id="1" sex="m" status="d" child="2" father=""></grand>
   <grand name="bbb"  id="11" sex="m" status="d" child="1" father="1"></grand>
   <grand name="ccc" id="111" sex="m" status="d" child="1"  father="11"></grand>
   <grand name="ddd" id="1111" sex="m" status="d" child="3"  father="111"></grand>
   <grand name="eee" id="11111" sex="f" status="d" child=""  father="1111"></grand>
   <grand name="fff"  id="11112" sex="m" status="d" child="" father="1111"></grand>
</tree>

c# code:
 InitializeComponent();
 XDocument xdoc = XDocument.Load(" http://domaim.net/tree/index.xml");
 var name = xdoc.Descendants("grand").First().Attribute("name").Value;
 var sex = xdoc.Descendants("grand").First().Attribute("sex").Value;
 var alive = xdoc.Descendants("grand").First().Attribute("status").Value;
 var child = xdoc.Descendants("grand").First().Attribute("child").Value;
 var id = xdoc.Descendants("grand").First().Attribute("id").Value;
 var father = xdoc.Descendants("grand").First().Attribute("father").Value;
 textBox1.Text = name;
 if (sex == "m") textBox2.Text = "male"; else textBox2.Text = "female";
 if (child == "") textBox4.Text = "no child"; else textBox4.Text = child;
 if (alive == "d") textBox3.Text = "dead"; else textBox3.Text = "alive";

thank you for all

A: You can use Linq to XML and do something like this:
 datagrid.DataSource = (from n in doc.Descendants("grand")
                         where n.Attribute("father").Value==id
                             select new{
                                 Name = n.Attribute("name").Value,
                                 Sex = n.Attribute("sex").Value,
                                 Id = n.Attribute("id").Value,
                                 Status = n.Attribute("status").Value,
                                 Child = n.Attribute("child").Value,
                                 Father = n.Attribute("father").Value
                             }).ToList();

Hope it's what you're trying to achieve :)


text:
Q: How to Deal JPA / JPQL with SQL Server Keyword My Entity class
@Entity
class MasterStccycode{
   private static final long serialVersionUID = 1L;
   @Id
   @Basic(optional = false)
   @NotNull
   @Size(min = 1, max = 3)
   @Column(name = "CODE")
   private String code;

   @Size(max = 100)
   @Column(name = "DESC")
   private String desc;
}

my JPA Query
SELECT t.code, t.desc FROM MasterStccycode t
then I have this following exception

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'DESC'.
Error Code: 156
Call: SELECT CODE, DESC FROM master_stccycode
  Query: ReportQuery(referenceClass=MasterStccycode sql="SELECT CODE, DESC FROM master_stccycode")

I know the solution is to wrap the DESC keyword with [] into [DESC] but how can I do this on JPA QL?

A: DESC is a reserved word on most databases.  You should rename the field.
You could also quote the field, but just renaming it would be best.
@Column(name = "\"DESC\"")


text:
Q: three js multiple scenes (gltf) so i have this code
//Variables for setup

let container;
let camera;
let renderer;
let scene;
let mutant;

function init() {
  container = document.querySelector(".scene");

  //Create scene
  scene = new THREE.Scene();

  const fov = 935;
  const aspect = container.clientWidth / container.clientHeight;
  const near = 0.1;
  const far = 9500;

  //Camera setup
  camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.set(0, -80, 120);

  const ambient = new THREE.AmbientLight(0x404040, 2);
  scene.add(ambient);

  const light = new THREE.DirectionalLight(0xffffff, 2);
  light.position.set(50, 50, 120);
  scene.add(light);
  //Renderer
  renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
  renderer.setSize(container.clientWidth, container.clientHeight);
  renderer.setPixelRatio(window.devicePixelRatio);

  container.appendChild(renderer.domElement);

  //Load Model
  let loader = new THREE.GLTFLoader();
  loader.load("mutant/scene.gltf", function(gltf) {
    scene.add(gltf.scene);
    mutant = gltf.scene.children[0];
    animate();
  });
}

function animate() {
  requestAnimationFrame(animate);
  mutant.rotation.y = 160.3;
  // mutant.rotation.z = 6;
  mutant.rotation.z += 0.01;
  mutant.rotation.x = -1.70;
  renderer.render(scene, camera);
}

init();

function onWindowResize() {
  camera.aspect = container.clientWidth / container.clientHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(container.clientWidth, container.clientHeight);
}

window.addEventListener("resize", onWindowResize);

that loads a 3d model into a website however i want to add multiple scenes so like it loads
mutant/scene.gltf and golem/scene.gltf for example, two models or more how do i do that?
i tried adding another div with class scene and like copying all the files again with names like instead of app.js app2.js etc. didn't work sadly assistance would be highly appreciated
index code:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="./style.css" />
    <title>Document</title>

A: There is no need to create a separate scene when importing a second model. You can reuse the entire setup, even the loader instance. Try it like so:
const manager = new THREE.LoadingManager();
manager.onLoad = () => animate();

const loader = new THREE.GLTFLoader(manager);

loader.load("mutant/scene.gltf", function(gltf) {
    scene.add(gltf.scene);
    mutant = gltf.scene.children[0];
});

loader.load("golem/scene.gltf", function(gltf) {
    scene.add(gltf.scene);
    golem = gltf.scene.children[0];
});

You just have to make sure to position both assets properly. With the above code, they are placed at the same spot.


text:
Q: Why my reputation for upvote is missing? In few of my answer to a question, my reputation is missing for upvote. See the screenshots below for that.

In first one im missing 20 reputation and in second one 10.
Please tell me why this??


text:
Q: migrating starcraft 2 from my old laptop to a new computer
Possible Duplicate:
Can I transfer an installation?

I wonder if there is any way that I can simply copy sc2 with all latest patches to my new computer? There's no doubt that patching from the earliest version to the latest takes very long time. So I am trying to avoid it as much as possible if I could apply all these patches directly to my new computer.


text:
Q: Correct syntax for using php to set  attribute I need to set a div's background colour using PHP. Here's what I'm doing at the moment:
<div class="box" style="background-color:"<?php echo $permacolour; ?>"">

However, this isn't working. What am I doing wrong?
Thanks

A: <div class="box" style="background-color:<?=$permacolour?>">

quotes do not belong to PHP syntax. PHP tags are <?, <?php and ?> only

A: style="background-color:"<?php echo $permacolour; ?>""

You have two sets of quotes here. Try this:
style="background-color:<?php echo $permacolour; ?>"

A: To be near your original post, here's the correct way :
<div class="box" style="background-color: <?php echo $permacolour; ?>">

The problem is that you were writing the background color surrounded by double quotes. The result would have been like

instead of

So just remove the double quotes between the value you are good to go.
Of course, this suppose you defined $permacolour or you made sure the value of $permacolour is sanitized and filtered if inputed by a user.
The answer of @your-common-sense is based on the shorthand syntax that is not always activated on hosted servers.

A: <div class="box" style="background-color:<?php echo $permacolour; ?>;">

A: remove the double quotes
style="<?php echo $permacolour ; ?>"

or without quotes at all would be easier for some versions in html
style=<?php echo $permacolor ;?>


text:
Q: How to connect changes some field in model to reflect on view? How to connect changes some field in model to reflect on view ?
I have model which holds font-weight and I have that model in view, but how to connect changes of font-weight filed in model to reflect on el from view ?

A: There are several approachs that can be applied here on depending that how much delicate you want to be.
1. re-render the whole View any time the Model change
initialize: function(){
  this.model.on( "change", this.render, this );
}

2. be more precise and only re-render what is needed
initialize: function(){
  this.model.on( "change:title", this.renderTitle, this );
  this.model.on( "change:body", this.renderBody, this );
  this.model.on( "change:fontWeight", this.renderFontWeight, this );
}

This needs the company of minimal render methods that modify the DOM as a surgeon:
renderTitle: function(){
  this.$el.find( "h1" ).html( this.model.get( "title" ) );
},

renderBody: function(){
  this.$el.find( "p" ).html( this.model.get( "body" ) );
},

renderFontWeight: function(){
  this.$el.find( "p" ).css( "font-weight", this.model.get( "fontWeight" ) );
}

3. use subviews for every part of the Model
I'm not offering any example for this approach because the implementation can be more complex. Just think that your actual View is instantiating several SubViews, one for the title, other for the body, and so on. Each one with its own render and binding the changes in its concrete Model attribute and re-render when the attribute changes.
You can check working jsFiddle code for the approachs 1. and 2.

A: try this:
var Font = {};

Font.Model = Backbone.Model.extend({

    defaults: {
        font_family: 'Arial, Helvetica, sans-serif',
        font_size:   12,
        font_weight: 'normal'
    }
});

Font.View = Backbone.View.extend({

    initialize: function() {

        var this_view = this;

        this.model.bind('change:font_weight', function(model) {

            // Do something with this_view.el
            alert('handle the font-weight change');

        });
    }
});

var myFontModel = new Font.Model();

var myFontView = new Font.View({
    model: myFontModel
});

myFontModel.set({font_weight: 'bold'});


text:
Q: Binding Shopping Cart Check box Session onto another Gridview I am new to asp.net and I am trying to make a shopping cart. I have a shop set up that has a list of school supplies and a check box next to each one with a "Add to Cart" button on the bottom. I want to store only the checked items into a session and call it to another gridview on my Shopping Cart page. For some reason my gridview on my Shopping cart page is not appearing.
Shop.aspx
    <asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            <asp:BoundField DataField="Price" DataFormatString="{0:c2}" HeaderText="Price" SortExpression="Price" />
            <asp:TemplateField HeaderText="Add To Cart">
                <ItemTemplate>
                    <asp:CheckBox ID="cbAdd" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="White" ForeColor="#000066" />
        <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
        <RowStyle ForeColor="#000066" />
        <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#F1F1F1" />
        <SortedAscendingHeaderStyle BackColor="#007DBB" />
        <SortedDescendingCellStyle BackColor="#CAC9C9" />
        <SortedDescendingHeaderStyle BackColor="#00547E" />
    </asp:GridView>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table] ORDER BY [Id], [Name], [Price]"></asp:SqlDataSource>

<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:Button ID="btnAdd" runat="server" Text="Add To Cart" OnClick="btnAdd_Click" />

Shop.aspx.cs
protected void Page_Load(object sender, EventArgs e)//bind list to gridview
    {

    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {

        DataTable dt = new DataTable();//create new datatable
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("ID"), new DataColumn("Name"), new DataColumn("Country") });
        foreach (GridViewRow row in gvProducts.Rows)//for each row in the gridview
        {
            CheckBox ckRow = (CheckBox)row.FindControl("ckAdd");

            if (ckRow !=null && ckRow.Checked)
            {
                dt.Columns.Add("ID");
                dt.Columns.Add("Name");
                dt.Columns.Add("Price");

                Session["ShoppingCart"] = dt;//store datatable as session called ShoppingCart
            }

            Response.Redirect("~/ShoppingCart.aspx");
        }

ShoppingCart.aspx

Shopping Cart

<asp:GridView ID="gvProductsList" runat="server" AutoGenerateColumns="true" ViewStateMode="Enabled">
    <Columns>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label ID="lblID" runat="server" Text='<%# Bind("ID")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Price">
            <ItemTemplate>
                <asp:Label ID="lblPrice" runat="server" Text='<%# Bind("Price")%>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Quantity">
            <ItemTemplate>
                <asp:Textbox ID="txtQuantity" runat="server" Text='<%# Bind("Count")%>'></asp:Textbox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Product Total">
            <ItemTemplate>
                <asp:Label ID="lblProductTotal" runat="server" Text='<%# Convert.ToInt32(Eval("Quantity"))*Convert.ToInt32(Eval("Price"))%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                 <asp:Label ID="lblTotal" runat="server" Text="Order Total: "></asp:Label>
            </FooterTemplate>
        </asp:TemplateField>

ShoppingCart.aspx.cs
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DataTable dt = (DataTable)Session["ShoppingCart"];

            gvProductsList.DataSource = dt;
            gvProductsList.DataBind();
        }
    }

A: Try this:-
    List<GridViewRow> gridcheckedrows = gvProducts.Rows.Cast<GridViewRow>().
                                        Where(x => (x.FindControl("cbAdd") as CheckBox)
                                       .Checked == true).ToList();

I used below custom data to bind the grid gvProducts
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("Name");
            dt.Columns.Add("Price");
            DataRow dr = dt.NewRow();
            dr[0] = "1";
            dr[1] = "Sharique";
            dr[2] = "120";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "2";
            dr[1] = "Ansari";
            dr[2] = "100";
            dt.Rows.Add(dr);
            gvProducts.DataSource = dt;
            gvProducts.DataBind();
        }

    }

use this to bind you grid gvProductsList
List<GridViewRow> gridcheckedrows = gvProducts.Rows.Cast<GridViewRow>().Where(x => (x.FindControl("cbAdd") as CheckBox).Checked == true).ToList();

        DataTable dt = new DataTable();
        dt.Columns.Add("Id");
        dt.Columns.Add("Name");
        dt.Columns.Add("Price");
        dt.Columns.Add("Count");
        dt.Columns.Add("Quantity");
        foreach (GridViewRow gvr in gridcheckedrows)
        {
            DataRow dr = dt.NewRow();
            dr["Id"] = gvr.Cells[0].Text;
            dr["Name"] = gvr.Cells[1].Text;
            dr["Price"] = gvr.Cells[2].Text;
            dr["Count"] = "1";
            dr["Quantity"] = "2";
            dt.Rows.Add(dr);

        }
        gvProductsList.DataSource = dt;
        gvProductsList.DataBind();

and for grid gvProductsList use below html
<asp:GridView ID="gvProductsList" runat="server">
        <Columns>
            <asp:TemplateField HeaderText="ID">
                <ItemTemplate>
                    <asp:Label ID="lblID" runat="server" Text='<%# Bind("ID")%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name")%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Price">
                <ItemTemplate>
                    <asp:Label ID="lblPrice" runat="server" Text='<%# Bind("Price")%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Quantity">
                <ItemTemplate>
                    <asp:TextBox ID="txtQuantity" runat="server" Text='<%# Bind("Count")%>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Product Total">
                <ItemTemplate>
                    <asp:Label ID="lblProductTotal" runat="server" Text='<%# ((Convert.ToInt32(Eval("Quantity")))*(Convert.ToInt32(Eval("Price"))))%>'></asp:Label>

                </ItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lblTotal" runat="server" Text="Order Total: "></asp:Label>
                </FooterTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

Hope this will help you.


text:
Q: How to Restrict Custom api access using AWS Cognito I am using Spring Boot in my application. While searching for some IAM tools, I actually liked Auth0, but iam not affordable their pricing. So, I found another called AWS Cognito.
Below is Auth0 to restrict our custom access api
 https://auth0.com/docs/api-auth/restrict-access-api

Currently, I am trying to restrict access API using AWS cognito, but I am not finding correct documentation to achieve this. Can anyone please tell me whether restricting api access can be possible using aws cognito.

A: It depends on how much fine-grained control you want over the access to your api.
Allow or Deny Scenario
In some cases, you either want to block someone completely, or give them access to all of your api. In this all or nothing scenario, the simplest route would be to use Cognito User Pools on their own to authorize your users. Cognito User Pools is just used to authenticate the user (are they who they say they are), and to provide tools to make sign up, and sign in easier.
If the user passes authentication, then you can pass one of the tokens returned by cognito user pools (the identity token) to API Gateway. As long as you have set up your api methods to have the Cognito User Pools authorizer in API Gateway, then this is enough for them to accept the identity token as authorization to access the methods.
Fine-Grained Access
However, in other cases, you need more fine-grained control. You may want all authenticated users to have access to a certain subset of your api methods, but only admins to have access to more restricted methods.
In this case, you will also need to use Cognito Identity Pools, to define user roles (e.g. UNAUTHENTICATED_USER, PAID_USER, ADMIN etc), and their associated IAM roles, which will have policies that give them access, or deny them access to various parts of your api.
You then set the authorizer for your api gateway resources to be AWS_IAM (instead of Cognito User Pools as in the all or nothing example above). And API Gateway will use the role credentials obtained from the Cognito Identity Pool to determine if the current user's role has the permissions to access the requested resource.
For example, perhaps your PAID_USER user role, will have the following IAM role attached:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "execute-api:Invoke",
      "Effect": "Allow",
      "Resource": [
        "arn:aws:execute-api:*:*:fjfkdlsjflds/*"
      ]
    },
    {
      "Action": "execute-api:Invoke",
      "Effect": "Deny",
      "Resource": [
        "arn:aws:execute-api:*:*:fjfkdlsjflds/*/admin/*"
      ]
    }
  ]
}

This gives them access to your api, apart from the api methods (resources) that you have set up under /admin/.
I highly recommend this AWS reinvent talk on Serverless Authentication and Authorization, which goes over these options with some good examples.

A: As I understand What you are trying to do is to resolve the authorization for your APIs. Cognito comes to picture in case of Authentication (Instead of your own database and user handling it supports everything). By using Cognito you can create a User pool and Identity pool to handle the User authentication and create the access token for the authorization for subsequent API calls. The following you need to do
1) Register with AWS Cognito and create a user management pool and Identitiy pool
2) Create a spring boot app (as you mentioned spring boot in your stack) for authentication.
3) Add spring security dependency
4) Register the appln as a resource app in COgnito
5) Do the authentication and return back the token you generated.
6) Create another application (for actual business you may have multiple microservices)
7) Register those spring boot app as resource server in cognito
8) Add the spring security dependency on the new app
9) Create a handler by extending WebSecurityConfigAdaper and override configure
10) Create a filter by extending OncePerRequestFilter
11) Authenticate the token by checking the claims
12) Restrict the API access to all calls in cofigure method of configurer