问:
X509 Certificate Public Key Padding
I'm porting some Java code to C#, but it appears as though the public key padding between Java and C# is inconsistent.

Here is my Java code:

```<code>package Encryption;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.io.ByteArrayInputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.xml.bind.DatatypeConverter;
/**
 *
 * @author Cameron
 */
public class Encryptiontest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        String publicKey = "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";
        ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(publicKey));
        X509Certificate x509certificate;
        try
        {
            x509certificate = (X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(bytearrayinputstream);
            RSAPublicKey key = (RSAPublicKey)x509certificate.getPublicKey();
            System.out.println(DatatypeConverter.printBase64Binary(key.getEncoded()));
        }
        catch (CertificateException certificateexception)
        {
        }
    }

}
</code>```

When I print the base64 representation of the RSAPublicKey, this is what I get:

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvUihVNnWYpu3uJmcLy+PBecKu4ziVD7OIeZ/V+tJkXbc5+6OW8G+QDtJKuJkkuxGNLBNmLHbCyXsJ/US3kKkU7/7yK7jfWRNdqAKJdDTVxsWnxlo+/28ScGrAV6wK2bbK8GQBpsYRn1HKGCGceWIBCSqUfI7rwgwDnvqcW5PeivORd4+or5DdhgUMwiV5Vr2fvdcAiQR1CKgMphxO4+OmZ4khpB/HT/xS4FscvfFsSBLM37jBMrnhY5yNKPeHZB2eYvehnnw22NFHJNksa+vVFXL9aJcZWJc/bqqlhlhL8eLdYSR/KA006PSInW8yWtd4IFVKJ1Moa41gCUZL81voQIDAQAB

However, the result is different with C# with the same base64 public key. Here is my C# code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace EncryptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            String publicKey = "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";
            byte[] data = Convert.FromBase64String(publicKey);

            X509Certificate x509certificate = new X509Certificate(data);
            byte[] rsaPublicKey = x509certificate.GetPublicKey();

            string base64 = Convert.ToBase64String(rsaPublicKey);

            Console.WriteLine(base64);
            Console.ReadKey();
        }
    }
}
</code>```

C# output:

MIIBCgKCAQEAvUihVNnWYpu3uJmcLy+PBecKu4ziVD7OIeZ/V+tJkXbc5+6OW8G+QDtJKuJkkuxGNLBNmLHbCyXsJ/US3kKkU7/7yK7jfWRNdqAKJdDTVxsWnxlo+/28ScGrAV6wK2bbK8GQBpsYRn1HKGCGceWIBCSqUfI7rwgwDnvqcW5PeivORd4+or5DdhgUMwiV5Vr2fvdcAiQR1CKgMphxO4+OmZ4khpB/HT/xS4FscvfFsSBLM37jBMrnhY5yNKPeHZB2eYvehnnw22NFHJNksa+vVFXL9aJcZWJc/bqqlhlhL8eLdYSR/KA006PSInW8yWtd4IFVKJ1Moa41gCUZL81voQIDAQAB

Why are the two similar, but padded differently? How do I make the C# output look like the Java output?

答:
Here is another way you could get the Base64 representation of the public key:

```<code>string base64 = Convert.ToBase64String(x509certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks);
</code>```

For details please see Exporting a Certificate as BASE-64 encoded .cer

Title: X509 Certificate Public Key Padding

Body:
I'm porting some Java code to C#, but it appears as though the public key padding between Java and C# is inconsistent.

Here is my Java code:

package Encryption;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.io.ByteArrayInputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.xml.bind.DatatypeConverter;
/**
 *
 * @author Cameron
 */
public class Encryptiontest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        String publicKey = "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";
        ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(publicKey));
        X509Certificate x509certificate;
        try
        {
            x509certificate = (X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(bytearrayinputstream);
            RSAPublicKey key = (RSAPublicKey)x509certificate.getPublicKey();
            System.out.println(DatatypeConverter.printBase64Binary(key.getEncoded()));
        }
        catch (CertificateException certificateexception)
        {
        }
    }

}

When I print the base64 representation of the RSAPublicKey, this is what I get:

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvUihVNnWYpu3uJmcLy+PBecKu4ziVD7OIeZ/V+tJkXbc5+6OW8G+QDtJKuJkkuxGNLBNmLHbCyXsJ/US3kKkU7/7yK7jfWRNdqAKJdDTVxsWnxlo+/28ScGrAV6wK2bbK8GQBpsYRn1HKGCGceWIBCSqUfI7rwgwDnvqcW5PeivORd4+or5DdhgUMwiV5Vr2fvdcAiQR1CKgMphxO4+OmZ4khpB/HT/xS4FscvfFsSBLM37jBMrnhY5yNKPeHZB2eYvehnnw22NFHJNksa+vVFXL9aJcZWJc/bqqlhlhL8eLdYSR/KA006PSInW8yWtd4IFVKJ1Moa41gCUZL81voQIDAQAB

However, the result is different with C# with the same base64 public key. Here is my C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace EncryptionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            String publicKey = "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";
            byte[] data = Convert.FromBase64String(publicKey);

            X509Certificate x509certificate = new X509Certificate(data);
            byte[] rsaPublicKey = x509certificate.GetPublicKey();

            string base64 = Convert.ToBase64String(rsaPublicKey);

            Console.WriteLine(base64);
            Console.ReadKey();
        }
    }
}

C# output:

MIIBCgKCAQEAvUihVNnWYpu3uJmcLy+PBecKu4ziVD7OIeZ/V+tJkXbc5+6OW8G+QDtJKuJkkuxGNLBNmLHbCyXsJ/US3kKkU7/7yK7jfWRNdqAKJdDTVxsWnxlo+/28ScGrAV6wK2bbK8GQBpsYRn1HKGCGceWIBCSqUfI7rwgwDnvqcW5PeivORd4+or5DdhgUMwiV5Vr2fvdcAiQR1CKgMphxO4+OmZ4khpB/HT/xS4FscvfFsSBLM37jBMrnhY5yNKPeHZB2eYvehnnw22NFHJNksa+vVFXL9aJcZWJc/bqqlhlhL8eLdYSR/KA006PSInW8yWtd4IFVKJ1Moa41gCUZL81voQIDAQAB

Why are the two similar, but padded differently? How do I make the C# output look like the Java output?

Body:
Here is another way you could get the Base64 representation of the public key:

string base64 = Convert.ToBase64String(x509certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks);

For details please see Exporting a Certificate as BASE-64 encoded .cer


来源: stackexchange

问:
Can't get upper axis values through linking with lower axis in gnu plot
I am trying to link the upper axis with the lower axis in gnu plot, that is print out values on the upper axis given a relationship between the upper axis quantities and the lower axis ones. The relationship between them is

x2 = 2*c**2/(2*x1**2-c**2) with c=1.548458.
The following should be sufficient

```<code>set xlabel "Quantity lower"
set xtics nomirror
set x2label "Quantity Upper"
set x2tics nomirror
set link x2 via 2*(2*1.548458)**2/(2*x**2-(2*1.548458)**2) inverse sqrt((2*1.548458)**2*(2+x)/2/x)

#set link x via 1239.8/x inverse 1239.8/x

set ylabel "Quantity y"
set ytics 0.2
set samples 400
Spectrum(x) = exp(-(x-500)**2/(400))

set xrange[30:2000]

set format x2 "%.2f"
plot Spectrum(x) w l title "Spectrum"
</code>```

I've also log formatted the x axis via

set logscale x
set format x "10^{%L}"

but regardless of whether I include the log formatting I am unable to get any meanginful values printed out on the upper axis. (The function for y is for illustrative purposes only, the value for y in my actual script relies on reading in data from a file)

I'd like to print out values on the upper axis for say two values of x=100, 1000 say.  Thanks!

答:
I don't know how to set tics automatically. But at least you can set them explicitly.

You want to set x2 tics at given x1 values. As the set x2tics command takes tic positions in x2 coordinates, you    can convert the given x1 values into x2 values. I have modified your script to illustrate what I mean:

```<code>set xlabel "Quantity lower"
set xtics nomirror
set x2label "Quantity Upper"
set x2tics nomirror

# avoid warnings by setting the xrange before linking the axes
set xrange[30:2000]

# setup the link functions
c = 1.548458 # or 2*1.548458 ?
link_x1_x2(x) = 2*c**2/(2*x**2-c**2)
link_x2_x1(x) = c*sqrt((2+x)/(2*x))

set link x2 via link_x1_x2(x) inverse link_x2_x1(x)

# you want to set x2 tics at x1 = 100 and x1 = 1000
# check the corresponding x2 values
print "x2 = x1( 100) = ", link_x1_x2(100)
print "x2 = x1(1000) = ", link_x1_x2(1000)

# set the tics with formatted tic labels as an example
set x2tics ("a: %.2e" link_x1_x2(100), "b: %.2e" link_x1_x2(1000))

set ylabel "Quantity y"
set ytics 0.2
set samples 400
Spectrum(x) = exp(-(x-500)**2/(400))

# this seems not to work with explicit tics
# set format x2 "%.2f"

plot Spectrum(x) w l title "Spectrum"
</code>```

This is the output:

If you need logarithmic axes and the set link command does not work, you can replace it by setting the x2axis properties explicitly with set x2range. See the modified script:

```<code>set xlabel "Quantity lower"
set xtics nomirror
set x2label "Quantity Upper"
set x2tics nomirror

# setup the link functions
c = 1.548458 # or 2*1.548458 ?
link_x1_x2(x) = 2*c**2/(2*x**2-c**2)
link_x2_x1(x) = c*sqrt((2+x)/(2*x))

xmin = 30
xmax = 2000
set xrange[xmin:xmax]
set x2range[link_x1_x2(xmin):link_x1_x2(xmax)]

set logscale x
set logscale y
set logscale x2

# set the tics at x1 = 100 and x1 = 1000
set x2tics ("a: %.2e" link_x1_x2(100), "b: %.2e" link_x1_x2(1000))

set ylabel "Quantity y"
#set ytics 0.2 # this must be improved for logarithmic plotting
set samples 400
Spectrum(x) = exp(-(x-500)**2/(400))

plot Spectrum(x) w l title "Spectrum"
</code>```

This is the result:

Note that the drop of the function at about x1 = 1000 is caused by numerical underflow.

Update:

As we did not get the automatic linking to work for logarithmic plots, I would add minor tics manually. See help set xtics for details.

```<code># just for a check
set grid mxtics
# set the tics at x1 = 100 and x1 = 1000
# set minor tics in between (at level 1)
set x2tics ("a: %.2e" link_x1_x2(100), \
            "" link_x1_x2(200) 1,      \
            "" link_x1_x2(300) 1,      \
            "" link_x1_x2(400) 1,      \
            "" link_x1_x2(500) 1,      \
            "" link_x1_x2(600) 1,      \
            "" link_x1_x2(700) 1,      \
            "" link_x1_x2(800) 1,      \
            "" link_x1_x2(900) 1,      \
            "b: %.2e" link_x1_x2(1000))
</code>```

Now we have this result:

ContentLicense: CC BY-SA 4.0

Body:
I am trying to link the upper axis with the lower axis in gnu plot, that is print out values on the upper axis given a relationship between the upper axis quantities and the lower axis ones. The relationship between them is

x2 = 2*c**2/(2*x1**2-c**2) with c=1.548458.
The following should be sufficient

set xlabel "Quantity lower"
set xtics nomirror
set x2label "Quantity Upper"
set x2tics nomirror
set link x2 via 2*(2*1.548458)**2/(2*x**2-(2*1.548458)**2) inverse sqrt((2*1.548458)**2*(2+x)/2/x)

#set link x via 1239.8/x inverse 1239.8/x

set ylabel "Quantity y"
set ytics 0.2
set samples 400
Spectrum(x) = exp(-(x-500)**2/(400))

set xrange[30:2000]

set format x2 "%.2f"
plot Spectrum(x) w l title "Spectrum"

I've also log formatted the x axis via

set logscale x
set format x "10^{%L}"

but regardless of whether I include the log formatting I am unable to get any meanginful values printed out on the upper axis. (The function for y is for illustrative purposes only, the value for y in my actual script relies on reading in data from a file)

I'd like to print out values on the upper axis for say two values of x=100, 1000 say.  Thanks!

Body:
I don't know how to set tics automatically. But at least you can set them explicitly.

You want to set x2 tics at given x1 values. As the set x2tics command takes tic positions in x2 coordinates, you    can convert the given x1 values into x2 values. I have modified your script to illustrate what I mean:

set xlabel "Quantity lower"
set xtics nomirror
set x2label "Quantity Upper"
set x2tics nomirror

# avoid warnings by setting the xrange before linking the axes
set xrange[30:2000]

# setup the link functions
c = 1.548458 # or 2*1.548458 ?
link_x1_x2(x) = 2*c**2/(2*x**2-c**2)
link_x2_x1(x) = c*sqrt((2+x)/(2*x))

set link x2 via link_x1_x2(x) inverse link_x2_x1(x)

# you want to set x2 tics at x1 = 100 and x1 = 1000
# check the corresponding x2 values
print "x2 = x1( 100) = ", link_x1_x2(100)
print "x2 = x1(1000) = ", link_x1_x2(1000)

# set the tics with formatted tic labels as an example
set x2tics ("a: %.2e" link_x1_x2(100), "b: %.2e" link_x1_x2(1000))

set ylabel "Quantity y"
set ytics 0.2
set samples 400
Spectrum(x) = exp(-(x-500)**2/(400))

# this seems not to work with explicit tics
# set format x2 "%.2f"

plot Spectrum(x) w l title "Spectrum"

This is the output:

If you need logarithmic axes and the set link command does not work, you can replace it by setting the x2axis properties explicitly with set x2range. See the modified script:

set xlabel "Quantity lower"
set xtics nomirror
set x2label "Quantity Upper"
set x2tics nomirror

# setup the link functions
c = 1.548458 # or 2*1.548458 ?
link_x1_x2(x) = 2*c**2/(2*x**2-c**2)
link_x2_x1(x) = c*sqrt((2+x)/(2*x))

xmin = 30
xmax = 2000
set xrange[xmin:xmax]
set x2range[link_x1_x2(xmin):link_x1_x2(xmax)]

set logscale x
set logscale y
set logscale x2

# set the tics at x1 = 100 and x1 = 1000
set x2tics ("a: %.2e" link_x1_x2(100), "b: %.2e" link_x1_x2(1000))

set ylabel "Quantity y"
#set ytics 0.2 # this must be improved for logarithmic plotting
set samples 400
Spectrum(x) = exp(-(x-500)**2/(400))

plot Spectrum(x) w l title "Spectrum"

This is the result:

Note that the drop of the function at about x1 = 1000 is caused by numerical underflow.

Update:

As we did not get the automatic linking to work for logarithmic plots, I would add minor tics manually. See help set xtics for details.

# just for a check
set grid mxtics
# set the tics at x1 = 100 and x1 = 1000
# set minor tics in between (at level 1)
set x2tics ("a: %.2e" link_x1_x2(100), \
            "" link_x1_x2(200) 1,      \
            "" link_x1_x2(300) 1,      \
            "" link_x1_x2(400) 1,      \
            "" link_x1_x2(500) 1,      \
            "" link_x1_x2(600) 1,      \
            "" link_x1_x2(700) 1,      \
            "" link_x1_x2(800) 1,      \
            "" link_x1_x2(900) 1,      \
            "b: %.2e" link_x1_x2(1000))

Now we have this result:


答:
We can use run! to go over the outer vector and clojure.string/join to turn each inner vector into a printable string.

Assuming your vector is defined as input:

```<code>(require '[clojure.string :as str])
(run! (comp println str/join) input)
</code>```

Title: How to print elements in a vector of vectors

Body:
I have a vector of vectors, and I want to print elements in each vector

I tried the pprint but did not work as wanted

This is the vector of vectors I wish to print:

[["+" "+" "+" "#" "!" "-" "#" "#" "#" "-" "-" "-" "-"]
 ["!" "#" "+" "+" "+" "#" "+" "+" "+" "-" "#" "#" "-"]
 ["#" "#" "#" "#" "+" "#" "+" "#" "+" "#" "-" "#" "#"]
 ["+" "+" "+" "#" "+" "+" "+" "#" "+" "#" "-" "-" "-"]
 ["+" "#" "+" "#" "#" "#" "#" "+" "+" "-" "#" "#" "-"]
 ["+" "#" "+" "+" "+" "+" "+" "+" "#" "-" "-" "-" "-"]
 ["+" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
 ["+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "+" "@"]]

This is the output I want:

+++#--###--#-
!#+++#+++-##-
####+#+#+#!##
+++#+++#+#!!!
+#+####++!##!
+#++++++#!!!!
+############
++++++++++++@

Body:
We can use run! to go over the outer vector and clojure.string/join to turn each inner vector into a printable string.

Assuming your vector is defined as input:

(require '[clojure.string :as str])
(run! (comp println str/join) input)


问:
Deployed Docker-Compose returns "502 Bad Gateway"
Please assist.

I found a blog post, https://blog.ssdnodes.com/blog/host-multiple-ssl-websites-docker-nginx/) regarding deploying multiple docker-compose application with the same nginx-proxy but with different VIRTUAL_HOST names

But for some reason, both applications are returning an Error 502 Bad Gateway

The following error is what I see when I run docker-compose logs nginx

2019/05/29 20:52:26 [error] 8#8: *15 connect() failed (111: Connection refused) while connecting to upstream, client: 52.209.30.187, server: gregsithole.com, request: "GET / HTTP/1.1", upstream: "http://172.20.0.5:80/", host: "gregsithole.com"

And I believe the upstream is using an internal docker network IP because that's not the IP for my Server. My upstream is determined by the following file: https://raw.githubusercontent.com/jwilder/nginx-proxy/master/nginx.tmpl

But I'm not too familiar with how it works.

The following is an example of my docker-compose files:

nginx-proxy/docker-compose.yaml

```<code>version: "3.6"
services:
  nginx:
    image: nginx
    container_name: nginx-proxy
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - conf:/etc/nginx/conf.d
      - vhost:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - certs:/etc/nginx/certs
    labels:
      - "com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy=true"

  dockergen:
    image: jwilder/docker-gen
    container_name: nginx-proxy-gen
    restart: always
    depends_on:
      - nginx
    command: -notify-sighup nginx-proxy -watch -wait 5s:30s /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf
    volumes:
      - conf:/etc/nginx/conf.d
      - vhost:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - certs:/etc/nginx/certs
      - /var/run/docker.sock:/tmp/docker.sock:ro
      - ./nginx.tmpl:/etc/docker-gen/templates/nginx.tmpl:ro

  letsencrypt:
    image: jrcs/letsencrypt-nginx-proxy-companion
    container_name: nginx-proxy-le
    restart: always
    depends_on:
      - nginx
      - dockergen
    environment:
      NGINX_PROXY_CONTAINER: nginx-proxy
      NGINX_DOCKER_GEN_CONTAINER: nginx-proxy-gen
    volumes:
      - conf:/etc/nginx/conf.d
      - vhost:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - certs:/etc/nginx/certs
      - /var/run/docker.sock:/var/run/docker.sock:ro

volumes:
  conf:
  vhost:
  html:
  certs:

networks:
  default:
    external:
      name: nginx-proxy
</code>```

dockerized-ghost/docker-compose.yaml

```<code>version: "3.6"
services:

  ghost:
    image: ghost
    restart: always
    expose:
      - 80
    volumes:
      - ../../ghost:/var/lib/ghost/content
    environment:
      NODE_ENV: production
      url: https://blog.gregsithole.com
      VIRTUAL_HOST: blog.gregsithole.com
      LETSENCRYPT_HOST: blog.gregsithole.com
      LETSENCRYPT_EMAIL: hidden-email

networks:
  default:
    external:
      name: nginx-proxy
</code>```

Please assist

答:
You should assign the network nginx-proxy to the service ghost:

```<code>  ghost:
    networks:
      - nginx-proxy
    ...

</code>```

Also assign the newtwork to nginx

```<code>  nginx:
    networks:
      - nginx-proxy
    ...

</code>```

Also put the network configuration like this:

```<code>networks:
  nginx-proxy:
    external: true
  default:
</code>```

And its all you need. Remember that in the docker compose file you have to declare the network as external, but that's not enough. You have also assign it individually to each service you want to be part of the network.

I recommend you to upgrade to Træfik or envoy. Nginx is limited in terms of scalability unless you pay for it.

Body:
Please assist.

I found a blog post, https://blog.ssdnodes.com/blog/host-multiple-ssl-websites-docker-nginx/) regarding deploying multiple docker-compose application with the same nginx-proxy but with different VIRTUAL_HOST names

But for some reason, both applications are returning an Error 502 Bad Gateway

The following error is what I see when I run docker-compose logs nginx

2019/05/29 20:52:26 [error] 8#8: *15 connect() failed (111: Connection refused) while connecting to upstream, client: 52.209.30.187, server: gregsithole.com, request: "GET / HTTP/1.1", upstream: "http://172.20.0.5:80/", host: "gregsithole.com"

And I believe the upstream is using an internal docker network IP because that's not the IP for my Server. My upstream is determined by the following file: https://raw.githubusercontent.com/jwilder/nginx-proxy/master/nginx.tmpl

But I'm not too familiar with how it works.

The following is an example of my docker-compose files:

nginx-proxy/docker-compose.yaml

version: "3.6"
services:
  nginx:
    image: nginx
    container_name: nginx-proxy
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - conf:/etc/nginx/conf.d
      - vhost:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - certs:/etc/nginx/certs
    labels:
      - "com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy=true"

  dockergen:
    image: jwilder/docker-gen
    container_name: nginx-proxy-gen
    restart: always
    depends_on:
      - nginx
    command: -notify-sighup nginx-proxy -watch -wait 5s:30s /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf
    volumes:
      - conf:/etc/nginx/conf.d
      - vhost:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - certs:/etc/nginx/certs
      - /var/run/docker.sock:/tmp/docker.sock:ro
      - ./nginx.tmpl:/etc/docker-gen/templates/nginx.tmpl:ro

  letsencrypt:
    image: jrcs/letsencrypt-nginx-proxy-companion
    container_name: nginx-proxy-le
    restart: always
    depends_on:
      - nginx
      - dockergen
    environment:
      NGINX_PROXY_CONTAINER: nginx-proxy
      NGINX_DOCKER_GEN_CONTAINER: nginx-proxy-gen
    volumes:
      - conf:/etc/nginx/conf.d
      - vhost:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - certs:/etc/nginx/certs
      - /var/run/docker.sock:/var/run/docker.sock:ro

volumes:
  conf:
  vhost:
  html:
  certs:

networks:
  default:
    external:
      name: nginx-proxy

dockerized-ghost/docker-compose.yaml

version: "3.6"
services:

  ghost:
    image: ghost
    restart: always
    expose:
      - 80
    volumes:
      - ../../ghost:/var/lib/ghost/content
    environment:
      NODE_ENV: production
      url: https://blog.gregsithole.com
      VIRTUAL_HOST: blog.gregsithole.com
      LETSENCRYPT_HOST: blog.gregsithole.com
      LETSENCRYPT_EMAIL: hidden-email

networks:
  default:
    external:
      name: nginx-proxy

Please assist

Body:
You should assign the network nginx-proxy to the service ghost:

  ghost:
    networks:
      - nginx-proxy
    ...

Also assign the newtwork to nginx

  nginx:
    networks:
      - nginx-proxy
    ...

Also put the network configuration like this:

networks:
  nginx-proxy:
    external: true
  default:

And its all you need. Remember that in the docker compose file you have to declare the network as external, but that's not enough. You have also assign it individually to each service you want to be part of the network.

I recommend you to upgrade to Træfik or envoy. Nginx is limited in terms of scalability unless you pay for it.


问:
Typescript complaining about type on destructuring
I have the following code:

```<code>import { GraphQLNonNull, GraphQLString, GraphQLList, GraphQLInt } from 'graphql';

import systemType from './type';
import { resolver } from 'graphql-sequelize';

let a = ({System}) => ({
  system: {
    type: systemType,
    args: {
      id: {
        description: 'ID of system',
        type: new GraphQLNonNull(GraphQLInt)
      }
    },
    resolve: resolver(System, {
      after: (result: any[]) => (result && result.length ? result[0] : result)
    })
  },
  systems: {
    type: new GraphQLList(systemType),
    args: {
      names: {
        description: 'List option names to retrieve',
        type: new GraphQLList(GraphQLString)
      },
      limit: {
        type: GraphQLInt
      },
      order: {
        type: GraphQLString
      }
    },
    resolve: resolver(System, {
      before: (findOptions: any, { query }: any) => ({
        order: [['name', 'DESC']],
        ...findOptions
      })
    })
  }
});

export = { a: a };
</code>```

The VSCode is complaining with the TS7031 warning:

```<code>Binding element 'System' implicitly has an 'any' type
</code>```

How can I get rid of that warning?

答:
TypeScript cannot infer what type the System value should be from your code (or, more specifically, it cannot infer the type of first parameter to function a). Just add an explicit type annotation to fix this:

```<code>let a = ({System}: { System: string }) => ({

});
</code>```

Replace string with the actual type of System (perhaps typeof systemType?)

Body:
I have the following code:

import { GraphQLNonNull, GraphQLString, GraphQLList, GraphQLInt } from 'graphql';

import systemType from './type';
import { resolver } from 'graphql-sequelize';

let a = ({System}) => ({
  system: {
    type: systemType,
    args: {
      id: {
        description: 'ID of system',
        type: new GraphQLNonNull(GraphQLInt)
      }
    },
    resolve: resolver(System, {
      after: (result: any[]) => (result && result.length ? result[0] : result)
    })
  },
  systems: {
    type: new GraphQLList(systemType),
    args: {
      names: {
        description: 'List option names to retrieve',
        type: new GraphQLList(GraphQLString)
      },
      limit: {
        type: GraphQLInt
      },
      order: {
        type: GraphQLString
      }
    },
    resolve: resolver(System, {
      before: (findOptions: any, { query }: any) => ({
        order: [['name', 'DESC']],
        ...findOptions
      })
    })
  }
});

export = { a: a };

The VSCode is complaining with the TS7031 warning:

Binding element 'System' implicitly has an 'any' type

How can I get rid of that warning?

Body:
TypeScript cannot infer what type the System value should be from your code (or, more specifically, it cannot infer the type of first parameter to function a). Just add an explicit type annotation to fix this:

let a = ({System}: { System: string }) => ({

});

Replace string with the actual type of System (perhaps typeof systemType?)


问:
Core-dumped due to unique_ptr or vector in classes with cyclic references
I am trying to handle with a code with cyclic references classes. And I found I got some problem with unique_ptr or vector, when I tried to define them as class members.

This code contains 3 classes. I will show all of them in order to avoid any ambiguity.

First, I start my code by a class called as startup in main.cpp:

```<code>#include <memory>
#include <vector>
#include "startup.h"
#include "Derived_B.h"
int main() {
    std::unique_ptr<startup> go(new startup);
    return 0;
}
</code>```

In startup class, the derived class is declared (note the base class in not this one):

```<code>//Header file
#include <memory>
class startup {
public:
    startup();
    ~startup();
    class Derived_B *dcb;
};
//.cpp
#include "startup.h"
#include "Derived_B.h"
startup::startup() {
    dcb = new Derived_B(this);
}
startup::~startup() {
delete dcb;
}
</code>```

Before I show the derived classes, I will show the base class:

```<code>//Header file
#include "startup.h"
class Base {
public:
    class startup *go;
    class Derived_B *&dcb;
    Base(startup *up):go(up),
                      dcb(up->dcb){}
    ~Base(){}
};
</code>```

Now, the derived class is:

```<code>//Header file
#include <memory>
#include <vector>
#include "Base.h"
class Derived_B:public Base {
public:
    Derived_B(startup *up);
    ~Derived_B(){}
    std::unique_ptr<double[]> apple; //Unique pointer here may give problem
    std::unique_ptr<double[]> apple2; //Unique pointer here may give problem
    std::vector<double> orange; //Vector here may give problem too
};
//.cpp
#include "Derived_B.h"
Derived_B::Derived_B(startup *up):Base(up) {

}
</code>```

I constructed these class in this way in order to let the startup class and Derived_B class know each orther's public member directly. However after I added unique_ptr or vector in the Derived_B class, time to time I will get problem of core dumped.

I have checked it with valgrind, and the result is here:

```<code>==7999== 1 errors in context 1 of 2:
==7999== Invalid write of size 8
==7999==    at 0x400967: _Vector_impl (stl_vector.h:87)
==7999==    by 0x400967: _Vector_base (stl_vector.h:125)
==7999==    by 0x400967: vector (stl_vector.h:257)
==7999==    by 0x400967: Derived_B::Derived_B(startup*) (Derived_B.cpp:7)
==7999==    by 0x4008F0: startup::startup() (startup.cpp:11)
==7999==    by 0x40076A: main (main.cpp:9)
==7999==  Address 0x5ab6d00 is 8 bytes after a block of size 40 alloc'd
==7999==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7999==    by 0x4008E2: startup::startup() (startup.cpp:11)
==7999==    by 0x40076A: main (main.cpp:9)
==7999==
==7999==
==7999== 1 errors in context 2 of 2:
==7999== Invalid write of size 8
==7999==    at 0x40095F: _Vector_impl (stl_vector.h:87)
==7999==    by 0x40095F: _Vector_base (stl_vector.h:125)
==7999==    by 0x40095F: vector (stl_vector.h:257)
==7999==    by 0x40095F: Derived_B::Derived_B(startup*) (Derived_B.cpp:7)
==7999==    by 0x4008F0: startup::startup() (startup.cpp:11)
==7999==    by 0x40076A: main (main.cpp:9)
==7999==  Address 0x5ab6cf8 is 0 bytes after a block of size 40 alloc'd
==7999==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7999==    by 0x4008E2: startup::startup() (startup.cpp:11)
==7999==    by 0x40076A: main (main.cpp:9)
==7999==
==7999== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
</code>```

Please note that the problem happens quite randomly, sometimes valgrind will report unique_ptr having problem.
Could someone tell me how to solve this problem please?

Edit 2:
In order to deal with the problem of cyclic reference, I used the combination of shared_ptr and unique_ptr. I will show what I have changed in the startup class and Base class:

```<code>//In startup.h
std::shared_ptr<class Derived_B> dcb;//original code: class Derived_B *dcb;
//In startup.cpp
dcb.reset(new Derived_B(this));//original code: dcb = new Derived_B(this);

//In Base.h
class startup *&go;
std::weak_ptr<class Derived_B> dcb; //original code: class Derived_B *&dcb;
</code>```

At the beginning, this change seems work.But after I add new vector member in the Derived_B class, the similar problem comes again. In addition, this problem happens before the destructor. I can show part of the valgrind test:

```<code>Constructor of startup.
--12397-- REDIR: 0x54613b0 (libc.so.6:__GI_mempcpy) redirected to 0x4c34fa0 (__GI_mempcpy)
Constructor of Base.
==12397== Invalid write of size 8
==12397==    at 0x400F54: _Head_base (tuple:105)
==12397==    by 0x400F54: _Tuple_impl (tuple:202)
==12397==    by 0x400F54: tuple (tuple:602)
==12397==    by 0x400F54: unique_ptr (unique_ptr.h:415)
==12397==    by 0x400F54: Derived_B::Derived_B(startup*) (Derived_B.cpp:7)
==12397==    by 0x400C9E: startup::startup() (startup.cpp:13)
==12397==    by 0x400A6A: main (main.cpp:10)
==12397==  Address 0x5ab7168 is 0 bytes after a block of size 88 alloc'd
==12397==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12397==    by 0x400C90: startup::startup() (startup.cpp:13)
==12397==    by 0x400A6A: main (main.cpp:10)
==12397==
==12397== Invalid write of size 8
==12397==    at 0x400F5C: _Head_base (tuple:105)
==12397==    by 0x400F5C: _Tuple_impl (tuple:202)
==12397==    by 0x400F5C: tuple (tuple:602)
==12397==    by 0x400F5C: unique_ptr (unique_ptr.h:415)
==12397==    by 0x400F5C: Derived_B::Derived_B(startup*) (Derived_B.cpp:7)
==12397==    by 0x400C9E: startup::startup() (startup.cpp:13)
==12397==    by 0x400A6A: main (main.cpp:10)
==12397==  Address 0x5ab7170 is 8 bytes after a block of size 88 alloc'd
==12397==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12397==    by 0x400C90: startup::startup() (startup.cpp:13)
==12397==    by 0x400A6A: main (main.cpp:10)
==12397==
Constructor of Derived_B.
</code>```

Edit 3 (Problem may be solved):
I think the problem may be related with how I made the executable code. After I deleted all the .o files, and re-make the code, there is no more problem.
Here is my Makefile:

```<code># makefile
FLAG = -O2 -g
COMPLIER = g++ -std=c++14
#OBJ =
OBJ = startup.o Derived_B.o #Derived_A.o
spTest: ${OBJ} main.cpp
    ${COMPLIER} ${FLAG} -o spTest ${OBJ} main.cpp
Derived_B.o: Derived_B.h Derived_B.cpp Base.h
    ${COMPLIER} ${FLAG} -c Derived_B.cpp
startup.o: startup.h startup.cpp
    ${COMPLIER} ${FLAG} -c startup.cpp
.PHONY: clean
clean:
    -rm *.o spTest
</code>```

答:
You're creating a circular reference by having two objects refer to each other, so you shouldn't be using a unique pointer. Try using a weak pointer.

How to break shared_ptr cyclic reference using weak_ptr

Body:
I am trying to handle with a code with cyclic references classes. And I found I got some problem with unique_ptr or vector, when I tried to define them as class members.

This code contains 3 classes. I will show all of them in order to avoid any ambiguity.

First, I start my code by a class called as startup in main.cpp:

#include <memory>
#include <vector>
#include "startup.h"
#include "Derived_B.h"
int main() {
    std::unique_ptr<startup> go(new startup);
    return 0;
}

In startup class, the derived class is declared (note the base class in not this one):

//Header file
#include <memory>
class startup {
public:
    startup();
    ~startup();
    class Derived_B *dcb;
};
//.cpp
#include "startup.h"
#include "Derived_B.h"
startup::startup() {
    dcb = new Derived_B(this);
}
startup::~startup() {
delete dcb;
}

Before I show the derived classes, I will show the base class:

//Header file
#include "startup.h"
class Base {
public:
    class startup *go;
    class Derived_B *&dcb;
    Base(startup *up):go(up),
                      dcb(up->dcb){}
    ~Base(){}
};

Now, the derived class is:

//Header file
#include <memory>
#include <vector>
#include "Base.h"
class Derived_B:public Base {
public:
    Derived_B(startup *up);
    ~Derived_B(){}
    std::unique_ptr<double[]> apple; //Unique pointer here may give problem
    std::unique_ptr<double[]> apple2; //Unique pointer here may give problem
    std::vector<double> orange; //Vector here may give problem too
};
//.cpp
#include "Derived_B.h"
Derived_B::Derived_B(startup *up):Base(up) {

}

I constructed these class in this way in order to let the startup class and Derived_B class know each orther's public member directly. However after I added unique_ptr or vector in the Derived_B class, time to time I will get problem of core dumped.

I have checked it with valgrind, and the result is here:

==7999== 1 errors in context 1 of 2:
==7999== Invalid write of size 8
==7999==    at 0x400967: _Vector_impl (stl_vector.h:87)
==7999==    by 0x400967: _Vector_base (stl_vector.h:125)
==7999==    by 0x400967: vector (stl_vector.h:257)
==7999==    by 0x400967: Derived_B::Derived_B(startup*) (Derived_B.cpp:7)
==7999==    by 0x4008F0: startup::startup() (startup.cpp:11)
==7999==    by 0x40076A: main (main.cpp:9)
==7999==  Address 0x5ab6d00 is 8 bytes after a block of size 40 alloc'd
==7999==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7999==    by 0x4008E2: startup::startup() (startup.cpp:11)
==7999==    by 0x40076A: main (main.cpp:9)
==7999==
==7999==
==7999== 1 errors in context 2 of 2:
==7999== Invalid write of size 8
==7999==    at 0x40095F: _Vector_impl (stl_vector.h:87)
==7999==    by 0x40095F: _Vector_base (stl_vector.h:125)
==7999==    by 0x40095F: vector (stl_vector.h:257)
==7999==    by 0x40095F: Derived_B::Derived_B(startup*) (Derived_B.cpp:7)
==7999==    by 0x4008F0: startup::startup() (startup.cpp:11)
==7999==    by 0x40076A: main (main.cpp:9)
==7999==  Address 0x5ab6cf8 is 0 bytes after a block of size 40 alloc'd
==7999==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7999==    by 0x4008E2: startup::startup() (startup.cpp:11)
==7999==    by 0x40076A: main (main.cpp:9)
==7999==
==7999== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

Please note that the problem happens quite randomly, sometimes valgrind will report unique_ptr having problem.
Could someone tell me how to solve this problem please?

Edit 2:
In order to deal with the problem of cyclic reference, I used the combination of shared_ptr and unique_ptr. I will show what I have changed in the startup class and Base class:

//In startup.h
std::shared_ptr<class Derived_B> dcb;//original code: class Derived_B *dcb;
//In startup.cpp
dcb.reset(new Derived_B(this));//original code: dcb = new Derived_B(this);

//In Base.h
class startup *&go;
std::weak_ptr<class Derived_B> dcb; //original code: class Derived_B *&dcb;

At the beginning, this change seems work.But after I add new vector member in the Derived_B class, the similar problem comes again. In addition, this problem happens before the destructor. I can show part of the valgrind test:

Constructor of startup.
--12397-- REDIR: 0x54613b0 (libc.so.6:__GI_mempcpy) redirected to 0x4c34fa0 (__GI_mempcpy)
Constructor of Base.
==12397== Invalid write of size 8
==12397==    at 0x400F54: _Head_base (tuple:105)
==12397==    by 0x400F54: _Tuple_impl (tuple:202)
==12397==    by 0x400F54: tuple (tuple:602)
==12397==    by 0x400F54: unique_ptr (unique_ptr.h:415)
==12397==    by 0x400F54: Derived_B::Derived_B(startup*) (Derived_B.cpp:7)
==12397==    by 0x400C9E: startup::startup() (startup.cpp:13)
==12397==    by 0x400A6A: main (main.cpp:10)
==12397==  Address 0x5ab7168 is 0 bytes after a block of size 88 alloc'd
==12397==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12397==    by 0x400C90: startup::startup() (startup.cpp:13)
==12397==    by 0x400A6A: main (main.cpp:10)
==12397==
==12397== Invalid write of size 8
==12397==    at 0x400F5C: _Head_base (tuple:105)
==12397==    by 0x400F5C: _Tuple_impl (tuple:202)
==12397==    by 0x400F5C: tuple (tuple:602)
==12397==    by 0x400F5C: unique_ptr (unique_ptr.h:415)
==12397==    by 0x400F5C: Derived_B::Derived_B(startup*) (Derived_B.cpp:7)
==12397==    by 0x400C9E: startup::startup() (startup.cpp:13)
==12397==    by 0x400A6A: main (main.cpp:10)
==12397==  Address 0x5ab7170 is 8 bytes after a block of size 88 alloc'd
==12397==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==12397==    by 0x400C90: startup::startup() (startup.cpp:13)
==12397==    by 0x400A6A: main (main.cpp:10)
==12397==
Constructor of Derived_B.

Edit 3 (Problem may be solved):
I think the problem may be related with how I made the executable code. After I deleted all the .o files, and re-make the code, there is no more problem.
Here is my Makefile:

# makefile
FLAG = -O2 -g
COMPLIER = g++ -std=c++14
#OBJ =
OBJ = startup.o Derived_B.o #Derived_A.o
spTest: ${OBJ} main.cpp
    ${COMPLIER} ${FLAG} -o spTest ${OBJ} main.cpp
Derived_B.o: Derived_B.h Derived_B.cpp Base.h
    ${COMPLIER} ${FLAG} -c Derived_B.cpp
startup.o: startup.h startup.cpp
    ${COMPLIER} ${FLAG} -c startup.cpp
.PHONY: clean
clean:
    -rm *.o spTest


问:
WCF Security Clarification Needed
I have created a WPF application and data storing and fetching based on my WCF services this is working fine.

When I try to implement security in WCF I got some problem.

This is the intranet application so I have enabled WCF security as transport security like below format ---  transport clientCredentialType="Windows"

The problem is who are all having an intranet they can access my service. This I should stop. Only my application users can access.

I have created IIS server user groups but the problem is every user I should add the user in that group.

My Question:
1. How to enable security who is access my WPF application?

答:
The problem is you're confusing security with authentication. Essentially security is securing the transport connection between your client and your services (i.e., the network traffic). As you've figured out by using client creditial type of "windows" it uses your windows login to validate that the client can talk to the services, but the client refers to your WPF application, not to the user of the WPF application.

What you need to be looking at is authentication. This refers to authenticating the user of your application with your WCF service. This page has some links to help with that: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/authentication-in-wcf  in particular I would recommend looking at asp.net membership provider: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider

Title: WCF Security Clarification Needed


问:
PowerShell - Rename duplicate filenames in an object array
If I have some JSON like this:

```<code>$inputJson = @"
{
    "attachments" :
        [
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment3.com"
            }
        ]
}
</code>```

where there is an attachments array and each element in that array has the same name but different URLs, how can I change all the names so that it outputs like this:

```<code>$outputJson = @"
{
    "attachments" :
        [
            {
                "name":  "(attachment.eml)[1].eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "(attachment.eml)[2].eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "(attachment.eml)[3].eml",
                "attachment_url":  "https://www.attachment3.com"
            }
        ]
}
"@
</code>```

which renames each attachment to prevent duplicate names, but it preserves the URLs.

Ideally, the code would also make sure none of the new names already exist in the array as well. So if there is already an attachment named (attachment.eml)[1].eml in the array, it would handle that as well.

I've thought about somehow using Group-Object but I haven't quite figured out how to make that work.

答:
Requesting for code is considered off-topic here. However, for self-training purposes, the following code snippet could do the job. Partially commented and itemized to (auxiliary) intermediate variables:

```<code>$inputJson = @"
{
    "attachments" :
        [
            {
                "name":  "(attachment.eml)[2].eml",
                "attachment_url":  "https://www.attachment222.com"
            },
            {
                "name":  "attachmentOne.eml",
                "attachment_url":  "https://www.attachmentOne.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment3.com"
            },
            {
                "name":  "attachmnt.eml",
                "attachment_url":  "https://www.attachmnt1.com"
            },
            {
                "name":  "attachmnt.eml",
                "attachment_url":  "https://www.attachmnt2.com"
            }

        ]
}
"@
$objectJson     = $inputJson              | ConvertFrom-Json
$AttachsGrouped = $objectJson.attachments | Group-Object -Property Name
$newAttachments = $AttachsGrouped         | ForEach-Object {
    # debug output
    write-host $_.Count, $_.Group.GetType().Name, $_.name -ForegroundColor Cyan
    if ( $_.Count -gt 1 ) {
        $addCnt = 1
        $(  for ( $i = 0; $i -lt $_.Count; $i++ )
            {
                # make sure none of the new names already exist in the array
                While ( "($($_.name))[$($i+$addCnt)].eml" -in
                    $objectJson.attachments.name ) { $addCnt++ }
                [PSCustomObject]@{
                    'name'           = "($($_.name))[$($i+$addCnt)].eml"
                    'attachment_url' = $_.Group[$i].attachment_url
                }
            }
        )
    } else {
        # retain original definition
        $_.Group[0]
    }
}
$outputJson = [PSCustomObject]@{
                                    # for better output readability
    'attachments' = $newAttachments | Sort-Object -Property Name
}
# result
$outputJson   # | ConvertTo-Json -Depth 2
</code>```

Result:

```<code>$outputJson
</code>```

```<code>attachments
-----------
{@{name=(attachment.eml)[1].eml; attachment_url=https://www.attachment1.com},...
</code>```

```<code>$outputJson.Attachments
</code>```

```<code>name                    attachment_url
----                    --------------
(attachment.eml)[1].eml https://www.attachment1.com
(attachment.eml)[2].eml https://www.attachment222.com
(attachment.eml)[3].eml https://www.attachment2.com
(attachment.eml)[4].eml https://www.attachment3.com
(attachmnt.eml)[1].eml  https://www.attachmnt1.com
(attachmnt.eml)[2].eml  https://www.attachmnt2.com
attachmentOne.eml       https://www.attachmentOne.com
</code>```

Body:
If I have some JSON like this:

$inputJson = @"
{
    "attachments" :
        [
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment3.com"
            }
        ]
}

where there is an attachments array and each element in that array has the same name but different URLs, how can I change all the names so that it outputs like this:

$outputJson = @"
{
    "attachments" :
        [
            {
                "name":  "(attachment.eml)[1].eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "(attachment.eml)[2].eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "(attachment.eml)[3].eml",
                "attachment_url":  "https://www.attachment3.com"
            }
        ]
}
"@

which renames each attachment to prevent duplicate names, but it preserves the URLs.

Ideally, the code would also make sure none of the new names already exist in the array as well. So if there is already an attachment named (attachment.eml)[1].eml in the array, it would handle that as well.

I've thought about somehow using Group-Object but I haven't quite figured out how to make that work.

Body:
Requesting for code is considered off-topic here. However, for self-training purposes, the following code snippet could do the job. Partially commented and itemized to (auxiliary) intermediate variables:

$inputJson = @"
{
    "attachments" :
        [
            {
                "name":  "(attachment.eml)[2].eml",
                "attachment_url":  "https://www.attachment222.com"
            },
            {
                "name":  "attachmentOne.eml",
                "attachment_url":  "https://www.attachmentOne.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment1.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment2.com"
            },
            {
                "name":  "attachment.eml",
                "attachment_url":  "https://www.attachment3.com"
            },
            {
                "name":  "attachmnt.eml",
                "attachment_url":  "https://www.attachmnt1.com"
            },
            {
                "name":  "attachmnt.eml",
                "attachment_url":  "https://www.attachmnt2.com"
            }

        ]
}
"@
$objectJson     = $inputJson              | ConvertFrom-Json
$AttachsGrouped = $objectJson.attachments | Group-Object -Property Name
$newAttachments = $AttachsGrouped         | ForEach-Object {
    # debug output
    write-host $_.Count, $_.Group.GetType().Name, $_.name -ForegroundColor Cyan
    if ( $_.Count -gt 1 ) {
        $addCnt = 1
        $(  for ( $i = 0; $i -lt $_.Count; $i++ )
            {
                # make sure none of the new names already exist in the array
                While ( "($($_.name))[$($i+$addCnt)].eml" -in
                    $objectJson.attachments.name ) { $addCnt++ }
                [PSCustomObject]@{
                    'name'           = "($($_.name))[$($i+$addCnt)].eml"
                    'attachment_url' = $_.Group[$i].attachment_url
                }
            }
        )
    } else {
        # retain original definition
        $_.Group[0]
    }
}
$outputJson = [PSCustomObject]@{
                                    # for better output readability
    'attachments' = $newAttachments | Sort-Object -Property Name
}
# result
$outputJson   # | ConvertTo-Json -Depth 2

Result:

$outputJson

attachments
-----------
{@{name=(attachment.eml)[1].eml; attachment_url=https://www.attachment1.com},...

$outputJson.Attachments

name                    attachment_url
----                    --------------
(attachment.eml)[1].eml https://www.attachment1.com
(attachment.eml)[2].eml https://www.attachment222.com
(attachment.eml)[3].eml https://www.attachment2.com
(attachment.eml)[4].eml https://www.attachment3.com
(attachmnt.eml)[1].eml  https://www.attachmnt1.com
(attachmnt.eml)[2].eml  https://www.attachmnt2.com
attachmentOne.eml       https://www.attachmentOne.com


问:
How can I view Arabic/Persian numbers in a HTML page with strict doctype?
I have an HTML page that is right-to-left. When I don't use any doctype, my numbers are in Arabic/Persian, but when I use strict mode they turn to English.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">
</code>```

Before adding doctype:

After adding doctype:

also I added these meta tags to my page:

```<code><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="fa" />
</code>```

So how can I view Arabic numbers in a page with strict doctype (in IE because Firefox doesn't show Arabic numbers anyway)?

答:
This works for me, regardless of the text direction (in Chrome, Safari, Firefox and Opera):

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style type="text/css">
            body { direction: rtl; }
        </style>
    </head>

    <body>
        ۴۲
    </body>
</html>
</code>```

(Omitted the content-language since that isn’t necessary here.)

ContentLicense: CC BY-SA 3.0

Body:
I have an HTML page that is right-to-left. When I don't use any doctype, my numbers are in Arabic/Persian, but when I use strict mode they turn to English.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">

Before adding doctype:

After adding doctype:

also I added these meta tags to my page:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Language" content="fa" />

So how can I view Arabic numbers in a page with strict doctype (in IE because Firefox doesn't show Arabic numbers anyway)?

Body:
This works for me, regardless of the text direction (in Chrome, Safari, Firefox and Opera):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Final//EN">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style type="text/css">
            body { direction: rtl; }
        </style>
    </head>

    <body>
        ۴۲
    </body>
</html>

(Omitted the content-language since that isn’t necessary here.)


问:
Nodejs firesbase firestore does not retrieve any data using admin sdk
I am trying to read data from firestore database of firebase using admin sdk. The function returns nothing even I don't receive any error. The objective is to get the data using admin sdk and pass it to the browser using ejs variable. </p>

<p>Here is my code. </p>

```<code>var admin = require('firebase-admin');
var serviceAccount = require("path to json file");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "mydatabase id"
});

var db = admin.firestore();
var courses = db.collection("courses");

app.get("/", function (req, res) {
    var email = req.query.id;
    courses.where("email", "==", email).get().then(function (data) {
        console.log(data)
        res.render("public/main.ejs", {
            data: data
        })
    }).catch(function (error) {
        console.log(error)
    })

});
</code>```

答:
Try</p>

```<code>app.get("/", function (req, res) {
  var email = req.query.id;
  var coursesRef = admin.firestore().collection('courses');
  coursesRef.where("email", "==", email).get().then(function (data) {

    data.forEach(doc => {
      console.log(doc.data())
    });

      res.render("public/main.ejs", {
          data: data
      })
  }).catch(function (error) {
      console.log(error)
  })

});
</code>```

Body:
I am trying to read data from firestore database of firebase using admin sdk. The function returns nothing even I don't receive any error. The objective is to get the data using admin sdk and pass it to the browser using ejs variable.

Here is my code.

var admin = require('firebase-admin');
var serviceAccount = require("path to json file");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "mydatabase id"
});

var db = admin.firestore();
var courses = db.collection("courses");

app.get("/", function (req, res) {
    var email = req.query.id;
    courses.where("email", "==", email).get().then(function (data) {
        console.log(data)
        res.render("public/main.ejs", {
            data: data
        })
    }).catch(function (error) {
        console.log(error)
    })

});

Body:
Try

app.get("/", function (req, res) {
  var email = req.query.id;
  var coursesRef = admin.firestore().collection('courses');
  coursesRef.where("email", "==", email).get().then(function (data) {

    data.forEach(doc => {
      console.log(doc.data())
    });

      res.render("public/main.ejs", {
          data: data
      })
  }).catch(function (error) {
      console.log(error)
  })

});


问:
How enable omemo on Ejabberd 16.09-4 Debian9?
Is it possible (and eventually how) to enable OMEMO comunications for Ejabberd 16.09-4 on a Linux box Debian9?

I would like to enable OMEMO for using this feature on Android Conversation.

I've seen here that need to enable:

```<code>force_node_config:
</code>```

but this code option is not present on Ejabberd 16.09-4 config.

Many thanks!

答:
You don't need a forced node configuration (there is by the way some config options missing. I assume you are talking about this).

If your users are adding their chat partners to the contact list (roster), OMEMO works out of the box even without the forced whitelist access model. Overriding the node configuration only comes in handy if you want to enable OMEMO between users that don't have each other added to their contact lists.

Body:
Is it possible (and eventually how) to enable OMEMO comunications for Ejabberd 16.09-4 on a Linux box Debian9?

I would like to enable OMEMO for using this feature on Android Conversation.

I've seen here that need to enable:

force_node_config:

but this code option is not present on Ejabberd 16.09-4 config.

Many thanks!


问:
Apache Beam - What happens with Windows/Triggers after multiple GroupByKey?
The windowing section of the Beam programming model guide shows a
window defined and used in the GroupyByKey transform after a ParDo.
(section 7.1.1).

How long does a window remain in scope for an element?

Let's imagine a pipeline like this:

```<code>my_pcollection = p | MySourceOfData()

results_pcoll = (my_pcollection
                 | beam.WindowInto(..., triggering=...)
                 | beam.GroupByKey()
                 | beam.ParDo(DoSomeFormattingFn())
                 | beam.Combine.Globally(sum))
</code>```

Suppose that the first window is aggregating by key, but in the
second window you may want to combine elements across all keys.

How will the results_pcoll look like? Will it be windowed? Will it be per-key?

答:
In Beam, it is important to remember that every element has a window associated to it.

In the code snippet, elements in my_pcollection are associated to the Global Window. When you add a beam.WindowInto, you're adding a window to each element - and when they go into the GroupByKey, elements will be grouped by both: key, and window.

When you go downstream to a ParDo, and a Combine, your elements continue to have the same window, and the same trigger.

This happens because Beam tries to allow your data to continue to flow through your pipeline, so it keeps the same window and trigger semantics.

With those considerations, your results_pcoll will have the same window, and the same trigger semantics that you added at the beginning of the pipeline.

By combining Globally, you'll have a single aggregation over all keys, but you will also have one aggregation for each window.

Body:
The windowing section of the Beam programming model guide shows a
window defined and used in the GroupyByKey transform after a ParDo.
(section 7.1.1).

How long does a window remain in scope for an element?

Let's imagine a pipeline like this:

my_pcollection = p | MySourceOfData()

results_pcoll = (my_pcollection
                 | beam.WindowInto(..., triggering=...)
                 | beam.GroupByKey()
                 | beam.ParDo(DoSomeFormattingFn())
                 | beam.Combine.Globally(sum))

Suppose that the first window is aggregating by key, but in the
second window you may want to combine elements across all keys.

How will the results_pcoll look like? Will it be windowed? Will it be per-key?


问:
Users are not able to login after Yii to Laravel migration
especially PHP team.  I have a scenario, see if anyone has some tips?

I have an old system developed on Yii Framework. The user table there has encrypted passwords.  I recently moved those users to our new system developed using Laravel.  However, we could not bring the passwords as they were encrypted.      Client wants to keep same login / password on the new system for all users. Is it possible ?

答:
Are you the developer?

Are you using the same table and column and value for password?

I think you should be able to identify the hashing mechanism Yii used to store and verify passwords.

Let's imagine your Yii app used this for hashing passwords:

https://www.yiiframework.com/doc/api/1.1/CPasswordHelper#hashPassword-detail

(You should check the old app's code and make sure what algorithm was used)

Then could try to modify your Login system in Laravel to use the same algorithm from Yii old app.

I'm not familiar with Laravel so I cannot say more on that but you should be able to customize it somehow.


问:
Count numer of independent observations in group with repeated meassures
I want to count the number of independent observations per group in a group that has repeated measures.

Here's some toy data

```<code>library(dplyr)
df <- bind_rows(mtcars, mtcars, mtcars) %>%
 mutate(id=rep(row.names(mtcars),3))
</code>```

In this data,

```<code>df %>% group_by(cyl, id) %>% count()
</code>```

shows

```<code># A tibble: 32 x 3
# Groups:   cyl, id [32]
     cyl id                 n
   <dbl> <chr>          <int>
 1     4 Datsun 710         3
 2     4 Fiat 128           3
 3     4 Fiat X1-9          3
 4     4 Honda Civic        3
 5     4 Lotus Europa       3
 6     4 Merc 230           3
 7     4 Merc 240D          3
 8     4 Porsche 914-2      3
 9     4 Toyota Corolla     3
10     4 Toyota Corona      3
# … with 22 more rows
</code>```

This is the number of observations per individual (aka each car). To get the number of independent observations per group (how many cars for each cyl) I could do it like this.

```<code>df %>% group_by(cyl,id) %>% count() %>% ungroup() %>% group_by(cyl) %>% count()
# A tibble: 3 x 2
# Groups:   cyl [3]
    cyl     n
  <dbl> <int>
1     4    11
2     6     7
3     8    14
</code>```

which gives the correct result (check mtcars %>% group_by(cyl) %>% count())

The group_by(...) %>% count() %>% ungroup() %>% group_by() %>% count() is not intuitive to me.

What am I missing? Is there a better way to do this?

Related question, is there a way to pipe the count into the original df or you need a new object and left_join(...)?

答:
You need n_distinct() -

```<code>df %>% group_by(cyl) %>% summarize(n = n_distinct(id))

# A tibble: 3 x 2
    cyl     n
  <dbl> <int>
1     4    11
2     6     7
3     8    14
</code>```

For your related question you can do -

```<code>df %>%
  group_by(cyl) %>%
  mutate(n = n_distinct(id)) %>%
  ungroup()
</code>```

Body:
I want to count the number of independent observations per group in a group that has repeated measures.

Here's some toy data

library(dplyr)
df <- bind_rows(mtcars, mtcars, mtcars) %>%
 mutate(id=rep(row.names(mtcars),3))

In this data,

df %>% group_by(cyl, id) %>% count()

shows

# A tibble: 32 x 3
# Groups:   cyl, id [32]
     cyl id                 n
   <dbl> <chr>          <int>
 1     4 Datsun 710         3
 2     4 Fiat 128           3
 3     4 Fiat X1-9          3
 4     4 Honda Civic        3
 5     4 Lotus Europa       3
 6     4 Merc 230           3
 7     4 Merc 240D          3
 8     4 Porsche 914-2      3
 9     4 Toyota Corolla     3
10     4 Toyota Corona      3
# … with 22 more rows

This is the number of observations per individual (aka each car). To get the number of independent observations per group (how many cars for each cyl) I could do it like this.

df %>% group_by(cyl,id) %>% count() %>% ungroup() %>% group_by(cyl) %>% count()
# A tibble: 3 x 2
# Groups:   cyl [3]
    cyl     n
  <dbl> <int>
1     4    11
2     6     7
3     8    14

which gives the correct result (check mtcars %>% group_by(cyl) %>% count())

The group_by(...) %>% count() %>% ungroup() %>% group_by() %>% count() is not intuitive to me.

What am I missing? Is there a better way to do this?

Related question, is there a way to pipe the count into the original df or you need a new object and left_join(...)?

Body:
You need n_distinct() -

df %>% group_by(cyl) %>% summarize(n = n_distinct(id))

# A tibble: 3 x 2
    cyl     n
  <dbl> <int>
1     4    11
2     6     7
3     8    14

For your related question you can do -

df %>%
  group_by(cyl) %>%
  mutate(n = n_distinct(id)) %>%
  ungroup()


问:
How do I cast my NSArray to List<String> in xamarin ios
In my xamarin ios project I am fetching some array from a file

Using

```<code>NSArray TimeFilePath = NSBundle.MainBundle.PathForResource("Time","txt");
            arrTime =  NSArray.FromFile(TimeFilePath);
</code>```

Now I have to convert TimeFilePath to a List

I tried the following but It failed

```<code>List<string>items = (List<string>)TimeFilePath;
</code>```

Help me out how do I convert NSArray to List in C#

答:
I needed it to be done in one line and it took me quite some time to figure out, so I'm sharing my result here.

It is possible to do with Linq by using Enumerable.Range.

This example does it by iterating the NSArray and calling ToString() on every object in the NSArray and calling ToList() at the end.

```<code>Enumerable.Range(0, (int)((NSArray)arrTime).Count)
   .Select(i => ((NSArray)arrTime)
   .GetItem<NSString>(nuint.Parse(i.ToString())).ToString())
   .ToList()
</code>```

Body:
In my xamarin ios project I am fetching some array from a file

Using

NSArray TimeFilePath = NSBundle.MainBundle.PathForResource("Time","txt");
            arrTime =  NSArray.FromFile(TimeFilePath);

Now I have to convert TimeFilePath to a List

I tried the following but It failed

List<string>items = (List<string>)TimeFilePath;

Help me out how do I convert NSArray to List in C#

Body:
I needed it to be done in one line and it took me quite some time to figure out, so I'm sharing my result here.

It is possible to do with Linq by using Enumerable.Range.

This example does it by iterating the NSArray and calling ToString() on every object in the NSArray and calling ToList() at the end.

Enumerable.Range(0, (int)((NSArray)arrTime).Count)
   .Select(i => ((NSArray)arrTime)
   .GetItem<NSString>(nuint.Parse(i.ToString())).ToString())
   .ToList()


问:
Blazor The URI 'https://mydomain.tk/login' is not contained by the base URI
I have a problem that non of the pages work, only index page.
It works on my own machine (when testing in visual studio), but when hosting on a linux ubuntu machine with apache2 this error appears.

The webpage used to be server hosted client model (and it was working fine, no problems at all, just slow), but now that I changed it to server only (that works with SignalR) it doesn't work anymore.

I managed to fix websocket connection in apache settings so it's connecting.
Only when trying to go to another page for example /login
this happens:

feel free to try https://miniturtle.tk

using version 3.0.0-preview5

Ubuntu 16.04.6 LTS

I think it's the apache config files.

/etc/systemd/system/kestrel-FatGo.service:

[Unit]
Description=FatGo
[Service]
WorkingDirectory=/var/FatGo/publish
ExecStart=/usr/bin/dotnet /var/FatGo/publish/FatGo.dll
Restart=always
RestartSec=10
SyslogIdentifier=dotnet-demo
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target```
</div>
</div>
</p>

<p>/etc/apache2/conf-enabled/FatGo.conf:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><VirtualHost *:443>
ServerName miniturtle.tk
ServerAlias www.miniturtle.tk
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/apache.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache.key

ProxyPreserveHost On
ProxyPass / http://127.0.0.1:5000/ retry=1 acquire=3000 connectiontimeout=28800 timeout=28800 Keepalive=On
ProxyPassReverse / http://127.0.0.1:5000/

RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
RewriteRule /(.*) ws://127.0.0.1:5000/$1 [P]

ErrorLog /var/log/apache2/FatGo-error.log
CustomLog /var/log/apache2/FatGo-access.log common
LimitRequestFieldSize 10000000
LimitRequestBody 10000000
</VirtualHost></code>```

/etc/apache2/sites-available/FatGo.conf:

<VirtualHost *:80>
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</VirtualHost>

<VirtualHost *:443>
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:5000/
    ProxyPassReverse / http://127.0.0.1:5000/
    ErrorLog /var/log/apache2/FatGo-error.log
    CustomLog /var/log/apache2/FatGo-access.log common
    SSLEngine on
    SSLProtocol all -SSLv2
    SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:!RC4+RSA:+HIGH:+MEDIUM:!LOW:!RC4
    SSLCertificateFile /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key
</VirtualHost>```

If you could help me with this, I would appreciate it very much :)
Thanks for reading

P.S. I'm not a experienced web developer

答:
Did you notice that the scheme of the base URI is http, whereas the scheme for the login url is https? I've no knowledge of Ubuntu, but it seems as though you'll have to adjust some settings in your app's config files.

Hope this helps...

Body:
I have a problem that non of the pages work, only index page.
It works on my own machine (when testing in visual studio), but when hosting on a linux ubuntu machine with apache2 this error appears.

The webpage used to be server hosted client model (and it was working fine, no problems at all, just slow), but now that I changed it to server only (that works with SignalR) it doesn't work anymore.

I managed to fix websocket connection in apache settings so it's connecting.
Only when trying to go to another page for example /login
this happens:

feel free to try https://miniturtle.tk

using version 3.0.0-preview5

Ubuntu 16.04.6 LTS

I think it's the apache config files.

/etc/systemd/system/kestrel-FatGo.service:

[Unit]
Description=FatGo
[Service]
WorkingDirectory=/var/FatGo/publish
ExecStart=/usr/bin/dotnet /var/FatGo/publish/FatGo.dll
Restart=always
RestartSec=10
SyslogIdentifier=dotnet-demo
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target

/etc/apache2/conf-enabled/FatGo.conf:

<VirtualHost *:443>
ServerName miniturtle.tk
ServerAlias www.miniturtle.tk
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/apache.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache.key

ProxyPreserveHost On
ProxyPass / http://127.0.0.1:5000/ retry=1 acquire=3000 connectiontimeout=28800 timeout=28800 Keepalive=On
ProxyPassReverse / http://127.0.0.1:5000/

RewriteEngine on
RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
RewriteRule /(.*) ws://127.0.0.1:5000/$1 [P]

ErrorLog /var/log/apache2/FatGo-error.log
CustomLog /var/log/apache2/FatGo-access.log common
LimitRequestFieldSize 10000000
LimitRequestBody 10000000
</VirtualHost>

/etc/apache2/sites-available/FatGo.conf:

<VirtualHost *:80>
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</VirtualHost>

<VirtualHost *:443>
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:5000/
    ProxyPassReverse / http://127.0.0.1:5000/
    ErrorLog /var/log/apache2/FatGo-error.log
    CustomLog /var/log/apache2/FatGo-access.log common
    SSLEngine on
    SSLProtocol all -SSLv2
    SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:!RC4+RSA:+HIGH:+MEDIUM:!LOW:!RC4
    SSLCertificateFile /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key
</VirtualHost>

If you could help me with this, I would appreciate it very much :)
Thanks for reading

P.S. I'm not a experienced web developer


问:
Position div depending on the height of another div
I have a
 (let's call it "image") that contains some images  and so on.
This div's width is set at 100% of the screen, and the images inside rescale depending on the width. So, depending on the browser's width, the height of my div changes.

Now I would like to create another div (let's call it "after_image") that starts after this image, without using "relative", but by retrieving the height of
, and using that as a "top: px" attribute.

Is it possible? Maybe a

答:
Here is how you can achieve what you want, although this is the wrong approach in my opinion.

const
  image = document.querySelector('#image'),
  after = document.querySelector('#after_image')

after.style.top = image.getBoundingClientRect().bottom + 'px'```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#image {
  width: 200px;
  height: 2750px;
  box-sizing: border-box;
  border: solid blue 3px;
  background: skyblue;
}

#after_image {
  width: 200px;
  height: 500px;
  position: absolute;
  box-sizing: border-box;
  border: solid orangered 3px;
  background: pink;
}</code>```

```
</div>
</div>
</p>

<p>If you really want to do it this way, it is best to bind your JS statement to the <code>resize</code> event.</p>

```window.addEventListener('resize', function(){
  after.style.top = image.getBoundingClientRect().bottom + 'px'
}
```

Body:
Here is how you can achieve what you want, although this is the wrong approach in my opinion.

const
  image = document.querySelector('#image'),
  after = document.querySelector('#after_image')

after.style.top = image.getBoundingClientRect().bottom + 'px'

#image {
  width: 200px;
  height: 2750px;
  box-sizing: border-box;
  border: solid blue 3px;
  background: skyblue;
}

#after_image {
  width: 200px;
  height: 500px;
  position: absolute;
  box-sizing: border-box;
  border: solid orangered 3px;
  background: pink;
}

<div id='image'>
  <img src='' />
</div>
<div id='after_image'></div>

If you really want to do it this way, it is best to bind your JS statement to the resize event.

window.addEventListener('resize', function(){
  after.style.top = image.getBoundingClientRect().bottom + 'px'
}


问:
Difference between events and delegates and its respective applications
I don't see advantages of using events over delegates, other than being syntactical sugar. Perhaps I am misunderstanding, but it seems that event is just a placeholder for delegate.

Would you explain to me the differences and when to use which?  What are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it.

When would you use delegates over events and vice versa? Please state your real world experience with both, say in the production code.

答:
Although I've got no technical reasons for it, I use events in UI style code, in other words, in the higher levels of the code, and use delegates for logic that lays deeper in the code. As I say you could use either, but I find this use pattern to be logically sound, if nothing else, it helps document the types of callbacks and their hierarchy too.

Edit: I think the difference in usage patterns I have would be that, I find it perfectly acceptable to ignore events, they are hooks/stubs, if you need to know about the event, listen to them, if you don't care about the event just ignore it. That's why I use them for UI, kindof Javascript/Browser event style. However when I have a delegate, I expect REALLY expect someone to handle the delegate's task, and throw an exception if not handled.

OwnerDisplayName: Sasha

LastEditorDisplayName: RoBorg

OwnerDisplayName: Robert Gould

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Robert Gould


问:
How do I activate the click event for a button on Android?
How do I activate the click event for a button on Android?</p>

答: You push the button (please elaborate if that wasn't the answer you were looking for)</p>


问:
Multiuser chat OMEMO encrypted messages and MAM (XEP-0313)
i am trying to use the Monitoring plugin for offline storage of OMEMO encrypted multi user chat messages. The Monitoring plugin for Openfire does not save this type of messages, because their stanzas do not contain the body element. Is this a missing functionality in the Monitoring plugin (OMEMO with XEP-0313) or is it a conscious decision? And if it is a conscious decision what are the reasons?
Thanks.</p>

答: Related thread on the Ignite Realtime forums.</p>


问:
Option is both a functor and a monad?
Is Scala's Option both a monad and a functor?

As I understand it, functor is just a data type that exposes the following API:

Functor:

wrap (or apply) which takes a primitive and wraps it inside the functor

map which takes a functor, unwraps it, applies some function and re-wraps it

So Option is a functor. Because I can apply an Option to a primitive giving me Option[T]. I can also map on Option to obtain what's inside the functor and repackage inside Option.

How is monad different? I had thought that a monad also had an apply function and a map function. From this article I gather that a monad also has flatMap? Which is defined as simply map but without repackaging the result inside a monad? (Or is it map without repacking the result inside a functor?!)

Since Option supplies both map and flatMap does that mean that Option is both a functor and a monad?

答:
Short answer: Yes.

Longer answer: Every monad is an applicative functor and every applicative functor is a functor. In Object-Oriented terms: Monad <: Applicative <: Functor.

Title: Option is both a functor and a monad?


问:
Angular Universal not rendering content inside of router-outlet
I am trying to render my Angular 7 application with SSR using Angular Universal from this link https://angular.io/guide/universal. I had thought I had everything working from there since I was able to view the page source and see everything that is inside of the app.component rendered to the page. However, I am unable to render any of the routes inside of the router-outlet tag

I have simply stripped my app down to be doing exactly what the documentation says. I read in there something about ensuring ModuleMapLoaderModule is inside of the app.server.module in order for lazy loading to work. This does come default with the angular-cli command for universal so I am not sure what is going on.

app.server.module

```<code>import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';

import { AppComponent } from './app.component';
import { AppModule } from './app.module';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ModuleMapLoaderModule,
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule {}
</code>```

tsconfig.server.json

```<code>  "extends": "./tsconfig.app.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app-server",
  },
  "angularCompilerOptions": {
    "entryModule": "app/app.server.module#AppServerModule"
  }
}
</code>```

server.ts

```<code>import 'zone.js/dist/zone-node';
import { enableProdMode } from '@angular/core';
// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

import * as express from 'express';
import { join } from 'path';

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'browser');

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

// Serve static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
  maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'index.html'), { req });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});
</code>```

Rendered output

```<code><html lang="en">

<head>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- ...Rendered CSS styles... -->
<body>
    <app-root _nghost-sc0="" ng-version="7.2.15">
        <!-- ...Header code that has been rendered... -->

        <router-outlet _ngcontent-sc0=""></router-outlet> <!-- This is where I am expecting the content of the route to be -->

        <!-- ...Footer code that has been rendered... -->
    </app-root>
</body>

</html>
</code>```

app.routing.module.ts

```<code>// Angular Imports

// Pages
// ...Page Imports..

const routes: Routes = [
  { path: '', component: HomePageComponent, pathMatch: 'full' },
  { path: 'events/:id', component: EventDetailPageComponent }, // This is the detail page I am testing with
  { path: 'unknown-error', component: UnknownErrorPageComponent },
  { path: '404', component: NotFoundPageComponent },
  { path: '**', redirectTo: '404' }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
  ],
  exports: [
    RouterModule,
  ]
})
export class AppRoutingModule { }
</code>```

I have been having basically zero luck attempting to find accurate documentation on this for Angular 7 and any help would be greatly appreciated! Thanks

答: I do not have any experience with server side rendering, but a common issue with Angular apps when they are deployed to a server is the resolution of sub-directories. Basically the root will load but all other items that are handled in the angular routing will not work when accessed through the url. The web server is looking for those physical directories instead of allowing Angular routing to direct the page to a virtual directory. If this sounds like your issue there are some option outlined here</p>

Body:
I am trying to render my Angular 7 application with SSR using Angular Universal from this link https://angular.io/guide/universal. I had thought I had everything working from there since I was able to view the page source and see everything that is inside of the app.component rendered to the page. However, I am unable to render any of the routes inside of the router-outlet tag

I have simply stripped my app down to be doing exactly what the documentation says. I read in there something about ensuring ModuleMapLoaderModule is inside of the app.server.module in order for lazy loading to work. This does come default with the angular-cli command for universal so I am not sure what is going on.

app.server.module

import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';

import { AppComponent } from './app.component';
import { AppModule } from './app.module';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ModuleMapLoaderModule,
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule {}

tsconfig.server.json

  "extends": "./tsconfig.app.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app-server",
  },
  "angularCompilerOptions": {
    "entryModule": "app/app.server.module#AppServerModule"
  }
}

server.ts

import 'zone.js/dist/zone-node';
import { enableProdMode } from '@angular/core';
// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

import * as express from 'express';
import { join } from 'path';

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'browser');

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

// Serve static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
  maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'index.html'), { req });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

Rendered output

    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <app-root _nghost-sc0="" ng-version="7.2.15">

        <router-outlet _ngcontent-sc0=""></router-outlet>

    </app-root>

app.routing.module.ts

// Angular Imports

// Pages
// ...Page Imports..

const routes: Routes = [
  { path: '', component: HomePageComponent, pathMatch: 'full' },
  { path: 'events/:id', component: EventDetailPageComponent }, // This is the detail page I am testing with
  { path: 'unknown-error', component: UnknownErrorPageComponent },
  { path: '404', component: NotFoundPageComponent },
  { path: '**', redirectTo: '404' }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
  ],
  exports: [
    RouterModule,
  ]
})
export class AppRoutingModule { }

I have been having basically zero luck attempting to find accurate documentation on this for Angular 7 and any help would be greatly appreciated! Thanks


问:
java ClassNotFoundException for org.h2.Driver
I am trying to use H2 to connect to a database in Java (using Eclipse as the IDE). The sample does (below) throws a ClassNotFoundException. The thing is, I did add the h2 jar file to the system CLASSPATH. I have even checked it's there several times via printenv in the console. Am I omitting a step?

CODE:

```<code>import java.sql.*;

public class Program {

 /**
  * @param args
  */
 public static void main(String[] args)
  throws Exception{

  try{
   System.out.println("hello, world!");
   Class.forName("org.h2.Driver");
   Connection conn = DriverManager.getConnection("jdbc:h2:~/testdb", "sa", "");
   // add application code here
   conn.close();
  }catch(ClassNotFoundException ex){
   System.out.println( "ERROR: Class not found: " + ex.getMessage() );

  }
  System.exit(0);

 }

}
</code>```

答:
If you use Gradle change dependency in build.gradle:

```<code>testCompile group: 'com.h2database', name: 'h2', version: '1.4.199'
</code>```

to

```<code>compile group: 'com.h2database', name: 'h2', version: '1.4.199'
</code>```

Body:
I am trying to use H2 to connect to a database in Java (using Eclipse as the IDE). The sample does (below) throws a ClassNotFoundException. The thing is, I did add the h2 jar file to the system CLASSPATH. I have even checked it's there several times via printenv in the console. Am I omitting a step?

CODE:

import java.sql.*;

public class Program {

 /**
  * @param args
  */
 public static void main(String[] args)
  throws Exception{

  try{
   System.out.println("hello, world!");
   Class.forName("org.h2.Driver");
   Connection conn = DriverManager.getConnection("jdbc:h2:~/testdb", "sa", "");
   // add application code here
   conn.close();
  }catch(ClassNotFoundException ex){
   System.out.println( "ERROR: Class not found: " + ex.getMessage() );

  }
  System.exit(0);

 }

}

Body:
If you use Gradle change dependency in build.gradle:

testCompile group: 'com.h2database', name: 'h2', version: '1.4.199'

to

compile group: 'com.h2database', name: 'h2', version: '1.4.199'


问:
Looping an array together with a jquery hover function
I'm trying to... God, this is hard to explain.

I got an array called 'triggers' with these variables:

"#1_trigger","#2_trigger","#3_trigger"

And inside a jQuery each(), I create another variable called 'targets' that copies everything from 'triggers' and replaces all _trigger to _target. I then append the 'triggers' to anchor IDs, and 'targets' to hidden div IDs.

What I want to do, is this: When hovering a _trigger, the _target will show up. I've managed to make it work with only one variable, but not with multiple.

As I said, it's kind of hard to explain what I want to do in text, so here's a demo and my progress so far:
http://jsfiddle.net/WJWe3/6/

I've been stuck with this one for too many hours now, please help!

答:
Something like this maybe?

http://jsfiddle.net/WJWe3/11/


问:
IF statement using cell formatted value
In Google Sheets, how can you use the IF statement using the output of a cell's formatted value?

I've created a Google Sheet with a date value in B1. The cell is formatted using the date format. B1 is then copied across to the right so that it increments the days of the month.

In B2, based on the B1 date, I want to display the day value (ie Thu, Fri, Sat etc.). Similarly to the first step, I set the date format under Format > Number > More formats > More date and time formats, then from the select box, choose the day and I want to display the "Tue" date format.

Then in B8, I want to display an amount of 30 every Thursday, otherwise, show 0.

This is where it doesn't work. Does it seem like the rendered cell's value can't be used in an IF statement? My desired output is that every the value in row 2 is a 'Thu' display 30.

As a side note, I jumped on Google support and asked this same question. Even though they are technical support, I thought I'd give them a try anyway, after all, I am paying for GSuite.

This is the formula they came back to me with: =if(B2=B1, "30", "0").

Of course, this formula will work in B8, because B2 is equal to B1 in the actual cell value, it doesn't take into account the formatted cell value. This formula will fail the output we need as it will always display 30 instead of only then row 2 is 'Thu'.

So essentially, is there a function in Google Sheets for a rendered cell value?  Or another solution around this?

Note: I do NOT want to use any scripting to get this to work.

答:
try it like this:

```<code>=IF(TEXT(B2, "ddd")="Thu", 30, 0)
</code>```

Title: IF statement using cell formatted value

Body:
try it like this:

=IF(TEXT(B2, "ddd")="Thu", 30, 0)