问:
Mockito not working for a Boolean Function
I have a function which tells whether the office is open or closed. I have written a test case which is giving result as False but expecting True. I am not able to figure out reason.</p>
```<code>    public class Office {
        public LocalTime openTime;
        public LocalTime closeTime;
        public LocalTime currentTime;

            public boolean isOfficeOpen() {
            currentTime = getCurrentTime();

            if (currentTime.isAfter(openTime)&&currentTime.isBefore(closeTime)) {
                return true;
            } else {
                return false;
            }

        }
        public LocalTime getCurrentTime(){ return  LocalTime.now(); }
    }

:

@Test
public void is_office_open_pass_test(){
    Office offc = Mockito.mock(Office.class);
    LocalTime openingTime = LocalTime.parse("10:30:00");
    LocalTime closingTime = LocalTime.parse("23:00:00");
    LocalTime currentTime = openingTime.plusHours(1);
    Mockito.when(offc.getCurrentTime()).thenReturn(currentTime);
    boolean status = offc.isOfficeOpen();
    assertTrue(status);
}
</code>```

答:
You are trying to test a mock which is not something that you normally do. You should test implementation, and mock dependencies.

```<code>@AllArgsConstructor // if you are not using lombok, just create all args constructor yourself
public class Office {
    public LocalTime openTime;
    public LocalTime closeTime;
    public Producer<LocalTime> currentTimeProvider;

        public boolean isOfficeOpen() {
        currentTime = getCurrentTime();

        if (currentTime.isAfter(openTime)&&currentTime.isBefore(closeTime)) {
            return true;
        } else {
            return false;
        }

    }
    public LocalTime getCurrentTime(){ return  this.currentTimeProvider.get() }
}
</code>```

:

```<code>@Test
public void is_office_open_pass_test(){
    LocalTime openingTime = LocalTime.parse("10:30:00");
    LocalTime closingTime = LocalTime.parse("23:00:00");
    LocalTime currentTime = openingTime.plusHours(1);

    Office offc = new Office(openingTime,closingTime,()->currentTime)
    boolean status = offc.isOfficeOpen();
    assertTrue(status);
}
</code>```

Body:
I have a function which tells whether the office is open or closed. I have written a test case which is giving result as False but expecting True. I am not able to figure out reason.

    public class Office {
        public LocalTime openTime;
        public LocalTime closeTime;
        public LocalTime currentTime;

            public boolean isOfficeOpen() {
            currentTime = getCurrentTime();

            if (currentTime.isAfter(openTime)&&currentTime.isBefore(closeTime)) {
                return true;
            } else {
                return false;
            }

        }
        public LocalTime getCurrentTime(){ return  LocalTime.now(); }
    }

:

@Test
public void is_office_open_pass_test(){
    Office offc = Mockito.mock(Office.class);
    LocalTime openingTime = LocalTime.parse("10:30:00");
    LocalTime closingTime = LocalTime.parse("23:00:00");
    LocalTime currentTime = openingTime.plusHours(1);
    Mockito.when(offc.getCurrentTime()).thenReturn(currentTime);
    boolean status = offc.isOfficeOpen();
    assertTrue(status);
}

Body:
You are trying to test a mock which is not something that you normally do. You should test implementation, and mock dependencies.

@AllArgsConstructor // if you are not using lombok, just create all args constructor yourself
public class Office {
    public LocalTime openTime;
    public LocalTime closeTime;
    public Producer<LocalTime> currentTimeProvider;

        public boolean isOfficeOpen() {
        currentTime = getCurrentTime();

        if (currentTime.isAfter(openTime)&&currentTime.isBefore(closeTime)) {
            return true;
        } else {
            return false;
        }

    }
    public LocalTime getCurrentTime(){ return  this.currentTimeProvider.get() }
}

:

@Test
public void is_office_open_pass_test(){
    LocalTime openingTime = LocalTime.parse("10:30:00");
    LocalTime closingTime = LocalTime.parse("23:00:00");
    LocalTime currentTime = openingTime.plusHours(1);

    Office offc = new Office(openingTime,closingTime,()->currentTime)
    boolean status = offc.isOfficeOpen();
    assertTrue(status);
}


来源: stackexchange

问:
How to align text views differently under a vstack in swiftui?
I am trying to have 3 text views and an image view inside a vstack and have them align differently.

Here is my code:

```<code>VStack(alignment: .leading) {
        Text("This is the first paragraph").foregroundColor(Color.red)
        Spacer().frame(height: 10)
        Text("This is a paragraph with ").foregroundColor(Color.blue) + Text("multiple colors.").foregroundColor(Color.green)
        Spacer().frame(height: 10)
        if #available(iOS 15.0, *) {
            AsyncImage(url: URL(string: "https://www.example.org/img/image.png")) { image in
                image.resizable()
            } placeholder: {
                Color.red
            }
            .frame(width: 128, height: 128)
            .clipShape(RoundedRectangle(cornerRadius: 25))
        }
        Spacer().frame(height: 10)
        Text("Final paragraph").foregroundColor(Color.red)
        Spacer()
    }
</code>```

Here  in the below image I would like the first line and the image to be center aligned:

I tried it like below but then the left aligned text didn't leave a margin like the above image.

```<code>struct ContentView: View {
var body: some View {
    VStack {
        HStack {
            Text("This is the first paragraph").foregroundColor(Color.red).frame(alignment: .leading)
        }
        Spacer().frame(height: 10)
        HStack {
            Text("This is a paragraph with ").foregroundColor(Color.blue) + Text("multiple colors.").foregroundColor(Color.green)
            Spacer()
        }
        Spacer().frame(height: 10)
        HStack {
            if #available(iOS 15.0, *) {
                AsyncImage(url: URL(string: "https://www.example.org/img/image.png")) { image in
                    image.resizable()
                } placeholder: {
                    Color.red
                }
                .frame(width: 128, height: 128)
                .clipShape(RoundedRectangle(cornerRadius: 25))
            }
        }
        Spacer().frame(height: 10)
        HStack {
            Text("Final paragraph").foregroundColor(Color.red)
            Spacer()
        }
        Spacer()
    }
  }
}
</code>```

The view:

答:
I can assume that you just need padding in right place to have something like "margins", so a solution can be like

```<code>var body: some View {
    VStack(alignment: .leading) {
        Text("This is the first paragraph")
            .foregroundColor(Color.red)
            .frame(maxWidth: .infinity)    // << default center !!

        Spacer().frame(height: 10)
        Text("This is a paragraph with ").foregroundColor(Color.blue) + Text("multiple colors.").foregroundColor(Color.green)
        Spacer().frame(height: 10)
        if #available(iOS 15.0, *) {
            AsyncImage(url: URL(string: "https://www.example.org/img/image.png")) { image in
                image.resizable()
            } placeholder: {
                Color.red
            }
            .frame(width: 128, height: 128)
            .clipShape(RoundedRectangle(cornerRadius: 25))
            .frame(maxWidth: .infinity)  // << for center !!
        }
        Spacer().frame(height: 10)
        Text("Final paragraph").foregroundColor(Color.red)
        Spacer()
    }
    .padding(.horizontal, 24)   // << for margins !!
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to have 3 text views and an image view inside a vstack and have them align differently.

Here is my code:

VStack(alignment: .leading) {
        Text("This is the first paragraph").foregroundColor(Color.red)
        Spacer().frame(height: 10)
        Text("This is a paragraph with ").foregroundColor(Color.blue) + Text("multiple colors.").foregroundColor(Color.green)
        Spacer().frame(height: 10)
        if #available(iOS 15.0, *) {
            AsyncImage(url: URL(string: "https://www.example.org/img/image.png")) { image in
                image.resizable()
            } placeholder: {
                Color.red
            }
            .frame(width: 128, height: 128)
            .clipShape(RoundedRectangle(cornerRadius: 25))
        }
        Spacer().frame(height: 10)
        Text("Final paragraph").foregroundColor(Color.red)
        Spacer()
    }

Here  in the below image I would like the first line and the image to be center aligned:

I tried it like below but then the left aligned text didn't leave a margin like the above image.

struct ContentView: View {
var body: some View {
    VStack {
        HStack {
            Text("This is the first paragraph").foregroundColor(Color.red).frame(alignment: .leading)
        }
        Spacer().frame(height: 10)
        HStack {
            Text("This is a paragraph with ").foregroundColor(Color.blue) + Text("multiple colors.").foregroundColor(Color.green)
            Spacer()
        }
        Spacer().frame(height: 10)
        HStack {
            if #available(iOS 15.0, *) {
                AsyncImage(url: URL(string: "https://www.example.org/img/image.png")) { image in
                    image.resizable()
                } placeholder: {
                    Color.red
                }
                .frame(width: 128, height: 128)
                .clipShape(RoundedRectangle(cornerRadius: 25))
            }
        }
        Spacer().frame(height: 10)
        HStack {
            Text("Final paragraph").foregroundColor(Color.red)
            Spacer()
        }
        Spacer()
    }
  }
}

The view:

Body:
I can assume that you just need padding in right place to have something like "margins", so a solution can be like

var body: some View {
    VStack(alignment: .leading) {
        Text("This is the first paragraph")
            .foregroundColor(Color.red)
            .frame(maxWidth: .infinity)    // << default center !!

        Spacer().frame(height: 10)
        Text("This is a paragraph with ").foregroundColor(Color.blue) + Text("multiple colors.").foregroundColor(Color.green)
        Spacer().frame(height: 10)
        if #available(iOS 15.0, *) {
            AsyncImage(url: URL(string: "https://www.example.org/img/image.png")) { image in
                image.resizable()
            } placeholder: {
                Color.red
            }
            .frame(width: 128, height: 128)
            .clipShape(RoundedRectangle(cornerRadius: 25))
            .frame(maxWidth: .infinity)  // << for center !!
        }
        Spacer().frame(height: 10)
        Text("Final paragraph").foregroundColor(Color.red)
        Spacer()
    }
    .padding(.horizontal, 24)   // << for margins !!
}


问:
Digital Ocean Kubernetes: Cert-Manager Certificate creation stuck at Created new CertificateRequest resource
I am following this tutorial to use a trusted TLS certificate in my ingress rules. All works, however

```<code>kubectl describe certificate quickstart-example-tls
</code>```

gives & gets stuck at Created new CertificateRequest resource

```<code>....
Status:
  Conditions:
    Last Transition Time:        2022-02-08T10:00:01Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      False
    Type:                        Ready
    Last Transition Time:        2022-02-08T10:00:02Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      True
    Type:                        Issuing
  Next Private Key Secret Name:  quickstart-example-tls-d87r6
Events:
  Type    Reason     Age   From          Message
  ----    ------     ----  ----          -------
  Normal  Issuing    21m   cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  21m   cert-manager  Stored new private key in temporary Secret resource "quickstart-example-tls-d87r6"
  Normal  Requested  21m   cert-manager  Created new CertificateRequest resource "quickstart-example-tls-kxwqd"

</code>```

First let me share my ingress rules and Issuers:

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: flask-ingress
spec:
  ingressClassName: nginx
  rules:
  - host: www.<Domain>.net
    http:
      paths:
      - pathType: Prefix
        path: /
        backend:
          service:
            name: flask
            port:
              number: 5000
</code>```

I set up DNS (in digital ocean) rules so curling (via web) works.

```<code>curl "http://www.<Domain>.net"
<p>Hello, World!</p>%
</code>```

Here my issuer file:

```<code>apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: letsencrypt-staging
  namespace: default
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: <MY-EMAIL>
    privateKeySecretRef:
      name: letsencrypt-staging
    solvers:
    - http01:
        ingress:
          class: nginx
</code>```
```<code># kubectl get issuer
NAME                  READY   AGE
letsencrypt-staging   True    26s

</code>```

Now I update my ingress rule and start the challenge:

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: flask-ingress
  annotations:
    cert-manager.io/issuer: letsencrypt-staging
spec:
  tls:
  - hosts:
     - www.<DOMAIN>.net
    secretName: quickstart-example-tls
  ingressClassName: nginx
  rules:
  - host: www.<DOMAIN>.net
    http:
      paths:
      - pathType: Prefix
        path: /
        backend:
          service:
            name: flask
            port:
              number: 5000
</code>```
```<code>#kubectl get certificate
NAME                     READY   SECRET                   AGE
quickstart-example-tls   False   quickstart-example-tls   88s
</code>```

Here the detailed output:

```<code>#kubectl describe certificate quickstart-example-tls
Name:         quickstart-example-tls
Namespace:    default
Labels:       <none>
Annotations:  <none>
API Version:  cert-manager.io/v1
Kind:         Certificate
Metadata:
  Creation Timestamp:  2022-02-08T10:34:40Z
  Generation:          1
  Managed Fields:
    API Version:  cert-manager.io/v1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:ownerReferences:
          .:
          k:{"uid":"<UID>"}:
            .:
            f:apiVersion:
            f:blockOwnerDeletion:
            f:controller:
            f:kind:
            f:name:
            f:uid:
      f:spec:
        .:
        f:dnsNames:
        f:issuerRef:
          .:
          f:group:
          f:kind:
          f:name:
        f:secretName:
        f:usages:
      f:status:
        .:
        f:conditions:
        f:nextPrivateKeySecretName:
    Manager:    controller
    Operation:  Update
    Time:       2022-02-08T10:34:41Z
  Owner References:
    API Version:           networking.k8s.io/v1
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Ingress
    Name:                  flask-ingress
    UID:                   <UID>
  Resource Version:        321990
  UID:                     <UID>
Spec:
  Dns Names:
    www.<DOMAIN>.net
  Issuer Ref:
    Group:      cert-manager.io
    Kind:       Issuer
    Name:       letsencrypt-staging
  Secret Name:  quickstart-example-tls
  Usages:
    digital signature
    key encipherment
Status:
  Conditions:
    Last Transition Time:        2022-02-08T10:34:40Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      True
    Type:                        Issuing
    Last Transition Time:        2022-02-08T10:34:40Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      False
    Type:                        Ready
  Next Private Key Secret Name:  quickstart-example-tls-w4psf
Events:
  Type    Reason     Age    From          Message
  ----    ------     ----   ----          -------
  Normal  Issuing    2m14s  cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  2m13s  cert-manager  Stored new private key in temporary Secret resource "quickstart-example-tls-w4psf"
  Normal  Requested  2m13s  cert-manager  Created new CertificateRequest resource "quickstart-example-tls-znhlv"
</code>```

So this is were things get stucked and IDK why.

```<code># kubectl describe certificaterequest quickstart-example-tls
Name:         quickstart-example-tls-znhlv
Namespace:    default
Labels:       <none>
Annotations:  cert-manager.io/certificate-name: quickstart-example-tls
              cert-manager.io/certificate-revision: 1
              cert-manager.io/private-key-secret-name: quickstart-example-tls-w4psf
API Version:  cert-manager.io/v1
Kind:         CertificateRequest
Metadata:
  Creation Timestamp:  2022-02-08T10:34:41Z
  Generate Name:       quickstart-example-tls-
  Generation:          1
  Managed Fields:
    API Version:  cert-manager.io/v1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .:
          f:cert-manager.io/certificate-name:
          f:cert-manager.io/certificate-revision:
          f:cert-manager.io/private-key-secret-name:
        f:generateName:
        f:ownerReferences:
          .:
          k:{"uid":"<UID>"}:
            .:
            f:apiVersion:
            f:blockOwnerDeletion:
            f:controller:
            f:kind:
            f:name:
            f:uid:
      f:spec:
        .:
        f:issuerRef:
          .:
          f:group:
          f:kind:
          f:name:
        f:request:
        f:usages:
      f:status:
        .:
        f:conditions:
    Manager:    controller
    Operation:  Update
    Time:       2022-02-08T10:34:41Z
  Owner References:
    API Version:           cert-manager.io/v1
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Certificate
    Name:                  quickstart-example-tls
    UID:                   <UID>
  Resource Version:        322003
  UID:                     <UID>
Spec:
  Extra:
    authentication.kubernetes.io/pod-name:
      cert-manager-6d8d028374dbb-f43n7
    authentication.kubernetes.io/pod-uid:
      <UID>
  Groups:
    system:serviceaccounts
    system:serviceaccounts:cert-manager
    system:authenticated
  Issuer Ref:
    Group:  cert-manager.io
    Kind:   Issuer
    Name:   letsencrypt-staging
  Request:  <Request ID>
  UID:      <UID>
  Usages:
    digital signature
    key encipherment
  Username:  system:serviceaccount:cert-manager:cert-manager
Status:
  Conditions:
    Last Transition Time:  2022-02-08T10:34:41Z
    Message:               Certificate request has been approved by cert-manager.io
    Reason:                cert-manager.io
    Status:                True
    Type:                  Approved
    Last Transition Time:  2022-02-08T10:34:43Z
    Message:               Waiting on certificate issuance from order default/quickstart-example-tls-znhlv-138543614: "pending"
    Reason:                Pending
    Status:                False
    Type:                  Ready
Events:
  Type    Reason           Age    From          Message
  ----    ------           ----   ----          -------
  Normal  cert-manager.io  4m54s  cert-manager  Certificate request has been approved by cert-manager.io
  Normal  OrderCreated     4m53s  cert-manager  Created Order resource default/quickstart-example-tls-znhlv-138543614
</code>```

Having a look at the challenge, all seems to work.

```<code>....
Status:
  Conditions:
    Last Transition Time:        2022-02-08T10:00:01Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      False
    Type:                        Ready
    Last Transition Time:        2022-02-08T10:00:02Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      True
    Type:                        Issuing
  Next Private Key Secret Name:  quickstart-example-tls-d87r6
Events:
  Type    Reason     Age   From          Message
  ----    ------     ----  ----          -------
  Normal  Issuing    21m   cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  21m   cert-manager  Stored new private key in temporary Secret resource "quickstart-example-tls-d87r6"
  Normal  Requested  21m   cert-manager  Created new CertificateRequest resource "quickstart-example-tls-kxwqd"

</code>```0
```<code>....
Status:
  Conditions:
    Last Transition Time:        2022-02-08T10:00:01Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      False
    Type:                        Ready
    Last Transition Time:        2022-02-08T10:00:02Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      True
    Type:                        Issuing
  Next Private Key Secret Name:  quickstart-example-tls-d87r6
Events:
  Type    Reason     Age   From          Message
  ----    ------     ----  ----          -------
  Normal  Issuing    21m   cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  21m   cert-manager  Stored new private key in temporary Secret resource "quickstart-example-tls-d87r6"
  Normal  Requested  21m   cert-manager  Created new CertificateRequest resource "quickstart-example-tls-kxwqd"

</code>```1

All seems to be fine, but I do not get the certificate?

A couple of additional things:

I use digital ocean managed kubernetes 1.21

I installed ingress-nginx via UI in digital ocean to namespace ingress-nginx

I use cert-manager 1.7

```<code>....
Status:
  Conditions:
    Last Transition Time:        2022-02-08T10:00:01Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      False
    Type:                        Ready
    Last Transition Time:        2022-02-08T10:00:02Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      True
    Type:                        Issuing
  Next Private Key Secret Name:  quickstart-example-tls-d87r6
Events:
  Type    Reason     Age   From          Message
  ----    ------     ----  ----          -------
  Normal  Issuing    21m   cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  21m   cert-manager  Stored new private key in temporary Secret resource "quickstart-example-tls-d87r6"
  Normal  Requested  21m   cert-manager  Created new CertificateRequest resource "quickstart-example-tls-kxwqd"

</code>```2

Looking add the logs from cert-manager, I get that get request failed although it works actually.

```<code># kubectl logs cert-manager-6d8d6b5dbb-f4xn7 -n cert-manager
E0208 15:07:31.660877       1 sync.go:186] cert-manager/challenges "msg"="propagation check failed" "error"="failed to perform self check GET request 'http://www.<DOMAIN>.net/.well-known/acme-challenge/<SOMEToken>': Get \"http://www.<DOMAIN>.net/.well-known/acme-challenge/<SOMEToken>\": EOF" "dnsName"="www.<DOMAIN>.net" "resource_kind"="Challenge" "resource_name"="quickstart-example-tls-znhlv-138543614-1891152753" "resource_namespace"="default" "resource_version"="v1" "type"="HTTP-01"
</code>```

答:
@Rychu linked me to the answer here. This goes also back to this post step 5

For my case I did

Added a DNS entry on digital ocean for "workaround.<"DOMAIN">.net" to point to my load balancer and then I updated my ingress_controller:

```<code>cat ingress_nginx_svc.yaml
</code>```
```<code>apiVersion: v1
kind: Service
metadata:
  annotations:
    service.beta.kubernetes.io/do-loadbalancer-enable-proxy-protocol: 'true'
    service.beta.kubernetes.io/do-loadbalancer-hostname: "workaround.<DOMAIN>.net"
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/version: 1.0.4
    helm.sh/chart: ingress-nginx-4.0.6
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  externalTrafficPolicy: Cluster
  ports:
  - appProtocol: http
    name: http
    nodePort: 31799
    port: 80
    protocol: TCP
    targetPort: http
  - appProtocol: https
    name: https
    nodePort: 32533
    port: 443
    protocol: TCP
    targetPort: https
  selector:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
  type: LoadBalancer
</code>```
```<code>kubectl apply -f ingress_nginx_svc.yaml
</code>```

Then you should see something like this

```<code># kubectl describe certificate
  Type    Reason     Age                  From          Message
  ----    ------     ----                 ----          -------
  Normal  Issuing    15m                  cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  15m                  cert-manager  Stored new private key in temporary Secret resource "quickstart-example-tls-zj57f"
  Normal  Requested  15m                  cert-manager  Created new CertificateRequest resource "quickstart-example-tls-gc599"
  Normal  Issuing    8m3s                 cert-manager  Issuing certificate as Secret was previously issued by Issuer.cert-manager.io/letsencrypt-staging
  Normal  Reused     8m2s                 cert-manager  Reusing private key stored in existing Secret resource "quickstart-example-tls"
  Normal  Requested  8m2s                 cert-manager  Created new CertificateRequest resource "quickstart-example-tls-55xcw"
  Normal  Issuing    7m33s (x2 over 11m)  cert-manager  The certificate has been successfully issued
</code>```

That solved my problem! Thanks again @Rychu for pointing me to that

Body:
I am following this tutorial to use a trusted TLS certificate in my ingress rules. All works, however

kubectl describe certificate quickstart-example-tls

gives & gets stuck at Created new CertificateRequest resource

....
Status:
  Conditions:
    Last Transition Time:        2022-02-08T10:00:01Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      False
    Type:                        Ready
    Last Transition Time:        2022-02-08T10:00:02Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      True
    Type:                        Issuing
  Next Private Key Secret Name:  quickstart-example-tls-d87r6
Events:
  Type    Reason     Age   From          Message
  ----    ------     ----  ----          -------
  Normal  Issuing    21m   cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  21m   cert-manager  Stored new private key in temporary Secret resource "quickstart-example-tls-d87r6"
  Normal  Requested  21m   cert-manager  Created new CertificateRequest resource "quickstart-example-tls-kxwqd"

First let me share my ingress rules and Issuers:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: flask-ingress
spec:
  ingressClassName: nginx
  rules:
  - host: www.<Domain>.net
    http:
      paths:
      - pathType: Prefix
        path: /
        backend:
          service:
            name: flask
            port:
              number: 5000

I set up DNS (in digital ocean) rules so curling (via web) works.

curl "http://www.<Domain>.net"

Hello, World!
%

Here my issuer file:

apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: letsencrypt-staging
  namespace: default
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: <MY-EMAIL>
    privateKeySecretRef:
      name: letsencrypt-staging
    solvers:
    - http01:
        ingress:
          class: nginx

# kubectl get issuer
NAME                  READY   AGE
letsencrypt-staging   True    26s

Now I update my ingress rule and start the challenge:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: flask-ingress
  annotations:
    cert-manager.io/issuer: letsencrypt-staging
spec:
  tls:
  - hosts:
     - www.<DOMAIN>.net
    secretName: quickstart-example-tls
  ingressClassName: nginx
  rules:
  - host: www.<DOMAIN>.net
    http:
      paths:
      - pathType: Prefix
        path: /
        backend:
          service:
            name: flask
            port:
              number: 5000

#kubectl get certificate
NAME                     READY   SECRET                   AGE
quickstart-example-tls   False   quickstart-example-tls   88s

Here the detailed output:

#kubectl describe certificate quickstart-example-tls
Name:         quickstart-example-tls
Namespace:    default
Labels:       <none>
Annotations:  <none>
API Version:  cert-manager.io/v1
Kind:         Certificate
Metadata:
  Creation Timestamp:  2022-02-08T10:34:40Z
  Generation:          1
  Managed Fields:
    API Version:  cert-manager.io/v1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:ownerReferences:
          .:
          k:{"uid":"<UID>"}:
            .:
            f:apiVersion:
            f:blockOwnerDeletion:
            f:controller:
            f:kind:
            f:name:
            f:uid:
      f:spec:
        .:
        f:dnsNames:
        f:issuerRef:
          .:
          f:group:
          f:kind:
          f:name:
        f:secretName:
        f:usages:
      f:status:
        .:
        f:conditions:
        f:nextPrivateKeySecretName:
    Manager:    controller
    Operation:  Update
    Time:       2022-02-08T10:34:41Z
  Owner References:
    API Version:           networking.k8s.io/v1
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Ingress
    Name:                  flask-ingress
    UID:                   <UID>
  Resource Version:        321990
  UID:                     <UID>
Spec:
  Dns Names:
    www.<DOMAIN>.net
  Issuer Ref:
    Group:      cert-manager.io
    Kind:       Issuer
    Name:       letsencrypt-staging
  Secret Name:  quickstart-example-tls
  Usages:
    digital signature
    key encipherment
Status:
  Conditions:
    Last Transition Time:        2022-02-08T10:34:40Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      True
    Type:                        Issuing
    Last Transition Time:        2022-02-08T10:34:40Z
    Message:                     Issuing certificate as Secret does not exist
    Observed Generation:         1
    Reason:                      DoesNotExist
    Status:                      False
    Type:                        Ready
  Next Private Key Secret Name:  quickstart-example-tls-w4psf
Events:
  Type    Reason     Age    From          Message
  ----    ------     ----   ----          -------
  Normal  Issuing    2m14s  cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  2m13s  cert-manager  Stored new private key in temporary Secret resource "quickstart-example-tls-w4psf"
  Normal  Requested  2m13s  cert-manager  Created new CertificateRequest resource "quickstart-example-tls-znhlv"

So this is were things get stucked and IDK why.

# kubectl describe certificaterequest quickstart-example-tls
Name:         quickstart-example-tls-znhlv
Namespace:    default
Labels:       <none>
Annotations:  cert-manager.io/certificate-name: quickstart-example-tls
              cert-manager.io/certificate-revision: 1
              cert-manager.io/private-key-secret-name: quickstart-example-tls-w4psf
API Version:  cert-manager.io/v1
Kind:         CertificateRequest
Metadata:
  Creation Timestamp:  2022-02-08T10:34:41Z
  Generate Name:       quickstart-example-tls-
  Generation:          1
  Managed Fields:
    API Version:  cert-manager.io/v1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .:
          f:cert-manager.io/certificate-name:
          f:cert-manager.io/certificate-revision:
          f:cert-manager.io/private-key-secret-name:
        f:generateName:
        f:ownerReferences:
          .:
          k:{"uid":"<UID>"}:
            .:
            f:apiVersion:
            f:blockOwnerDeletion:
            f:controller:
            f:kind:
            f:name:
            f:uid:
      f:spec:
        .:
        f:issuerRef:
          .:
          f:group:
          f:kind:
          f:name:
        f:request:
        f:usages:
      f:status:
        .:
        f:conditions:
    Manager:    controller
    Operation:  Update
    Time:       2022-02-08T10:34:41Z
  Owner References:
    API Version:           cert-manager.io/v1
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Certificate
    Name:                  quickstart-example-tls
    UID:                   <UID>
  Resource Version:        322003
  UID:                     <UID>
Spec:
  Extra:
    authentication.kubernetes.io/pod-name:
      cert-manager-6d8d028374dbb-f43n7
    authentication.kubernetes.io/pod-uid:
      <UID>
  Groups:
    system:serviceaccounts
    system:serviceaccounts:cert-manager
    system:authenticated
  Issuer Ref:
    Group:  cert-manager.io
    Kind:   Issuer
    Name:   letsencrypt-staging
  Request:  <Request ID>
  UID:      <UID>
  Usages:
    digital signature
    key encipherment
  Username:  system:serviceaccount:cert-manager:cert-manager
Status:
  Conditions:
    Last Transition Time:  2022-02-08T10:34:41Z
    Message:               Certificate request has been approved by cert-manager.io
    Reason:                cert-manager.io
    Status:                True
    Type:                  Approved
    Last Transition Time:  2022-02-08T10:34:43Z
    Message:               Waiting on certificate issuance from order default/quickstart-example-tls-znhlv-138543614: "pending"
    Reason:                Pending
    Status:                False
    Type:                  Ready
Events:
  Type    Reason           Age    From          Message
  ----    ------           ----   ----          -------
  Normal  cert-manager.io  4m54s  cert-manager  Certificate request has been approved by cert-manager.io
  Normal  OrderCreated     4m53s  cert-manager  Created Order resource default/quickstart-example-tls-znhlv-138543614

Having a look at the challenge, all seems to work.

# kubectl describe challenges --all-namespaces
Name:         quickstart-example-tls-znhlv-138543614-1891152753
Namespace:    default
Labels:       <none>
Annotations:  <none>
API Version:  acme.cert-manager.io/v1
Kind:         Challenge
Metadata:
  Creation Timestamp:  2022-02-08T10:34:44Z
  Finalizers:
    finalizer.acme.cert-manager.io
  Generation:  1
  Managed Fields:
    API Version:  acme.cert-manager.io/v1
    Fields Type:  FieldsV1
    fieldsV1:
      f:metadata:
        f:finalizers:
          .:
          v:"finalizer.acme.cert-manager.io":
        f:ownerReferences:
          .:
          k:{"uid":"<UID>"}:
            .:
            f:apiVersion:
            f:blockOwnerDeletion:
            f:controller:
            f:kind:
            f:name:
            f:uid:
      f:spec:
        .:
        f:authorizationURL:
        f:dnsName:
        f:issuerRef:
          .:
          f:group:
          f:kind:
          f:name:
        f:key:
        f:solver:
          .:
          f:http01:
            .:
            f:ingress:
              .:
              f:class:
        f:token:
        f:type:
        f:url:
        f:wildcard:
      f:status:
        .:
        f:presented:
        f:processing:
        f:reason:
        f:state:
    Manager:    controller
    Operation:  Update
    Time:       2022-02-08T10:34:46Z
  Owner References:
    API Version:           acme.cert-manager.io/v1
    Block Owner Deletion:  true
    Controller:            true
    Kind:                  Order
    Name:                  quickstart-example-tls-znhlv-138543614
    UID:                   <UID>
  Resource Version:        322038
  UID:                     <UID>
Spec:
  Authorization URL:  https://acme-staging-v02.api.letsencrypt.org/acme/authz-v3/<NR>
  Dns Name:           www.<DOMAIN>.net
  Issuer Ref:
    Group:  cert-manager.io
    Kind:   Issuer
    Name:   letsencrypt-staging
  Key:      <SOMEKEY>
  Solver:
    http01:
      Ingress:
        Class:  nginx
  Token:        <SOMEToken>
  Type:         HTTP-01
  URL:          https://acme-staging-v02.api.letsencrypt.org/acme/chall-v3/<NR>/
  Wildcard:     false
Status:
  Presented:   true
  Processing:  true
  Reason:      Waiting for HTTP-01 challenge propagation: failed to perform self check GET request 'http://www.<DOMAIN>.net/.well-known/acme-challenge/<SOMEToken>': Get "http://www.<DOMAIN>.net/.well-known/acme-challenge/<SOMEToken>": EOF
  State:       pending
Events:
  Type    Reason     Age    From          Message
  ----    ------     ----   ----          -------
  Normal  Started    6m18s  cert-manager  Challenge scheduled for processing
  Normal  Presented  6m17s  cert-manager  Presented challenge using HTTP-01 challenge mechanism

#curl "http://www.<DOMAIN>.net/.well-known/acme-challenge/<SOMEToken>"
<SOMEKEY>%

All seems to be fine, but I do not get the certificate?

A couple of additional things:

I use digital ocean managed kubernetes 1.21

I installed ingress-nginx via UI in digital ocean to namespace ingress-nginx

I use cert-manager 1.7

#kubectl get pods -n cert-manager
NAME                                     READY   STATUS    RESTARTS   AGE
cert-manager-6d8d6b5dbb-f4xn7            1/1     Running   0          47h
cert-manager-cainjector-d6cbc4d9-g6j8c   1/1     Running   0          47h
cert-manager-webhook-85fb68c79b-sv8pb    1/1     Running   0          47h

Looking add the logs from cert-manager, I get that get request failed although it works actually.

# kubectl logs cert-manager-6d8d6b5dbb-f4xn7 -n cert-manager
E0208 15:07:31.660877       1 sync.go:186] cert-manager/challenges "msg"="propagation check failed" "error"="failed to perform self check GET request 'http://www.<DOMAIN>.net/.well-known/acme-challenge/<SOMEToken>': Get \"http://www.<DOMAIN>.net/.well-known/acme-challenge/<SOMEToken>\": EOF" "dnsName"="www.<DOMAIN>.net" "resource_kind"="Challenge" "resource_name"="quickstart-example-tls-znhlv-138543614-1891152753" "resource_namespace"="default" "resource_version"="v1" "type"="HTTP-01"

Body:
@Rychu linked me to the answer here. This goes also back to this post step 5

For my case I did

Added a DNS entry on digital ocean for "workaround.<"DOMAIN">.net" to point to my load balancer and then I updated my ingress_controller:

cat ingress_nginx_svc.yaml

apiVersion: v1
kind: Service
metadata:
  annotations:
    service.beta.kubernetes.io/do-loadbalancer-enable-proxy-protocol: 'true'
    service.beta.kubernetes.io/do-loadbalancer-hostname: "workaround.<DOMAIN>.net"
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/version: 1.0.4
    helm.sh/chart: ingress-nginx-4.0.6
  name: ingress-nginx-controller
  namespace: ingress-nginx
spec:
  externalTrafficPolicy: Cluster
  ports:
  - appProtocol: http
    name: http
    nodePort: 31799
    port: 80
    protocol: TCP
    targetPort: http
  - appProtocol: https
    name: https
    nodePort: 32533
    port: 443
    protocol: TCP
    targetPort: https
  selector:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
  type: LoadBalancer

kubectl apply -f ingress_nginx_svc.yaml

Then you should see something like this

# kubectl describe certificate
  Type    Reason     Age                  From          Message
  ----    ------     ----                 ----          -------
  Normal  Issuing    15m                  cert-manager  Issuing certificate as Secret does not exist
  Normal  Generated  15m                  cert-manager  Stored new private key in temporary Secret resource "quickstart-example-tls-zj57f"
  Normal  Requested  15m                  cert-manager  Created new CertificateRequest resource "quickstart-example-tls-gc599"
  Normal  Issuing    8m3s                 cert-manager  Issuing certificate as Secret was previously issued by Issuer.cert-manager.io/letsencrypt-staging
  Normal  Reused     8m2s                 cert-manager  Reusing private key stored in existing Secret resource "quickstart-example-tls"
  Normal  Requested  8m2s                 cert-manager  Created new CertificateRequest resource "quickstart-example-tls-55xcw"
  Normal  Issuing    7m33s (x2 over 11m)  cert-manager  The certificate has been successfully issued

That solved my problem! Thanks again @Rychu for pointing me to that


问:
Maven clean compile does not work
I have maven-compiler-plugin in my pom file as follows but compiler get angry with generic parameters. my maven version is "Apache Maven 3.0.3 (r1075438; 2011-02-28 19:31:09+0200)"

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
        <compilerVersion>1.6</compilerVersion>
    </configuration>
</plugin>
</code>```

and the class which compiler get angry is as follows

```<code>List<EulTransactionHistory> list = hibernateTemplate.findByCriteria(criteria, -1, 1);
EulTransactionHistory existingRecord = DBUtils.oneAndOnlyOne(list);
</code>```

and the spec for DBUtils.oneAndOnlyOne is as follows

```<code>public static <T> T oneAndOnlyOne(List<T> list) {...}
</code>```

finally the exception is

```<code>Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project etlscheduler: Compilation failure: Compilation failure SchedulerDaoImpl.java:[329,18] incompatible types
found   : java.lang.Object
required: com.aric.etlscheduler.domain.EulTransactionHistory
</code>```

Moreover when I compile this project with eclipse it compiles sucessfully.

答: The jar containing the com.aric.etlscheduler.domain.EulTransactionHistory class is missing from the classpath of your project. Make sure you have added the jar as dependency in your project's pom.

ContentLicense: CC BY-SA 3.0

Title: Maven clean compile does not work

Body:
I have maven-compiler-plugin in my pom file as follows but compiler get angry with generic parameters. my maven version is "Apache Maven 3.0.3 (r1075438; 2011-02-28 19:31:09+0200)"

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
        <compilerVersion>1.6</compilerVersion>
    </configuration>
</plugin>

and the class which compiler get angry is as follows

List<EulTransactionHistory> list = hibernateTemplate.findByCriteria(criteria, -1, 1);
EulTransactionHistory existingRecord = DBUtils.oneAndOnlyOne(list);

and the spec for DBUtils.oneAndOnlyOne is as follows

public static <T> T oneAndOnlyOne(List<T> list) {...}

finally the exception is

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project etlscheduler: Compilation failure: Compilation failure SchedulerDaoImpl.java:[329,18] incompatible types
found   : java.lang.Object
required: com.aric.etlscheduler.domain.EulTransactionHistory

Moreover when I compile this project with eclipse it compiles sucessfully.


答:
This may be done with min/max and group by/summarise

```<code>library(dplyr)
data %>%
   group_by(Location) %>%
   summarise(Min = min(DateTime), Max = max(DateTime))
</code>```

splitting to a list and then looping is not really needed.  In case, if it is just to understand the usage with map - loop over the split list with map, apply summarise to return the min/max as columns and bind the output list element rbinded with _dfr

```<code>library(purrr)
map_dfr(data_grouped, ~ .x %>%
  summarise(Location = first(Location),
    Min = min(DateTime), Max = max(DateTime)))
</code>```

Title: Using Purr and Map to extract information from grouped data

Body:
I have a data set that I need to gather grouped data, such as the minimum time, maximum time, etc.

> data
# A tibble: 9 x 3
  DateTime            Location Temperature
  <dttm>              <chr>          <dbl>
1 2022-01-30 18:00:00 A               122
2 2022-01-30 18:00:00 B               123
3 2022-01-30 18:00:20 C               112
4 2022-01-30 18:01:00 A               123
5 2022-01-30 18:01:00 B               124
6 2022-01-30 18:01:20 C               114
7 2022-01-30 18:02:00 A               122.
8 2022-01-30 18:02:00 B               123
9 2022-01-30 18:02:20 C               115

I would like to have to a summary something like

Location   Min                       Max
A          2022-01-30 18:00:00       2022-01-30 18:02:00
B          2022-01-30 18:00:00       2022-01-30 18:02:00
C          2022-01-30 18:00:20       2022-01-30 18:00:20

I was able to split it into grouped tibbles using the following:

> data_grouped <- data %>%
+   split(.$Location)
> data
# A tibble: 9 x 3
  DateTime            Location Temperature
  <dttm>              <chr>          <dbl>
1 2022-01-30 18:00:00 A               122
2 2022-01-30 18:00:00 B               123
3 2022-01-30 18:00:20 C               112
4 2022-01-30 18:01:00 A               123
5 2022-01-30 18:01:00 B               124
6 2022-01-30 18:01:20 C               114
7 2022-01-30 18:02:00 A               122.
8 2022-01-30 18:02:00 B               123
9 2022-01-30 18:02:20 C               115
> data_grouped <- data %>%
+   split(.$Location)
> data_grouped
$A
# A tibble: 3 x 3
  DateTime            Location Temperature
  <dttm>              <chr>          <dbl>
1 2022-01-30 18:00:00 A               122
2 2022-01-30 18:01:00 A               123
3 2022-01-30 18:02:00 A               122.

$B
# A tibble: 3 x 3
  DateTime            Location Temperature
  <dttm>              <chr>          <dbl>
1 2022-01-30 18:00:00 B                123
2 2022-01-30 18:01:00 B                124
3 2022-01-30 18:02:00 B                123

$C
# A tibble: 3 x 3
  DateTime            Location Temperature
  <dttm>              <chr>          <dbl>
1 2022-01-30 18:00:20 C                112
2 2022-01-30 18:01:20 C                114
3 2022-01-30 18:02:20 C                115

But I cannot get it any further.  Can someone offer me some suggestions?  A working copy of the data is below.

library(tidyverse)
library(lubridate)
library(purrr)

data <- tibble(
  DateTime = ymd_hms("2022-01-30 18:00:00",
                     "2022-01-30 18:00:00",
                     "2022-01-30 18:00:20",
                     "2022-01-30 18:01:00",
                     "2022-01-30 18:01:00",
                     "2022-01-30 18:01:20",
                     "2022-01-30 18:02:00",
                     "2022-01-30 18:02:00",
                     "2022-01-30 18:02:20"),
  Location = rep(c("A","B","C"),3),
  Temperature = c(122,123,112,123,124,114,122.5,123,115)
)

Thank you kindly!

Shawn Way

Body:
This may be done with min/max and group by/summarise

library(dplyr)
data %>%
   group_by(Location) %>%
   summarise(Min = min(DateTime), Max = max(DateTime))

splitting to a list and then looping is not really needed.  In case, if it is just to understand the usage with map - loop over the split list with map, apply summarise to return the min/max as columns and bind the output list element rbinded with _dfr

library(purrr)
map_dfr(data_grouped, ~ .x %>%
  summarise(Location = first(Location),
    Min = min(DateTime), Max = max(DateTime)))


问:
How to optimize django .get() with prefetch and select related?
I am currently experimenting with django to get a little bit more knowledgeable about queries and the orm. I am simply just doing trial and error on how to optimize them or even write them. Assuming my models are as follow,

```<code>class Book(models.Model):
    name = models.CharField()
    isbn = models.CharField()
    author = models.ForeignKey('Author', related_name='books')

class Author(models.Model):
    name = models.CharField()

class ReadingList(models.Model):
    books = models.ManyToMany(Book, related_name='reading_lists')

</code>```

I learned that I am able to optimize my query as follows

```<code># example 1
query = Book.objects.all()  # or .filter(...)
query = query.only('name')
query = query.select_related('author')
query = query.prefetch_related('reading_lists')
</code>```

this is definitely very useful especially with very long queries as it lets you easily break them up. However, when trying .get(), I end up getting errors: 'Book' object has no attribute 'only', 'Book' object has no attribute 'select_related', 'Book' object has no attribute 'prefetch_related'

As it turns out, in order for me to use .only(), .select_related(), and .prefetch_related() is if I write them before the .get()

```<code># example 2
Book.objects.only('name').select_related('author').prefetch_related('reading_lists').get(...)
</code>```

Is there a way in which I can write example 2 in the same way as example 1, just using .get()?

答:
QuerySets are lazy, so you can keep chaining and end the call with a .get(…) that will then fetch the object:

```<code>query = Book.objects.all()
query = query.only('name')
query = query.select_related('author')
query = query.prefetch_related('reading_lists')
item = query.get(…)</code>```

Body:
I am currently experimenting with django to get a little bit more knowledgeable about queries and the orm. I am simply just doing trial and error on how to optimize them or even write them. Assuming my models are as follow,

class Book(models.Model):
    name = models.CharField()
    isbn = models.CharField()
    author = models.ForeignKey('Author', related_name='books')

class Author(models.Model):
    name = models.CharField()

class ReadingList(models.Model):
    books = models.ManyToMany(Book, related_name='reading_lists')

I learned that I am able to optimize my query as follows

# example 1
query = Book.objects.all()  # or .filter(...)
query = query.only('name')
query = query.select_related('author')
query = query.prefetch_related('reading_lists')

this is definitely very useful especially with very long queries as it lets you easily break them up. However, when trying .get(), I end up getting errors: 'Book' object has no attribute 'only', 'Book' object has no attribute 'select_related', 'Book' object has no attribute 'prefetch_related'

As it turns out, in order for me to use .only(), .select_related(), and .prefetch_related() is if I write them before the .get()

# example 2
Book.objects.only('name').select_related('author').prefetch_related('reading_lists').get(...)

Is there a way in which I can write example 2 in the same way as example 1, just using .get()?

Body:
QuerySets are lazy, so you can keep chaining and end the call with a .get(…) that will then fetch the object:

query = Book.objects.all()
query = query.only('name')
query = query.select_related('author')
query = query.prefetch_related('reading_lists')
item = query.get(…)


问:
Blockchair - dump files does not contain decimal bitcoin values
I hope this is the correct place to ask this.

I have downloaded a dump file from Blockchair containing blockchain transactions. Everything looks fine, but the decimal separator is removed in the values for the amount of bitcoins.

For example:

This is the real amount of btc: 0.00253658

This is what the dump file shows: 253658

Hash link: https://blockchair.com/bitcoin/transaction/16fbf725fab270860323cca7a16c71002af2c419b067dc0787e7ab461811d35a

Dump file row:

Does someone know how to fix this?

答: Someone on another forum gave me the answer: the result in the dump file is given in Statoshi, not bitcoin. 1 Satoshi = 1e10^(-8) BTC.</p>


问:
How to modify subscribe result in angular template?
I have an observable this.result$ to which i am subscribing inside template . for e.g result is- [{id : "1", value: "test"}]. How can I add new object to this so that it become like this-
[{id : "1", value: "test"},{id : "2", value: "new"}]

```<code><mat-form-field *ngIf="result$ | async">
  <mat-select [compareWith] = "compareFn">
    <mat-option *ngFor = "let item of result$ | async" [value]="item">
       {{item.value}}
    </mat-option>
  </mat-select>
</mat-form-field>
</code>```

答:
I recommend you to change the code for this.
In your .ts file for example:

```<code>objectList: any[] = [];

ngOnInit(): void {
   this.result$.subscribe(r => {
         this.objectList.push(r);
    });
}

addNewObject(newObject: any): void {
   this.objectList.push(newObject);
}
</code>```

In your .html file use this.

```<code><mat-form-field *ngIf="objectList && objectList.lenght > 0">
  <mat-select [compareWith] = "compareFn">
    <mat-option *ngFor = "let item of objectList" [value]="item">
       {{item.value}}
    </mat-option>
  </mat-select>
</mat-form-field>
</code>```

Body:
I have an observable this.result$ to which i am subscribing inside template . for e.g result is- [{id : "1", value: "test"}]. How can I add new object to this so that it become like this-
[{id : "1", value: "test"},{id : "2", value: "new"}]

<mat-form-field *ngIf="result$ | async">
  <mat-select [compareWith] = "compareFn">
    <mat-option *ngFor = "let item of result$ | async" [value]="item">
       {{item.value}}
    </mat-option>
  </mat-select>
</mat-form-field>

Body:
I recommend you to change the code for this.
In your .ts file for example:

objectList: any[] = [];

ngOnInit(): void {
   this.result$.subscribe(r => {
         this.objectList.push(r);
    });
}

addNewObject(newObject: any): void {
   this.objectList.push(newObject);
}

In your .html file use this.

<mat-form-field *ngIf="objectList && objectList.lenght > 0">
  <mat-select [compareWith] = "compareFn">
    <mat-option *ngFor = "let item of objectList" [value]="item">
       {{item.value}}
    </mat-option>
  </mat-select>
</mat-form-field>


问:
How to get Text BOLD in Alert or Confirm box?
How to get BOLD Text and change color of text in Alert or Confirm box?</p>

```<code>var conFrm =  confirm("Following List(s) already Sent...!\n<strong>List Name:  </strong>"+ss.replace(",","\n<b>Name: </b>")+"\n Do you want to send again...!");
</code>```

Body:
How to get BOLD Text and change color of text in Alert or Confirm box?

var conFrm =  confirm("Following List(s) already Sent...!\nList Name:  "+ss.replace(",","\nName: ")+"\n Do you want to send again...!");

Body:
Add this function to your source:

function toUnicodeVariant(str, variant, flags) {
    const offsets = {
        m: [0x1d670, 0x1d7f6],
        b: [0x1d400, 0x1d7ce],
        i: [0x1d434, 0x00030],
        bi: [0x1d468, 0x00030],
        c: [0x1d49c, 0x00030],
        bc: [0x1d4d0, 0x00030],
        g: [0x1d504, 0x00030],
        d: [0x1d538, 0x1d7d8],
        bg: [0x1d56c, 0x00030],
        s: [0x1d5a0, 0x1d7e2],
        bs: [0x1d5d4, 0x1d7ec],
        is: [0x1d608, 0x00030],
        bis: [0x1d63c, 0x00030],
        o: [0x24B6, 0x2460],
        p: [0x249C, 0x2474],
        w: [0xff21, 0xff10],
        u: [0x2090, 0xff10]
    }

    const variantOffsets = {
        'monospace': 'm',
        'bold': 'b',
        'italic': 'i',
        'bold italic': 'bi',
        'script': 'c',
        'bold script': 'bc',
        'gothic': 'g',
        'gothic bold': 'bg',
        'doublestruck': 'd',
        'sans': 's',
        'bold sans': 'bs',
        'italic sans': 'is',
        'bold italic sans': 'bis',
        'parenthesis': 'p',
        'circled': 'o',
        'fullwidth': 'w'
    }

    // special characters (absolute values)
    var special = {
        m: {
            ' ': 0x2000,
            '-': 0x2013
        },
        i: {
            'h': 0x210e
        },
        g: {
            'C': 0x212d,
            'H': 0x210c,
            'I': 0x2111,
            'R': 0x211c,
            'Z': 0x2128
        },
        o: {
            '0': 0x24EA,
            '1': 0x2460,
            '2': 0x2461,
            '3': 0x2462,
            '4': 0x2463,
            '5': 0x2464,
            '6': 0x2465,
            '7': 0x2466,
            '8': 0x2467,
            '9': 0x2468,
        },
        p: {},
        w: {}
    }
    //support for parenthesized latin letters small cases
    for (var i = 97; i <= 122; i++) {
        special.p[String.fromCharCode(i)] = 0x249C + (i - 97)
    }
    //support for full width latin letters small cases
    for (var i = 97; i <= 122; i++) {
        special.w[String.fromCharCode(i)] = 0xff41 + (i - 97)
    }

    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    const numbers = '0123456789';

    var getType = function (variant) {
        if (variantOffsets[variant]) return variantOffsets[variant]
        if (offsets[variant]) return variant;
        return 'm'; //monospace as default
    }
    var getFlag = function (flag, flags) {
        if (!flags) return false
        return flags.split(',').indexOf(flag) > -1
    }

    var type = getType(variant);
    var underline = getFlag('underline', flags);
    var strike = getFlag('strike', flags);
    var result = '';

    for (var k of str) {
        let index
        let c = k
        if (special[type] && special[type][c]) c = String.fromCodePoint(special[type][c])
        if (type && (index = chars.indexOf(c)) > -1) {
            result += String.fromCodePoint(index + offsets[type][0])
        } else if (type && (index = numbers.indexOf(c)) > -1) {
            result += String.fromCodePoint(index + offsets[type][1])
        } else {
            result += c
        }
        if (underline) result += '\u0332' // add combining underline
        if (strike) result += '\u0336' // add combining strike
    }
    return result
}

Call it like:

alert('your chance is: ' + toUnicodeVariant('100%', 'bold sans', 'bold'));

Read more about this here: https://github.com/davidkonrad/toUnicodeVariant


问:
Groovy: Maps deep nesting
I got a map matrix that looks like this:

```<code>def matrix = [
    field1:[role1:[state1:["f1r1s1",true],
                   state2:["f1r1s2",false]],
            role2:[state1:["f1r2s1",true],
                   state2:["f1r2s2",false]]
           ],
    field2:[role1:[state1:["f2r1s1",true],
                   state2:["f2r1s2",false]],
            role2:[state1:["f2r2s1",true],
                   state2:["f1r2s2",false]]
           ]
]
</code>```

I am trying to get all fields where role is "role1" and state is "state1". Easy? Help pls.

答:
You can do:

```<code>def map = matrix.inject([:]) { map, elem -> map << [ (elem.key): elem.value[ 'role1' ][ 'state1' ] ] }
</code>```

to get your required result:

```<code>[field1:[f1r1s1, true], field2:[f2r1s1, true]]
</code>```

Title: Groovy: Maps deep nesting

Body:
I got a map matrix that looks like this:

def matrix = [
    field1:[role1:[state1:["f1r1s1",true],
                   state2:["f1r1s2",false]],
            role2:[state1:["f1r2s1",true],
                   state2:["f1r2s2",false]]
           ],
    field2:[role1:[state1:["f2r1s1",true],
                   state2:["f2r1s2",false]],
            role2:[state1:["f2r2s1",true],
                   state2:["f1r2s2",false]]
           ]
]

I am trying to get all fields where role is "role1" and state is "state1". Easy? Help pls.

Body:
You can do:

def map = matrix.inject([:]) { map, elem -> map << [ (elem.key): elem.value[ 'role1' ][ 'state1' ] ] }

to get your required result:

[field1:[f1r1s1, true], field2:[f2r1s1, true]]


问:
setVisibility(View.GONE) not working for textview
I am retrieving and displaying values from a database but all queries don't return the same number of columns so I have to hide the ones that are not required.
java:

```<code>package com.example.testback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class Stations extends Activity implements OnItemSelectedListener {

    String lat,lng,marker;
    Spinner s1, s2;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stations);
        // TODO Auto-generated method stub

        Display display =getWindowManager().getDefaultDisplay();
        int height = display.getHeight();
        int top=(int) (height/5.4);
        LinearLayout l=(LinearLayout)findViewById(R.id.linearL2);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                   LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, top,0,0);
        l.setLayoutParams(lp);

        s1 = (Spinner) findViewById(R.id.countries);
        s2 = (Spinner) findViewById(R.id.region);
        s1.setOnItemSelectedListener(this);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.Countries, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s1.setAdapter(adapter);

        Bundle extras = getIntent().getExtras();
        String name= extras.getString("name");
        DataBaseHelper myDbHelper = new DataBaseHelper(
                this.getApplicationContext());
        myDbHelper = new DataBaseHelper(this);

        try {
            myDbHelper.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }

        // Open the database
        try {

            myDbHelper.openDataBase();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }

        // Get the readable version
        SQLiteDatabase db = myDbHelper.getReadableDatabase();
        Cursor cur;
        cur = db.rawQuery("SELECT * FROM REGIONS WHERE _id='"+name+"';", null);
        int i = 0;
        cur.moveToFirst();
        TextView v=(TextView)findViewById(R.id.address);
        v.setText(cur.getString(1));
        int index;

        index=cur.getColumnIndex("ph1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.ph1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
            v=(TextView)findViewById(R.id.tit_ph1);
            v.setVisibility(View.VISIBLE);
        } else{
            v=(TextView)findViewById(R.id.ph1);
            v.setVisibility(View.GONE);
            v=(TextView)findViewById(R.id.tit_ph1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("ph2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.ph2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
            v=(TextView)findViewById(R.id.tit_ph2);
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.ph2);
            v.setVisibility(View.GONE);
            v=(TextView)findViewById(R.id.tit_ph2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("fax");
        if(index!=-1){
            v=(TextView)findViewById(R.id.fax);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
            v=(TextView)findViewById(R.id.tit_fax);
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.fax);
            v.setVisibility(View.GONE);
            v=(TextView)findViewById(R.id.tit_fax);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("email1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.email1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.email1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("email2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.email2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.email2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_ph1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_ph1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_ph1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_ph2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_ph2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_ph2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_fax");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_fax);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_fax);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_email1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_email1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_email1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_email2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_email2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_email2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_ph1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_ph1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_ph1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_ph2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_ph2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_ph2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_fax");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_fax);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_fax);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_email1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_email1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_email1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_email2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_email2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_email2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_ph1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_ph1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_ph1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_ph2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_ph2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_ph2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_fax");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_fax);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_fax);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_email1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_email1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_email1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_email2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_email2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_email2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndexOrThrow("loc_lat");
        lat=cur.getString(index);
        index=cur.getColumnIndexOrThrow("loc_long");
        lng=cur.getString(index);
        index=cur.getColumnIndexOrThrow("marker");
        marker=cur.getString(index);
        /*while (cur.isAfterLast() == false) {
            //list.add(cur.getString(0));
            cur.moveToNext();
        }*/

        cur.moveToPosition(0);

        // Close
        myDbHelper.close();
    }
    public void go(View view){
        Intent i = new Intent(Stations.this, Map.class);
        i.putExtra("lat",lat);
        i.putExtra("long",lng);
        i.putExtra("marker",marker);
        startActivity(i);
        finish();
    }
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        List<String> list = new ArrayList<String>();
        if (s1.getSelectedItem().equals("India")) {
            list.add("Select Station");
            DataBaseHelper myDbHelper = new DataBaseHelper(
                    this.getApplicationContext());
            myDbHelper = new DataBaseHelper(this);

            try {
                myDbHelper.createDataBase();
            } catch (IOException ioe) {
                throw new Error("Unable to create database");
            }

            // Open the database
            try {

                myDbHelper.openDataBase();
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }

            // Get the readable version
            SQLiteDatabase db = myDbHelper.getReadableDatabase();
            Cursor cur;
            cur = db.rawQuery("SELECT * FROM REGIONS ORDER BY _id ASC;", null);
            int i = 0;
            cur.moveToFirst();
            while (cur.isAfterLast() == false) {
                list.add(cur.getString(0));
                cur.moveToNext();
            }

            cur.moveToPosition(0);

            // Close
            myDbHelper.close();
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("SAARC Countries")) {
            list.add("Select Station");
            list.add("Chittagong");
            list.add("Colombo");
            list.add("Dhaka");
            list.add("Kabul");
            list.add("Kathmandu");
            list.add("Male");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("Russia")) {
            list.add("Moscow");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("USA and Canada")) {
            list.add("Select Station");

            list.add("Chicago");
            list.add("Los Angeles");
            list.add("New York");
            list.add("Toronto");
            list.add("Washington DC");
            list.add("Newark Airport (EWR)");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("Southeast Asia, Australia")) {
            list.add("Select Station");
            list.add("Bangkok");
            list.add("Hongkong");
            list.add("Jatarka");
            list.add("Melbourne");
            list.add("Sydney");
            list.add("Yangon");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("Gulf and Middle East")) {
            list.add("Select Station");
            list.add("Bahrain");
            list.add("Beirut");
            list.add("Cairo");
            list.add("Dubai");
            list.add("Muscat");
            list.add("Tehran");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        }

        else if (s1.getSelectedItem().equals("UK and Europe")) {
            list.add("Select Station");

            list.add("Amsterdam");
            list.add("Frankfurt");
            list.add("London");
            list.add("Madrid");
            list.add("Zurich");
            list.add("Paris");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("Far East")) {
            list.add("Select Station");

            list.add("Osaka");
            list.add("Seoul");
            list.add("Tokyo");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        }
        s2.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                if (s2.getSelectedItem().toString() != "Select Station") {
                    String s = s2.getSelectedItem().toString();
                    Intent i = new Intent(Stations.this, Stations.class);
                    i.putExtra("name", s);
                    startActivity(i);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}
</code>```

The xml for that element is:

```<code><LinearLayout
    android:id="@+id/linearLayout4"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

        <TextView
            android:id="@+id/tit_fax"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight=".4"
            android:text="FAX"
            android:visibility="visible"
            android:textSize="14dp" />

        <TextView
            android:id="@+id/fax"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight=".6"
            android:visibility="visible"
            android:text=" " />
</LinearLayout>
</code>```

But it is still visible when it should have been gone

答:
Also can happen (not this case) that the gone is ignored if the view is referenced by a group like this</p>
```<code>            <androidx.constraintlayout.widget.Group
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:constraint_referenced_ids="myTextView"
                tools:visibility="visible" />
</code>```

Body:
I am retrieving and displaying values from a database but all queries don't return the same number of columns so I have to hide the ones that are not required.
java:

package com.example.testback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class Stations extends Activity implements OnItemSelectedListener {

    String lat,lng,marker;
    Spinner s1, s2;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stations);
        // TODO Auto-generated method stub

        Display display =getWindowManager().getDefaultDisplay();
        int height = display.getHeight();
        int top=(int) (height/5.4);
        LinearLayout l=(LinearLayout)findViewById(R.id.linearL2);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                   LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, top,0,0);
        l.setLayoutParams(lp);

        s1 = (Spinner) findViewById(R.id.countries);
        s2 = (Spinner) findViewById(R.id.region);
        s1.setOnItemSelectedListener(this);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.Countries, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s1.setAdapter(adapter);

        Bundle extras = getIntent().getExtras();
        String name= extras.getString("name");
        DataBaseHelper myDbHelper = new DataBaseHelper(
                this.getApplicationContext());
        myDbHelper = new DataBaseHelper(this);

        try {
            myDbHelper.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }

        // Open the database
        try {

            myDbHelper.openDataBase();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        }

        // Get the readable version
        SQLiteDatabase db = myDbHelper.getReadableDatabase();
        Cursor cur;
        cur = db.rawQuery("SELECT * FROM REGIONS WHERE _id='"+name+"';", null);
        int i = 0;
        cur.moveToFirst();
        TextView v=(TextView)findViewById(R.id.address);
        v.setText(cur.getString(1));
        int index;

        index=cur.getColumnIndex("ph1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.ph1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
            v=(TextView)findViewById(R.id.tit_ph1);
            v.setVisibility(View.VISIBLE);
        } else{
            v=(TextView)findViewById(R.id.ph1);
            v.setVisibility(View.GONE);
            v=(TextView)findViewById(R.id.tit_ph1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("ph2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.ph2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
            v=(TextView)findViewById(R.id.tit_ph2);
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.ph2);
            v.setVisibility(View.GONE);
            v=(TextView)findViewById(R.id.tit_ph2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("fax");
        if(index!=-1){
            v=(TextView)findViewById(R.id.fax);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
            v=(TextView)findViewById(R.id.tit_fax);
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.fax);
            v.setVisibility(View.GONE);
            v=(TextView)findViewById(R.id.tit_fax);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("email1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.email1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.email1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("email2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.email2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.email2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_ph1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_ph1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_ph1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_ph2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_ph2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_ph2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_fax");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_fax);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_fax);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_email1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_email1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_email1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("dom_email2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.dom_email2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.dom_email2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_ph1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_ph1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_ph1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_ph2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_ph2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_ph2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_fax");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_fax);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_fax);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_email1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_email1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_email1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("int_email2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.int_email2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.int_email2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_ph1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_ph1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_ph1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_ph2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_ph2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_ph2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_fax");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_fax);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_fax);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_email1");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_email1);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_email1);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndex("cargo_email2");
        if(index!=-1){
            v=(TextView)findViewById(R.id.cargo_email2);
            v.setText(cur.getString(index));
            v.setVisibility(View.VISIBLE);
        }else{
            v=(TextView)findViewById(R.id.cargo_email2);
            v.setVisibility(View.GONE);
        }

        index=cur.getColumnIndexOrThrow("loc_lat");
        lat=cur.getString(index);
        index=cur.getColumnIndexOrThrow("loc_long");
        lng=cur.getString(index);
        index=cur.getColumnIndexOrThrow("marker");
        marker=cur.getString(index);
        /*while (cur.isAfterLast() == false) {
            //list.add(cur.getString(0));
            cur.moveToNext();
        }*/

        cur.moveToPosition(0);

        // Close
        myDbHelper.close();
    }
    public void go(View view){
        Intent i = new Intent(Stations.this, Map.class);
        i.putExtra("lat",lat);
        i.putExtra("long",lng);
        i.putExtra("marker",marker);
        startActivity(i);
        finish();
    }
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        List<String> list = new ArrayList<String>();
        if (s1.getSelectedItem().equals("India")) {
            list.add("Select Station");
            DataBaseHelper myDbHelper = new DataBaseHelper(
                    this.getApplicationContext());
            myDbHelper = new DataBaseHelper(this);

            try {
                myDbHelper.createDataBase();
            } catch (IOException ioe) {
                throw new Error("Unable to create database");
            }

            // Open the database
            try {

                myDbHelper.openDataBase();
            } catch (SQLException sqle) {
                sqle.printStackTrace();
            }

            // Get the readable version
            SQLiteDatabase db = myDbHelper.getReadableDatabase();
            Cursor cur;
            cur = db.rawQuery("SELECT * FROM REGIONS ORDER BY _id ASC;", null);
            int i = 0;
            cur.moveToFirst();
            while (cur.isAfterLast() == false) {
                list.add(cur.getString(0));
                cur.moveToNext();
            }

            cur.moveToPosition(0);

            // Close
            myDbHelper.close();
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("SAARC Countries")) {
            list.add("Select Station");
            list.add("Chittagong");
            list.add("Colombo");
            list.add("Dhaka");
            list.add("Kabul");
            list.add("Kathmandu");
            list.add("Male");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("Russia")) {
            list.add("Moscow");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("USA and Canada")) {
            list.add("Select Station");

            list.add("Chicago");
            list.add("Los Angeles");
            list.add("New York");
            list.add("Toronto");
            list.add("Washington DC");
            list.add("Newark Airport (EWR)");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("Southeast Asia, Australia")) {
            list.add("Select Station");
            list.add("Bangkok");
            list.add("Hongkong");
            list.add("Jatarka");
            list.add("Melbourne");
            list.add("Sydney");
            list.add("Yangon");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("Gulf and Middle East")) {
            list.add("Select Station");
            list.add("Bahrain");
            list.add("Beirut");
            list.add("Cairo");
            list.add("Dubai");
            list.add("Muscat");
            list.add("Tehran");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        }

        else if (s1.getSelectedItem().equals("UK and Europe")) {
            list.add("Select Station");

            list.add("Amsterdam");
            list.add("Frankfurt");
            list.add("London");
            list.add("Madrid");
            list.add("Zurich");
            list.add("Paris");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        } else if (s1.getSelectedItem().equals("Far East")) {
            list.add("Select Station");

            list.add("Osaka");
            list.add("Seoul");
            list.add("Tokyo");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, list);
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            s2.setAdapter(dataAdapter);
        }
        s2.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                if (s2.getSelectedItem().toString() != "Select Station") {
                    String s = s2.getSelectedItem().toString();
                    Intent i = new Intent(Stations.this, Stations.class);
                    i.putExtra("name", s);
                    startActivity(i);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}

The xml for that element is:

<LinearLayout
    android:id="@+id/linearLayout4"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

        <TextView
            android:id="@+id/tit_fax"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight=".4"
            android:text="FAX"
            android:visibility="visible"
            android:textSize="14dp" />

        <TextView
            android:id="@+id/fax"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight=".6"
            android:visibility="visible"
            android:text=" " />
</LinearLayout>

But it is still visible when it should have been gone

Body:
Also can happen (not this case) that the gone is ignored if the view is referenced by a group like this

            <androidx.constraintlayout.widget.Group
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:constraint_referenced_ids="myTextView"
                tools:visibility="visible" />