text:
Q: kubeadm based kubernetes (v1.24.2) worker nodes are still in "NotReady" status even after installing calico CNI ("Error querying BIRD") kubeadm based kubernetes (v1.24.2) worker nodes are still in "NotReady" status even after installing calico CNI ("dial unix /var/run/bird/bird.ctl: connect: no such file or directory")
I have deployed calico CNI on kubeadm based kubernetes cluster but the worker nodes still have the "NotReady" status value.
TCP/IP port 179 is open on all the nodes.
The SELinux reports no denials.
On one of the worker nodes the logs of kubelet service yields the ouput below.
$ journalctl -x -u kubelet.service;

Aug 26 10:32:39 centos7-03-08 kubelet[2063]: I0826 10:32:39.855197    2063 kubelet.go:2182] "SyncLoop (probe)" probe="readiness" status="" pod="calico-system/calico-node-brpjc"
Aug 26 10:32:40 centos7-03-08 kubelet[2063]: I0826 10:32:40.007016    2063 prober.go:121] "Probe failed" probeType="Readiness" pod="calico-system/calico-node-brpjc" podUID=d1206cc9-f573-42c0-a43b-d1d5f3dae106 containerName="calico-node" probeResult=failure output=<
Aug 26 10:32:40 centos7-03-08 kubelet[2063]: calico/node is not ready: BIRD is not ready: Error querying BIRD: unable to connect to BIRDv4 socket: dial unix /var/run/bird/bird.ctl: connect: no such file or directory
Aug 26 10:32:40 centos7-03-08 kubelet[2063]: >
Aug 26 10:32:40 centos7-03-08 kubelet[2063]: I0826 10:32:40.997572    2063 prober.go:121] "Probe failed" probeType="Readiness" pod="calico-system/calico-node-brpjc" podUID=d1206cc9-f573-42c0-a43b-d1d5f3dae106 containerName="calico-node" probeResult=failure output=<
Aug 26 10:32:40 centos7-03-08 kubelet[2063]: calico/node is not ready: BIRD is not ready: Error querying BIRD: unable to connect to BIRDv4 socket: dial unix /var/run/bird/bird.ctl: connect: no such file or directory
Aug 26 10:32:40 centos7-03-08 kubelet[2063]: >
Aug 26 10:32:44 centos7-03-08 kubelet[2063]: E0826 10:32:44.011224    2063 kubelet.go:2349] "Container runtime network not ready" networkReady="NetworkReady=false reason:NetworkPluginNotReady message:Network plugin returns error: No CNI configuration file in /etc/cni/net.d/. Has your network provider started?"
Aug 26 10:32:47 centos7-03-08 kubelet[2063]: I0826 10:32:47.172929    2063 kubelet.go:2182] "SyncLoop (probe)" probe="readiness" status="ready" pod="calico-system/calico-node-brpjc"
Aug 26 10:32:49 centos7-03-08 kubelet[2063]: E0826 10:32:49.013157    2063 kubelet.go:2349] "Container runtime network not ready" networkReady="NetworkReady=false reason:NetworkPluginNotReady message:Network plugin returns error: No CNI configuration file in /etc/cni/net.d/. Has your network provider started?"
Aug 26 10:32:54 centos7-03-08 kubelet[2063]: E0826 10:32:54.014957    2063 kubelet.go:2349] "Container runtime network not ready" networkReady="NetworkReady=false reason:NetworkPluginNotReady message:Network plugin returns error: No CNI configuration file in /etc/cni/net.d/. Has your network provider started?"
Aug 26 10:32:59 centos7-03-08 kubelet[2063]: E0826 10:32:59.016829    2063 kubelet.go:2349] "Container runtime network not ready" networkReady="NetworkReady=false reason:NetworkPluginNotReady message:Network plugin returns error: No CNI configuration file in /etc/cni/net.d/. Has your network provider started?"

The kubelet seems to complain about "BIRD" not being ready as shown in the line below.
Aug 26 10:32:40 centos7-03-08 kubelet[2063]: >
Aug 26 10:32:40 centos7-03-08 kubelet[2063]: I0826 10:32:40.997572    2063 prober.go:121] "Probe failed" probeType="Readiness" pod="calico-system/calico-node-brpjc" podUID=d1206cc9-f573-42c0-a43b-d1d5f3dae106 containerName="calico-node" probeResult=failure output=<
Aug 26 10:32:40 centos7-03-08 kubelet[2063]: calico/node is not ready: BIRD is not ready: Error querying BIRD: unable to connect to BIRDv4 socket: dial unix /var/run/bird/bird.ctl: connect: no such file or directory

Where does "BIRD" come from and how can this be resolved?
I have one control plane VM and three worker VMs. Each VM has three network interfaces. Two of them are active and have static IP addresses assigned to them, one for each.
All the four nodes (1 control plane node + 3 worker nodes) have identical contents in their /etc/cni/net.d/ directories as well as /var/lib/calico/ directories.
$ ssh somebody@192.168.12.17 "ls -tlr /etc/cni/net.d/ /var/lib/calico/";date;
/etc/cni/net.d/:
total 8
-rw-r--r--. 1 root root  805 Aug 25 20:36 10-calico.conflist
-rw-------. 1 root root 2718 Aug 25 20:37 calico-kubeconfig

/var/lib/calico/:
total 8
-rw-r--r--. 1 root root 13 Aug 25 20:37 nodename
-rw-r--r--. 1 root root  4 Aug 25 20:37 mtu

$

The kubelet service in the control-plane node has the following log output snipped
$ journalctl -x -u kubelet.service -f;

Aug 26 15:05:40 centos7-03-05 kubelet[2625]: I0826 15:05:40.546857    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-apiserver-centos7-03-05" status=Running
Aug 26 15:05:40 centos7-03-05 kubelet[2625]: I0826 15:05:40.546952    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-controller-manager-centos7-03-05" status=Running
Aug 26 15:05:40 centos7-03-05 kubelet[2625]: I0826 15:05:40.546973    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-scheduler-centos7-03-05" status=Running
Aug 26 15:06:40 centos7-03-05 kubelet[2625]: I0826 15:06:40.547921    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-controller-manager-centos7-03-05" status=Running
Aug 26 15:06:40 centos7-03-05 kubelet[2625]: I0826 15:06:40.548010    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-apiserver-centos7-03-05" status=Running
Aug 26 15:06:40 centos7-03-05 kubelet[2625]: I0826 15:06:40.548030    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-scheduler-centos7-03-05" status=Running
Aug 26 15:07:40 centos7-03-05 kubelet[2625]: I0826 15:07:40.549112    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-controller-manager-centos7-03-05" status=Running
Aug 26 15:07:40 centos7-03-05 kubelet[2625]: I0826 15:07:40.549179    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-apiserver-centos7-03-05" status=Running
Aug 26 15:07:40 centos7-03-05 kubelet[2625]: I0826 15:07:40.549198    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-scheduler-centos7-03-05" status=Running
Aug 26 15:08:40 centos7-03-05 kubelet[2625]: I0826 15:08:40.549414    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-scheduler-centos7-03-05" status=Running
Aug 26 15:08:40 centos7-03-05 kubelet[2625]: I0826 15:08:40.549501    2625 kubelet_getters.go:176] "Pod status updated" pod="kube-system/kube-controller-manager-centos7-03-05" status=Running

I installed calico CNI using the commands below as per the official documentation at "https://projectcalico.docs.tigera.io/getting-started/kubernetes/self-managed-onprem/onpremises".
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.24.0/manifests/tigera-operator.yaml
kubectl create -f /tmp/custom-resources.yaml

The contents of "/tmp/custom-resources.yaml" are shown below.
---

  # This section includes base Calico installation configuration.
  # For more information, see: https://projectcalico.docs.tigera.io/master/reference/installation/api#operator.tigera.io/v1.Installation
  apiVersion: operator.tigera.io/v1
  kind: Installation
  metadata:
    name: default
  spec:
    # Configures Calico networking.
    calicoNetwork:
      # Note: The ipPools section cannot be modified post-install.
      ipPools:
        -
          blockSize: 26
          cidr: 172.22.0.0/16
          encapsulation: VXLANCrossSubnet
          natOutgoing: Enabled
          nodeSelector: all()

---

  # This section configures the Calico API server.
  # For more information, see: https://projectcalico.docs.tigera.io/master/reference/installation/api#operator.tigera.io/v1.APIServer
  apiVersion: operator.tigera.io/v1
  kind: APIServer
  metadata:
    name: default
  spec: {}

The config file I supplied to kubeadm init command --config argument contains the following section (this is abbreviated version of the file)
  apiVersion: kubeadm.k8s.io/v1beta3
  kind: ClusterConfiguration
  networking:
    dnsDomain: cluster.local
    serviceSubnet: 172.21.0.0/16
    podSubnet: 172.22.0.0/16

The contents of "/etc/cni/net.d/10-calico.conflist" on the controlplane and worker nodes are identical.
$ cat /etc/cni/net.d/10-calico.conflist

{
  "name": "k8s-pod-network",
  "cniVersion": "0.3.1",
  "plugins": [
    {
      "type": "calico",
      "datastore_type": "kubernetes",
      "mtu": 0,
      "nodename_file_optional": false,
      "log_level": "Info",
      "log_file_path": "/var/log/calico/cni/cni.log",
      "ipam": { "type": "calico-ipam", "assign_ipv4" : "true", "assign_ipv6" : "false"},
      "container_settings": {
          "allow_ip_forwarding": false
      },
      "policy": {
          "type": "k8s"
      },
      "kubernetes": {
          "k8s_api_root":"https://172.21.0.1:443",
          "kubeconfig": "/etc/cni/net.d/calico-kubeconfig"
      }
    },
    {
      "type": "bandwidth",
      "capabilities": {"bandwidth": true}
    },
    {"type": "portmap", "snat": true, "capabilities": {"portMappings": true}}
  ]
}

I have deployed a pod on this system but the pod is in pending state as the worker nodes are not in "Ready" state.
The output of the command below explains so
$ kubectl describe pod/my-nginx -n ns-test-02;

Yields the output below
{             kube_apiserver_node_01="192.168.12.17";             {               kubectl                 --kubeconfig=/home/somebody/kubernetes-via-kubeadm/kubeadm/${kube_apiserver_node_01}/admin.conf                 describe pod/my-nginx              -n ns-test-02               ;             };           };
Name:         my-nginx
Namespace:    ns-test-02
Priority:     0
Node:         <none>
Labels:       app=nginx
              purpose=learning
Annotations:  <none>
Status:       Pending
IP:
IPs:          <none>
Containers:
  my-nginx:
    Image:        nginx
    Port:         80/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-blxv4 (ro)
Conditions:
  Type           Status
  PodScheduled   False
Volumes:
  kube-api-access-blxv4:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type     Reason            Age   From               Message
  ----     ------            ----  ----               -------
  Warning  FailedScheduling  22m   default-scheduler  0/4 nodes are available: 1 node(s) had untolerated taint {node-role.kubernetes.io/master: }, 3 node(s) had untolerated taint {node.kubernetes.io/not-ready: }. preemption: 0/4 nodes are available: 4 Preemption is not helpful for scheduling.
  Warning  FailedScheduling  16m   default-scheduler  0/4 nodes are available: 1 node(s) had untolerated taint {node-role.kubernetes.io/master: }, 3 node(s) had untolerated taint {node.kubernetes.io/not-ready: }. preemption: 0/4 nodes are available: 4 Preemption is not helpful for scheduling.

Note the events section
Events:
  Type     Reason            Age   From               Message
  ----     ------            ----  ----               -------
  Warning  FailedScheduling  22m   default-scheduler  0/4 nodes are available: 1 node(s) had untolerated taint {node-role.kubernetes.io/master: }, 3 node(s) had untolerated taint {node.kubernetes.io/not-ready: }. preemption: 0/4 nodes are available: 4 Preemption is not helpful for scheduling.
  Warning  FailedScheduling  16m   default-scheduler  0/4 nodes are available: 1 node(s) had untolerated taint {node-role.kubernetes.io/master: }, 3 node(s) had untolerated taint {node.kubernetes.io/not-ready: }. preemption: 0/4 nodes are available: 4 Preemption is not helpful for scheduling.

The pod/my-nginx object was constructed using the command below.
{
  kube_apiserver_node_01="192.168.12.17";
  kubectl \
    --kubeconfig=/home/somebody/kubernetes-via-kubeadm/kubeadm/${kube_apiserver_node_01}/admin.conf \
    create \
    namespace ns-test-02 \
  ;
}

{
  kube_apiserver_node_01="192.168.12.17";
  kubectl \
    --kubeconfig=/home/somebody/kubernetes-via-kubeadm/kubeadm/${kube_apiserver_node_01}/admin.conf \
    --namespace=ns-test-02 \
    run my-nginx \
    --image=nginx \
    --restart=Never \
    --port=80 \
    --expose=true \
    --labels='purpose=learning,app=nginx' \
  ;
}

Below is a listing of the nodes,pods,services objects in the kubeadm based kubernetes cluster.
{             kube_apiserver_node_01="192.168.12.17";             {               kubectl                 --kubeconfig=/home/somebody/kubernetes-via-kubeadm/kubeadm/${kube_apiserver_node_01}/admin.conf                 get nodes,pods,services -A                 -o wide               ;             };           };
NAME                 STATUS     ROLES           AGE     VERSION   INTERNAL-IP     EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION                CONTAINER-RUNTIME
node/centos7-03-05   Ready      control-plane   5h33m   v1.24.2   192.168.12.17   <none>        CentOS Linux 7 (Core)   3.10.0-1160.76.1.el7.x86_64   cri-o://1.24.2
node/centos7-03-08   NotReady   <none>          5h33m   v1.24.2   192.168.12.20   <none>        CentOS Linux 7 (Core)   3.10.0-1160.76.1.el7.x86_64   cri-o://1.24.2
node/centos7-03-09   NotReady   <none>          5h32m   v1.24.2   192.168.12.21   <none>        CentOS Linux 7 (Core)   3.10.0-1160.76.1.el7.x86_64   cri-o://1.24.2
node/centos7-03-10   NotReady   <none>          5h32m   v1.24.2   192.168.12.22   <none>        CentOS Linux 7 (Core)   3.10.0-1160.76.1.el7.x86_64   cri-o://1.24.2

NAMESPACE          NAME                                           READY   STATUS    RESTARTS        AGE     IP               NODE            NOMINATED NODE   READINESS GATES
calico-apiserver   pod/calico-apiserver-658d588b56-bs5j6          1/1     Running   0               4h42m   172.22.147.134   centos7-03-05   <none>           <none>
calico-apiserver   pod/calico-apiserver-658d588b56-zxhpg          1/1     Running   0               4h42m   172.22.147.133   centos7-03-05   <none>           <none>
calico-system      pod/calico-kube-controllers-5f44c7d7d7-n7lfd   1/1     Running   2 (4h43m ago)   4h45m   172.22.147.129   centos7-03-05   <none>           <none>
calico-system      pod/calico-node-bj9f9                          1/1     Running   2 (4h42m ago)   4h45m   192.168.12.22    centos7-03-10   <none>           <none>
calico-system      pod/calico-node-brpjc                          1/1     Running   0               4h45m   192.168.12.20    centos7-03-08   <none>           <none>
calico-system      pod/calico-node-ksqqn                          1/1     Running   0               4h45m   192.168.12.17    centos7-03-05   <none>           <none>
calico-system      pod/calico-node-vpjx7                          1/1     Running   3 (4h42m ago)   4h45m   192.168.12.21    centos7-03-09   <none>           <none>
calico-system      pod/calico-typha-77c99dcb74-76rt4              1/1     Running   0               4h45m   192.168.12.22    centos7-03-10   <none>           <none>
calico-system      pod/calico-typha-77c99dcb74-qs5x8              1/1     Running   0               4h45m   192.168.12.21    centos7-03-09   <none>           <none>
calico-system      pod/csi-node-driver-gdr4r                      2/2     Running   0               4h44m   172.22.147.131   centos7-03-05   <none>           <none>
kube-system        pod/coredns-6d4b75cb6d-h4kxp                   1/1     Running   0               5h33m   172.22.147.130   centos7-03-05   <none>           <none>
kube-system        pod/coredns-6d4b75cb6d-n9f9h                   1/1     Running   0               5h33m   172.22.147.132   centos7-03-05   <none>           <none>
kube-system        pod/kube-apiserver-centos7-03-05               1/1     Running   0               5h33m   192.168.12.17    centos7-03-05   <none>           <none>
kube-system        pod/kube-controller-manager-centos7-03-05      1/1     Running   1 (4h43m ago)   5h33m   192.168.12.17    centos7-03-05   <none>           <none>
kube-system        pod/kube-proxy-5qfsl                           1/1     Running   0               5h32m   192.168.12.22    centos7-03-10   <none>           <none>
kube-system        pod/kube-proxy-r62r4                           1/1     Running   0               5h33m   192.168.12.17    centos7-03-05   <none>           <none>
kube-system        pod/kube-proxy-t7lnr                           1/1     Running   0               5h32m   192.168.12.21    centos7-03-09   <none>           <none>
kube-system        pod/kube-proxy-v4wjs                           1/1     Running   0               5h33m   192.168.12.20    centos7-03-08   <none>           <none>
kube-system        pod/kube-scheduler-centos7-03-05               1/1     Running   1 (4h43m ago)   5h33m   192.168.12.17    centos7-03-05   <none>           <none>
ns-test-02         pod/my-nginx                                   0/1     Pending   0               36s     <none>           <none>          <none>           <none>
tigera-operator    pod/tigera-operator-7ff575f7f7-6qhft           1/1     Running   1 (4h43m ago)   4h45m   192.168.12.20    centos7-03-08   <none>           <none>

NAMESPACE          NAME                                      TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                  AGE     SELECTOR
calico-apiserver   service/calico-api                        ClusterIP   172.21.182.168   <none>        443/TCP                  4h42m   apiserver=true
calico-system      service/calico-kube-controllers-metrics   ClusterIP   172.21.46.154    <none>        9094/TCP                 4h42m   k8s-app=calico-kube-controllers
calico-system      service/calico-typha                      ClusterIP   172.21.208.66    <none>        5473/TCP                 4h45m   k8s-app=calico-typha
default            service/kubernetes                        ClusterIP   172.21.0.1       <none>        443/TCP                  5h33m   <none>
kube-system        service/kube-dns                          ClusterIP   172.21.0.10      <none>        53/UDP,53/TCP,9153/TCP   5h33m   k8s-app=kube-dns
ns-test-02         service/my-nginx                          ClusterIP   172.21.208.139   <none>        80/TCP                   36s     app=nginx,purpose=learning


text:
Q: How to use MCabber (a Jabber client) with Google Enterprise Account? My company has signed up with Google Apps for Business so I have a Gmail address of the form myname@mycompany.com.
I use MCabber as a chat client and am unable to connect using my working mcabberrc file (which works with my @gmail.com account) with the JID set to the company email address.
I have tried several different configuration settings related to SSL and setting the server/port, but the more research I do, the more it seems it should not be necessary (just setting the JID is expected to work).
With the default mcabberrc, MCabber reports:
01-20 21:36:08  Connecting to server

01-20 21:36:08   with resource mcabber.c387d12b

A: Just copying the End User's answer that worked. I confirmed the same problem previously and compared my settings. This worked.
FYI: Set the server=talk.google.com, port=5223, and enable ssl and disable tls, and set ssl_ignore_checks=1

redpajama_set_name: RedPajamaStackExchange


text:
Q: python inheritance __init__ confusion I am using python 2.7 and confused about inheritance concept.
I want to make a script that can download from various manga (japanese comic site)
Every manga site uses a different method to save their file. So i have a "Manga_site" class and class called "mangacanblog" (this is a website manga).
Every manga site has a: homepage,collection,page,etc. and it's all different for each site. my question is. is this script correct to store those homepage,collection_page,etc variable? or should I use self.homepage in mangacanblog class and not in the Manga_site class?
class Manga_site:

    def __init__(self,homepage,collection_page,base_manga_page,manga_title = ""):
        self.homepage = homepage
        self.collection_page = collection_page
        self.base_manga_page = base_manga_page
        self.manga_title = manga_title

class Mangacanblog(Manga_site):

    def __init__(self,manga_title):
        homepage = bloglink
        collection_page = collectionpagelink
        manga_title = manga_title.lower()
        base_manga_page = basepagelink

A: In your Mangacanblog's __init__() function you are just setting local variables homepage, collection_page, etc, not instance variables, to make them instance variables you have to use self. , and this needs to be used in both super class as well as subclass.
But a better thing to do would be to call super(Manga_site).__init__()  to let the super class handle its initialization, and then you can initialize sub class just the way you want to.
But for this, you would need to define Manga_site as a new style class, by inheriting from object class. Example -
class Manga_site(object):

    def __init__(self,homepage,collection_page,base_manga_page,manga_title = ""):
        self.homepage = homepage
        self.collection_page = collection_page
        self.base_manga_page = base_manga_page
        self.manga_title = manga_title

class Mangacanblog(Manga_site):

    def __init__(self,manga_title):
        super(Mangacanblog, self).__init__(bloglink, collectionpagelink, basepagelink, manga_title.lower())

I have guessing you would define bloglink and collectionpagelink , before you use them in the subclass.

But this given, from the example you have given, what you are trying to achieve may be to use objects of class, and not inheritence.
Inheritence is used when the subclass has extra attributes/properties and extra methods.
You create different objects of same class if you want to store different data in them. Example -
class Manga_site:

    def __init__(self,homepage,collection_page,base_manga_page,manga_title = ""):
        self.homepage = homepage
        self.collection_page = collection_page
        self.base_manga_page = base_manga_page
        self.manga_title = manga_title

mangacanblog = Manga_site('<homepage url>','<collection_page>',....)
anothermangasite = Manga_site('<another url>',....)

Then you can use these objects anyway you want to.


text:
Q: No search results for new records I added new records, and did a full crawl to the site, I see that the crawl was successful but when I search the site for the new records I do not see the results. I get "No results found".
its sharepoint 2010
what could it be?

A: Is only this record unsearchable or all records unsearchable?
Here is a checklist:
1.If it is an item in the list, go to the List settings>Advance settings to check whether the result is allowed to appear in the search results:

2.Check your permission in this list.
3.Check if this site is included in your content source.
4.Check if you have done any settings in the result source.
5.Have you set any crawl rules?
In addition,have you configured the search center?


text:
Q: Let-me-google-this-for-you link went through I happened to post a comment which contained a lmgtfy link.  Then I realized it was not nice, so I reposted it with a plain Google link.  After having been informed it was actually banned and there was a mechanism to prevent it, I started wondering if it was a bug.
The post where this happened is here: https://dba.stackexchange.com/q/104886/6219

A: That blacklist is currently only active on a few sites, like Stack Overflow and Server Fault, because those are the sites that were having problems with it most. If another site starts having problems with its use in the future, they can request it be added for their site.

Shog was irritated nice enough to go ahead and apply that blacklist rule network-wide, so you shouldn't be able to use it anywhere now.


text:
Q: where is the latest Synergy for Mac OS X? I use SynergyKM on my Mac OS X 10.5.7 MacBook Pro to share my keyboard with my Windows XP desktop.
On the Mac its recently stopped working.  Here's the log:
7/29/09 2:23:39 PM Synergyd[328] *** -[SDSynergyServerWrapper isEqualToString:]: unrecognized selector sent to instance 0x145930
7/29/09 2:23:39 PM Synergyd[328] Exception raised during posting of notification. Ignored.  exception: '*** -[SDSynergyServerWrapper isEqualToString:]: unrecognized selector sent to instance 0x145930'  invoked observer method: '*** -[LCSStdIOTaskWrapper readCompletition:]'  observer: 0x146110  notification name: 'NSFileHandleReadCompletionNotification'

I guess a recently system update broke it.  I went to go upgrade synergy, but it looks like the SynergyKM project and the original synergy projects are both dead (nothing released since v1.3.1 in 2006!).  Synergy is so useful, surely the project has been resurrected elsewhere?

A: Synergy+ takes over where synergy left off.
http://code.google.com/p/synergy-plus/

A: I've just been using the original synergy (both Mac and Windows).  Just set it up a couple weeks ago.  Maybe it hasn't been updated in a while, but it still works just fine for me.

A: The accepted answer is out-of-date.  On http://code.google.com/p/synergy-plus/:

Visit the new Synergy website. Synergy+ and Synergy have now combined
  efforts.

Note that my Mac keyboard didn't work on my Windows 7 machine with Synergy 1.3.8 (though the mouse did). Downgrading to 1.3.6 solved the problem.

A: I am happily using SynergyKM on Lepoard. Yes it hasn't been updated but it works 100% with the existing Synergy windows binaries if you need to work cross platform.
I suppose, if it ain't broken it hasn't needed fixing.


text:
Q: Prestashop Login First I use latest prestashop 1.6.1.4, I want to every customer firstly login on site and then they have access all over pages of website, without login user can't do anything on site.
So, I want know that there is any configuration at backoffice side and if Yes then how can do that?

A: There is no built in function to do this, but you can easily override the FrontController to achieve this behavior.
Put this code inside /override/classes/controller/FrontController.php:
<?php

class FrontController extends FrontControllerCore
{
    public function init()
    {
        parent::init();
        if (!$this->context->customer->isLogged() && $this->php_self != 'authentication' && $this->php_self != 'password')
        {
            Tools::redirect('index.php?controller=authentication?back=index');
        }
    }
}

If the user is not on an authentication page or a forgot password page he will be redirected to the authentication page. After log in he will be redirected to the home.

EDIT:
If the file FrontController.php doesn't exist, you will have to create it and delete the file /cache/class_index.php. class_index caches every classes path on your website. So if you create a new Class File, you need to delete it to let Prestashop search for newly created ones.

A: There is no such configuration for this in back office. You can only achieve this by developing a custom module for your store, that uses a hook that is called on all the pages (hookDisplayHeader or hookDisplayTop etc.)
If you don't want to create a module for this then you can also achieve the same by overriding FrontController.php as it is called on each and every page of PrestaShop.


text:
Q: Internal error, too much debug info returned to client, in Spring REST If there is an exception thrown within my Spring REST code, the server sends something similar to the following back to the client:
{
  "timestamp": 1502184648199,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "org.foo.DataAccessException",
  "message": "SQL [select * from my_table]: Table does not exist",
  "path": "/my-api"
}

I am worried that much too much internal information is exposed to the client, if it's installed this way on the live system. It might contain SQL indicating our table structure, or any other information that might be in an Exception. (Although I'll admit it's useful for debugging on the test system.)
How can I prevent this detailed information being sent to the client? (Ideally still keep it behaving this way on our test system.)

A: I have faced with the same problem recently and I suggest you to try this way:
https://blog.jdriven.com/2016/06/spicy-spring-custom-error-json-response-with-errorattributes/
@Component
@Slf4j
public class MyCustomErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);

        if(LOGGER.isDebugEnabled()){

            Throwable throwable = getError(requestAttributes);
            if(throwable!=null) {
                Throwable cause = throwable.getCause();
                if (cause != null) {
                    Map<String, Object> causeErrorAttributes = new HashMap<>();
                    causeErrorAttributes.put("exception", cause.getClass().getName());
                    causeErrorAttributes.put("message", cause.getMessage());
                    errorAttributes.put("cause", causeErrorAttributes);
                }
            }
        }else{
            errorAttributes.remove("message");
            errorAttributes.remove("exception");
        }
        return errorAttributes;
    }

}

A: You can define your ExceptionHandler to define the custom response format in case of exception. Just define ExceptionHandler and override the default response format.
Sample code:
    @ExceptionHandler({ Exception.class })
public ResponseEntity<Object> handleAll(Exception ex, WebRequest request) {
    ApiError apiError = new ApiError(
      HttpStatus.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage(), "error occurred");
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}

take a look at Custom Error message spring rest


text:
Q: store value after log-in java for all other files I am developing an application in which the first window is

after clicking on log-in the log-in window appears and after correct credentials is is directed to choose time stamp and data set id window.
This is how I am accessing the value of API key (Login.java)
String value1=text1.getText();
String value2=text2.getText();
URL url = new URL("http://website-link/method/user.json?userName="+value1+"&password="+value2);

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
  sb.append(inputLine);
}

String Result;
Result=sb.toString();
String jsonSource = Result;
JSONArray array;
try {
  array = new JSONArray(jsonSource);
  for (int i = 0; i < array.length(); i++) {
    JSONObject firstObject = (JSONObject) array.get(i);
    System.out.println("APIkey is  " + firstObject.getString("apiKey"));
    APIkey=firstObject.getString("apiKey");
  }

I want that after successful log-in the user can anytime choose data set and time stamps.
That is Login.java is passing a value to Algorithm.java (for choosing the data set and timestamp window)
if (httpCon.getResponseCode()==200) {
  Algorithm frame=new Algorithm(APIkey);
  frame.setSize(450,200);
  frame.setVisible(true);
  dispose();
  JLabel label = new JLabel("Welcome:"+value1);
}

now this API key is used in Algorithm.java to set the connection and select some specific nodes based on entered time stamps and data set id.
Now I want that after log-in I can anytime click on the second button shown in this window and choose the time stamp and data set id. But in that case I don't have the value of API key as I am using this in Main.java (responsible for the  above window). And in Main.java the value of API key is null. I don't want the user to enter the log in username and password again and again.
if (e.getSource() == myFirstButton) {
  Login frame1=new Login();
  frame1.setSize(450,200);
  frame1.setVisible(true);
}

if (e.getSource() == mySecondButton) {
  Algorithm frame=new Algorithm(APIkey);
  frame.setSize(450,200);
  frame.setVisible(true);
}

Now how can I have the value of API key stored in all files once the user entered the correct access credentials in Login window and can use it anywhere.
Each of the file: Log-in.java , Algorithm.java,Main.java is extending jframe.
and Main.java is having the main() function
I am working in Netbeans 7.1.2. I am coding this in Swing Java. I am new to Java.

A: The fastest way to do this would be to have a global variable APIKey in Main.java and set it's value after the user logs-in. And if you do this, I would also add a Logout button to unset this variable.


text:
Q: nginx with ssl taking long time to load Can anyone tell me what is wrong with this config file. if i'm executing this without certificate, everything works properly. but with ssl it's taking too much time to load the website. maybe it's because i'm force redirecting to https or something. I'm not much familiar with nginx. tried to google for similar issue but did not get the solution from anywhere.
server {

client_max_body_size 100M;
server_name myserver.xyz; # managed by Certbot

listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate PEM_FILE_PATH; # managed by Certbot
ssl_certificate_key PEM_FILE_PATH; # managed by Certbot
include CERTBOT_CONFIG_FILE; # managed by Certbot
ssl_dhparam PEM_FILE; # managed by Certbot
root PROJECT_ROOT;
location / {

    try_files $uri $uri/ /index.html;
}

location /api/ {

    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

error_page 404 /404.html;
location = /40x.html {

}

error_page 500 502 503 504 /50x.html;
location = /50x.html {

}

}

server {
    listen 80 ;
    listen [::]:80 ;
    server_name myserver.xyz;

    return 301 https://$host$request_uri;

}

enter image description here


text:
Q: Urlopen error when URL created by reading from file I had tried to find the solution in the Web, but didn't find quite full solution for me.
I'm trying to create an URL by concatinating variables from code and from file, but urlopen() return urllib2.URLError: <urlopen error no host given>
This is my code:
#!/usr/bin/env python
# _*_ coding: utf-8 _*_

from urllib2 import urlopen
from billmgrvars import *
# These variables are from billmgrvars file
url = "https://" + dnsmgrIP + ":" + dnsmgrPort + "/dnsmgr?authinfo=" + resellerlogin + ":" + resellerpass + "&out=json&sform=ajax"

with open ("PTRlist.py") as PTRfile:
    for RRPTR in PTRfile.readlines():
        print (RRPTR)
        addPTRurl = url + "&clicked_button=ok&dtype=master&email=tech%40example.com&func=domain.edit&ip=&masterip=&name=" + str(RRPTR).replace("-", "%2D") + "&progressid=false&sok=ok&zoom-ip="
        print "URL: " + addPTRurl
        urlopen(addPTRurl)
PTRfile.close()

PTRlist.py file:
102.213.62.in-addr.arpa
43.24.212.in-addr.arpa

Running script:
102.213.62.in-addr.arpa

URL: https://1.2.3.4:1500/dnsmgr?authinfo=user:password&out=json&sform=ajax&clicked_button=ok&dtype=master&email=tech%40example.com&func=domain.edit&ip=&masterip=&name=102.213.62.in%2Daddr.arpa
&progressid=false&sok=ok&zoom-ip=
Traceback (most recent call last):
  File "./getPTRs.py", line 28, in <module>
    urlopen(addPTRurl)
  File "/usr/lib64/python2.6/urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib64/python2.6/urllib2.py", line 389, in open
    req = meth(req)
  File "/usr/lib64/python2.6/urllib2.py", line 1096, in do_request_
    raise URLError('no host given')
urllib2.URLError: <urlopen error no host given>

Don't know why this error.
If I just run script like:
testVariable = "https://1.2.3.4:1500/dnsmgr?authinfo=user:password&out=json&sform=ajax&clicked_button=ok&dtype=master&email=tech%40example.com&func=domain.edit&ip=&masterip=&name=102.213.62.in%2Daddr.arpa
    &progressid=false&sok=ok&zoom-ip="
urlopen(testVariable)

It works correctly. Please, help and thanks you.

A: I'm sorry for that post. Changed console width and found that my strings are read from file with \n at the end, so URL is broken.
So the solution is:
str(RRPTR).replace("-", "%2D").replace('\n', "") as the part of my URL.


text:
Q: PWM Control vs Variable Voltage Control - Calculating Duty Cycle I have a strange problem. We have an actuator which was controlled using varying voltage. For example, to achieve setting 1 we measured that the resistance of the coil is 32 Ohms and 2.09 V is supplied. That should see a current of 65.33mA and power of 0.136 W. Now we have to change it to a PWM control with constant 4.5 v supply. But how to calculate the duty cycle. The resistance remains the same. We need the same power. Is there any formula which can be used to calculate the effective current which is needed to drive in this case 0.136W?

A: If your frequency is high enough (like period 20 times shorter that actuator's time constant), you can consider your voltage just average: V = Vbus * D. So duty cycle would be D = V / Vbus.
This is based on the fact your actuator is a solenoid with inductance and resistance, making up time constant.


text:
Q: For loop weird behaviour The other day I was doing a javascript exercise and wound up with a weird behavior. I would appreciate if you could explain it.
so the goal was to make a little script that creates all the possible combinations of consequent letters in a word.
eg. "dog" >>>  ["d", "do", "dog", "o", "og", "g"];
function combCheck(w){
var arrayBase = [];
for (var i=0, y=1 ; y<=w.length; y++){
    arrayBase.push(w.slice(i,y));
    console.log("i is equal to: "+i);
    console.log("y is equal to: "+y);
    if (y==w.length) {
        i++;
        y = i;
        console.log("i in if part is equal to: " + i);
        console.log("y in if part is equal to: " + y);
    }
}
return arrayBase;

}
so everything runs cool and smooth but there is something I can't figure out.
    combCheck("dog");
VM720:5 i is equal to: 0
VM720:6 y is equal to: 1
VM720:5 i is equal to: 0
VM720:6 y is equal to: 2
VM720:5 i is equal to: 0
VM720:6 y is equal to: 3
VM720:10 i in if part is equal to: 1
VM720:11 y in if part is equal to: 1
VM720:5 i is equal to: 1
VM720:6 y is equal to: 2
VM720:5 i is equal to: 1
VM720:6 y is equal to: 3
VM720:10 i in if part is equal to: 2
VM720:11 y in if part is equal to: 2
VM720:5 i is equal to: 2
VM720:6 y is equal to: 3
VM720:10 i in if part is equal to: 3
VM720:11 y in if part is equal to: 3

as you can see in log line:10 interpreter enters the if statement and increases "i" by 1 and set the "y" to the value of "i" so they both have value of 1 but by the time interpreter gets back to the loop "y" gets increased by  1 again.
since "y" should not undergo the increment by the loop yet, I couldn't explain it in anyway.I mean shouldn't we set the y to "i+1" in the script?doesn't that make more sense?
Thanks in advance.

A: The behavior you have is not abnormal. In a for-loop, the iteration of a variable is at the tail end. You can think of the code executing, then ending by adding 1 to y.
If you want the iteration to be at the beginning, then you could use a while loop, and have the first statement in the loop be y++.


text:
Q: Apache module development I'm looking to build an apache module which will be able to listen to all of the other apache modules loaded. with my module i want to know when each of the modules request handler gets called and when it ends. i want to use this for request handlers, auth handlers, filters and other modules.
Is it possible with the apache module architecture
I have looked at the mod_info and mod_example but based on my understanding there is no way to get a callback before a particular module is being called and after the module handler finished.
Is there any way to make this happen ?

A: You cannot get control each time the core calls into a module. You would have to modify the macros that run the hooks to instrument them in a custom httpd build.


text:
Q: JPA CriteriaBuilder subquery? I have a SQL statement like this:
select * FROM T1
WHERE
0 = ( SELECT count(*) FROM T2 WHERE T2.T1ObjId = T1.ObjId AND T2.column = 'someText' )

And I'm trying to figure out how to write it using the JPA 2.0 Specification system.
I can't even figure out where to start with the query. I have a class that implements Specification<T1> and implements the toPredicate() method. I can't figure out where to go from there.
Any pointers?

A: Assuming that you have the following mapping:
@Entity
@Table(name = "T1")
public class Table1
{
   @Column(name = "ObjId")
   public Long objId;

   // ...
}

@Entity
@Table(name = "T2")
public class Table2
{
   @Column(name = "T1ObjId")
   public Long objId;

   @Column(name = "column")
   public String clmn;

   // ...
}

you can try to use something like this:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Table1> criteria = builder.createQuery(Table1.class);

Root<Table1> t1 = criteria.from(Table1.class);
Subquery<Long> sq = criteria.subquery(Long.class);
Root<Table2> t2 = sq.from(Table2.class);

ParameterExpression<String> clmnParameter = builder.parameter(String.class);
sq.select(builder.count(t2))
  .where(
     builder.equal(t2.get("objId"), t1.get("objId")),
     builder.equal(t2.get("clmn"), clmnParameter)
  );
criteria.select(t1);
criteria.where(builder.equal(sq, 0L));

TypedQuery<Table1> query = entityManager.createQuery(criteria);
query.setParameter(clmnParameter, "someText");
List<Table1> result = query.getResultList();

P.S. I would suggest you to read an excellent book - Java Persistence
with Hibernate (see 15.5 Subselects in second edition of this book)


text:
Q: MS Access VBA improve script I have this code in MS Access (I did it in VBA becasue I didn't find the way to create a procedure in Access). What it does is simple, it takes a field form a table and replace the value in another table where the ID is the same.
How can I get this faster? It is currently taking 8 minutes more or less to get it done (processor is always under 20%, so it is not about processor power).
Set rst = CurrentDb.OpenRecordset("Tab_personal_2")

 rst.MoveFirst

 DoCmd.SetWarnings False

 Do Until rst.EOF
    DoCmd.RunSQL ("UPDATE Tab_personal_3 SET RFC = '" & rst("RFC") & "' WHERE Id = " & rst("Id"))
    rst.MoveNext

 Loop

A: You should be able to do this in a single query:
UPDATE Tab_personal_3 t3
INNER JOIN Tab_personal_2 t2 ON t2.ID = t3.ID
SET t3.RFC = t2.RFC

Of course, you can execute this query through VBA, if you wish. But storing the query allows Access to store the execution plan, and increase the speed on the query.

A: I believe a single update query will work if the tables share an ID field:
UPDATE Tab_personal_3 INNER JOIN Tab_personal_2 ON Tab_personal_3.ageing_collection = Tab_personal_2.Id SET Tab_personal_3.RFC = Tab_personal_2.RFC;


text:
Q: How do I resolve a TesseractNotFoundError? I am trying to use pytesseract in Python but I always end up with the following error:
    raise TesseractNotFoundError()
pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your path

However, pytesseract and Tesseract are installed on my system.
Example code that produces this error:
import cv2
import pytesseract

img = cv2.imread('1d.png')
print(pytesseract.image_to_string(img))

How do I resolve this TesseractNotFoundError?

A: I faced the same problem. I hope you have installed from here and have also done pip install pytesseract.
If everything is fine you should see that the path C:\Program Files (x86)\Tesseract-OCR where tesseract.exe is available.
Adding Path variable did not helped me, I actually added new variable with name tesseract in environment variables with a value of C:\Program Files (x86)\Tesseract-OCR\tesseract.exe.
Typing tesseract in the command line should now work as expected by giving you usage informations. You can now use pytesseract as such (don't forget to restart your python kernel before running this!):
import pytesseract
from PIL import Image

value=Image.open("text_image.png")
text = pytesseract.image_to_string(value, config='')
print("text present in images:",text)

enjoy!

A: I face this same issue. I just use this command that will help me.
sudo apt install tesseract-ocr

Note that this will only work on Ubuntu.
sudo is a Unix exclusive command (Linux, Mac, Rasbian, etc.) while apt is Ubuntu specific.

A: I was also facing the same error when I was trying to make a text-extractor using pytesseract, but the solution was there in installation instructions for  pytesseract in pypi site: pytesseract
There are many alternatives to avoid the error,
But, adding one more parameter in the method pytesseract.image_to_string solved it for me, like
tessdata_dir_config = "/usr/share/tesseract-ocr/4.00/tessdata"
output = pytesseract.image_to_string(image, lang='eng', config=tessdata_dir_config)

A: I tried adding to the path variable like others have mentioned, but still received the same error. what worked was adding this to my script:

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files
  (x86)\Tesseract-OCR\tesseract.exe"

A: The following three commands will do the needful :
sudo apt update
# This will update your packages
sudo apt install tesseract-ocr
# This will install OCR
sudo apt install libtesseract-dev
# This will add it as development dependency

A: You can download tesseract-ocr setup using the following link,
Tesseract for windows
Then add new variable with name tesseract in environment variables with value C:\Program Files (x86)\Tesseract-OCR\tesseract.exe

A: You are probably missing tesseract-ocr from your machine. Check the installation instructions here: https://github.com/tesseract-ocr/tesseract/wiki
On a Mac, you can just install using homebrew:
brew install tesseract
It should run fine after that

A: Install tesseract from https://github.com/UB-Mannheim/tesseract/wiki and add the path of tesseract.exe to the Path environment variable.

A: Most likely you have different versions of Python installed, ensure that the installed Tesseract is on the same Python version.
which pip3 shows you the path to the pip3 installation and which python3 shows the corresponding path to the Python installation.
Ensure that these two are the same.

A: This occurs under windows (at least in tesseract version 3.05) when the current directory is on a different drive from where tesseract is installed.
Something in tesseract is expecting data files to be in \Program Files... (rather than C:\Program Files, say). So if you're not on the same drive letter as tesseract, it will fail. It would be great if we could work around it by temporarily changing drives (under windows only) to the tesseract installation drive before executing tesseract, and changing back after.
Example in your case: You can copy yourmodule_python.py to "C/Program Files (x86)/Tesseract-OCR/" and RUN!

A:
There Are few steps to set the path
1:goto this "https://github.com/UB-Mannheim/tesseract/wiki"
2:download the latest installers
3:install it
4: set the path in system variables such as "C:\Program Files\Tesseract-OCR" or
     "C:\ProgramFiles (x86)\Tesseract-OCR"
5 : open CMD type "tesseract" and some output except "not regonized type errors"

A: On Ubuntu under flask webframework this should be working
pytesseract.pytesseract.tesseract_cmd = r"/usr/bin/tesseract"
img = Image.open(picture_name)
print(pytesseract.image_to_string(img))

A: Under Windows 10 OS environment, the following method works for me:

*

*https://github.com/tesseract-ocr/tesseract/wiki
Download tesseract and install it. Windows version is available here:
https://github.com/UB-Mannheim/tesseract/wiki

*Find script file pytesseract.py from C:\Users\User\Anaconda3\Lib\site-packages\pytesseract and open it.
Change the following code from tesseract_cmd = 'tesseract' to: tesseract_cmd = 'D:/Program Files (x86)/Tesseract-OCR/tesseract.exe'

*You may also need add environment variable D:/Program Files (x86)/Tesseract-OCR/
Hope it works for you!

A: I'm running on a Mac OS and installed tesseract with brew so here's my take on this. Since pytesseract is just how you can access tesseract from python, you have to specify where tesseract is already on your computer.
For Mac OS
Try finding where the tesseract.exe is- if you installed it using
    brew, on your the terminal use:
>brew list tesseract

This should list where your tesseract.exe is, somewhere more or less like
> /usr/local/Cellar/tesseract/3.05.02/bin/tesseract

Then following their instructions:
pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>'

pytesseract.pytesseract.tesseract_cmd = r'/usr/local/Cellar/tesseract/3.05.02/bin/tesseract'

should do the trick!

A: For Mac:

*

*Install Pytesseract (pip install pytesseract should work)

*Install Tesseract but only with homebrew, pip installation somehow doesn't work. (brew install tesseract)

*Get the path of brew installation of Tesseract on your device (brew list tesseract)

*Add the path into your code, not in sys path. The path is to be added along with code, using pytesseract.pytesseract.tesseract_cmd = '<path received in step 3>' - (e.g. pytesseract.pytesseract.tesseract_cmd = '/usr/local/Cellar/tesseract/4.0.0_1/bin/tesseract')

This should work fine.

A: I got this error because I installed pytesseract with pip but forget to install the binary.
On Linux
sudo apt update
sudo apt install tesseract-ocr
sudo apt install libtesseract-dev

On Mac
brew install tesseract

On Windows
download binary from https://github.com/UB-Mannheim/tesseract/wiki. then add pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe' to your script. (replace path of tesseract binary if necessary)
references:
https://pypi.org/project/pytesseract/ (INSTALLATION section) and
https://github.com/tesseract-ocr/tesseract/wiki#installation

A: One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'

A:
CAUTION: ONLY FOR WINDOWS

I came across this problem today and all the answers mentioned here helped me, but I personally had to dig a lot to solve it. So let me help all others by putting out the solution to it in a very simple form:

*

*Download the executable 64 bit (32-bit if your computer is of 32
bit) exe from here.
(Name of the file would be tesseract-ocr-w64-setup-v5.0.0.20190526
(alpha))

*Install it. Let it install itself in the default C directory.

*Now go to your Environment variable (Reach there by just searching it in the start menu or Go to Control Panel > System > Advanced System Settings > Environment Variables)
a) Select PATH and then Edit it. Click on NEW and add the path where it is installed (Usually C:\Program Files\Tesseract-OCR\)
Now you will not get the error!

A: Are you importing
from tesseract import image_to_string

Don't import from pytesseract

A: I was also facing the same issue, just add C:\Program Files (x86)\Tesseract-OCR to your path variable.
If it still does not work, add C:\Program Files (x86)\Tesseract-OCR\tessdata to your path variable in a new line. And do not forget to restart your computer after adding the path variable.

A: I'm currently using Windows and needed to develop a PDF parser but adding a new environment variable via sysdm.cpl alone did not work. For other Windows user, I strongly suggest adding C:\Program Files (x86)\Tesseract-OCR to your profile.ps1 as well (if using Powershell that is).

A: Small mistake -- I knew I had to open/close my cmd to get the updated path to reflect. Using Jupyter Notebook I had to shutdown the client and re-initialize it also.

A: Just run these command if you are using linux,
sudo apt update
sudo apt install tesseract-ocr
sudo apt install libtesseract-dev

then run this,
python -m pip install tesseract tesseract-ocr pytesseract

A: for me it worked by putting single quote
pytesseract.pytesseract.tesseract_cmd =r'C:/Program Files/Tesseract-OCR/tesseract.exe'

actually putting inside double quotes was automatically inserting unwanted chracter

A: This is my path
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"  # your path may be different


text:
Q: figure()-Function from Pyplot throws ValueError I'm trying to plot some data using python and matplotlib.
For doing Updates on the plot, I'll use the set_ydata() function.
I'm using the example Code from here
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10*np.pi, 100)
y = np.sin(x)

plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'b-')

for phase in np.linspace(0, 10*np.pi, 100):
    line1.set_ydata(np.sin(0.5 * x + phase))
    fig.canvas.draw()

When running the program I get the Error
ValueError: max() arg is an empty sequence

After stepping through the Programm step-by-step, I found out, that this error occurs when the function plt.figure() is called.
What is the matter here?
Thanks!


text:
Q: Callbacks with ctypes (How to call a python function from C) Is it possible to call a Python function from a C dll function?
We consider this C function:
 void foo( void (*functionPtr)(int,int) , int a, int b);

On Python, I would like to call foo and set the callback to a Python function:
def callback(a, b):
    print("foo has finished its job (%d, %d)" % (a.value,b.value))

dll.foo( callback, c_int(a), c_int(b) )

Unfortunately, the ctypes documentation is pretty light on this topic and the above code does not work.

A: Use CFUNCTYPE to create a callback type:
c_callback = CFUNCTYPE(None, c_int, c_int)(callback)
dll.foo(c_callback, a, b)

A: import ctypes as c

@c.CFUNCTYPE(None, c.c_int, c.c_int)
def callback(a, b):
    print("foo has finished its job (%d, %d)" % (a.value, b.value))

dll.foo(callback, a, b) # assuming a,b are ints

If you need stdcall calling conventions, use WINFUNCTYPE instead.
Note: if foo may store the callback to be called at a later time then make sure that Python callback is alive (it is enough if it is defined at the global level using the decorator as shown in the example -- modules are essentially immortal in Python unless you try to remove them explicitly).


text:
Q: How to marshal struct to XML with alphabetically-sorted elements? I need to get XML string with ordered elements from structs with unordered fields.
There is main struct:
type Person struct {
    Name string
    Age  int
    OtherData interface{}
}

And there are also a great many other structs, such as:
type SomeStruct1 struct {
    Job   string
    Hobby string
}

type SomeStruct2 struct {
    SkillName  string
    SkillValue int
    *SomeStruct3
}

These structs can have other embedded structs.
I get structs like this:
    sample := &Person{}
    sample.Name = "Vasya"
    sample.Age = 35
    sample.OtherData = SomeStruct1{"programmer", "driving"}

Then I need to get XML with elements ordered by their names:
<Person>
    <Age>35</Age>
    <Name>Vasya</Name>
    <OtherData>
        <Hobby>driving</Hobby>
        <Job>programmer</Job>
    </OtherData>
</Person>


text:
Q: can not connect to clearDBmySQL from django DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'tajaratdatabase',
        'USER': '', #here I am using my username
        'PASSWORD':'', #here I am using my password
        'HOST':'us-cdbr-east-04.cleardb.com',
        'PORT':'3306',
    }
}

I f I use the same credentials on MySQLworkbench my connection is successfully established but if I try to connect from my terminal and run command python manage.py makemigrations I got an error
django.db.utils.OperationalError: (1044, "Access denied for user 'bf76.....'@'%' to database 'tajaratdatabase'")
how can I remove this error and can make my connection successful

A: make sure you are using the correct details for your database to connect


text:
Q: How to input 3 integers in one line Hello can I input 3 integers in one line in java?
im writing time converter
I want to input hh:mm:ss with : as separator for int hh, mm, ss
this is my code with 3 lines input
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int hh = in.nextInt();
    int mm = in.nextInt();
    int ss = in.nextInt();
    int result;
    result = (hh*3600)+(mm*60)+(ss);
    System.out.println(result);
}

A: In java, input is always in terms of String. Hence you will need to parse it to Integers after reading.
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Make use of split() method with ":" as a separator.
Then make use of Integer wrapper class to convert in to int data type.

A: You can use string as input and use ":" as separator and the parse string to int
      public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] input = in.nextLine().split(":");
        int hh = Integer.parseInt(input[0]);
        int mm = Integer.parseInt(input[1]);
        int ss = Integer.parseInt(input[2]);
        int result;
        result = (hh * 3600) + (mm * 60) + (ss);
        System.out.println(result);
      }


text:
Q: NodeJs express save image object to file system I have a nodeJs express endpoint with the following code:
var express = require('express');

const fileUpload = require('express-fileupload');

var router = express.Router()

router.post("/upload",fileUpload(),(req, res) => {
    console.log(req.files);
    res.send('Received!!!');
 });

The upload function works well. But how can I save the file uploaded to the file system? The file is an png image as a JSON object in the req.files variable, which contains name(string) and data(buffer).

A: Try this:

var express = require('express');

const fileUpload = require('express-fileupload');

var router = express.Router()

router.post("/upload",fileUpload(),(req, res) => {
    let sampleFile = req.files.fileName;

  // Use the mv() method to place the file somewhere on your server
    sampleFile.mv('./'+sampleFile.name, function(err) {
        if (err)
            return res.status(500).send(err);

        res.send('Received!!!');
    });
 });

Hope this help you


text:
Q: Post Processing Algorithm I am working on project In which I am supposed to make a web app which will be asking users to upload their inputs as "Rinex file" of Rover and Base Station and It will give more precise data after differential correction.
So I just want to know the algorithm of post processing kinematics.

A: If you are looking for source code, I will suggest you go through http://www.rtklib.com/.

There you can find library for post processing kinematics


text:
Q: log4net writing to file. How to open up permissions I was happily using log4net with my WPF program on an XP machine and happily using a fileAppender FileAppender to write log messages to c:\log.txt.  All was well.  However, it does not work on a Windows 7 machine.  No error or anything, just that the file isn't created, much less logged to.  A little research reveals that it's a file permissions problem (UAC) with Windows 7, and in fact it works if I run the executable as administrator.  It doesn't work if I just click on it (even though I'm logged on as administrator) and it doesn't work when I launch from Visual Studio.
Questions:
1.  Can someone point me to an example where I ask for permission to write to one and only one file (C:\log.txt).  I've seen some examples of where the app.config is configured to ask that the whole program is run with admin privileges.  This seems like overkill but I guess it would work.
2.  Is there as better way to send the information to a log file?  After all, perhaps C: does not exist on user machine.  I think I recall the idea of a "user partition" in Windows 7, but whatever I do has to work on XP and Vista.
Thanks a ton,
Dave

A: You should not be trying to write directly to the root folder. Under windows 7, you will either have to run as administrator or disable UAC for that to work and neither are recommended.
Instead you can write to a folder in the 'application data' area
If you are using a .config file to configure log, you can use something like
<file value="${ALLUSERSPROFILE}\CompanyName\ProductName\Log.txt" />

or
<file value="${APPDATA}\CompanyName\ProductName\Log.txt" />

depending on whether you want the log files to be specific to a user or not.
(Obviously you replace CompanyName and ProductName with your own details).
This should work on Xp/Vista/W7.

A: You have 3 options in my eyes:

*

*like mentioned always run your app as admin altough thats not a brilliant solution

*Use the local path of the executing app to store your log - I always prefer this method as I always know where my logs are ( AppDomain.CurrentDomain.BaseDirectory will help you)

*Use "My Documents" or some similar special folders - a quick google gives us: special folders
I hope this helps.


text:
Q: spring webflux how get request body in webfilter? i want to get the request body in a webfilter.
now, when the request body is to large,
final Flux<DataBuffer> body = exchange.getRequest().getBody();

this body has size 555,
how to get the request body in the webfilter?


text:
Q: Get contact details from a list of Contact Ids in Android I have a situation, where I am getting a List containing contact Ids. I need to retrieve the contact details of each of these contact Ids in single cursor (so that I can use that cursor to populate ListView).
I know how to retrieve contact details for one contact Id.
But I don't know how to fire a query for list of contact Ids. Can someone please help with a snippet of code?

A: Android: Get Contact Details (ID, Name, Phone, Photo). Got this from https://gist.github.com/evandrix/7058235
MyActivity.java
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;

public class MyActivity extends Activity {

    private static final String TAG = MyActivity.class.getSimpleName();
    private static final int REQUEST_CODE_PICK_CONTACTS = 1;
    private Uri uriContact;
    private String contactID;     // contacts unique ID

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onClickSelectContact(View btnSelectContact) {

        // using native contacts selection
        // Intent.ACTION_PICK = Pick an item from the data, returning what was selected.
        startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACTS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_PICK_CONTACTS && resultCode == RESULT_OK) {
            Log.d(TAG, "Response: " + data.toString());
            uriContact = data.getData();

            retrieveContactName();
            retrieveContactNumber();
            retrieveContactPhoto();

        }
    }

    private void retrieveContactPhoto() {

        Bitmap photo = null;

        try {
            InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
                    ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactID)));

            if (inputStream != null) {
                photo = BitmapFactory.decodeStream(inputStream);
                ImageView imageView = (ImageView) findViewById(R.id.img_contact);
                imageView.setImageBitmap(photo);
            }

            assert inputStream != null;
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void retrieveContactNumber() {

        String contactNumber = null;

        // getting contacts ID
        Cursor cursorID = getContentResolver().query(uriContact,
                new String[]{ContactsContract.Contacts._ID},
                null, null, null);

        if (cursorID.moveToFirst()) {

            contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
        }

        cursorID.close();

        Log.d(TAG, "Contact ID: " + contactID);

        // Using the contact ID now we will get contact phone number
        Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
                        ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

                new String[]{contactID},
                null);

        if (cursorPhone.moveToFirst()) {
            contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        }

        cursorPhone.close();

        Log.d(TAG, "Contact Phone Number: " + contactNumber);
    }

    private void retrieveContactName() {

        String contactName = null;

        // querying contact data store
        Cursor cursor = getContentResolver().query(uriContact, null, null, null, null);

        if (cursor.moveToFirst()) {

            // DISPLAY_NAME = The display name for the contact.
            // HAS_PHONE_NUMBER =   An indicator of whether this contact has at least one phone number.

            contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }

        cursor.close();

        Log.d(TAG, "Contact Name: " + contactName);

    }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- @res/layout/main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent" >

    <Button android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Select a Contact"
            android:onClick="onClickSelectContact" />

    <ImageView android:id="@+id/img_contact"
               android:layout_height="wrap_content"
               android:layout_width="match_parent"
               android:adjustViewBounds="true"
               android:contentDescription="Contacts Image"
                />
</LinearLayout>

And the manisfest should use permission
<uses-permission android:name="android.permission.READ_CONTACTS" />


text:
Q: Finding the longest repeated substring What would be the best approach (performance-wise) in solving this problem?
I was recommended to use suffix trees. Is this the best approach?

A: Have a look at http://en.wikipedia.org/wiki/Suffix_array as well - they are quite space-efficient and have some reasonably programmable algorithms to produce them, such as "Simple Linear Work Suffix Array Construction" by Karkkainen and Sanders

A: Here is a simple implementation of longest repeated substring using simplest suffix tree. Suffix tree is very easy to implement in this way.
#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;

class Node
{
public:
    char ch;
    unordered_map<char, Node*> children;
    vector<int> indexes; //store the indexes of the substring from where it starts
    Node(char c):ch(c){}
};

int maxLen = 0;
string maxStr = "";

void insertInSuffixTree(Node* root, string str, int index, string originalSuffix, int level=0)
{
    root->indexes.push_back(index);

    // it is repeated and length is greater than maxLen
    // then store the substring
    if(root->indexes.size() > 1 && maxLen < level)
    {
        maxLen = level;
        maxStr = originalSuffix.substr(0, level);
    }

    if(str.empty()) return;

    Node* child;
    if(root->children.count(str[0]) == 0) {
        child = new Node(str[0]);
        root->children[str[0]] = child;
    } else {
        child = root->children[str[0]];
    }

    insertInSuffixTree(child, str.substr(1), index, originalSuffix, level+1);
}

int main()
{
    string str = "banana"; //"abcabcaacb"; //"banana";  //"mississippi";
    Node* root = new  Node('@');

    //insert all substring in suffix tree
    for(int i=0; i<str.size(); i++){
        string s = str.substr(i);
        insertInSuffixTree(root, s, i, s);
    }

    cout << maxLen << "->" << maxStr << endl;

    return 1;
}

/*
s = "mississippi", return "issi"
s = "banana", return "ana"
s = "abcabcaacb", return "abca"
s = "aababa", return "aba"
*/

A: the LRS problem is one that is best solved using either a suffix tree or a suffix array. Both approaches have a best time complexity of O(n).
Here is an O(nlog(n)) solution to the LRS problem using a suffix array. My solution can be improved to O(n) if you have a linear construction time algorithm for the suffix array (which is quite hard to implement). The code was taken from my library. If you want more information on how suffix arrays work make sure to check out my tutorials
/**
 * Finds the longest repeated substring(s) of a string.
 *
 * Time complexity: O(nlogn), bounded by suffix array construction
 *
 * @author William Fiset, william.alexandre.fiset@gmail.com
 **/

import java.util.*;

public class LongestRepeatedSubstring {

  // Example usage
  public static void main(String[] args) {

    String str = "ABC$BCA$CAB";
    SuffixArray sa = new SuffixArray(str);
    System.out.printf("LRS(s) of %s is/are: %s\n", str, sa.lrs());

    str = "aaaaa";
    sa = new SuffixArray(str);
    System.out.printf("LRS(s) of %s is/are: %s\n", str, sa.lrs());

    str = "abcde";
    sa = new SuffixArray(str);
    System.out.printf("LRS(s) of %s is/are: %s\n", str, sa.lrs());

  }

}

class SuffixArray {

  // ALPHABET_SZ is the default alphabet size, this may need to be much larger
  int ALPHABET_SZ = 256, N;
  int[] T, lcp, sa, sa2, rank, tmp, c;

  public SuffixArray(String str) {
    this(toIntArray(str));
  }

  private static int[] toIntArray(String s) {
    int[] text = new int[s.length()];
    for(int i=0;i<s.length();i++)text[i] = s.charAt(i);
    return text;
  }

  // Designated constructor
  public SuffixArray(int[] text) {
    T = text;
    N = text.length;
    sa = new int[N];
    sa2 = new int[N];
    rank = new int[N];
    c = new int[Math.max(ALPHABET_SZ, N)];
    construct();
    kasai();
  }

  private void construct() {
    int i, p, r;
    for (i=0; i<N; ++i) c[rank[i] = T[i]]++;
    for (i=1; i<ALPHABET_SZ; ++i) c[i] += c[i-1];
    for (i=N-1; i>=0; --i) sa[--c[T[i]]] = i;
    for (p=1; p<N; p <<= 1) {
      for (r=0, i=N-p; i<N; ++i) sa2[r++] = i;
      for (i=0; i<N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p;
      Arrays.fill(c, 0, ALPHABET_SZ, 0);
      for (i=0; i<N; ++i) c[rank[i]]++;
      for (i=1; i<ALPHABET_SZ; ++i) c[i] += c[i-1];
      for (i=N-1; i>=0; --i) sa[--c[rank[sa2[i]]]] = sa2[i];
      for (sa2[sa[0]] = r = 0, i=1; i<N; ++i) {
          if (!(rank[sa[i-1]] == rank[sa[i]] &&
              sa[i-1]+p < N && sa[i]+p < N &&
              rank[sa[i-1]+p] == rank[sa[i]+p])) r++;
          sa2[sa[i]] = r;
      } tmp = rank; rank = sa2; sa2 = tmp;
      if (r == N-1) break; ALPHABET_SZ = r + 1;
    }
  }

  // Use Kasai algorithm to build LCP array
  private void kasai() {
    lcp = new int[N];
    int [] inv = new int[N];
    for (int i = 0; i < N; i++) inv[sa[i]] = i;
    for (int i = 0, len = 0; i < N; i++) {
      if (inv[i] > 0) {
        int k = sa[inv[i]-1];
        while( (i + len < N) && (k + len < N) && T[i+len] == T[k+len] ) len++;
        lcp[inv[i]-1] = len;
        if (len > 0) len--;
      }
    }
  }

  // Finds the LRS(s) (Longest Repeated Substring) that occurs in a string.
  // Traditionally we are only interested in substrings that appear at
  // least twice, so this method returns an empty set if this is not the case.
  // @return an ordered set of longest repeated substrings
  public TreeSet <String> lrs() {

    int max_len = 0;
    TreeSet <String> lrss = new TreeSet<>();

    for (int i = 0; i < N; i++) {
      if (lcp[i] > 0 && lcp[i] >= max_len) {

        // We found a longer LRS
        if ( lcp[i] > max_len )
          lrss.clear();

        // Append substring to the list and update max
        max_len = lcp[i];
        lrss.add( new String(T, sa[i], max_len) );

      }
    }

    return lrss;

  }

  public void display() {
    System.out.printf("-----i-----SA-----LCP---Suffix\n");
    for(int i = 0; i < N; i++) {
      int suffixLen = N - sa[i];
      String suffix = new String(T, sa[i], suffixLen);
      System.out.printf("% 7d % 7d % 7d %s\n", i, sa[i],lcp[i], suffix );
    }
  }

}

A: Check out this link: http://introcs.cs.princeton.edu/java/42sort/LRS.java.html
/*************************************************************************
 *  Compilation:  javac LRS.java
 *  Execution:    java LRS < file.txt
 *  Dependencies: StdIn.java
 *
 *  Reads a text corpus from stdin, replaces all consecutive blocks of
 *  whitespace with a single space, and then computes the longest
 *  repeated substring in that corpus. Suffix sorts the corpus using
 *  the system sort, then finds the longest repeated substring among
 *  consecutive suffixes in the sorted order.
 *
 *  % java LRS < mobydick.txt
 *  ',- Such a funny, sporty, gamy, jesty, joky, hoky-poky lad, is the Ocean, oh! Th'
 *
 *  % java LRS
 *  aaaaaaaaa
 *  'aaaaaaaa'
 *
 *  % java LRS
 *  abcdefg
 *  ''
 *
 *************************************************************************/

import java.util.Arrays;

public class LRS {

    // return the longest common prefix of s and t
    public static String lcp(String s, String t) {
        int n = Math.min(s.length(), t.length());
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) != t.charAt(i))
                return s.substring(0, i);
        }
        return s.substring(0, n);
    }

    // return the longest repeated string in s
    public static String lrs(String s) {

        // form the N suffixes
        int N  = s.length();
        String[] suffixes = new String[N];
        for (int i = 0; i < N; i++) {
            suffixes[i] = s.substring(i, N);
        }

        // sort them
        Arrays.sort(suffixes);

        // find longest repeated substring by comparing adjacent sorted suffixes
        String lrs = "";
        for (int i = 0; i < N - 1; i++) {
            String x = lcp(suffixes[i], suffixes[i+1]);
            if (x.length() > lrs.length())
                lrs = x;
        }
        return lrs;
    }

    // read in text, replacing all consecutive whitespace with a single space
    // then compute longest repeated substring
    public static void main(String[] args) {
        String s = StdIn.readAll();
        s = s.replaceAll("\\s+", " ");
        StdOut.println("'" + lrs(s) + "'");
    }
}

A: public class LongestSubString {

    public static void main(String[] args) {
        String s = findMaxRepeatedString("ssssssssssss this is a ddddddd word with iiiiiiiiiis and loads of these are ppppppppppppps");
        System.out.println(s);
    }

    private static String findMaxRepeatedString(String s) {
        Processor p = new Processor();
        char[] c = s.toCharArray();
        for (char ch : c) {
            p.process(ch);
        }
        System.out.println(p.bigger());
        return new String(new char[p.bigger().count]).replace('\0', p.bigger().letter);
    }

    static class  CharSet {
        int count;
        Character letter;
        boolean isLastPush;

        boolean assign(char c) {
            if (letter == null) {
                count++;
                letter = c;
                isLastPush = true;
                return true;
            }
            return false;
        }

        void reassign(char c) {
            count = 1;
            letter = c;
            isLastPush = true;
        }

        boolean push(char c) {
            if (isLastPush && letter == c) {
                count++;
                return true;
            }
            return false;
        }

        @Override
        public String toString() {
            return "CharSet [count=" + count + ", letter=" + letter + "]";
        }

    }

    static class  Processor {

        Character previousLetter = null;
        CharSet set1 = new CharSet();
        CharSet set2 = new CharSet();

        void process(char c) {
            if ((set1.assign(c)) || set1.push(c)) {
                set2.isLastPush = false;
            } else if ((set2.assign(c)) || set2.push(c)) {
                set1.isLastPush = false;
            } else {
                set1.isLastPush = set2.isLastPush = false;
                smaller().reassign(c);
            }
        }

        CharSet smaller() {
            return set1.count < set2.count ? set1 : set2;
        }

        CharSet bigger() {
            return set1.count < set2.count ? set2 : set1;
        }

    }
}

A: I had an interview and I needed to solve this problem. This is my solution:
public class FindLargestSubstring {

public static void main(String[] args) {
    String test = "ATCGATCGA";
    System.out.println(hasRepeatedSubString(test));
}

private static String hasRepeatedSubString(String string) {
    Hashtable<String, Integer> hashtable = new Hashtable<>();
    int length = string.length();
    for (int subLength = length - 1; subLength > 1; subLength--) {
        for (int i = 0; i <= length - subLength; i++) {
            String sub = string.substring(i, subLength + i);
            if (hashtable.containsKey(sub)) {
                return sub;
            } else {
                hashtable.put(sub, subLength);
            }
        }
    }
    return "No repeated substring!";
}}

A: There are way too many things that affect performance for us to answer this question with only what you've given us.  (Operating System, language, memory issues, the code itself)
If you're just looking for a mathematical analysis of the algorithm's efficiency, you probably want to change the question.
EDIT
When I mentioned "memory issues" and "the code" I didn't provide all the details.  The length of the strings you will be analyzing are a BIG factor.  Also, the code doesn't operate alone - it must sit inside a program to be useful.  What are the characteristics of that program which impact this algorithm's use and performance?
Basically, you can't performance tune until you have a real situation to test.  You can make very educated guesses about what is likely to perform best, but until you have real data and real code, you'll never be certain.


text:
Q: Autocomplete from object with JQuery I'm trying to build a web-app and I need one textfield with autocomplete, but I'm trying and it doesn't work. The problem is I need autocomplete from a js object (builded with Json).
My object looks like this:
    prod = {
"1":["1","alpargatas","asdf","1","10.5","2"],
"2":["2","volcom","adfw","2","40","5"],
"3":["3","botas","afafew","1","30","12"],
"4":["4","tenis","qrfqr ","1","40","9"]
};

And my script's like this:
<input id="v1_busqueda_in"/>

$(function() {

$( "#v1_busqueda_in" ).autocomplete(
{
    source:data,
    select: function( event, ui ) {
        $( "#v1_busqueda_in" ).val( ui.item[0] + " / " + ui.item[1] );
        return false;
    }
}).data( "autocomplete" )._renderItem = function( ul, item ) {
    return $( "

" )
        .data( "item.autocomplete", item )
        .append( "" + item[0] + " / " + item[1] + "" )
        .appendTo( ul );
    };

});

I'm getting the values using sentences like prod[2][0], but I dont know how I can autocomplete with the second variable and take the first as a selected (ex: write a, autocomp. alpargatas, js takes 1)
I need some help, thanks ;)

A:   <!doctype html>

  <meta charset="utf-8">
      <title>jQuery UI Autocomplete - Custom data and display</title>
    <link rel="stylesheet"   href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

   <link rel="stylesheet" href="/resources/demos/style.css" />

      Select a project (type "j" for a start):


text:
Q: Where to put Business Logic? In VB.Net? Or in SQL? I'm creating an application that allows me to create scheduled tasks. I have a threaded process that runs in the background every minute, and triggers the following class:
Namespace MyName.space
  Public Class RunJob
  ...
  End Class
End Namespace

A job can either be "Run Once" or "Recurring".
I am querying the job table in vb.net, storing the results in a dataset so that I can iterate over them one at a time. I then started thinking about functions to validate if a job should run or not based on its unique criteria.
For example, the simplest of all would be the "Run Once" jobs:
If Type = "Run Once"
    JobShouldRun = Helpers.Validate_RunOnce(WhenToRun, RunCount)
ElseIf Type = "Recurring"
    ...
End If

The function would check if the "WhenToRun" is within 5 minutes of the current date and time configured on the server. I chose a 5 minute window in the event of a task failure so that a minute later it'll try again and still have 3-4 tries left.
But then I started thinking that I could control more of this within the SQL Query to get the jobs themselves, and skip validating this "easy" on within vb.net, but I'm unsure of which method would be more optimal. So I could limit the result set to begin with in my initial query:
SELECT
     JobId
    ,JobType -- Run Once or Recurring
    ,WhenToRun

FROM JobTable a
WHERE Active = 1
AND (
      JobType = 'Run Once'
      AND TotalRuns = 0
      AND DATEDIFF(minute, getdate(), a.WhenToRun) BETWEEN 1 AND 5
    )
OR JobType = 'Recurring'

Then I started thinking, should I perform all my logic with either UNION or JOINS, or a complex WHERE/AND/OR conditioning on the recurring jobs as well? They get quite a bit more complicated... Such as weekly and what days of the week, and what time, etc. Or every "int" years in "Jan|March|Etc" on the Last day of the month.
So I started thinking along these lines:
SELECT
     JobID
    ,JobType
    ...
FROM JobTable
WHERE RecurringType = 'Weekly'
AND ... more conditions based on all the custom job settings

UNION ALL

SELECT
     JobID
    ,...
FROM JobTable
WHERE RecurringType = 'Monthly'
AND ... more conditions based on all the custom job settings

This query would end up quite large and complex, but my question is, should I handle this in vb.net or SQL, or the easy stuff in SQL and the more complicated conditions in vb.net? I'm unsure of the performance impact of either direction.

A: You're basically asking "Where do I put code for business logic?  In the app?  Or in the database?"  It can be a hotly debated topic, but it's sensible to consider both options.  There are some tradeoffs with each approach, and it seems kinda cavalier to say one way is right and the other is wrong.
If your BL code is in the app, you get the primary benefit of the robustness of the .Net Framework.  I love tsql, but you just can't do as much with it as you can VB.Net. If I can stereotype developers, I suspect in general they'll be more comfortable with .Net code.  For most, it's probably easier to debug than tsql.  Since the .Net code is compiled to an assembly, it's not likely to be altered either.
If your BL code is in tsql, you may find that performance is a bit better.  You also abstract away some of the complexity from the .Net code and make that code base a bit smaller (some might argue this is bad thing).  If there are bugs that need to be fixed, it's usually easier to redeploy a stored procedure (or user-defined function, view, etc) than to redeploy an application (especially if it involves multiple workstations).  On the downside, it's easy for other to see (steal!) your code, or make changes to it.
As a general guideline, the more complex the business logic is, the more likely I'd be to put it in the app.  If it's pretty simple and not likely to change, I'll consider putting it in tsql.  That being said, if I had to pick one or the other with no exceptions, I'd put the BL in the app.


text:
Q: Batch file to backup data to networked drive? I am trying to create a backup of some local files on one machine, to a networked hard drive on another machine. The source computer is running Windows Server 2008 R2, and the destination machine is running Windows Server 2003 R2. I want to create a batch file that will run on the source computer, and copy all of the files in the D:\MICROS folder to a separate network drive. \marketing\TeraByte\marketingdata\MICROS\TESTBKUP\ is where the files will need to end up. The batch file will be executed through the task scheduler, and should run regardless of whether or not a user is logged in. I tried to make the batch file myself, and this was the best I could come up with
rem 05.21.2014 - script to Backup the 1 TB drive attached to marketing server.
rem - use program to determine day of wek - then use the DAY of THE WEEK as the sub dir name
set y =%date:~-4,4%
set m =%date:~-10,2%
set d =%date:~-7,2%
set today = %y%%m%%d%
set DOW=%1
echo on
echo DOW
net use M: /D
net use M: \\marketing\TeraByte\marketingdata\
xCopy D:\MICROS\*.*       M:\MICROS\TESTBKUP\            /CDEFHIY > M:\MICROS\BU%today%MICROS%DOW%.TXT
echo Yes, the task really did execute >> \\marketing\TeraByte\MarketingData\MICROS\TESTBKUP\testlog.txt\
pause
:end

The stuff at the beginning is just used to generate a date, and that was all copy/pasted from a script my boss had already created. Where my code starts is after the "echo DOW" line. Whenever I try to get this to run, the task scheduler returns an operational code 2, and says the operation successfully completed, but none of the files were actually copied.
What really confuses me about this whole thing, is that even though this script doesn't work, despite mapping the drive and using UNC paths, is that the following script created by my boss never mentions any network locations, yet it runs flawlessly and backs up the files to exactly the correct network drive. The Z: drive isn't even mapped on the server that script runs on, and yet it somehow knows it needs to go over the network.:
rem
rem 04.09.2010 - script to Backup to 4 Terabyte drive attached to Stephs new windows 7 64bit PC
rem - use program to determine day of week - then use the DAY of THE WEEK as the sub dir name
REM 5.25.10 add RevAcctg and exclusion directories
set y=%date:~-4,4%
set m=%date:~-10,2%
set d=%date:~-7,2%
set today=%y%%m%%d%
set DOW=%1
echo on
echo dow
xCopy  \\MArketing2\AlysonAvino\*.*     Z:\backup\AlysonAvini\%DOW%\        /CDEFHIY >  Z:\BU%today%Alyson%DOW%.TXT
rem goto end
xCopy  D:\DiskImage\*.*        V:\backup\DiskImage\               /CDEFHIY >  V:\BU%today%DiskImage%DOW%.TXT
xCopy  D:\MarkWolf\*.*         Z:\backup\MarkWolf\%DOW%\          /CDEFHIY >  Z:\BU%today%MarkWolf%DOW%.TXT
xcopy  \\otbdata\greatPlains\Bill  Z:\Backup\Bill\%DOW%\          /CDEFHIY >  Z:\BU%today%Bill%DOW%.txt
xcopy  \\otbdata\greatPlains\MSDynamicsGP\FrxServer  Z:\Backup\FrxServer\%DOW%\            /CDEFHIY >  Z:\BU%today%FrxServer%DOW%.txt
xcopy  \\otbdata\greatPlains\CrystalReports  Z:\Backup\CrystalReports\BU%today%\  /CDEFHIY >  Z:\BU%today%Crystal%DOW%.txt
xcopy  \\otbdata\greatPlains\RevAcctG  Z:\Backup\RevAcctG\BU%today%\  /CDEFHIY >  Z:\BU%today%RevAcctG%DOW%.txt
xcopy  D:\administration\*.*  Z:\BACKUP\ADMINISTRATION\%DOW%\     /CDEFHIY >  Z:\BU%today%ADMIN%DOW%.TXT
xcopy  D:\accounting\*.*      Z:\backup\ACCOUNTING\%DOW%\         /CDEFHIY >  Z:\BU%today%ACCT%DOW%.TXT
xCopy  D:\HR\*.*              Z:\backup\HR\%DOW%\                 /CDEFHIY >  Z:\BU%today%HR%DOW%.TXT
xcopy  F:\marketingdata\*.*   Z:\backup\MARKETING\%DOW%\          /CDEFHIY >  Z:\BU%today%MRKT%DOW%.TXT
xcopy  D:\surveillance\*.*    Z:\backup\Surveillence\%DOW%\       /CDEFHIY >  Z:\BU%today%Surv%DOW%.TXT
xCopy  D:\CD\*.*              Z:\backup\CD\%DOW%\                 /CDEFHIY >  Z:\BU%today%CD.TXT
xCopy  C:\Maintenance\*.*     Z:\backup\Maint\%DOW%\              /CDEFHIY >  Z:\BU%today%Maint%DOW%.TXT
xCopy  D:\Schedule\*.*        Z:\backup\Schedule\%DOW%\           /CDEFHIY >  Z:\BU%today%Schedule%DOW%.TXT
xCopy  D:\printshop\*.*       Z:\backup\printshop\%DOW%\          /CDEFHIY >  Z:\BU%today%printshop%DOW%.TXT
xCopy  F:\Exclusion\*.*       Z:\backup\Exclusion\%DOW%\          /CDEFHIY >  Z:\BU%today%Exclusion%DOW%.TXT
xCopy  F:\GAMING\*.*          Z:\backup\GAMING\%DOW%\             /CDEFHIY >  Z:\BU%today%GAMING%DOW%.TXT
xCopy  F:\LUBA\*.*            Z:\backup\SrvrLUBA\%DOW%\           /CDEFHIY >  Z:\BU%today%SrvrLuba%DOW%.TXT
xCopy  F:\AdamSecured\*.*     Z:\backup\AdamSecured\%DOW%\        /CDEFHIY >  Z:\BU%today%AdamSecured%DOW%.TXT
xCopy  D:\DOWNLOADS\*.*       Z:\backup\DOWNLOADS\%DOW%\          /CDEFHIY >  Z:\BU%today%DOWNLOADS%DOW%.TXT
xCopy  F:\MartyFiles\*.*      Z:\backup\MartyFiles\%DOW%\         /CDEFHIY >  Z:\BU%today%MartyFiles%DOW%.TXT
xCopy  F:\LUBAold\*.*         Z:\backup\LUBAold\%DOW%\            /CDEFHIY >  Z:\BU%today%LUBAold%DOW%.TXT
xCopy  D:\TestSecurity\*.*    Z:\backup\TestSecurity\%DOW%\       /CDEFHIY >  Z:\BU%today%TestSecurity%DOW%.TXT
:end
rem do this on mkt2 server XCOPY  G:\*.*    Z:\BACKUP\CreativeGraphics\%DOW%\   /CDEFHIY   > Z:\BU%Today%CreativeGraphics%DOW%.TXT

I've been working on this for days and have had no success. I've tried every possible fix I could think of, and trawled the internet for answers, but to no avail.

A: use this it will work:
net use z: \\SERVER\d$ /user:<Username> <Password>
xcopy Z:\test\*.* e:\xcopy /j /v /y >> e:\backup_log.txt

Windows scheduler cannot see user map drives so i am creating map drive alias in the code using "net use" command and after that we can use xcopy command with the newly created alias and sending the out put of the xcopy command to "e:\backup_log.txt" file


text:
Q: Detect GPS in Polygon in Android Google Map API version 2 I am a new Android developer. I am developing an application about map using Google Map. I created a Polygon on the map and I want to detect through GPS when the position is within Polygon but I do not know how to detect it.
Could you please provide any example or solution? Thank you and sorry for my English.


text:
Q: WiX 3.8 Causing VS 2013 RC Catastrophic Failure I have been attempting to install WiX 3.8 for Visual Studio 2013 RC all morning. Every time I attempt to load the "Merge Module Project" or any WiX-related extensions, I am met with a catastrophic error such as this:
Catastrophic failure (Exception from HRESULT: 0x80000FFFF(E_UNEXPECTED))
Anyone else receive this error before? If so - how did you fix it?
Thanks.

A: I simply reinstalled VS 2013 RC, and the error was fixed.


text:
Q: Rails: Capybara can't log in user with Devise fixture data I'm writing integration tests for my app, and am trying to sign in the user using Capybara. When I create a User object in the test itself and enter that user's details, it passes and the user is logged in.
But when I try signing in using a fixture's details, the user never gets logged in. As can be seen in test.log, a 401 error is being returned:
Started POST "/users/sign_in" for 127.0.0.1 at 2015-10-14 18:54:21 +0000
Processing by Devise::SessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "user"=>{"email"=>"user@company.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Log in"}
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
Processing by Devise::SessionsController#new as HTML

Below are some other relevant files. The first two are the same test; the first version being the test that successfully logs the user in, and the second being the one that doesn't.
(Successfully logs in) project_flows_test.rb
require 'test_helper'

class ProjectFlowsTest < ActionDispatch::IntegrationTest

  test "fixtures debugging" do
    @user = User.create(email: "user@company.com", password: "useruser123")
    visit new_user_session_path
    fill_in "Email", with: @user.email
    fill_in "Password", with: @user.password
    click_button "Log in"
  end
end

(Doesn't log in and returns 401) project_flows_test.rb
require 'test_helper'

class ProjectFlowsTest < ActionDispatch::IntegrationTest

  test "fixtures debugging" do
    visit new_user_session_path
    fill_in "Email", with: users(:standard_user).email
    fill_in "Password", with: users(:standard_user).password
    click_button "Log in"
  end
end

A: If the devise user already exists inside your fixtures you need to make sure the password is encrypted or else your test will not pass.
Example:
# users.yml
user:
  email: someemail@email.com
  encrypted_password: <%= Devise::Encryptor.digest(User, "password") %>

A: You need to add password_confirmation during the creation as well as comfirmed_at.
@user = User.create(email: "user@company.com", password: "useruser123", password_confirmation: "useruser123", comfirmed_at: Time.new)


text:
Q: How to access the nested element of a ElementRef.nativeElement in angular I am using NG-ZORRO library and would like to customize it's DatePicker.
For example, I would like to highlight some of the days with different color like screenshot below, and the days that I would like to highlight are dynamic (based on a date list get from database):

My idea was create a directive, bind the host element with ElementRef and add custom class to the element with Renderer2. Here is what I have so far:

html
<nz-date-picker nzInline customDatePicker></nz-date-picker>

ts
@Directive({
    selector: `[customDatePicker]`
})
export class CustomDatePickerDirective {

    constructor(@Host() @Self() @Optional() public hostDatePicker: NzDatePickerComponent, renderer: Renderer2, hostElement: ElementRef) {
        console.log(this.hostDatePicker);
        renderer.addClass(hostElement.nativeElement, 'custom-color');
    }
}

The problem is renderer.addClass will only add the custom class at top element (<nz-date-picker> element), but the element I need to inject the custom class is within this element, I am thinking if there is any way I can look for the child/nested elements? I inspect the <nz-date-picker> element with devtools, the element that I will need to add the custom class is pretty deep inside (within the red box of the screenshot below):

A: You can use vanilla JS for this.
You can use the title attribute to easily pick a cell:
@Directive({
  selector: `[customDatePicker]`,
})
export class CustomDatePickerDirective {
  @Input() highlights: {day: string, color: string}[] = [];
  constructor(private hostElement: ElementRef) {};

  ngAfterViewInit() {
    const datePicker = this.hostElement.nativeElement as HTMLElement;
    for (const h of this.highlights) {
      const cell = datePicker.querySelector<HTMLElement>(`[title='${h.day}']`);
      cell.style.backgroundColor = h.color;
    }
  }
}

<nz-date-picker nzInline customDatePicker [highlights]="highlights"></nz-date-picker>

export class AppComponent {
  highlights = [
    { day: '7/8/2022', color: 'red' },
    { day: '7/18/2022', color: 'green' },
  ];
}

Of course you can set classes instead of just colors. The syntax is cell.classList.add('className').
stackblitz: https://stackblitz.com/edit/angular-ivy-wap1jw?file=src/app/custom.directive.ts


text:
Q: Last item of array enters even by using foreach laravel 5.7 I am making a project in Laravel 5.7, so I have a field in which user can select multiple values in a field (I have used select2 plugin for that), if I dd($request->veryeasy) it results in an array containing all values selected in the form field, but when I insert the array into database using foreach loop, the last value saves only in the db, my code:
//dd($request->veryeasy);
$diffi_lvl_sbj_type = new DiffiLvlSbjType;
foreach ($request->veryeasy as $veryeasy) {
    $diffi_lvl_sbj_type->sbj_type_id = $veryeasy;
    $diffi_lvl_sbj_type->difficulty_level_id = 1;
    $diffi_lvl_sbj_type->subject_id = $request->subject_id;
    $diffi_lvl_sbj_type->save();
}

A: You created "$diffi_lvl_sbj_type" outside of the foreach loop. But you want to store multiple records. For multiple records, we need to have multiple "diffi_lvl_sbj_type" variables.
How about this one ?
foreach ($request->veryeasy as $veryeasy) {
   $diffi_lvl_sbj_type = new DiffiLvlSbjType;
    $diffi_lvl_sbj_type->sbj_type_id = $veryeasy;
    $diffi_lvl_sbj_type->difficulty_level_id = 1;
    $diffi_lvl_sbj_type->subject_id = $request->subject_id;
    $diffi_lvl_sbj_type->save();
}