text:
Q: certificate is valid for ingress.local, not gitlab.mydomain I'm new to Kubernetes.

*

*I have installed a freshly new Kubernetes Cluster by using RKE (rancher tool for creating k8 clusters).

*I added the gitlab chart (https://charts.gitlab.io/) and launch it.

*Being on several issues with PersistentStorage, etc that I managed to resolve.

But I'm now stuck on one last issue: the pod for gitlab-runner is failing with the following logs:
ERROR: Registering runner... failed runner=Mk5hMxa5 status=couldn't execute POST against https://gitlab.mydomain.com/api/v4/runners: Post https://gitlab.mydomain.com/api/v4/runners: x509: certificate is valid for ingress.local, not gitlab.mydomain.com
PANIC: Failed to register this runner. Perhaps you are having network problems

Description of the certificate using kubectl describe certificate gitlab-gitlab-tls -n gitlab:
Name:         gitlab-gitlab-tls
Namespace:    gitlab
Labels:       app=unicorn
              chart=unicorn-2.4.6
              heritage=Tiller
              io.cattle.field/appId=gitlab
              release=gitlab
Annotations:  <none>
API Version:  certmanager.k8s.io/v1alpha1
Kind:         Certificate
Metadata:
  Creation Timestamp:  2019-11-13T13:49:10Z
  Generation:          3
  Owner References:
    API Version:           extensions/v1beta1
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Ingress
    Name:                  gitlab-unicorn
    UID:                   5640645f-550b-4073-bdf0-df8b089b0c94
  Resource Version:        6824
  Self Link:               /apis/certmanager.k8s.io/v1alpha1/namespaces/gitlab/certificates/gitlab-gitlab-tls
  UID:                     30ac32bd-c7f3-4f9b-9e3b-966b6090e1a9
Spec:
  Acme:
    Config:
      Domains:
        gitlab.mydomain.com
      http01:
        Ingress Class:  gitlab-nginx
  Dns Names:
    gitlab.mydomain.com
  Issuer Ref:
    Kind:       Issuer
    Name:       gitlab-issuer
  Secret Name:  gitlab-gitlab-tls
Status:
  Conditions:
    Last Transition Time:  2019-11-13T13:49:10Z
    Message:               Certificate issuance in progress. Temporary certificate issued.
    Reason:                TemporaryCertificate
    Status:                False
    Type:                  Ready
Events:                    <none>

Description of the issuer using kubectl describe issuer gitlab-issuer -n gitlab:
Name:         gitlab-issuer
Namespace:    gitlab
Labels:       app=certmanager-issuer
              chart=certmanager-issuer-0.1.0
              heritage=Tiller
              release=gitlab
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"certmanager.k8s.io/v1alpha1","kind":"Issuer","metadata":{"annotations":{},"creationTimestamp":"2019-11-13T13:49:10Z","gener...
API Version:  certmanager.k8s.io/v1alpha1
Kind:         Issuer
Metadata:
  Creation Timestamp:  2019-11-13T13:49:10Z
  Generation:          4
  Resource Version:    24537
  Self Link:           /apis/certmanager.k8s.io/v1alpha1/namespaces/gitlab/issuers/gitlab-issuer
  UID:                 b9971d7a-5220-47ca-a7f9-607aa3f9be4f
Spec:
  Acme:
    Email:  mh@mydomain.com
    http01:
    Private Key Secret Ref:
      Name:  gitlab-acme-key
    Server:  https://acme-v02.api.letsencrypt.org/directory
Status:
  Acme:
    Last Registered Email:  mh@mydomain.com
    Uri:                    https://acme-v02.api.letsencrypt.org/acme/acct/71695690
  Conditions:
    Last Transition Time:  2019-11-13T13:49:12Z
    Message:               The ACME account was registered with the ACME server
    Reason:                ACMEAccountRegistered
    Status:                True
    Type:                  Ready
Events:                    <none>

Description of the challenge using kubectl describe challenges.certmanager.k8s.io -n gitlab gitlab-gitlab-tls-3386074437-0:
Name:         gitlab-gitlab-tls-3386074437-0
Namespace:    gitlab
Labels:       acme.cert-manager.io/order-name=gitlab-gitlab-tls-3386074437
Annotations:  <none>
API Version:  certmanager.k8s.io/v1alpha1
Kind:         Challenge
Metadata:
  Creation Timestamp:  2019-11-13T13:49:15Z
  Finalizers:
    finalizer.acme.cert-manager.io
  Generation:  4
  Owner References:
    API Version:           certmanager.k8s.io/v1alpha1
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Order
    Name:                  gitlab-gitlab-tls-3386074437
    UID:                   1f01771e-2e38-491f-9b2d-ab5f4fda60e2
  Resource Version:        6915
  Self Link:               /apis/certmanager.k8s.io/v1alpha1/namespaces/gitlab/challenges/gitlab-gitlab-tls-3386074437-0
  UID:                     4c115a6f-a76f-4859-a5db-6acd9c039d71
Spec:
  Authz URL:  https://acme-v02.api.letsencrypt.org/acme/authz-v3/1220588820
  Config:
    http01:
      Ingress Class:  gitlab-nginx
  Dns Name:           gitlab.mydomain.com
  Issuer Ref:
    Kind:    Issuer
    Name:    gitlab-issuer
  Key:       lSJdy9Os7BmI56EQCkcEl8t36pcR1hWNjri2Vvq0iv8.lPWns02SmS3zXwFzHdma_RyhwwlzWLRDkdlugFXDlZY
  Token:     lSJdy9Os7BmI56EQCkcEl8t36pcR1hWNjri2Vvq0iv8
  Type:      http-01
  URL:       https://acme-v02.api.letsencrypt.org/acme/chall-v3/1220588820/AwsnPw
  Wildcard:  false
Status:
  Presented:   true
  Processing:  true
  Reason:      Waiting for http-01 challenge propagation: wrong status code '404', expected '200'
  State:       pending
Events:        <none>

Logs found in cert-manager pod:
I1113 14:20:21.857235       1 pod.go:58] cert-manager/controller/challenges/http01/selfCheck/http01/ensurePod "level"=0 "msg"="found one existing HTTP01 solver pod" "dnsName"="gitlab.mydomain.com" "related_resource_kind"="Pod" "related_resource_name"="cm-acme-http-solver-ttkmj" "related_resource_namespace"="gitlab" "resource_kind"="Challenge" "resource_name"="gitlab-gitlab-tls-3386074437-0" "resource_namespace"="gitlab" "type"="http-01"
I1113 14:20:21.857458       1 service.go:43] cert-manager/controller/challenges/http01/selfCheck/http01/ensureService "level"=0 "msg"="found one existing HTTP01 solver Service for challenge resource" "dnsName"="gitlab.mydomain.com" "related_resource_kind"="Service" "related_resource_name"="cm-acme-http-solver-sdlw7" "related_resource_namespace"="gitlab" "resource_kind"="Challenge" "resource_name"="gitlab-gitlab-tls-3386074437-0" "resource_namespace"="gitlab" "type"="http-01"
I1113 14:20:21.857592       1 ingress.go:91] cert-manager/controller/challenges/http01/selfCheck/http01/ensureIngress "level"=0 "msg"="found one existing HTTP01 solver ingress" "dnsName"="gitlab.mydomain.com" "related_resource_kind"="Ingress" "related_resource_name"="cm-acme-http-solver-7jzwk" "related_resource_namespace"="gitlab" "resource_kind"="Challenge" "resource_name"="gitlab-gitlab-tls-3386074437-0" "resource_namespace"="gitlab" "type"="http-01"
E1113 14:20:21.864785       1 sync.go:183] cert-manager/controller/challenges "msg"="propagation check failed" "error"="wrong status code '404', expected '200'" "dnsName"="gitlab.mydomain.com" "resource_kind"="Challenge" "resource_name"="gitlab-gitlab-tls-3386074437-0" "resource_namespace"="gitlab" "type"="http-01"

*

*The DNS gitlab.mydomain.com is set to point to the IP of my LoadBalancer where NGINX is running.

*If I go to https://gitlab.mydomain.com in the browser:

*

*The browser is saying the connexion is not secure

*The result is "default backend - 404".

Edits
Description of the ingress-controller by using kubectl describe svc gitlab-nginx-ingress-controller -n gitlab:
Name:              gitlab-nginx-ingress-controller
Namespace:         gitlab
Labels:            app=nginx-ingress
                   chart=nginx-ingress-0.30.0-1
                   component=controller
                   heritage=Tiller
                   io.cattle.field/appId=gitlab
                   release=gitlab
Annotations:       field.cattle.io/ipAddresses: null
                   field.cattle.io/targetDnsRecordIds: null
                   field.cattle.io/targetWorkloadIds: null
Selector:          <none>
Type:              ExternalName
IP:
External Name:     gitlab.mydomain.com
Port:              http  80/TCP
TargetPort:        http/TCP
NodePort:          http  31487/TCP
Endpoints:         10.42.0.7:80,10.42.1.9:80,10.42.2.12:80
Port:              https  443/TCP
TargetPort:        https/TCP
NodePort:          https  31560/TCP
Endpoints:         10.42.0.7:443,10.42.1.9:443,10.42.2.12:443
Port:              gitlab-shell  22/TCP
TargetPort:        gitlab-shell/TCP
NodePort:          gitlab-shell  30539/TCP
Endpoints:         10.42.0.7:22,10.42.1.9:22,10.42.2.12:22
Session Affinity:  None
Events:            <none>

Running kubectl get ingress -n gitlab gives me a bunch of ingress:
NAME                        HOSTS                 ADDRESS             PORTS     AGE
cm-acme-http-solver-5rjg4   minio.mydomain.com      gitlab.mydomain.com   80        4d23h
cm-acme-http-solver-7jzwk   gitlab.mydomain.com     gitlab.mydomain.com   80        4d23h
cm-acme-http-solver-tzs25   registry.mydomain.com   gitlab.mydomain.com   80        4d23h
gitlab-minio                minio.mydomain.com      gitlab.mydomain.com   80, 443   4d23h
gitlab-registry             registry.mydomain.com   gitlab.mydomain.com   80, 443   4d23h
gitlab-unicorn              gitlab.mydomain.com     gitlab.mydomain.com   80, 443   4d23h

Description of the gitlab-unicorn by using kubectl describe ingress  gitlab-unicron -n gitlab
Name:             gitlab-unicorn
Namespace:        gitlab
Address:          gitlab.mydomain.com
Default backend:  default-http-backend:80 (<none>)
TLS:
  gitlab-gitlab-tls terminates gitlab.mydomain.com
Rules:
  Host               Path  Backends
  ----               ----  --------
  gitlab.mydomain.com
                     /                gitlab-unicorn:8181 (10.42.0.9:8181,10.42.1.8:8181)
                     /admin/sidekiq   gitlab-unicorn:8080 (10.42.0.9:8080,10.42.1.8:8080)
Annotations:
  certmanager.k8s.io/issuer:                          gitlab-issuer
  field.cattle.io/publicEndpoints:                    [{"addresses":[""],"port":443,"protocol":"HTTPS","serviceName":"gitlab:gitlab-unicorn","ingressName":"gitlab:gitlab-unicorn","hostname":"gitlab.mydomain.com","path":"/","allNodes":false},{"addresses":[""],"port":443,"protocol":"HTTPS","serviceName":"gitlab:gitlab-unicorn","ingressName":"gitlab:gitlab-unicorn","hostname":"gitlab.mydomain.com","path":"/admin/sidekiq","allNodes":false}]
  kubernetes.io/ingress.class:                        gitlab-nginx
  kubernetes.io/ingress.provider:                     nginx
  nginx.ingress.kubernetes.io/proxy-body-size:        512m
  nginx.ingress.kubernetes.io/proxy-connect-timeout:  15
  nginx.ingress.kubernetes.io/proxy-read-timeout:     600
Events:                                               <none>

Description of cm-acme-http-solver-7jzwk by using kubectl describe ingress cm-acme-http-solver-7jzwk  -n gitlab:
Name:             cm-acme-http-solver-7jzwk
Namespace:        gitlab
Address:          gitlab.mydomain.com
Default backend:  default-http-backend:80 (<none>)
Rules:
  Host               Path  Backends
  ----               ----  --------
  gitlab.mydomain.com
                     /.well-known/acme-challenge/lSJdy9Os7BmI56EQCkcEl8t36pcR1hWNjri2Vvq0iv8   cm-acme-http-solver-sdlw7:8089 (10.42.2.19:8089)
Annotations:
  field.cattle.io/publicEndpoints:                     [{"addresses":[""],"port":80,"protocol":"HTTP","serviceName":"gitlab:cm-acme-http-solver-sdlw7","ingressName":"gitlab:cm-acme-http-solver-7jzwk","hostname":"gitlab.mydomain.com","path":"/.well-known/acme-challenge/lSJdy9Os7BmI56EQCkcEl8t36pcR1hWNjri2Vvq0iv8","allNodes":false}]
  kubernetes.io/ingress.class:                         gitlab-nginx
  nginx.ingress.kubernetes.io/whitelist-source-range:  0.0.0.0/0,::/0
Events:                                                <none>

Ports open on my LoadBalancer and on every nodes of my cluster (I know I should close somes but I will first manage to make my gitlab setup working):
80/tcp                     ALLOW       Anywhere
443/tcp                    ALLOW       Anywhere
22/tcp                     ALLOW       Anywhere
2376/tcp                   ALLOW       Anywhere
2379/tcp                   ALLOW       Anywhere
2380/tcp                   ALLOW       Anywhere
6443/tcp                   ALLOW       Anywhere
6783/tcp                   ALLOW       Anywhere
6783:6784/udp              ALLOW       Anywhere
8472/udp                   ALLOW       Anywhere
4789/udp                   ALLOW       Anywhere
9099/tcp                   ALLOW       Anywhere
10250/tcp                  ALLOW       Anywhere
10254/tcp                  ALLOW       Anywhere
30000:32767/tcp            ALLOW       Anywhere
30000:32767/udp            ALLOW       Anywhere
80/tcp (v6)                ALLOW       Anywhere (v6)
443/tcp (v6)               ALLOW       Anywhere (v6)
22/tcp (v6)                ALLOW       Anywhere (v6)
2376/tcp (v6)              ALLOW       Anywhere (v6)
2379/tcp (v6)              ALLOW       Anywhere (v6)
2380/tcp (v6)              ALLOW       Anywhere (v6)
6443/tcp (v6)              ALLOW       Anywhere (v6)
6783/tcp (v6)              ALLOW       Anywhere (v6)
6783:6784/udp (v6)         ALLOW       Anywhere (v6)
8472/udp (v6)              ALLOW       Anywhere (v6)
4789/udp (v6)              ALLOW       Anywhere (v6)
9099/tcp (v6)              ALLOW       Anywhere (v6)
10250/tcp (v6)             ALLOW       Anywhere (v6)
10254/tcp (v6)             ALLOW       Anywhere (v6)
30000:32767/tcp (v6)       ALLOW       Anywhere (v6)
30000:32767/udp (v6)       ALLOW       Anywhere (v6)

kubectl get pods -n gitlab
cm-acme-http-solver-4d8s5                               1/1     Running            0          5d
cm-acme-http-solver-ttkmj                               1/1     Running            0          5d
cm-acme-http-solver-ws7kv                               1/1     Running            0          5d
gitlab-certmanager-57bc6fb4fd-6rfds                     1/1     Running            0          5d
gitlab-gitaly-0                                         1/1     Running            0          5d
gitlab-gitlab-exporter-57b99467d4-knbgk                 1/1     Running            0          5d
gitlab-gitlab-runner-64b74bcd59-mxwvm                   0/1     CrashLoopBackOff   10         55m
gitlab-gitlab-shell-cff8b68f7-zng2c                     1/1     Running            0          5d
gitlab-gitlab-shell-cff8b68f7-zqvfr                     1/1     Running            0          5d
gitlab-issuer.1-lqs7c                                   0/1     Completed          0          5d
gitlab-migrations.1-c4njn                               0/1     Completed          0          5d
gitlab-minio-75567fcbb6-jjxhw                           1/1     Running            6          5d
gitlab-minio-create-buckets.1-6zljh                     0/1     Completed          0          5d
gitlab-nginx-ingress-controller-698fbc4c64-4wt97        1/1     Running            0          5d
gitlab-nginx-ingress-controller-698fbc4c64-5kv2h        1/1     Running            0          5d
gitlab-nginx-ingress-controller-698fbc4c64-jxljq        1/1     Running            0          5d
gitlab-nginx-ingress-default-backend-6cd54c5f86-2jrkd   1/1     Running            0          5d
gitlab-nginx-ingress-default-backend-6cd54c5f86-cxlmx   1/1     Running            0          5d
gitlab-postgresql-66d8d9574b-hbx78                      2/2     Running            0          5d
gitlab-prometheus-server-6fb685b9c7-c8bqj               2/2     Running            0          5d
gitlab-redis-7668c4d476-tcln5                           2/2     Running            0          5d
gitlab-registry-7bb984c765-7ww6j                        1/1     Running            0          5d
gitlab-registry-7bb984c765-t5jjq                        1/1     Running            0          5d
gitlab-sidekiq-all-in-1-8fd95bf7b-hfnjz                 1/1     Running            0          5d
gitlab-task-runner-5cd7bf5bb9-gnv8p                     1/1     Running            0          5d
gitlab-unicorn-864bd864f5-47zxg                         2/2     Running            0          5d
gitlab-unicorn-864bd864f5-gjms2                         2/2     Running            0          5d

Their are 3 acme-http-solver:

*

*One for registry.mydomain.com

*One for minio.mydomain.com

*One for gitlab.mydomain.com

The logs for the one pointing to gitlab.mydomain.com:
I1113 13:49:21.207782       1 solver.go:39] cert-manager/acmesolver "level"=0 "msg"="starting listener"  "expected_domain"="gitlab.mydomain.com" "expected_key"="lSJdy9Os7BmI56EQCkcEl8t36pcR1hWNjri2Vvq0iv8.lPWns02SmS3zXwFzHdma_RyhwwlzWLRDkdlugFXDlZY" "expected_token"="lSJdy9Os7BmI56EQCkcEl8t36pcR1hWNjri2Vvq0iv8" "listen_port"=8089

Results of kubectl get svc -n gitlab:
cm-acme-http-solver-48b2j                 NodePort       10.43.58.52     <none>              8089:30090/TCP                            5d23h
cm-acme-http-solver-h42mk                 NodePort       10.43.23.141    <none>              8089:30415/TCP                            5d23h
cm-acme-http-solver-sdlw7                 NodePort       10.43.86.27     <none>              8089:32309/TCP                            5d23h
gitlab-gitaly                             ClusterIP      None            <none>              8075/TCP,9236/TCP                         5d23h
gitlab-gitlab-exporter                    ClusterIP      10.43.187.247   <none>              9168/TCP                                  5d23h
gitlab-gitlab-shell                       ClusterIP      10.43.246.124   <none>              22/TCP                                    5d23h
gitlab-minio-svc                          ClusterIP      10.43.117.249   <none>              9000/TCP                                  5d23h
gitlab-nginx-ingress-controller           ExternalName   <none>          gitlab.mydomain.com   80:31487/TCP,443:31560/TCP,22:30539/TCP   5d23h
gitlab-nginx-ingress-controller-metrics   ClusterIP      10.43.152.252   <none>              9913/TCP                                  5d23h
gitlab-nginx-ingress-controller-stats     ClusterIP      10.43.173.191   <none>              18080/TCP                                 5d23h
gitlab-nginx-ingress-default-backend      ClusterIP      10.43.116.121   <none>              80/TCP                                    5d23h
gitlab-postgresql                         ClusterIP      10.43.97.139    <none>              5432/TCP                                  5d23h
gitlab-prometheus-server                  ClusterIP      10.43.67.220    <none>              80/TCP                                    5d23h
gitlab-redis                              ClusterIP      10.43.36.138    <none>              6379/TCP,9121/TCP                         5d23h
gitlab-registry                           ClusterIP      10.43.54.244    <none>              5000/TCP                                  5d23h
gitlab-unicorn                            ClusterIP      10.43.76.61     <none>              8080/TCP,8181/TCP                         5d23h

Logs of the pod gitlab-nginx-ingress-controller-698fbc4c64-jxljq (others nginx-ingress-controller gives same logs): https://textuploader.com/1o9we

Any hint on what could be wrong in my configuration ?
Fell free to ask for more information on my setup.
Many thanks.

A: Well the issue is, Gitlab requires a valid SSL certificate for the domain in question. Which you do not seem to have according to the output of:
E1113 14:20:21.864785       1 sync.go:183] cert-manager/controller/challenges "msg"="propagation check failed" "error"="wrong status code '404', expected '200'" "dnsName"="gitlab.mydomain.com" "resource_kind"="Challenge" "resource_name"="gitlab-gitlab-tls-3386074437-0" "resource_namespace"="gitlab" "type"="http-01"

Status:
  Presented:   true
  Processing:  true
  Reason:      Waiting for http-01 challenge propagation: wrong status code '404', expected '200'
  State:       pending

The http-01 challenge is where it will try to do a web request to your domain, and it should return a 200 HTTP response. When you said yourself that https://gitlab.mydomain.com gives you a 404 response (hence it will fail to issue a valid certificate). To further diagnose this, check the output of the ingress responsible for the domain, and follow it down the "chain" until you identify where the 404 is being responded by.

A: The http01 challenge relies on port 80 (http) to be exposed to be able to answer the challenge. The option controller.service.enableHttp configures http, and is enabled by default (see here. But even if you've not touched this config, there might be an upstream component (i.e. a firewall) that blocks traffic on port 80.
Could you check if your ingress Service is listening on port 80, and reachable from the internet? You can try to go to your public IP on port 80 via a browser to check if you get a response from the ingress controller (or a backend).


text:
Q: Switch to different Activity with buttons Android I have buttons on a screen, I want to go through different activities when I push the buttons on the screen.
the application is working but the button stops.
Please, help me. I'm learning android. Sorry bad English.
My class file;
public void git1(View view) {

    this.view = view;
    Intent intent1 = new Intent(getApplicationContext(),first.class);
    startActivity(intent1);

}

public void git2(View view) {

    this.view = view;
    Intent intent2 = new Intent(getApplicationContext(),second.class);
    startActivity(intent2);

}

public void git3(View view) {

    this.view = view;
    Intent intent = new Intent(getApplicationContext(),third.class);
    startActivity(intent);

}

public void git4(View view) {

    this.view = view;
    Intent intent = new Intent(getApplicationContext(),fourth.class);
    startActivity(intent);

}

public void git5(View view) {

    this.view = view;
    Intent intent = new Intent(getApplicationContext(),fifth.class);
    startActivity(intent);

}

That's how the design looks.

My XML file;
<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Anket Seçiniz :"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="16dp" />

<Button
    android:id="@+id/s1button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="45dp"
    android:onClick="git1"
    android:text="1. Hasta Memnuniyeti Anketi "
    android:textAlignment="textStart"
    app:layout_constraintBottom_toTopOf="@+id/s2button"
    app:layout_constraintStart_toStartOf="@+id/s2button" />

<Button
    android:id="@+id/s2button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/s1button"
    android:layout_marginTop="34dp"
    android:onClick="git2"
    android:text="2. Diş Bakımı Anketi "
    android:textAlignment="textStart"
    app:layout_constraintBottom_toTopOf="@+id/s3button"
    app:layout_constraintStart_toStartOf="@+id/s3button" />

<Button
    android:id="@+id/s3button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/s2button"
    android:layout_marginTop="25dp"
    android:onClick="git3"
    android:text="3. Türkiye Geneli Fenotip Anketi "
    android:textAlignment="textStart"
    app:layout_constraintStart_toStartOf="@+id/s4button"
    tools:layout_editor_absoluteY="231dp" />

<Button
    android:id="@+id/s4button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/s3button"
    android:layout_marginTop="31dp"
    android:onClick="git4"
    android:text="4. Yabani Hayvanlar Anketi"
    android:textAlignment="textStart"
    app:layout_constraintStart_toStartOf="@+id/s5button"
    tools:layout_editor_absoluteY="307dp" />

<Button
    android:id="@+id/s5button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/s4button"
    android:layout_marginTop="37dp"
    android:onClick="git5"
    android:text="5. ÜRÜN MEMNUNİYET ANKETİ"
    android:textAlignment="textStart"
    app:layout_constraintTop_toBottomOf="@+id/s4button"
    tools:layout_editor_absoluteX="31dp" />

A: For example:
@Override
public void onCreate(Bundle savedInstanceState) {
Button b1 = (Button) findViewById(R.id.buttonplay);
b1.setOnClickListener(this);
//{YOUR APP}
}

@Override
public void onClick(View v) {
// Perform action on click
switch(v.getId()) {
case R.id.buttonplay:
    //Play voicefile
    MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
    break;
case R.id.buttonstop:
    //Stop MediaPlayer
    MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
    break;
 }

}}

I hope I've helped

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Upload a file MVC php I have this code:
     // assign params by methods
       switch($method){
        case "GET": // view
            // we need to remove _route in the $_GET params
            unset($_GET['_route']);
            // merege the params
            $this->params_ = array_merge($this->params_, $_GET);
        break;
        case "POST": // create
        case "PUT":  // update
        case "DELETE": // delete
        {
            // ignore the file upload
            if(!array_key_exists('HTTP_X_FILE_NAME',$_SERVER))
            {
                if($method == "POST"){
                    $this->params_ = array_merge($this->params_,      $_POST);
                }else{
                    // temp params
                    $p = array();
                    // the request payload
                    $content = file_get_contents("php://input");
                    // parse the content string to check we have [data] field or not
                    parse_str($content, $p);
                    // if we have data field
                    $p = json_decode($content, true);
                    // merge the data to existing params
                    $this->params_ = array_merge($this->params_, $p);
                }
            }
        }
        break;
    }

from http://www.elvishsu.com/2014/01/start-your-own-mvc-framework-with-php.html#.V7lBVnUrLxs
Please can anyone tell me how to deal with file uploads in this situation
I mean how should I deal with:
 if(array_key_exists('HTTP_X_FILE_NAME',$_SERVER))

Thanks

A: This is what I resolve into:
// assign params by methods
    switch($method){
        case "GET": // view
            // we need to remove _route in the $_GET params
            unset($_GET['_route']);
            // merege the params
            $this->params_ = array_merge($this->params_, $_GET);
        break;
        case "POST": // create
        case "PUT":  // update
        case "DELETE": // delete
        {

                if($method == "POST" && isset($_FILES)){
                    if (!empty($_FILES))
                    {
                        $this->params_ = array_merge($this->params_, $_POST);
                        $this->params_ = array_merge($this->params_, $_FILES);
                    }else{
                        $this->params_ = array_merge($this->params_, $_POST);
                    }
                }else{
                    // temp params
                    $p = array();
                    // the request payload
                    $content = file_get_contents("php://input");
                    // parse the content string to check we have [data] field or not
                    parse_str($content, $p);
                    // if we have data field
                    $p = json_decode($content, true);
                    // merge the data to existing params
                    $this->params_ = array_merge($this->params_, $p);
                }

        }
        break;
    }

I put it here in case anyone is also trying to build MVC from that tutorial and find it difficult to upload
Thanks everyone


text:
Q: Getting 404 error after running serve -l ./build after building react-app I get 404 error when I try to run this command
serve -l build

after building a react app, this is my ./app.js and react-router that is implemented inside the file.
import React from "react";
import Header from "./Components/Header";
import LeafletContainer from "./container/LeafletContainer";
import SignUp from "./Components/SignUp";
import Profile from "./Components/Profile";
import SavedLocations from "./Components/SavedLocations";
import Swiper from "./Components/swiper";

import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

const Slash = () => {
  return (
    <>
      <Header />
      <LeafletContainer />
      <Swiper />
    </>
  );
};

function App() {
  return (
    <div className="wrapper">
      <Router>
        <Switch>
          <Route exact path="/" component={Slash} />
          <Route exact path="/signup" component={SignUp} />
          <Route exact path="/profile" component={Profile} />
          <Route exact path="/locations" component={SavedLocations} />
        </Switch>
      </Router>
    </div>
  );
}

export default App;

and also I have defined this line in ./package.json
{
...,
    "homepage": "."
...,
}

A: With -l flag you should provide a endpoint/ports which should listen. I suppose you should use -s flag in your case:
serve -s build

Or you can add port to your command like this:
serve -l 3232 build

Then you can find your app on localhost:3232


text:
Q: How can i use uitableview cell for performing segue I started to learn Swift 2 weeks ago. With some courses and youtube videos, I learn basics of uitableview but I couldn't get how can I use specific table view cell like a button.
What I wanna do?
I am trying to use the sidebar menu(https://github.com/yannickl/FlowingMenu) for my project, everything is cool and working okay instead of using cells.
In every basic tutorial people showing how to use segue with uitableview but they only use 2 pages and independent from cell value, no matter what text in your cell it calls segue for the second controller.
I want to use the sidebar menu with cells and if my cell value is "main menu" I want to perform "toMainMenu" segue.
I only know using cells with arrays don't know is there any other way for work with cells, and my main goal is cell-specific segue.
I watched a lot of tutorials but can't find anything useful for me.
import UIKit

import FlowingMenu
class SideBarMenu: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var surnameLabel: UILabel!
@IBOutlet weak var topBar: UINavigationBar!
@IBOutlet weak var backButtonItem: UIBarButtonItem!
@IBOutlet weak var userTableView: UITableView!
@IBOutlet weak var profilePic: UIImageView!
let CellName  = "Menu"
let mainColor = UIColor(hex: 0xC4ABAA)
var sections = ["Main Menu", "Settings", "Profile"]
override func viewDidLoad() {
    super.viewDidLoad()
    userTableView.delegate = self
    userTableView.dataSource = self
    nameLabel.text = Helper.name
    surnameLabel.text = Helper.surname

    topBar.tintColor              = .black
    topBar.barTintColor           = mainColor
    topBar.titleTextAttributes    = [
        NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Light", size: 22)!,
        NSAttributedString.Key.foregroundColor: UIColor.black
    ]
    userTableView.backgroundColor = mainColor
    view.backgroundColor          = mainColor
}

// MARK: - Managing the Status Bar

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

// MARK: - UITableView DataSource Methods

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = sections[indexPath.row]
    cell.contentView.backgroundColor = mainColor
    return cell
}

// MARK: - UITableView Delegate Methods

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("Select row at")
}
@IBAction func profileButton(_ sender: Any) {
    performSegue(withIdentifier: "toProfile", sender: nil)
}

}
I want to perform "toSettings" segue when "Settings" cell clicked.

A: Implement the UITableViewDelegate protocol method tableView(_:didSelectRowAt:) as below
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
   switch sections[indexPath.row] {
   case "Main Menu":
      performSegue(with: "toMainMenu", sender: nil)
   case "Settings":
      performSegue(with: "toSettings", sender: nil)
   case "Profile":
      performSegue(with: "toProfile", sender: nil)
   }
}

If you need to configure or pass some data to the destination controller, you can override the controller's prepare(for:sender:) method to get a reference, for example:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "toMainMenu" {
      let dvc = segue.destination as! MenuViewController
      // now you have a reference
   }
}

A: If I understand, your menu is a tableView, so you need to segue to the view you wanna open in the table didSelectAt

A: You can use override prepare for segue. so when you link your views with a segue you set an identifier for each one and can call whatever you need from there.


text:
Q: HC-05 bluetooth module on Arduino + Debugging I'm kind of stuck here. I have a HC-05 Bluetooth module - from ebay- and i'm testing it to make certain it works. I have uploaded the following sketch to the chip:
//////////////////////////////////////////////////////////////////////////////////

// REMIXED BY: TECHBITAR (HAZIM BITAR)
// LICENSE: PUBLIC DOMAIN
// DATE: MAY 2, 2012
// CONTACT: techbitar at gmail dot com

char INBYTE;
int  LED = 13; // LED on pin 13

void setup() {
  Serial.begin(9600);
  pinMode(LED, OUTPUT);
}

void loop() {
  Serial.println("Press 1 to turn Arduino pin 13 LED ON or 0 to turn it OFF:");
  while (!Serial.available());   // stay here so long as COM port is empty
  INBYTE = Serial.read();        // read next available byte
  if( INBYTE == '0' ) digitalWrite(LED, LOW);  // if it's a 0 (zero) tun LED off
  if( INBYTE == '1' ) digitalWrite(LED, HIGH); // if it's a 1 (one) turn LED on
  delay(50);
}

I have used three different bluetooth terminal on android as well as the TeraTerm terminal on WIN7 to test if the blutooth module successfully communicates. For whatever reason, all 4 receive the line Press 1 to turn Arduino pin 13 LED ON or 0 to turn it OFF:but when I enter 1 in the terminals and send it to the module, the LED does not turn on.
Note:
The LED works
I'm affirmative I've wired everything appropriately
My RX and TX serial lines must work otherwise I would not be able to upload the sketch.
Is it possible that the HC-05 is not working and is unable to receive information? What can I do to test otherwise?
Thanks alot!

A: Thanks @SunGa for the loop-back idea. It worked, so I can confirm the Bluetooth module is in good health. Reading through other forums to try to understand why pin 0 could not receive the serial signal sent by the Bluetooth module I discovered that this was a common issue. It so turns out that since RX and TX are hard wired to the USB to TTL converter chip on the board, sometimes the state of Pin 0 and Pin 1 get "stuck" and they can't be used appropriately ( which is unfortunate! and poor engineering imo).
I was able to successfully send and receive data by making use of the SoftwareSerial library
and remapping Pins 10 and 11 to RX and TX.
That said, If an AtMega chip was used as a stand alone microcontroller (e.g. DIYduino) then Pins 0 and 1 could be used to communicate to the Bluetooth module!
Hope this can help others who face the same issue

A: I am not at all familiar with Arduino. But can suggest you to configure loop-back connections at HC05 pins and test only communication between Android (or PC) terminal and HC05. This will figure out whether HC05 is working or not.

A: I have encountered the same problem and found an awesome solution. The solution exists as the library called SoftwareSerial.h". This library does really do wonders, as it helps in the most important things, "Debugging" the app that you are using, may it be android app or ios app.
I have used the following setup/apparatus:

*

*Adruino module

*LightBlue Explorer App(ios 10)

*HC-05 Bluetooth Module(BLE)
Please note: Connect ur Bluetooth rx pin to adriuno pin 9 and Bluetooth tx pin to adruino pin 10.
In this way you can use see the adruino board serial interface for debugging purpose.

#include <SoftwareSerial.h>
int state = 0;
SoftwareSerial Bluetooth(10,9);
int data;

void setup() {
  // put your setup code here, to run once:
  pinMode(4,OUTPUT);
  Serial.begin(9600);
  Bluetooth.begin(9600);
}

void loop() {
  if(Bluetooth.available() > 0)
  {
    data = Bluetooth.read();
    if(data == '1')
    {
      digitalWrite(4,HIGH);
      Serial.println("LED Turned ON");
    }
    else{
      digitalWrite(4,LOW);
      Serial.println("LED Turned OFF");
    }
    Serial.println(data);
  }
  delay(1000);
}

For more information, please refer Bluetooth Module Debugging


text:
Q: HOW can I list all the possibilities? Removing one coin from each of the triangles — more specifically, one a, one b, and one c — forms a pattern (like the example shown).

Every possibility is listed below (ignore the circles and squares around some of them).

How can you systematically list all of the possibilities, so that you get that answer?

A: We have to derive the underlying structure of the problem, forgetting about the artistic paraphernalia. We have three lines of $a$,$b$, $c$ and should select one element from each numbered line and one element from each letterized column:
$$\left[\matrix{a_1&b_1&c_1\cr a_2&b_2&c_2\cr a_3&b_3&c_3\cr}\right]\ .$$
As in a $3\times3$-determinant there are $6$ ways to do this: Select one object from the first line ($3$ ways), then one allowed element from the second line ($2$ ways) and then the only remaining element from the third line.
You can arrange the admissible selection lexicographically as follows:
$$a_1b_2c_3,\ a_1b_3c_2, \ b_1a_2c_3, \ b_1c_2a_3, \ c_1a_2b_3, \ c_1b_3a_2\ .$$


text:
Q: Spark DataFrame mapPartitions I need to proceed distributed calculation on Spark DataFrame invoking some arbitrary (not SQL) logic on chunks of DataFrame.
I did:
def some_func(df_chunk):
    pan_df = df_chunk.toPandas()
    #whatever logic here

df = sqlContext.read.parquet(...)
result = df.mapPartitions(some_func)

Unfortunatelly it leads to:

AttributeError: 'itertools.chain' object has no attribute 'toPandas'

I expected to have spark DataFrame object within each map invocation, instead I got 'itertools.chain'. Why? And how to overcome this?

A: Try this:
>>> columns = df.columns
>>> df.rdd.mapPartitions(lambda iter: [pd.DataFrame(list(iter), columns=columns)])


text:
Q: EXC_BAD_ACCESS error with iOS8 ABMembersViewController Since iOS8 went live the other day, I've started to get lots of crash reports to do with address book / contact functionality. It's one of those annoying ones where the stack trace gives no clues about where in my code the problem originates. I've tried reproducing this in the iOS8 simulator by using the most obviously related functionality, but so far without joy (I don't own any devices running iOS8 yet).
The actual error is: Crashed: com.apple.main-thread
EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0x0000000000000010
Here's the stack trace:
0   libobjc.A.dylib  objc_msgSend + 16 respondsToSelector:
1   AddressBookUI    -[ABMembersViewController membersController:shouldAllowSelectingPersonWithRecordID:] + 100
2   AddressBookUI    -[ABMembersFilteredDataSource tableView:cellForRowAtIndexPath:] + 488
3   UIKit            -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 544
4   UIKit            -[UITableView _updateVisibleCellsNow:isRecursive:] + 2360
5   UIKit            -[UITableView layoutSubviews] + 172
6   UIKit            -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 572
7   QuartzCore       -[CALayer layoutSublayers] + 168
8   QuartzCore       CA::Layer::layout_if_needed(CA::Transaction*) + 320
9   QuartzCore       CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32
10  QuartzCore       CA::Context::commit_transaction(CA::Transaction*) + 276
11  QuartzCore       CA::Transaction::commit() + 436
12  QuartzCore       CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 80
13  CoreFoundation   __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
18  UIKit            UIApplicationMain + 1488
19  Prayer Partner   main.m line 14 main
20  libdyld.dylib     start + 4

I thought I'd post it here in case anybody has had any similar errors.


text:
Q: Como inserir dados no mysql via ajax + php + foundation 5 Queria saber como posso inserir dados no MySQL via Ajax + PHP utilizando o Framework Zurb Foundation 5? A propriedade "data-reveal-ajax" do framework já substitui uma função Ajax de inserção?

A: O data-reveal-ajax funciona simplesmente para abrir um modal com conteúdo de uma url ou uma pagina que faz alguma requisição ele por si só não é capaz de fazer requisições Ajax.


text:
Q: PL/SQL Function Json parsing error with google maps api I am trying to create a function that accepts a postcode, calls the google api then parses it and returns a sdo_geometry (longitude & latitude), how ever i am unable to get this function to work and not sure where i am going wrong, i did make one mistake since posting but corrected i still get a parse error.
Any help or suggestions for other methods would be greatful. also not sure why im down voted but i hope i can
CREATE OR REPLACE FUNCTION google_geocode( p_postcode varchar2 )
RETURN sdo_geometry IS
 l_http_req  utl_http.req;
 l_http_response  UTL_HTTP.resp;
 l_lat long;
 l_long long;
BEGIN

 l_http_req := utl_http.begin_request(
   url => 'https://maps.googleapis.com/maps/api/geocode/json?address=' || utl_url.escape(p_postcode));
 l_http_response := UTL_HTTP.get_response(l_http_req);

apex_json.parse (l_http_response);
--DBMS_OUTPUT.PUT_LINE(apex_json.get_number('results.location.lat'));
--DBMS_OUTPUT.PUT_LINE(apex_json.get_number('results.location.lng'));
l_lat := apex_json.get_number('results.location.lat');
l_long := apex_json.get_number('results.location.lng');

RETURN sdo_geometry
                    (
                    2001,
                    4326,
                    sdo_point_type(
                                   TO_NUMBER(l_lat),
                                   TO_NUMBER(l_long),
                                   null),
                    null,
                    null);
END google_geocode;

the errors im getting are, the first two i have since fixed but still get parsing error

A: The error you're getting is stating there is no definition of apex_json.parse that matches the arguments you are trying to pass it.
If you look at the documentation, you will see that there are four signatures for parse:
APEX_JSON.PARSE (
    p_values   in out nocopy t_values,
    p_source   in varchar2,
    p_strict   in boolean default true );

APEX_JSON.PARSE (
    p_values   in out nocopy t_values,
    p_source   in clob,
    p_strict   in boolean default true );

APEX_JSON.PARSE (
    p_source   IN VARCHAR2,
    p_strict   IN BOOLEAN DEFAULT TRUE );

APEX_JSON.PARSE (
    p_source   IN CLOB,
    p_strict   IN BOOLEAN DEFAULT TRUE );

Currently you are providing a single utl_http.resp, but there is no support for such a call.
You will need to read the data from your utl_http.resp object into a CLOB and then pass that to the parse procedure.

A: You need to change variable name:
l_http_req := utl_http.begin_request(
   url => 'https://maps.googleapis.com/maps/api/geocode/json?address='
           || utl_url.escape(p_postcode));

l_http_response := UTL_HTTP.get_response(l_http_request);
                                         -- should be l_http_req


text:
Q: Installing 4 memory modules in a dual-socket server motherboard with 16 memory slots I have a server board with two Xeon E5-2600 v3 processors and 16 memory slots. I ordered two quad-channel memory kits, but only one of them has arrived, so I only have four memory modules. Which slots should I install the memory modules into? The slots are labeled as follows:
p1a1 p1a2 p1b1 p1b2 p1c1 p1c2 p1d1 p1d2 p2a1 p2a2 p2b1 p2b2 p2c1 p2c2 p2d1 p2d2

A: Here's what the memory slot labels mean:

*

*The first two characters p1 and p2 refer to the processor to which the slot belongs. Each processor can access each others' memory but performance will be significantly degraded if accessing memory on a slot for a different processor. For more information, see the Wikipedia article on non-uniform memory access.

*The third character, which may be a, b, c, or d, refers to each of the four memory channels on each processor. Type E, EP, and EX processors starting from the Sandy Bridge generation (including your Haswell-EP processors) support quad-channel memory.

*The fourth character refers to the two memory slots for each memory channel. For optimal performance, you should populate all memory channels with one module each first before adding additional modules on each channel.

As you don't presently have enough memory modules to enable quad-channel mode for both processors, you should install two memory modules, using channels a and b, for each processor. The processors will fall back to dual-channel mode.
Therefore, you should install the modules in p1a1, p1b1, p2a1, and p2b1. When you get the other four memory modules, install them in p1c1, p1d1, p2c1, and p2d1.


text:
Q: ExecCommand CreateLink and IMG I use webbrowser-control (MSHTML Edit) in design mode. When I try to insert a hyperlink for a selected text it works fine. But when I try to insert a hyperlink for a selected picture I got the error:
Error 100
Function expected

Code:
var
 pCmd : OleVariant;
begin
 html_doc.execCommand('CreateLink', True, pCmd);
end;

How to insert a hyperlink in a picture in another way, different from using execCommand?


text:
Q: How to select distinct records based on multiple row values? I have a table
CREATE TABLE event
  uuid character varying(50),
  created timestamp without time zone DEFAULT now(),
  event_type character varying(50))

And the data is like this

I need to fetch the latest event_type that is 'NotSaved' or 'Saved' per uuid
Like in this case uuid_1234, Saved and uuid_1235, NotSaved.
I tried with distinct, subquery and max but didn't give correct result

A: use row_number()
select * from
 (
  select *,row_number() over(partition by uuid order by createdtimestamp desc) rn
 from event
) a where a.rn=1

and below also work
 SELECT DISTINCT ON (uuid )
    uuid , createdtimestamp
FROM event
ORDER BY event_timestamp DESC

A: One way to do this is to join the table with itself.
First, create the select statement to pull out the uuid and the latest created date specifying the required event types.
select uuid, max(created)
from event
where event_type in ('NotSaved', 'Saved')

Notice we can't get the event_type column (or any additional columns) in this statement. Only the uuid, and the max of created.
Then, using this select statement as an "inline table", join the event table to it to get the remaining columns.
select distinct e.uuid, e.created, e.event_type
from event e
inner join (select uuid, max(created)
            from event
            where event_type in ('NotSaved', 'Saved')) maxe
on e.uuid = maxe.uuid and e.created = maxe.created;

We give the inline table an alias, maxe, since it doesn't actually exist and we need a way to refer to it.  The alias e, for the event table is just for convenience, it makes the join condition easier to type and read.


text:
Q: What is page tables, pages, and page table entry? I am really confused about these 3 things and I have been trying to understand this for a good solid 2 hours and no luck.
Q.
If I have a 47-bit virtual address space with a page size of 16 KB and that page table entry takes 8 bytes. How many levels of page tables would be required to map the virtual address space if every page table is required to fit a single page?
I know what a page table is, but what exactly is the difference between a page table entry and a page? In the answer key, it starts off with this:
A 1-page page table contains 2^11 PTE (x8 bytes), pointing to 2^11 pages (addressing 2^25 bytes). Can someone explain to me where 2^11 pages came from?
More or less, I am confused about what it means by a page and what the difference is with a page table entry.

A: The logical address space into an array of PAGES. In your case a page is 16KB or 2^14 bytes.
The PAGE TABLE contains the mappings from pages to physical PAGE FRAMES where the size of the page frame is the same as the page size.
Your answer (but not question) states a page table entry is 8 bytes (2^3). Assuming that is correct you can fit 2^14 / 2^3 = 2^11 page table entries into a single page.
If you have a 2^47 bit address space, you'd need 2^47 / 2^14 = 2^33 page table entires to span the entire address space. You'd need 2^33 / 2^11 = 2^22 pages worth of page table entries.
This question presumes using nested page tables.
(2^11)^2 = 2^22
You then need two levels of page table.
The entire question is rather stupid, contrived, and does not reflect the real world. I cannot believe that operating systems are taught in this way.


text:
Q: Save edited data to mongodb database using reclinejs I had implemented the inline edit using the reclinejs in django and i am able to edit the data and update it,but when i refresh the page it revert back to old data, I tried many things but none worked.How can i save the edited data into the database.I am using mongodb as my database.
Below is the js(reclinejs) code by which i can edit the data.
(data_edit.js)
$(document).ready(function() {

var dataset = new recline.Model.Dataset({
    formUrl: formJSONUrl,
    dataUrl: mongoAPIUrl,
    backend: "MongoAPI"
});

dataset.fetch().done(function(dataset) {
    var grid = new recline.View.Grid({
  model: dataset
});
$('#data-grid').append(grid.el);

dataset.fetch().done(function(dataset) {
  if (console) {
    console.log(dataset.records);
  }
});

$('#save-button').bind('click', function() {
              //alert($(this).text());
              dataset.save();
            });

        });

      })
~

This is the html file code responsible for view
data_view.html
{% block content %}

{%  trans "Data View" %} {{ xform.title }}

          <form action="?" method="POST">
             {% csrf_token %}
  <input type="submit" value="Save">
  <input type="hidden" name="data" value="">
</form>


text:
Q: The orientation of the device is returned incorrectly in iOS 8.1.3 I am navigating from a controller to another controller(which invokes device camera), but found that the orientation of the second controller is returned by iOS as portrait, even though I am in portrait mode.
Inititally I was on portrait mode while I was in the first controller, then tilted the device to landscape mode and navigated to the next controller(which invoked camera).
I want to perform some activity only when the orientation is landscape, so i check this condition, but the control never comes into this even when I have the device in landscape.
if(orientation == UIDeviceOrientationLandscapeLeft || orientation == UIDeviceOrientationLandscapeRight)
{
  // perform an activity
}

A: You can get the accurate orientation by using [[UIApplication sharedApplication] statusBarOrientation] property. Click here for a quick comparison.


text:
Q: System.Reflection.MissingRuntimeArtifactException - in release mode I'm trying to compile UWP app. It runs fine in Debug mode, but when trying to run it in release mode I get this error:

Exception thrown: 'System.Reflection.MissingRuntimeArtifactException' in System.Private.Reflection.Core.dll
Additional information: MakeGenericMethod_NoMetadata, System.Linq.Enumerable.Distinct<System.Int32>(System.Collections.Generic.IEnumerable<System.Int32>).

When breaking in the exception in VS2015 also get this message (still release mode):

ExecutionEnvironment.cs not found

I found a similar issue/solution in SO, but that didn't work in my case: https://stackoverflow.com/a/31548178/4140832
I'm using the UWP SDK 1.1.
UPDATE: I also found this: http://dotnet.github.io/native/troubleshooter/method.html#
... but I'm unsure if this is the answer and unsure how to use the tool based on the information provided above.
UPDATE 2: .NET Native General Troubleshooting: https://msdn.microsoft.com/en-us/library/dn600643(v=vs.110).aspx

A: I found a solution. It turned out to be related to the particular combination of AutoMapper and .NET Native. Changing Runtime Directives was a detour in this particular case.
In my code I had a AutoMapper configuration that looks something like this:
Mapper.CreateMap<SomethingGood, ISomething>().As<SomethingBetter>();

This works when the app was not compiled to the .NET Native tool chain (i.e. when running in debug mode). However, when compiling for release this AutoMapper code breaks.
Also, in the class SomethingBetter I had more properties defined than what was defined in ISomething and the SomethingGood class. This was a mistake, but it went unnoticed in debug mode. When compiling to .NET Native the App would throw a 'System.Reflection.MissingRuntimeArtifactException'.
To track down this bugs I used the .NET Native debug engine. Without using this it was close to impossible to figure out that was the root cause for the exception.
This blog post explains using the .NET Native debugger very nicely: http://blogs.msdn.com/b/visualstudioalm/archive/2015/07/29/debugging-net-native-windows-universal-apps.aspx
Also, putting this try/catch at the end of all the AutoMapper.Mapper.CreateMap's was very helpful to track down the properties causing the issue:
        try
        {
            AutoMapper.Mapper.AssertConfigurationIsValid();
        }
        catch (Exception ex)
        {

            throw ex;
        }


text:
Q: Find the smallest number Given n numbers we need to find(if possible) the least number k in the range [a,b] such that each number is either divisible by k or divides k. Can we find such number k ?
Example: let n=4 and numbers are 1,20,5,2 and range is [8,16]. Ans is k=10 since each number is either divisible by k or divides k.
My observations: k=1 always if a=1. for other cases i thought of taking lcm of given numbers but there is no guarantee that it will lie in given range and also be smallest!!
So can you help me find how to solve this problem??

A: Let $X$ be your list of integers, $X_\ell = \{x \in X \mid x < a\}$ be the list members less than $a$, $X_m = \{x \in X \mid a \leq x \leq b\}$ be the list members in $[a,b]$, and $X_u = \{x \in X \mid x > b\}$ be the list members greater than $b$.  If there is a solution, it is divisible by every member of $X_\ell$ and divides every member of $X_u$.
Compute $L = \mathrm{lcm} (X_\ell)$, the least common multiple of the list members less than $a$.  If $X_\ell = \varnothing$, see below.  If there is a solution, it is divisible by this $L$.  We therefore must have $L \leq b$, otherwise no solution exists in the required interval.
Compute $U = \gcd (X_u)$, the greatest common divisor of the list members greater than $b$.  If $X_u = \varnothing$, see below.  If there is a solution, it divides this $U$.  We therefore must have $a \leq U$, otherwise no solution exists in the required interval.
It is possible that one of $X_\ell$ or $X_u$ is empty.  It may happen that $X_m$ is also empty.

*

*If $X_\ell = X_m = X_u = \varnothing$, then the problem is ill-posed since there is no list of integers.

*If $X_\ell = X_m = \varnothing$, then the solution is a divisor of $\gcd(X_u)$ that happens to be in $[a,b]$, which can be found (if it exists) using the prime decomposition of that $\gcd$.

*If $X_u = X_m = \varnothing$, then the solution is a multiple of $\mathrm{lcm}(X_\ell)$ that happens to be in $[a,b]$, which can be found (if it exists) using the prime decomposition of that $\mathrm{lcm}$.

*If $X_\ell = \varnothing$ and $X_m \neq \varnothing$, then set $L = \gcd{X_m}$.

*If $X_u = \varnothing$ and $X_m \neq \varnothing$, then set $U = \mathrm{lcm}(X_m)$.

Note that in the latter two cases, these $U$ and $L$ need not be in $[a,b]$ since the bounds specified by $X_m$ are not strict (each $x \in X_m$ could either divide or be divided by the solution, so the $L$ and $U$ constructed in these cases are conservative.)
If we have not already shown that no solution exists or finished the problem by considering prime decompositions of some $\gcd$ or $\mathrm{lcm}$...  By the above, if $L \not \mid U$, then no solution exists.  Also, if $L \not \mid x $ for some $x \in X_m$ then no solution exists.  Further, if $x \not \mid U$ for some $x \in X_m$ then no solution exists.
If all the numbers are small, as in your example, construct the factorization into primes of $R = U/L = \prod_{i=1}^N p_i^{n_i}$ and for each divisor $r$ of this $R$ determine whether $rL$ is a solution.  (In a program, this can be done with nested for loops, one per prime with nonzero exponent.)  The check is that $a \leq rL \leq b$, and $rL$ is a solution for all of $X_m$.  If you make the sorted list of candidate divisors of $R$, drop the list prefix that is too small and the list suffix that is too large, where all this dropping can be done on one pass through the list or while sorting it, this will tend to be a very short list.
If the numbers are not small, this process could take too long.  For instance, $U/L > 10^{200}$ and is not easily factored, or the product of all the $n_i$ is larger than a few billion, or $X_m$ is huge...  If this is the case, post more information about the ranges of numbers that are actually expected.
Edit:  originally did not have "$rL | U$" in the check.  Since we are adding factors to $L$ it is no longer guaranteed that $rL | U$.  Therefore, we have to check this each time.  Also pointed out that the list can be culled in one pass through the list, so is at worst a linear time operation in the size of $\prod_i n_i$.
Re-edit:  Over-thought the problem:  As constructed, $rL$ always divides $U$, so there is no need to check for this.
Third edit:  $X_\ell$ or $X_u$ could be empty...  and also $X_m$ empty with one of them.


text:
Q: Show and Hide handlers are applied multiple times on each click This is my html code:
{{ member.user.username }}

and this is my jQuery code
function showMembershipData(id)
    {
        $("#memberInfo_"+id).slideDown();
        $("#username_"+id).click(function(){
            hideMembershipData(id);
        });
    }

    function hideMembershipData(id) {
        $("#memberInfo_" + id).slideUp();
        $("#username_" + id).click(function() {
            showMembershipData(id);
        });
    }

I want the user name to be clickable and when clicked open the "more information" pane, or close it if it is opened. What happens now is:

*

*username clicked for 1 time: pane opens.

*Clicked 2nd time: pane closes. Up to here is fine...

*clicked 3rd time pane opens and closes 2 times in a row (i.e. 4 operations: open, close, open, close)

and so on...  Why? What am I doing wrong?

A: You are assigning handler inside each handler, and you only need to assign handler once or even consider using event delegation $.on(event, selector, handler) if you are adding and removing items.
consider code below, and remove handlers from markup:

*

*add class username to elements with id username_xxx

*add class memberInfo to elements with id memeberInfo_xxx

*add data-id attribute to elements with id username_xxx
So markup going to look like:
 {{ member.user.username }}

And the script:
$('body').on('click', '.username', function(e) {
   var id = $(this).data('id')
   $('#memberInfo_'+id).toggle()
})

A: The problem with your code is that even handlers are been attached multiple times. Basically with jQuery if you do something like
$("#element").click(functionName);
$("#element").click(functionName);
$("#element").click(functionName);

Then clicking the element once will fire functionName thrice! You need to refactor your code a bit to make sure that the event handlers are added and removed appropriately. Try this
function showMembershipData(id)
    {
        $("#memberInfo_"+id).slideDown();
        $("#username_"+id).unbind("click").bind("click",(function(){
            hideMembershipData(id);
        });
    }

    function hideMembershipData(id) {
        $("#memberInfo_" + id).slideUp();
        $("#username_" + id).unbind("click").bind("click",(function() {
            showMembershipData(id);
        });
    }

A: You can make life a whole lot easier by using jQuery's slideToggle() method - try the following:

function showMembershipData(id)
{
    $("#memberInfo_"+id).slideToggle();
}

This will toggle the #memberInfo + id (whatever the ID is) when the link is clicked. Can I suggest using jQuery's click() function? (needs a class added to the username span):

$("#username_span").click(function()
{
    $("#memberInfo_"+id).slideToggle();
});

Don't forget to add it to your $(document).ready() bit or whatever. Once you've done that, you can remove the onClick from the span.
James

A: let's change the code a little bit, shall we
{{ member.user.username }}

on the jQuery side
$(".member").toggle(
    function() {  // click - show
        var id = $(this).attr("data-memberid");
        $("#memberInfo_" + id).stop().slideDown();
    },
    function() {  // click again - hide
        var id = $(this).attr("data-memberid");
        $("#memberInfo_" + id).stop().slideUp();

     });

easy :)

A: Agree with the guys above...you keep registering the events. If all you're doing is opening and closing one:
$('#clickme').click(function() {
    $('#book').slideToggle('slow', function() {
        // Animation complete.
    });
});

http://api.jquery.com/slideToggle/

A: Problem here is that you add an event handler each time showMembershipData gets called.
You should make sure only one event handler gets assigned.

A: It is happenign 2 times in a row because each time you call those functions they bind a click function which fires.
try
$("#username_"+id).click(function(){
  var $showHideElement =$("#memberInfo_"+id);
  if ($showHideElementis(':visible'){
    $showHideElement.slideUp();
  }else{
    $showHideElement.slideDown();
  }
})


text:
Q: How to append array on dictionary based on element exists On print  po menuList?[1]["subMenu"]
I got below message
▿ Optional<Any>
  ▿ some : 1 element
    ▿ 0 : 1 element
      ▿ 0 : 2 elements
        - key : subItem
        ▿ value : 4 elements
          ▿ 0 : 7 elements
            ▿ 0 : 2 elements
              - key : permission
              - value : access
            ▿ 1 : 2 elements
              - key : title
              - value : Create
            ▿ 2 : 2 elements
              - key : bar
              - value : sidebar
            ▿ 3 : 2 elements
              - key : isNotify
              - value : 0
            ▿ 4 : 2 elements
              - key : link
              - value : linker
            ▿ 5 : 2 elements
              - key : path
              - value : /dashboard
            ▿ 6 : 2 elements
              - key : icon
              - value : add

Trying to extract menuList?[i]["subMenu"]["subItem"] based on condition if value exist in side subItem then append to array else not.
few cases ["subItem"] may have 0 elements
    if let permissionList =  MenuList?[i]["subMenu"] {
        let subMenu =  (permissionList as AnyObject)
        if subMenu.count > 0 {
            for j in 0..<subMenu.count{
             let subItem =  subMenu["subItem"]
            }
        }

Its return nil for me
On try subMenu[0]
error: ambiguous use of 'subscript(_:)'
subMenu[0]

A: Here's a variant of George's function, expressing using a map operation rather than a hand-rolled loop:
func menuResult() -> [String] {
    // FIXME: Why is this even optional in the first place?
    guard let menuList = menuList else { return [] }

    return menuList.compactMap { menu -> [String] in
        guard let subMenu = menu["subMenu"] as? [String: String] else { return nil }
        return subMenu["subItem"]
    }
}

A: For example menuData like this:
let menuList: [[String: Any]]? = [
    ["abc": [
        "123": "test1",
        "456": "test2"
    ]],
    ["def": [
        "789": "test3",
        "101112": "test4"
    ]],
    ["subMenu": [
        "subItem": "Other correct path" // <- subMenu[2]["subMenu"]["subItem"]
    ]],
    ["subMenu": [
        "otherItem": "WRONG",
        "subItem": "CORRECT" // <- subMenu[3]["subMenu"]["subItem"]
    ]]
]

Code to get all items in the menuData array at menuData[i]["subMenu"]["subItem"]:
func menuResult() -> [String] {
    // menuList can't start nil
    guard let menuList = menuList else { return [] }
    var result = [String]()

    // Iterate every element of menuList
    for i in menuList.indices {
        // Get 'subMenu' dictionary if it exists
        if let subMenu = menuList[i]["subMenu"] as? [String: String] {
            // Get 'subItem' dictionary if it exists
            if let subItem = subMenu["subItem"] {
                // Store value at this path
                result.append(subItem)
            }
        }
    }

    return result
}

print(menuResult())
// Prints: ["Other correct path", "CORRECT"]


text:
Q: Data from database to JList I created a database, in which one of the table name is Location which has 2 columns named Stadium and City. I want that data in each column should get retrieved in 2 JList, but I don't know how. Can you guys tell me how to do it?

A: The normal way to display a table from a database is of course a JTable. But if you want to opt for 2 JLists instead, it is basically the same principle.
Create a model based on the contents of the database (in this case a ListModel). You can probably just extend from AbstractListModel. Once you have your model, it is trivial to create a JList for it by just passing the model in the constructor.
See the How to use lists tutorial and pay special attention on the Creating a model part of that tutorial


text:
Q: Calculating two fields in a form using JavaScript with a submit button and reset button Here the code that I made and not working looking to see how I would get my sum into the result field, Also looking how to make a reset button to clear all the text from the fields.
JSBin.

Calculator Using Forms & JavaScript

    <form>
        Number 1:
        <input type="number" id="num1" value="0" autofocus>

 Number 2:
        <input type="number" id="num2" value="0">

 Result:
        <input type="text" id="result" value="0" readonly>

    </form>

    <input type="button" onclick="addition()" value="addition">

A: Why do you want to submit the form?
You can use document.forms. to access the form.
Try this:

Calculator Using Forms & JavaScript

    <form name="calculator">
        Number 1:
        <input type="number" id="num1" value="0" autofocus>

 Number 2:
        <input type="number" id="num2" value="0">

 Result:
        <input type="text" id="result" value="0" readonly>

    </form>

    <input type="button" onclick="addition()" value="addition">
    <input type="button" onclick="reset()" value="reset">

A: just give an id to the form and in your reset function, just do
document.getElementById("myForm").reset();

updates:
according to ROBG's comments, you don't need to bind a function to the button.
you can simply add a
<input type="reset">

to reset all fields of the form, and if the button is out the form, you can do
    <input form="formID" type="reset">
to associate to specific form.

A: Do you want this one?
jsbin

Calculator Using Forms & JavaScript

    <form id="formId">
        Number 1:
        <input type="number" id="num1" value="0" autofocus>

 Number 2:
        <input type="number" id="num2" value="0">

 Result:
        <input type="text" id="result" value="0" readonly>

    </form>

    <input type="button" onclick="addition()" value="addition">
    <input type="button" onclick="reset()" value="reset">

A: Note that forms can be submitted without clicking the submit button, so if you want something to happen on submit, attach a listener to the form's submit handler. To reset a form only requires a reset button, no code.
Form controls must have a name to be successful and submit their value with the form, and you can pass a reference to the form using this from the listener so you don't need to use getElementById.
Implementing the above significantly reduces the amount of code required.
In the following, the submit listener returns false so prevents the form from submitting. If you want the form to submit, just remove the return statement from the in–line listener:

function addition(form) {
  form.result.value = +form.num1.value + +form.num2.value;
}
<form name="calculator" onsubmit="addition(this); return false;">
  Number 1:
  <input type="number" name="num1" value="0" autofocus>

 Number 2:
  <input type="number" name="num2" value="0">

 Result:
  <input type="text" name="result" value="0" readonly>

  <input type="submit" value="Submit form">
  <input type="reset">
</form>

You may not want to submit the form at all, in that case you can make the submit button a plain button and call the function from there, but remember to stop the form submitting otherwise.


text:
Q: bash: move new file as soon as it is written I'm trying to write a bash script to move files from a source to a destination, in order to save space on the disk of the source (source and destination are two different machines).
I can handle the moving part by using the scp protocol, but the problem is that the software I'm using writes a lot of files very quickly (luckily each file has the same extension) and I want to move a file as soon as it is written.
So, in the directory of the source, I'd like to:

*

*move the file on the destination,

*remove the file from the source,

... until the software stops to write new files on the source.
Any help?
Thank you in advance.

A: This is a job for inotifywait.
inotifywait -meclose_write . |
while read d e f
do
    echo Now is the time to move "$f".
done

Of course you can specify any source directory instead of ..


text:
Q: Why don't count the elements of array? In the file there are 9 dictionaries each with two keys. I want to obtain an array of dictionary.I get that array elements are: 0
This is the code:
NSString * path = [[NSBundle mainBundle]pathForResource:@"List" ofType: @"plist"];

 NSArray *array = [NSArray arrayWithContentsOfFile:path];

Thanks in advance

A: NSString *file = [[NSBundle mainBundle] pathForResource:@"List" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:file];
NSArray *array = [dict objectForKey:@"Array"];

Hope this helps
Your plist is an dictionary not an array. So check this out.


text:
Q: How can I display a property value infront of each JSON array item? Here is the JSON string that I am working with.
{
  "id": 1,
  "title": "A Test",
  "items": [
    {
      "id": 157,
      "title": "some article",
      "type": "Article"
    },
    {
      "id": 153,
      "title": "some other article",
      "type": "Article"
    }
   ]
}

I am using Json.Net for serialization. Is there anyway that I can format the JSON like this before displaying?
{
  "id": 1,
  "title": "A Test",
  "items": [
    "157" : {
      "title": "some article",
      "type": "Article"
    },
    "153" : {
      "title": "some other article",
      "type": "Article"
    }
   ]
}

Thanks in advance.

A: You can get pretty close to the output you want using Json.Net's LINQ-to-JSON API (JObjects) to transform the original JSON.  Here is one way to do it:
public static string Transform(string json)
{
    JObject root = JObject.Parse(json);

    JObject itemsObj = new JObject();

    foreach (JObject item in root["items"])
    {
        JToken id = item["id"];
        id.Parent.Remove();
        itemsObj.Add(id.ToString(), item);
    }

    root["items"].Parent.Remove();
    root.Add("items", itemsObj);

    return root.ToString();
}

If you pass your original JSON to this method, you will get the following output:
{
  "id": 1,
  "title": "A Test",
  "items": {
    "157": {
      "title": "some article",
      "type": "Article"
    },
    "153": {
      "title": "some other article",
      "type": "Article"
    }
  }
}

Fiddle: https://dotnetfiddle.net/1di41P


text:
Q: How to make a link to a sprite file itself created by Compass in a background: url() property? I have a sprite file created by Compass. And there is an image in that sprite file. And I have an element with a background: url() property. Is there some special helpers in Compass that allow to reference the sprite file in url()?
Here is an example:
        a {
            text-transform: uppercase;
            color: #FFF;
        }
        a:before {
            content: '';
            display: block;
            position: absolute;
            height: 20px;
            width: 24px;
            left: 9px;
            top: 18px;
            background: url("HOW TO GET SPRITE FILE HERE?") no-repeat scroll -55px 0 transparent;
        }

A: I'm not sure how you are generating your sprite, but you should be able to use sprite-url($map) to get the url. There are a couple of other ways to handle it though depending on how you generated the sprite. Here is a link to the documentation for sprite-url and if you scroll up on the page, it will give you the other ways that you can generate the sprite and output the necessary url: http://compass-style.org/reference/compass/helpers/sprites/#sprite-url


text:
Q: nonblocking TCP socket continuously receive EAGAIN on read() The TCP socket has been set to nonblocking.
Here's the code:
char * recv_response(int sockfd)
{
    char * resp_msg = (char *)malloc(MAX_RESP_LEN);

    int n, len;
    len = 0;
    while (1) {
        n = read(sockfd, resp_msg + len, 1024);
        printf("#recv_response. n = %d, len = %d#\n", n, len);
        if (n < 0) {
            if (errno == EAGAIN || errno == EWOULDBLOCK) {
                printf("#recv_response. errno = EAGAIN#\n");
                sleep(5);
                continue;
            }
            else if (errno == EINTR) {
                printf("recv interruputed\n");
                close(sockfd);
                return NULL;
            }
        }
        else if (n == 0)
            break;
        else
            len += n;
    }
    close(sockfd);
    resp_msg = realloc(resp_msg, len + 1);
    return resp_msg;
}

And here's how it works when sending GET request to a webpage:
#recv_response. n = -1, len = 0#
#recv_response. errno = EAGAIN#
#recv_response. n = 1024, len = 0#
#recv_response. n = 1024, len = 1024#
#recv_response. n = 1024, len = 2048#
#recv_response. n = 1024, len = 3072#
#recv_response. n = 1024, len = 4096#
#recv_response. n = 909, len = 5120#
#recv_response. n = -1, len = 6029#
#recv_response. errno = EAGAIN#
#recv_response. n = -1, len = 6029#
#recv_response. errno = EAGAIN#
#recv_response. n = -1, len = 6029#
#recv_response. errno = EAGAIN#
#recv_response. n = -1, len = 6029#
#recv_response. errno = EAGAIN#
^C

The read() should return n=0 to stop the while loop after all stuff in the webpage is read. But here it's not.
UPDATE:
The above failure case happens when I tested this code in office. When I came back to home it works:
#recv_response. n = -1, len = 0#
#recv_response. errno = EAGAIN#
#recv_response. n = 1024, len = 0#
#recv_response. n = 1024, len = 1024#
#recv_response. n = 1024, len = 2048#
#recv_response. n = 1024, len = 3072#
#recv_response. n = 1024, len = 4096#
#recv_response. n = 227, len = 5120#
#recv_response. n = 0, len = 5347#
HTTP/1.1 200 OK

I know that firewalls in company network may ban some network services like ping, but why here the read() can read stuff but can't stop?

A:
The read() should return n=0 to stop the while loop after all stuff in the webpage is read.

No it shouldn't. It should return zero when the peer closes the connection.
You are a victim of HTTP keep-alive. If you don't want that, send the header Connection: close. Otherwise you need to read all the headers, then get the body size from the Content-length header, and read exactly that many bytes.
Note that using non-blocking sockets in this way is completely and utterly pointless. Your sleep is either too short or too long. A blocking-mode recv() or read() blocks for exactly the right length of time, and it's one line of code. If you want a socket timeout, set SO_RCVTIMEO.


text:
Q: Morris.bar function is not recognized I'm trying to get a simple test page with a working Bar Graph using Morris. Here's my code.
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Morris Test</title>

        <link href="css/plugins/morris.css" rel="stylesheet">

When I open this page I get the error TypeError: Morris.bar is not a function. I've doubled checked that the path for Morris.min.js and Raphael.min.js are correct and I can't think of another reason that the function wouldn't be working.

A: This is not the correct syntax, use
Morris.Bar({ ... });

instead of Morris.bar


text:
Q: Test for the effect of UN ratification on corruption in a set of countries The UN has a convention against corruption (UNCAC) that has been signed by some 140 countries and ratified by most (link).
Transparency International publishes an annual report on corruption. They have data for most countries for the period 2000-2010, each country is given a score between zero and ten where ten is best (lowest level of corruption). There is usually a slight trend in the corruption score, indicating that there is some inertia in the level of corruption (link).
I want to test whether ratifying the convention has any positive effect on the level of corruption in the country.
My initial idea is to calculate the mean level of corruption 3 years before and after signing the treaty and using a students paired t-test to see if latter mean is significantly larger than the former.
Another approach, that I would know less about, is to use some kind of event model where dummy variables are used for the years after the convention is ratified.
What are your thoughts on this? Would the first approach work, is there anything I have overlooked? All feedback is appreciated.
Notes
I should note that this is a minor part of a course term paper. We weren't  supposed to do anything quantitative, just a write-up on a topic of our choice. However I want to take a quick look at the statistics since data is readily available and I prefer to look at numbers if possible. Hence, I don't need the ideal PhD-level statistical model, just something quick and simple.

A: It's probably not a good idea without digging deeper into the source surveys. TI themselves note that changes in a country's index can come from either a change in corruption or just a change in methodology of the sources that they use. The sources themselves change over time as well, so comparing the index from year to year is actually fairly complicated to do properly.
See the references at http://en.wikipedia.org/wiki/Corruption_Perceptions_Index

A: One problem with your pre-post paired t-test idea is that it chould give a small p-value if there's a general upward (or downward) trend in the corruption score over time regardless of ratification. You need some sort of comparison group in which the ratification status did not change between the two time points.
In principle, one approach to forming a comparison group could be to find a matched 'control' country that didn't change its ratification status during the same time period for each country (of a sample of those) that did. The 'control' country should have similar baseline corruption score, and ideally be as similar as possible in other respects that might affect the rate of change of corruption over time (that's what I mean by matching). I haven't looked at the data so I've no idea if this is feasible. You'd want to consider removing the country that changed status from your analysis if you can't find a 'control' country that matches closely enough (but what's 'close enough'?).
In any case it certainly wouldn't be simple, but drawing valid and defensible conclusions about causal effects from observational data seldom is. I agree with @JMS that it's probably not worth attempting in your situation.


text:
Q: Why my datagrid not updates using MVVM Whats wrong in my data binding ?
I am MVVM beginner and i have to take some data from user in textbox and then display that data in data grid, there are 3 textboxes and corresponding 3 textboxes respectively.
And a button which on click must save the entered data to the data grid columns.
I have everything working except the data is not updated to datagrid.
Here is my View:
 < Window x: Class = "DatagRidBelowTextUpdate.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "MainWindow"
Height = "350"
Width = "525" >
    < Grid >
    < Grid.RowDefinitions >
    < RowDefinition > < /RowDefinition> < RowDefinition Height = "30" > < /RowDefinition> < RowDefinition > < /RowDefinition> < /Grid.RowDefinitions> < Grid Grid.Row = "0" >
    < Grid.RowDefinitions >
    < RowDefinition > < /RowDefinition> < RowDefinition > < /RowDefinition> < RowDefinition > < /RowDefinition> < /Grid.RowDefinitions> < Grid.ColumnDefinitions >
    < ColumnDefinition > < /ColumnDefinition> < ColumnDefinition > < /ColumnDefinition> < /Grid.ColumnDefinitions> < TextBox Grid.Column = "1"
Grid.Row = "0"
Text = "{Binding EditModel.TextName}"
Height = "20"
Width = "80"
HorizontalAlignment = "Center" > < /TextBox> < TextBox Grid.Column = "1"
Grid.Row = "1"
Text = "{Binding EditModel.RollNumber}"
Height = "20"
Width = "80" > < /TextBox> < TextBox Grid.Column = "1"
Grid.Row = "2"
Text = "{Binding EditModel.Class}"
Height = "20"
Width = "80" > < /TextBox>  Name   RollNumber   Class  < /Grid> < Grid Grid.Row = "1" >
    < Button Width = "80"
Height = "20"
Command = "{Binding SaveStudentRecord}" > Save < /Button> < /Grid> < Grid Grid.Row = "2" >
    < DataGrid ItemsSource = "{Binding DGrid}" >
    < DataGrid.Columns >
    < DataGridTextColumn Header = "Name"
Binding = "{Binding  DgName, Mode=TwoWay}"
Width = "150" > < /DataGridTextColumn> < DataGridTextColumn Header = "Rollnumber"
Binding = "{Binding DgRollnumber, Mode=TwoWay}"
Width = "150" > < /DataGridTextColumn> < DataGridTextColumn Header = "Class"
Binding = "{Binding DgClass , Mode=TwoWay}"
Width = "150" > < /DataGridTextColumn> < /DataGrid.Columns> < /DataGrid> < /Grid> < /Grid> < /Window>

My ViewModel:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;

namespace DatagRidBelowTextUpdate {
    class ViewModel {
        private RelayCommand saveStudentRecord;
        private Model editModel;
        public bool canExecute {
            get;
            set;
        }
        public ObservableCollection < Model > DGrid;
        private string dgName;
        private string dgRollnumber;
        private string dgClass;
        public string DgName {
            get {
                return dgName;
            }
            set {
                dgName = value;
                PropertyChangedEventArgs("DgName");
            }
        }
        public string DgRollnumber {
            get {
                return dgRollnumber;
            }
            set {
                dgRollnumber = value;
                PropertyChangedEventArgs("DgRollnumber");
            }
        }
        public string DgClass {
            get {
                return dgClass;
            }
            set {
                dgClass = value;
                PropertyChangedEventArgs("DgClass");
            }
        }

        public Model EditModel {
            get {
                return editModel;
            }
            set {
                editModel = value;
                PropertyChangedEventArgs("EditModel");
            }
        }

        public ViewModel() {
            editModel = new Model();
            canExecute = true;
            DGrid = new ObservableCollection < Model > ();
        }
        public RelayCommand SaveStudentRecord {
            get {
                return saveStudentRecord = new RelayCommand(() => MyAction(), canExecute);
            }
        }

        private void MyAction() {
            string chck1 = editModel.TextName; //TextName; //I see on debugging that TextName contains the text entered so how to add this text to Datagrid column
            string chck2 = editModel.Class;
            string chck3 = editModel.RollNumber;
            //  DGrid = new ObservableCollection<Model>();
            //    dgClass = editModel.Class;
            //    dgName = editModel.TextName;
            //    dgRollnumber = editModel.RollNumber;
            DGrid.Add(editModel);
            //   editModel = new Model();

        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void PropertyChangedEventArgs(string propertyName) {
            if (PropertyChanged != null) {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

My Model:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace DatagRidBelowTextUpdate {
    class Model {
        private string textName;
        private string rollNumber;
        private string cclass;

        public string TextName {
            get {
                return textName;
            }
            set {
                textName = value;
                PropertyChangedEventArgs("TextName");
            }
        }

        public string RollNumber {
            get {
                return rollNumber;
            }
            set {
                rollNumber = value;
                PropertyChangedEventArgs("RollNumber");
            }
        }

        public string Class {
            get {
                return cclass;
            }
            set {
                cclass = value;
                PropertyChangedEventArgs("Class");
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void PropertyChangedEventArgs(string propertyName) {
            if (PropertyChanged != null) {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

What is wrong in the binding that it do not update the datagrid in button click MyAction()
EDIT:
(I dont want to use DGrid.Add(editModel); and i dont want to do AutoGenrateColumns to True, because o have to understand the binding concept of individual UI).I mean i wish to bind the columns in datagrid manually in xaml and then assign the textboxes data using textbox binded variables to the datagrid binded variables, i mean something like dgName=editModel.Name on button click.
Viem Model is:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;

namespace DatagRidBelowTextUpdate
{
    class ViewModel :INotifyPropertyChanged
    {
        private RelayCommand saveStudentRecord;
        private Model editModel;
        public bool canExecute { get; set; }
        public ObservableCollection<Model> DGrid { get; set; }
        private string dgName{ get; set; }
        private string dgRollnumber { get; set; }
        private string dgClass { get; set; }

        public string DgName
        {
            get
            {
                return dgName;
            }
            set
            {
                dgName = value;
                PropertyChangedEventArgs("DgName");
            }
        }
        public string DgRollnumber
        {
            get
            {
                return dgRollnumber;
            }
            set
            {
                dgRollnumber = value;
                PropertyChangedEventArgs("DgRollnumber");
            }
        }
        public string DgClass
        {
            get
            {
                return dgClass;
            }
            set
            {
                dgClass = value;
                PropertyChangedEventArgs("DgClass");
            }
        }

        public Model EditModel
        {
            get
            {
                return editModel;
            }
            set
            {
                editModel = value;
                PropertyChangedEventArgs("EditModel");
            }
        }

        public ViewModel()
        {
            editModel = new Model();
            canExecute = true;
        }
        public RelayCommand SaveStudentRecord
        {
            get { return saveStudentRecord = new RelayCommand(() => MyAction(), canExecute); }
        }

        private void MyAction()
        {
           dgClass = editModel.Class;
            dgName = editModel.TextName;
           dgRollnumber = editModel.RollNumber;
            //according to my understanding , the data in editModel.Class must be added to dgClass in View, obsolutley i am wrong, please correct me.
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void PropertyChangedEventArgs(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

View is:
<Window x:Class="DatagRidBelowTextUpdate.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <TextBox Grid.Column="1" Grid.Row="0" Text="{Binding EditModel.TextName}" Height="20" Width="80" HorizontalAlignment="Center"></TextBox>
            <TextBox Grid.Column="1" Grid.Row="1" Text="{Binding EditModel.RollNumber}"  Height="20" Width="80"></TextBox>
            <TextBox Grid.Column="1" Grid.Row="2" Text="{Binding EditModel.Class}" Height="20" Width="80"></TextBox>
            Name
            RollNumber
            Class
        </Grid>
        <Grid Grid.Row="1" >
            <Button Width="80" Height="20" Command="{Binding SaveStudentRecord}">Save</Button>
        </Grid>
        <Grid Grid.Row="2">
            <DataGrid ItemsSource="{Binding DGrid, Mode=TwoWay}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding DgName}" Width="150"></DataGridTextColumn>
                    <DataGridTextColumn Header="Rollnumber" Binding="{Binding DgRollnumber}" Width="150"></DataGridTextColumn>
                    <DataGridTextColumn Header="Class" Binding="{Binding DgClass}"  Width="150"></DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </Grid>
</Window>

A: First make sure that the ViewModel is set as the DataContext of your window. You can test by checking if the Commands that you created are being called when you click the Save button. You can check this link out to validate that.
Also change DGrid into a property. Because currently it is defined as a variable. Change
    public ObservableCollection<Model> DGrid;

to
    public ObservableCollection<Model> DGrid {get; set;}

and that should work! Hope that helps!


text:
Q: Python Raspberry Pi Adding Functions I have the below code for when motion is detected i call the camera and email functions. I tried adding the functions after printing Motion Detected but didnt work. Can someone help me where to add the functions? Need it for tomorrow if possible. Thanks
Edit: This is the whole code to help me find the error. Thanks
#!/usr/bin/python
import subprocess
import socket
import datetime
#Camera
import os
import pygame, sys
from pygame.locals import *
import pygame.camera
#Email
import os
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
#Sensor
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

COMMASPACE = ', '
GPIO.setmode(GPIO.BCM)
PIR_PIN = 7
GPIO.setup(PIR_PIN, GPIO.IN)

def MOTION(PIR_PIN):
      print("Motion Detected!")

print("PIR Module Test (CTRL+C to exit)")
time.sleep(2)
print("Ready")

try:
    GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
    while 1:
           time.sleep(100)
except KeyboardInterrupt:
     print(" Quit")
     GPIO.cleanup()

def camera():
width = 480
height = 360

#initialise pygame
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(width,height))
cam.start()

#setup window
windowSurfaceObj = pygame.display.set_mode((width,height),1,16)
pygame.display.set_caption('Camera')

#take a picture
image = cam.get_image()
cam.stop()

#display the picture
catSurfaceObj = image
windowSurfaceObj.blit(catSurfaceObj,(0,0))
pygame.display.update()

#save picture
pygame.image.save(windowSurfaceObj,'picture.jpg')

def email():
sender = ''
gmail_password = ''
recipients = ''
composed = ''

# Create the enclosing (outer) message
outer = MIMEMultipart()
outer['Subject'] = 'MOTION HAS BEEN DETECTED!'
outer['To'] = COMMASPACE.join(recipients)
outer['From'] = sender
outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

# List of attachments
attachments = ['/home/pi/Desktop/picture.jpg']

# Add the attachments to the message
for file in attachments:
    try:
        with open(file, 'rb') as fp:
            msg = MIMEBase('application', "octet-stream")
            msg.set_payload(fp.read())
        encoders.encode_base64(msg)
        msg.add_header('Content-Disposition', 'attachment',     filename=os.path.basename(file))
        outer.attach(msg)
    except:
        print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
        raise

composed = outer.as_string()

# Send the email
try:
    with smtplib.SMTP('smtp.gmail.com', 587) as s:
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(sender, gmail_password)
        s.sendmail(sender, recipients, composed)
        s.close()
    print("Email sent!")
except:
    print("Unable to send the email. Error: ", sys.exc_info()[0])
    raise

MOTION(PIR_PIN)


text:
Q: how to use git pull with GitPython? I am trying to pull filesfrom git using python but it's not working. Below is the code I was using:
import git
git.cmd.Git().pull('https://github.com/User/repo','master')

it asks for authentication and after that terminates.
Could someone please help me here? what's wrong with this code?

A: The first step is to create a git.Repo object to represent your repository.
from git import Repo

# rorepo is a Repo instance pointing to the git-python repository.
# For all you know, the first argument to Repo is a path to the repository
# you want to work with
repo = Repo(self.rorepo.working_tree_dir)
assert not repo.bare

In the above example, the directory self.rorepo.working_tree_dir equals /Users/mtrier/Development/git-python and is my working repository which contains the .git directory. You can also initialize GitPython with a bare repository.
This is what you asked for :

 repo = git.Repo('repo_name')
 o = repo.remotes.origin
 o.pull()

A: It depends on your OS but you should use a credential helper in order to cache the password (or token if you have 2FA activated) in it.
This is assuming your are trying to pull from a private repository.
On Windows, for example, that would be "manager", and you can cache your credentials with git credential fill.