问:
Handshake error to mysql via ssl
tldr:  I get the following error with a client/server setup with ssl:

Specifically: ssl configuration error: UseCertificateChainFile: SSL errors: PEM routines:PEM_read_bio:no start line SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib

The details:

I am hosting something similar to a mysql server on ec2 (specifically mongosqld)

I need to connect to it via ssl, so I create certs using openssl on the machine using this set of instructions provided by mysql: https://dev.mysql.com/doc/refman/5.7/en/creating-ssl-files-using-openssl.html

I run the server with the following command

mongosqld --schema=schema.drdl \
           --addr=0.0.0.0:3307 \
           --auth \
           --sslMode=allowSSL \
           --sslCAFile=ca.pem \
           --sslPEMKeyFile=server-key.pem

And on my machine, I attach to the server like so:

mysql --protocol tcp \
       --host my.host.on.amazon.com --port 3307 \
       --enable-cleartext-plugin \
       --ssl-cert mongosqlcerts/client-cert.pem
       --ssl-key mongosqlcerts/client-key.pem
       --ssl-ca mongosqlcerts/ca.pem

On the client side I get the following error:
SSL connection error: error:00000001:lib(0):func(0):reason(1)

On the server logs, a bit more helpful:

```<code>mongosqld starting: version=v2.3.1 pid=11461 host=ip-xx-xx-xx-xx
I CONTROL    [initandlisten] git version: fa3535342a4c5abe36e3cc28a2ecf72864dfc6fe
I CONTROL    [initandlisten] OpenSSL version: OpenSSL 1.0.1e 11 Feb 2013
I CONTROL    [initandlisten] options: {schema: {path: "schema.drdl"}, net: {bindIp: [0.0.0.0], ssl: {mode: "allowSSL", PEMKeyFile: "server-key.pem", CAFile: "ca.pem"}}, security: {enabled: true}}
I NETWORK    [initandlisten] waiting for connections at [::]:3307
I NETWORK    [initandlisten] waiting for connections at /tmp/mysql.sock
I NETWORK    [conn1] connection accepted from 108.20.XXX.XXX:63353 #1 (1 connection now open)
E NETWORK    [conn1] handshake error: ERROR 1043 (08S01): recv handshake response error: ERROR 1043 (08S01): ssl configuration error: UseCertificateChainFile: SSL errors: PEM routines:PEM_read_bio:no start line
SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib
2017-12-01T22:24:50.394+0000 I NETWORK    [conn1] end connection 108.20.XXX.XXX:63353 (0 connections now open)
</code>```

Specifically: ssl configuration error: UseCertificateChainFile: SSL errors: PEM routines:PEM_read_bio:no start line
    SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib

Can anyone help me parse that error.

Thanks friends!

答:
I got it!

so for the sslPEMKeyFile argument in mongosqld as stated in the docs you need to

Specifies the .pem file containing both the TLS/SSL certificate and key for MySQL clients. Specify the file name of the .pem file using relative or absolute paths.

So when I used openssl to create ca, server-cert and key files, I needed to create a new file that combined the private-key and the server-cert

so I created a new file called combined.pem with the following text in it:

-----BEGIN RSA PRIVATE KEY-----
(Your Private Key: your_domain_name.key)
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
(Your Primary SSL certificate: your_domain_name.crt)
-----END CERTIFICATE-----

and started the server with that and it worked!!!

Title: Handshake error to mysql via ssl

Body:
tldr:  I get the following error with a client/server setup with ssl:

Specifically: ssl configuration error: UseCertificateChainFile: SSL errors: PEM routines:PEM_read_bio:no start line SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib

The details:

I am hosting something similar to a mysql server on ec2 (specifically mongosqld)

I need to connect to it via ssl, so I create certs using openssl on the machine using this set of instructions provided by mysql: https://dev.mysql.com/doc/refman/5.7/en/creating-ssl-files-using-openssl.html

I run the server with the following command

mongosqld --schema=schema.drdl \
           --addr=0.0.0.0:3307 \
           --auth \
           --sslMode=allowSSL \
           --sslCAFile=ca.pem \
           --sslPEMKeyFile=server-key.pem

And on my machine, I attach to the server like so:

mysql --protocol tcp \
       --host my.host.on.amazon.com --port 3307 \
       --enable-cleartext-plugin \
       --ssl-cert mongosqlcerts/client-cert.pem
       --ssl-key mongosqlcerts/client-key.pem
       --ssl-ca mongosqlcerts/ca.pem

On the client side I get the following error:
SSL connection error: error:00000001:lib(0):func(0):reason(1)

On the server logs, a bit more helpful:

mongosqld starting: version=v2.3.1 pid=11461 host=ip-xx-xx-xx-xx
I CONTROL    [initandlisten] git version: fa3535342a4c5abe36e3cc28a2ecf72864dfc6fe
I CONTROL    [initandlisten] OpenSSL version: OpenSSL 1.0.1e 11 Feb 2013
I CONTROL    [initandlisten] options: {schema: {path: "schema.drdl"}, net: {bindIp: [0.0.0.0], ssl: {mode: "allowSSL", PEMKeyFile: "server-key.pem", CAFile: "ca.pem"}}, security: {enabled: true}}
I NETWORK    [initandlisten] waiting for connections at [::]:3307
I NETWORK    [initandlisten] waiting for connections at /tmp/mysql.sock
I NETWORK    [conn1] connection accepted from 108.20.XXX.XXX:63353 #1 (1 connection now open)
E NETWORK    [conn1] handshake error: ERROR 1043 (08S01): recv handshake response error: ERROR 1043 (08S01): ssl configuration error: UseCertificateChainFile: SSL errors: PEM routines:PEM_read_bio:no start line
SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib
2017-12-01T22:24:50.394+0000 I NETWORK    [conn1] end connection 108.20.XXX.XXX:63353 (0 connections now open)

Specifically: ssl configuration error: UseCertificateChainFile: SSL errors: PEM routines:PEM_read_bio:no start line
    SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib

Can anyone help me parse that error.

Thanks friends!


来源: stackexchange

问:
Why does Traefik not proxy new services in a Docker Swarm?
I try to setup traefik with a Docker Swarm. I have to VMs - one manger-node and one worker-node.
In addition I have created a external network with:

```<code>docker network create --driver=overlay proxy-net
</code>```

I start traefik as a service within my manager-node with the following docker-compose.yml file:

```<code>version: '3'

services:
  traefik:
     image: traefik:v1.4.4
     volumes:
       - /var/run/docker.sock:/var/run/docker.sock
       - $PWD/management/traefik/traefik.toml:/etc/traefik/traefik.toml
     ports:
       - 80:80
       - 8100:8080
     deploy:
       placement:
         constraints:
           - node.role == manager

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

My traefik.toml file looks like this:

```<code>Debug : "DEBUG"
defaultEntryPoints = ["http"]
[entryPoints]
    [entryPoints.http]
    address = ":80"

[web]
address = ":8080"

[docker]
watch = true
swarmmode = true
domain = "mydomain.com"
exposedbydefault = true
</code>```

When I now start a new service (e.g. emilevauge/whoami) with:

```<code>docker service create \
    --name whoami1 \
    --publish mode=host,target=80,published=8002 \
    --network proxy-net \
    --label traefik.docker.network=proxy-net \
    --label traefik.frontend.rule=Host:whoami.mydomain.com \
    --label traefik.port=8002 \
    emilevauge/whoami
</code>```

The service is seen by the traefik web frontend. So at first every thing looks fine. I can access the service directly on my worker node on port 8002.
But traefik does not seem to be able to proxy this service. When I browse my endpoint URL (whomai.mydomain.com) I get the answer:

```<code>Bad Gateway
</code>```

The traefik logfile (logLevel=DEBUG) shown messages like this:

```<code>proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_app.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label proxy_traefik.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_db.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Validation of load balancer method for backend backend-whoami1-whoami1-whoami1 failed: invalid load-balancing method ''. Using default method wrr."
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Configuration received from provider docker: {"backends":{"backend-whoami1-whoami1-whoami1":{"servers":{"service-0":{"url":"http://10.0.1.5:8002","weight":0}},"loadBalancer":{"method":"wrr"}}},"frontends":{"frontend-whoami1-whoami1-whoami1":{"entryPoints":["http"],"backend":"backend-whoami1-whoami1-whoami1","routes":{"service-whoami1":{"rule":"Host:whoami.mydomain.com"}},"passHostHeader":true,"priority":0,"basicAuth":[],"headers":{}}}}"
</code>```

I played around several hours with different configurations. I also read the very concise documentation about traefik and docker-swarm. But I don't get any idea what I'm doing wrong.

Can any body help me with some tips how to better understand the problem?

答:
As already mentioned, they need to be in the same overlay network which is not ingress. The ingress network is only for manager nodes.

Further more, your traefik service is not assigned to the proxy-net network. You're creating proxy-net in your traefik config part, but don't assigned it to it

```<code>version: '3'

services:
    traefik:
        image: traefik:v1.4.4
        volumes:
            - /var/run/docker.sock:/var/run/docker.sock
            - $PWD/management/traefik/traefik.toml:/etc/traefik/traefik.toml
        ports:
            - 80:80
            - 8100:8080
        networks:
        - proxy-net
        deploy:
        placement:
            constraints:
                - node.role == manager

networks:
    proxy-net:
        driver: overlay
</code>```

Further more, you should create a config with docker config create. Otherwise with $PWD/management/traefik/traefik.toml you need to copy the traefik.toml file to every manager node.

Append your compose file with

```<code>configs:
  traefik_conf_v1:
    file: ./traefik.toml
</code>```

and your traefik part with

```<code>    configs:
      - source: traefik_conf_v1
        target: /etc/traefik/traefik.toml
</code>```

Now back to your problem.

What's your service is missing is the label to the backend. Otherwise traefik doesn't know where the service is running (network assignment isn't enough!).

```<code>docker service create \
    --name whoami1 \
    --publish mode=host,target=80,published=8002 \
    --network proxy-net \
    --label traefik.backen=whoami1 \
    --label traefik.docker.network=proxy-net \
    --label traefik.frontend.rule=Host:whoami.mydomain.com \
    --label traefik.port=8002 \
    emilevauge/whoami
</code>```

This should work. And when it does, stop publishing ports of your services. That makes everything complicated when you're in a hurry and need to scale. Remember, work balancing is handle by the swarm itself.

And yeah, dynamic flexible reverse proxys is still a problem nowadays :)

Remember, you got your entry points on manager nodes with traefik, but not on the worker nodes.

ContentLicense: CC BY-SA 3.0

Body:
I try to setup traefik with a Docker Swarm. I have to VMs - one manger-node and one worker-node.
In addition I have created a external network with:

docker network create --driver=overlay proxy-net

I start traefik as a service within my manager-node with the following docker-compose.yml file:

version: '3'

services:
  traefik:
     image: traefik:v1.4.4
     volumes:
       - /var/run/docker.sock:/var/run/docker.sock
       - $PWD/management/traefik/traefik.toml:/etc/traefik/traefik.toml
     ports:
       - 80:80
       - 8100:8080
     deploy:
       placement:
         constraints:
           - node.role == manager

networks:
   default:
    external:
      name:  proxy-net

My traefik.toml file looks like this:

Debug : "DEBUG"
defaultEntryPoints = ["http"]
[entryPoints]
    [entryPoints.http]
    address = ":80"

[web]
address = ":8080"

[docker]
watch = true
swarmmode = true
domain = "mydomain.com"
exposedbydefault = true

When I now start a new service (e.g. emilevauge/whoami) with:

docker service create \
    --name whoami1 \
    --publish mode=host,target=80,published=8002 \
    --network proxy-net \
    --label traefik.docker.network=proxy-net \
    --label traefik.frontend.rule=Host:whoami.mydomain.com \
    --label traefik.port=8002 \
    emilevauge/whoami

The service is seen by the traefik web frontend. So at first every thing looks fine. I can access the service directly on my worker node on port 8002.
But traefik does not seem to be able to proxy this service. When I browse my endpoint URL (whomai.mydomain.com) I get the answer:

Bad Gateway

The traefik logfile (logLevel=DEBUG) shown messages like this:

proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_app.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label proxy_traefik.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Filtering container without port and no traefik.port label swarmpit_db.1 : strconv.Atoi: parsing "": invalid syntax"
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Validation of load balancer method for backend backend-whoami1-whoami1-whoami1 failed: invalid load-balancing method ''. Using default method wrr."
proxy_traefik.1.zl50yv6got5f@tocidoc001 time="2017-12-03T20:09:28Z" level=debug msg="Configuration received from provider docker: {"backends":{"backend-whoami1-whoami1-whoami1":{"servers":{"service-0":{"url":"http://10.0.1.5:8002","weight":0}},"loadBalancer":{"method":"wrr"}}},"frontends":{"frontend-whoami1-whoami1-whoami1":{"entryPoints":["http"],"backend":"backend-whoami1-whoami1-whoami1","routes":{"service-whoami1":{"rule":"Host:whoami.mydomain.com"}},"passHostHeader":true,"priority":0,"basicAuth":[],"headers":{}}}}"

I played around several hours with different configurations. I also read the very concise documentation about traefik and docker-swarm. But I don't get any idea what I'm doing wrong.

Can any body help me with some tips how to better understand the problem?

Body:
As already mentioned, they need to be in the same overlay network which is not ingress. The ingress network is only for manager nodes.

Further more, your traefik service is not assigned to the proxy-net network. You're creating proxy-net in your traefik config part, but don't assigned it to it

version: '3'

services:
    traefik:
        image: traefik:v1.4.4
        volumes:
            - /var/run/docker.sock:/var/run/docker.sock
            - $PWD/management/traefik/traefik.toml:/etc/traefik/traefik.toml
        ports:
            - 80:80
            - 8100:8080
        networks:
        - proxy-net
        deploy:
        placement:
            constraints:
                - node.role == manager

networks:
    proxy-net:
        driver: overlay

Further more, you should create a config with docker config create. Otherwise with $PWD/management/traefik/traefik.toml you need to copy the traefik.toml file to every manager node.

Append your compose file with

configs:
  traefik_conf_v1:
    file: ./traefik.toml

and your traefik part with

    configs:
      - source: traefik_conf_v1
        target: /etc/traefik/traefik.toml

Now back to your problem.

What's your service is missing is the label to the backend. Otherwise traefik doesn't know where the service is running (network assignment isn't enough!).

docker service create \
    --name whoami1 \
    --publish mode=host,target=80,published=8002 \
    --network proxy-net \
    --label traefik.backen=whoami1 \
    --label traefik.docker.network=proxy-net \
    --label traefik.frontend.rule=Host:whoami.mydomain.com \
    --label traefik.port=8002 \
    emilevauge/whoami

This should work. And when it does, stop publishing ports of your services. That makes everything complicated when you're in a hurry and need to scale. Remember, work balancing is handle by the swarm itself.

And yeah, dynamic flexible reverse proxys is still a problem nowadays :)

Remember, you got your entry points on manager nodes with traefik, but not on the worker nodes.


问:
Elmasri Employee Database - Determining those working at different locations

I am working on the Elmasri Employee DB. Please refer to this document document regarding its details.
I have obtained the employees working on two or more projects and their respective locations:

select w."Essn", p."Plocation"
from "Works_On" w, "Project" p, "Employee" e
where p."Pnumber" = w."Pno" and w."Essn" = e."Ssn"
        and
        w."Essn" in
        (select w1."Essn"
        from "Works_On" w1
        group by w1."Essn"
        having count(*) >= 2
        )
```

<p>The resulting relation looks like
<img src="https://i.stack.imgur.com/ZfjET.jpg" alt="this">.</p>

<p>I need to determine those employees that work on two or more different locations. Therefore, <code>987987987</code> and <code>999887777</code> are not eligible as they are working on two different projects but at the same location. The solution I came up is to group the employees based on their <code>Essn</code> and <code>Plocation</code> attributes and determine those that are equal to one. Updated code would be: </p>

<pre class="lang-sql prettyprint-override"><code>select base."Essn", base."Plocation"
from
    (select w."Essn", p."Plocation"
    from "Works_On" w, "Project" p, "Employee" e
    where p."Pnumber" = w."Pno" and w."Essn" = e."Ssn"
        and
        w."Essn" in
        (select w1."Essn"
        from "Works_On" w1
        group by w1."Essn"
        having count(*) >= 2
        )
    ) as base

group by base."Essn", base."Plocation"
having count(*) =1
</code>```

However, this obviously is not true as it would eliminate 33344555 - Stafford.

My question is: would it possible from the given base relation to determine those employees that work on more than x different locations?

答:
In order to find employees that work on two different projects on two different locations you probably just need this query

```<code>  select w."Essn"
  from "Works_On" w
  join "Project" p on p."Pnumber" = w."Pno"
  group by w."Essn"
  having count(distinct w."Pno") > 1 and count(distinct p."Plocation") > 1
</code>```

and having query like this should be sufficient as well

```<code>  select w."Essn"
  from "Works_On" w
  join "Project" p on p."Pnumber" = w."Pno"
  group by w."Essn"
  having count(distinct p."Plocation") > 1
</code>```

Body:
I am working on the Elmasri Employee DB. Please refer to this document document regarding its details.
I have obtained the employees working on two or more projects and their respective locations:

select w."Essn", p."Plocation"
from "Works_On" w, "Project" p, "Employee" e
where p."Pnumber" = w."Pno" and w."Essn" = e."Ssn"
        and
        w."Essn" in
        (select w1."Essn"
        from "Works_On" w1
        group by w1."Essn"
        having count(*) >= 2
        )

The resulting relation looks like
.

I need to determine those employees that work on two or more different locations. Therefore, 987987987 and 999887777 are not eligible as they are working on two different projects but at the same location. The solution I came up is to group the employees based on their Essn and Plocation attributes and determine those that are equal to one. Updated code would be:

select base."Essn", base."Plocation"
from
    (select w."Essn", p."Plocation"
    from "Works_On" w, "Project" p, "Employee" e
    where p."Pnumber" = w."Pno" and w."Essn" = e."Ssn"
        and
        w."Essn" in
        (select w1."Essn"
        from "Works_On" w1
        group by w1."Essn"
        having count(*) >= 2
        )
    ) as base

group by base."Essn", base."Plocation"
having count(*) =1

However, this obviously is not true as it would eliminate 33344555 - Stafford.

My question is: would it possible from the given base relation to determine those employees that work on more than x different locations?

Body:
In order to find employees that work on two different projects on two different locations you probably just need this query

  select w."Essn"
  from "Works_On" w
  join "Project" p on p."Pnumber" = w."Pno"
  group by w."Essn"
  having count(distinct w."Pno") > 1 and count(distinct p."Plocation") > 1

and having query like this should be sufficient as well

  select w."Essn"
  from "Works_On" w
  join "Project" p on p."Pnumber" = w."Pno"
  group by w."Essn"
  having count(distinct p."Plocation") > 1


问:
Changing text in a text file via user input. Python
So I have this login in system where they can enter their favourite artist and genre. this gets saved to a text file. But know I need an option where they can change their favourite artist and genre. This is the code so far. The user information is stored in a text file all on the same line. </p>

```<code>def registerUser():
 usrFile_write = open(textfile, "a")
 usrFile_write.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":")
 print("New Account Created!\n")
 usrFile_write.close()
 Menu()
def change():
menu=input("Change account preferences? (y/n")
if menu == "yes":
    NewA=input("What is your new favorite artist...")
    NewG=input("What is your new favorite genre...")
    FavAG = open("user_DB.txt","w")
    FavAG.write (NewA)
    FavAG.write ("\n")
    FavAG.write (NewG)
    FavAG.close()
</code>```

答:
First off, you should always use with statements when working with files. The benefits of this are well documented. So this:

```<code>usrFile_write = open(textfile, "a")
usrFile_write.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":")
print("New Account Created!\n")
usrFile_write.close()
</code>```

Becomes:

```<code>with open(textfile, "a") as usrFile:
    usrFile.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":")
    print("New Account Created!\n")
</code>```

Now, working in a plain text file, you can't really edit specific lines. In order to update an existing user entry, you will have to delete the existing entry and create a new one in its place. This requires reading through the file and re-writing the whole thing, except for the specific line. You can put this into a generalized deleteUser function for re-use later on:

```<code>def deleteUser(username):
    with open(textfile, "r") as usrFile:
        lines = usrFile.readlines()
    with open(textfile, "w") as usrFile:
        for line in lines:
            if line.split(":")[0] != username:
                usrFile.write(line)
</code>```

Then, to modify a user, you delete their entry and then create a new one with the new information.

This ought to cover you for now. I recommend looking into using a database like sqlite in the long term, this job is much better suited for it.

Body:
So I have this login in system where they can enter their favourite artist and genre. this gets saved to a text file. But know I need an option where they can change their favourite artist and genre. This is the code so far. The user information is stored in a text file all on the same line.

def registerUser():
 usrFile_write = open(textfile, "a")
 usrFile_write.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":")
 print("New Account Created!\n")
 usrFile_write.close()
 Menu()
def change():
menu=input("Change account preferences? (y/n")
if menu == "yes":
    NewA=input("What is your new favorite artist...")
    NewG=input("What is your new favorite genre...")
    FavAG = open("user_DB.txt","w")
    FavAG.write (NewA)
    FavAG.write ("\n")
    FavAG.write (NewG)
    FavAG.close()

Body:
First off, you should always use with statements when working with files. The benefits of this are well documented. So this:

usrFile_write = open(textfile, "a")
usrFile_write.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":")
print("New Account Created!\n")
usrFile_write.close()

Becomes:

with open(textfile, "a") as usrFile:
    usrFile.write("\n" + username + ":" + password + ":" + date + ":" favArtist + ":" + favGenre + ":")
    print("New Account Created!\n")

Now, working in a plain text file, you can't really edit specific lines. In order to update an existing user entry, you will have to delete the existing entry and create a new one in its place. This requires reading through the file and re-writing the whole thing, except for the specific line. You can put this into a generalized deleteUser function for re-use later on:

def deleteUser(username):
    with open(textfile, "r") as usrFile:
        lines = usrFile.readlines()
    with open(textfile, "w") as usrFile:
        for line in lines:
            if line.split(":")[0] != username:
                usrFile.write(line)

Then, to modify a user, you delete their entry and then create a new one with the new information.

This ought to cover you for now. I recommend looking into using a database like sqlite in the long term, this job is much better suited for it.


问:
docker ports are not accessible

One silly question. However i cannot answer ...

I have a few running containers

Here is DockerFile -

```<code>FROM microsoft/aspnetcore:2.0
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "DockerAgain.dll"]
</code>```

I used this command for creating containers

```<code>docker run -p 4004:80 from_command_line
</code>```

Problem

Browser returns "not found" error for http://localhost:4004
Why ? And how i can fix this ?
Port inside container is exposed, port redirecting is set ... i am confused and disappointed

答:
First thing to test is to check if your application is available inside the container with

```<code>docker exec <container id> [nc|curl|telnet|wget|whatever-you-got] localhost:80
</code>```

Nevertheless one common reason that your application is not available outside the container, is that your application is by default map on localhost eth, and not available to request from outside the container.

I don't know much asp.net but you have to map your application to interface 0.0.0.0

Title: docker ports are not accessible

Body:
One silly question. However i cannot answer ...

I have a few running containers

Here is DockerFile -

FROM microsoft/aspnetcore:2.0
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "DockerAgain.dll"]

I used this command for creating containers

docker run -p 4004:80 from_command_line

Problem

Browser returns "not found" error for http://localhost:4004
Why ? And how i can fix this ?
Port inside container is exposed, port redirecting is set ... i am confused and disappointed

Body:
First thing to test is to check if your application is available inside the container with

docker exec <container id> [nc|curl|telnet|wget|whatever-you-got] localhost:80

Nevertheless one common reason that your application is not available outside the container, is that your application is by default map on localhost eth, and not available to request from outside the container.

I don't know much asp.net but you have to map your application to interface 0.0.0.0


问:
Conditional compilation in Xcode
I would like to 'turn off' the compiler for a section of my code.  I do not want to use comments to 'hide' the code from the compiler because there are a lot of /*...*/ comments embedded in this section.  I would guess that there is a common way to use compiler directives or #defines or something to control the compilation.  In fact my desire to suppress compilation is not dependent on a condition like the SDK or the platform, I would just like to turn it off.  How does one accomplish this?

答:
A quick fix is to wrap that section of code with

```<code>#if 0
…
#endif
</code>```

where 0 means false. To enable it again,

```<code>#if 1
…
#endif
</code>```

Another option is to define a macro (Project Info -> Build -> Preprocessor macros) and define it when you want to disable that code, and undefine it when you want to enable that code. For instance,

```<code>#ifndef IGNORE_THIS_SECTION
…
#endif
</code>```

You can achieve a similar, ‘inverse’ effect by using #ifdef instead.

ContentLicense: CC BY-SA 2.5

Title: Conditional compilation in Xcode

Body:
A quick fix is to wrap that section of code with

#if 0
…
#endif

where 0 means false. To enable it again,

#if 1
…
#endif

Another option is to define a macro (Project Info -> Build -> Preprocessor macros) and define it when you want to disable that code, and undefine it when you want to enable that code. For instance,

#ifndef IGNORE_THIS_SECTION
…
#endif

You can achieve a similar, ‘inverse’ effect by using #ifdef instead.


问:
Status bar gets hidden when picking up image imagepicker
My requirement for the app is to show status bar through out the app.On certain Viewcontroller I am calling Image picker. on click on buttonImage, When current viewcontroller disappears and camera appears, status bar gets hidden that actually shifts navigation bar slightly upwards. the status bar and navigation bar resumes after completion of image pickup.

How can I keep status bar unaffected?

答:
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

Please right down this code in your respective class as UIImagePickerController dismiss will call this function and your status bar will not dissappear anymore.


问:
Apache port being automatically forwarded
I'm trying to have two different directory associated to two different ports. (8001 and 8004), but whenever I try to access port 8004 in a browser, it redirects automatically to port 8001.

Here's some extract of the config files that seems relevant:

In httpd.conf:

```<code>Listen 80
Listen 8001
Listen 8004
</code>```

Removed comment to line:

```<code>Include etc/apache24/extra/httpd-vhosts.conf
</code>```

In file httpd-vhosts.conf:

```<code><VirtualHost *:8001>
  DocumentRoot "<path_to_site_1>"

  <Directory "<path_to_site_1>">
    Require all granted
  </Directory>
  <Directory "<path_to_site_1>">
    AllowOverride All
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^ index.php [L]
  </Directory>
</VirtualHost>

<VirtualHost *:8004>
  DocumentRoot "path_to_site_2"

  <Directory "path_to_site_2">
    Require all granted
  </Directory>
  <Directory "path_to_site_2">
    AllowOverride All
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^ index.php [L]
  </Directory>
</VirtualHost>
</code>```

Here's a list of things I've tried, that didn't change anything:

Having the VirtualHost declaration in httpd.conf

Changing the order of the Virtual host declaration

Changing port 8004 to another port

Clear the browser cache and try a different browser

If I comment Listen 8001, it breaks everything.
Port 80 seems to point to the default www directory of this FreeBSD installation and still works properly, for phpMyAdmin is installed there and is still accessible.

Maybe of note, it's a FreeBSD installation running on Oracle VM VirtualBox.

Thank you for any help or ideas to follow.

答:
Unfortunately, in this case, the comportment wasn't due to Apache configuration but to the website installations. One was a WordPress installation and the other was a Drupal installation. I wasn't aware that by moving those website in the directory structure, they would no longer point at the right place. WordPress was doing the redirection.

The issue was solved with two different solution, one for each platform.

For WordPress:

In the file functions.php, located in the theme directory:

Add the following lines:

```<code>update_option( 'siteurl', '<new_url>' );
update_option( 'home', '<new_url>' );
</code>```

In the browser, fefresh the website a few time

Remove both lines from the file

For Drupal:

(using drush) In the directory where the website is located:

```<code>drush cache-rebuild
</code>```

The combination of both commands solved the issue with both installation.

Body:
I'm trying to have two different directory associated to two different ports. (8001 and 8004), but whenever I try to access port 8004 in a browser, it redirects automatically to port 8001.

Here's some extract of the config files that seems relevant:

In httpd.conf:

Listen 80
Listen 8001
Listen 8004

Removed comment to line:

Include etc/apache24/extra/httpd-vhosts.conf

In file httpd-vhosts.conf:

<VirtualHost *:8001>
  DocumentRoot "<path_to_site_1>"

  <Directory "<path_to_site_1>">
    Require all granted
  </Directory>
  <Directory "<path_to_site_1>">
    AllowOverride All
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^ index.php [L]
  </Directory>
</VirtualHost>

<VirtualHost *:8004>
  DocumentRoot "path_to_site_2"

  <Directory "path_to_site_2">
    Require all granted
  </Directory>
  <Directory "path_to_site_2">
    AllowOverride All
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^ index.php [L]
  </Directory>
</VirtualHost>

Here's a list of things I've tried, that didn't change anything:

Having the VirtualHost declaration in httpd.conf

Changing the order of the Virtual host declaration

Changing port 8004 to another port

Clear the browser cache and try a different browser

If I comment Listen 8001, it breaks everything.
Port 80 seems to point to the default www directory of this FreeBSD installation and still works properly, for phpMyAdmin is installed there and is still accessible.

Maybe of note, it's a FreeBSD installation running on Oracle VM VirtualBox.

Thank you for any help or ideas to follow.

Body:
Unfortunately, in this case, the comportment wasn't due to Apache configuration but to the website installations. One was a WordPress installation and the other was a Drupal installation. I wasn't aware that by moving those website in the directory structure, they would no longer point at the right place. WordPress was doing the redirection.

The issue was solved with two different solution, one for each platform.

For WordPress:

In the file functions.php, located in the theme directory:

Add the following lines:

update_option( 'siteurl', '<new_url>' );
update_option( 'home', '<new_url>' );

In the browser, fefresh the website a few time

Remove both lines from the file

For Drupal:

(using drush) In the directory where the website is located:

drush cache-rebuild

The combination of both commands solved the issue with both installation.


问:
Tabu list length vs cadency
I'm trying to solve TSP problem with tabu search. I understand most foundations of this heuristic method. But I have trouble with figuring out what is the difference between cadence of some tabu move and length of tabu list. These two data structures are mentioned in most tutorials and documents available on the web. I would be grateful for some explanation about this difference.</p>

答:
```<code>tabu_list = (attr1, cadence1), (attr2, cadence2), . . . ((attr n, cadence n)
</code>```

Move is forbidden if a certain attribute is on the list
of prohibited moves (tabu list).

1) Tabu list length - specifies the max number of elements, that can be on tabu_list

2) Cadency - specifies the number of iterations through, which the element (attribute, cadence) is on the tabu_list

Title: Tabu list length vs cadency

Body:
tabu_list = (attr1, cadence1), (attr2, cadence2), . . . ((attr n, cadence n)

Move is forbidden if a certain attribute is on the list
of prohibited moves (tabu list).

1) Tabu list length - specifies the max number of elements, that can be on tabu_list

2) Cadency - specifies the number of iterations through, which the element (attribute, cadence) is on the tabu_list


问:
How to use an array from file A in file B
What is the right way to use an array from file A in file B?

When u use the example below, i get aan error (in Zend "Notice: Undefined variable: prefs")
Then, if i var_dump $prefs, it shows me the correct array of type array.

Example:

FILE A

```<code>$prefs = array('test', 'anothertest');
</code>```

FILE B

```<code>require_once('PATH_TO_FILE_A');
echo $prefs[0];
//output: test
</code>```

答:
If you don't like this warning message, you can set a NULL $prefs before including file.

```<code>$prefs = '';
require_once('PATH_TO_FILE_A');
echo $prefs[0];
//output: test
</code>```

Zend is warning you because actually $prefs isn't declared on file B .

P.S. : Really, you don't need this. Just ignore that warning message.

Body:
What is the right way to use an array from file A in file B?

When u use the example below, i get aan error (in Zend "Notice: Undefined variable: prefs")
Then, if i var_dump $prefs, it shows me the correct array of type array.

Example:

FILE A

$prefs = array('test', 'anothertest');

FILE B

require_once('PATH_TO_FILE_A');
echo $prefs[0];
//output: test

Body:
If you don't like this warning message, you can set a NULL $prefs before including file.

$prefs = '';
require_once('PATH_TO_FILE_A');
echo $prefs[0];
//output: test

Zend is warning you because actually $prefs isn't declared on file B .

P.S. : Really, you don't need this. Just ignore that warning message.


问:
DynamicLink does not work when long tapping url and selecting "open in safari"
I tested DynamicLink to see two case. I don't know, if this is an issue of IOS or DynamicLink.

App installed /
Open link in inbox email: https://xxx.app.goo.gl/abc

Case 1:

Long tap to link and select "Open in Safari"

Tap to open App on Safari => Don't open App. But open app store- all link after tap "Open in safari". All will not work. => Don't open app But open app store

Case 2:

Long tap to link and select "Open in App" => open App

If copy and paste to safari -> tap to open App => Open App

all link after tap "Open in App". All will work ok. => open app

答:
The behavior you see is expected.

When you

Long tap on link and select "Open in Safari"

the Universal Links will be disabled on this iPhone for this domain. Firebase Dynamic Links are using iOS Universal Links under the hood. You will have to Long tap on link and select "Open in App" to re-enable the Universal Links. While Universal Links are disabled the Firebase Dynamic Links will not work correctly.


问:
Can I embed a local image on a Google Map?
I am leveraging Google Maps API from Delphi 10 Seattle.

```<code>procedure TfrmMain.FormCreate(Sender: TObject);
var
  aStream: TMemoryStream;
begin
  WebBrowser1.Navigate('about:blank');
  if Assigned(WebBrowser1.Document) then
  begin
    aStream := TMemoryStream.Create;
    try
      aStream.WriteBuffer(Pointer(HTMLStr)^, Length(HTMLStr));
      aStream.Seek(0, soFromBeginning);
      (WebBrowser1.Document as IPersistStreamInit)
        .Load(TStreamAdapter.Create(aStream));
    finally
      freeandnil(aStream);
    end;
    HTMLWindow2 := (WebBrowser1.Document as IHTMLDocument2).parentWindow;
  end;

  fContainer := TExternalContainer.Create(WebBrowser1);
end;
</code>```

This allows me to make JavaScript calls into the Map JS using an instance of IHtmlDocument2 interface.

```<code>procedure TfrmMain.btnStartPointClick(Sender: TObject);
begin
   HTMLWindow2.execScript(Format('EmbedImageAtLatLng(%s,%s, %s)',[edtLat.Text,edtLon.Text, edtImageName.txt]), 'JavaScript');
end;
</code>```

My client would like me to post a specific image at a specific location for use by his workers.  Is this possible.

Note:  this image is a local image and not served.  It is simply passed in.

答:
Not in a straight way, at least to my knowledge. But what you can do is make use of Google Drive REST API to upload your image and make it available to the workers.

PS: I mentioned Google Drive so you make use of the same Google account you have for Google Maps, but you could use any other content manager.

Body:
I am leveraging Google Maps API from Delphi 10 Seattle.

procedure TfrmMain.FormCreate(Sender: TObject);
var
  aStream: TMemoryStream;
begin
  WebBrowser1.Navigate('about:blank');
  if Assigned(WebBrowser1.Document) then
  begin
    aStream := TMemoryStream.Create;
    try
      aStream.WriteBuffer(Pointer(HTMLStr)^, Length(HTMLStr));
      aStream.Seek(0, soFromBeginning);
      (WebBrowser1.Document as IPersistStreamInit)
        .Load(TStreamAdapter.Create(aStream));
    finally
      freeandnil(aStream);
    end;
    HTMLWindow2 := (WebBrowser1.Document as IHTMLDocument2).parentWindow;
  end;

  fContainer := TExternalContainer.Create(WebBrowser1);
end;

This allows me to make JavaScript calls into the Map JS using an instance of IHtmlDocument2 interface.

procedure TfrmMain.btnStartPointClick(Sender: TObject);
begin
   HTMLWindow2.execScript(Format('EmbedImageAtLatLng(%s,%s, %s)',[edtLat.Text,edtLon.Text, edtImageName.txt]), 'JavaScript');
end;

My client would like me to post a specific image at a specific location for use by his workers.  Is this possible.

Note:  this image is a local image and not served.  It is simply passed in.


问:
getting javascript error when trying to get svg base64 image from javascript using selenium htmlunit
In my javascript i am converting an svg object into base 64
using

```<code>     var svg= svgObject;
    var serializer = new XMLSerializer();
    var svgString = serializer.serializeToString(svg);
    return new Blob([svgString], {type:"application/svg+xml"})
</code>```

When i run the code in a browser,i am able to get the base64 back properly.

However,when i run the javascript code, using selenium-htmlunit in java,
using :

```<code>ScriptResult result = page.executeJavaScript(javascriptfunction);
</code>```

i get this error below :

```<code>Cannot find function isFinite in object function Number() { [native code] }.
</code>```

How do i resolve this error so i can get the base64 image back after executing that javascript using htmlunit ?

答: Have done some tests with the current HtmlUnit code. The function Number.isFinite is available and works fine. You are using the latest version?</p>

Body:
In my javascript i am converting an svg object into base 64
using

     var svg= svgObject;
    var serializer = new XMLSerializer();
    var svgString = serializer.serializeToString(svg);
    return new Blob([svgString], {type:"application/svg+xml"})

When i run the code in a browser,i am able to get the base64 back properly.

However,when i run the javascript code, using selenium-htmlunit in java,
using :

ScriptResult result = page.executeJavaScript(javascriptfunction);

i get this error below :

Cannot find function isFinite in object function Number() { [native code] }.

How do i resolve this error so i can get the base64 image back after executing that javascript using htmlunit ?


问:
Minimum & Maximum Values in Crystal Reports 2008 Column
Say I have this column returned in a command for Crystal:

```<code>deposit_no
123
130
125
124
126
127
128
129
</code>```

and I need to have this in the report title:

Includes deposits between 123 - 130

I've tried a running formula for minimum and maximum and they aren't returning the correct values no matter how I manipulate them.  I've tried evaluate for every record, on change of the deposit_no field, etc.  I have no grouping on this report.

Edited to add:
While I preferred to handle this on the CR side of things, I changed my command to include what mson wrote below.  So technically, mson had the correct answer.

答:
create a stored procedure or view that has the information you want.  access the stored procedure or view through crystal reports.

crystal reports is a hindrance to properly coding anything.

the unexpected result you are getting may be because the column is not numeric.  often, number values are stored as varchar/nvarchar.  this is done especially for fields like zipcode/phone number/etc. where the value may be numeric, but you would never do math on them.

in any event, here are the snippets you can use to build in sql server (and then call from crystal)

select min(coalesce(cast(deposit_no as int),0)) as min_deposit from tableA

select max(coalesce(cast(deposit_no as int),0)) as max_deposit from tableA

OwnerDisplayName: GregD

Body:
Say I have this column returned in a command for Crystal:

deposit_no
123
130
125
124
126
127
128
129

and I need to have this in the report title:

Includes deposits between 123 - 130

I've tried a running formula for minimum and maximum and they aren't returning the correct values no matter how I manipulate them.  I've tried evaluate for every record, on change of the deposit_no field, etc.  I have no grouping on this report.

Edited to add:
While I preferred to handle this on the CR side of things, I changed my command to include what mson wrote below.  So technically, mson had the correct answer.

LastEditorDisplayName: GregD

OwnerDisplayName: mson


问:
SaltStack: is it possible to allow only state.apply for minions?
I know that there is Blackout mode for salt-minions (https://docs.saltstack.com/en/latest/topics/blackout/index.html) but it is configured on a master side. My need is to configure minion to do not run any commands (I mean any commands like salt '*' test.ping or salt '*' file.mkdir "/tmp/foobar") from a salt-master and only allow to run salt '*' state.apply with local state files.

Is it possible?

答: While I discover the codebase of Salt I found that there is solution for my issue there in upstream. I found that they added minion_blackout config to grains not only to pillar, so now I can configure that on my minion and allow only state.apply in minion_blackout_whitelist config.


问:
A "catch-all" for SFINAE functions?
I am trying to make a typed compare function that do some customized comparison for different types.

```<code> #include <type_traits>

template <typename T>
bool typedCompare(const T& lhs, const T& rhs)
{
    return lhs == rhs; // default case, use ==
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return (lhs - rhs) < 1e-10;
}

int main()
{
    typedCompare(1, 1);
    typedCompare(1.0, 1.0);
    return 0;
}
</code>```

Here I have a special version for double that compare the difference with a small amount (please ignore the fact that I did not use std::abs()). I have a few other custom types that I need to do some special comparison, and I cannot change their == operator for some reason.

Besides, I still want to have a "catch-all" style function that employs the == operator. My problem is that when trying to compile this code snippet the compiler complains about that typedCompare(1.0, 1.0) is ambiguous, it can choose either of the two functions provided.

Why? And how could I resolve this issue?

Thanks.

答:
I like both the solution from @max66 with a helper template and the multiple solutions from @Edgar Rokyan.

Here is another approach that can be used for what you want using a helper template function.

```<code>#include <type_traits>
#include <iostream>
#include <string>

// elipsis version is at the bottom of the overload resolution priority.
// it will only be used if nothing else matches the overload.
void typeCompare_specialized(...)
{
  std::cout << "SHOULD NEVER BE CALLED!!!\n";
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typeCompare_specialized(const T& lhs, const T& rhs)
{
  std::cout << "floating-point version\n";
  return (lhs - rhs) < 1e-10;
}

template <typename T>
typename std::enable_if<std::is_integral<T>::value, bool>::type
typeCompare_specialized(const T& lhs, const T& rhs)
{
  std::cout << "integral version\n";
  return lhs == rhs;
}

template <typename T>
auto typedCompare(const T& lhs, const T& rhs)
  -> typename std::enable_if<std::is_same<bool,decltype(typeCompare_specialized(lhs, rhs))>::value,bool>::type
{
  return typeCompare_specialized(lhs, rhs);
}

template <typename T>
auto typedCompare(const T& lhs, const T& rhs)
  -> typename std::enable_if<!std::is_same<bool,decltype(typeCompare_specialized(lhs, rhs))>::value,bool>::type
{
  std::cout << "catch-all version\n";
  return lhs == rhs;
}

int main()
{
  typedCompare(1, 1);
  typedCompare(1.0, 1.0);
  typedCompare(std::string("hello"), std::string("there"));

  return 0;
}
</code>```

Running the above program will yield the following output:

```<code>integral version
floating-point version
catch-all version
</code>```

Again, I would prefer to use one of the previous answers mentioned.  I include this possibility for completeness.

I would also like to add that you should make sure your typeCompare_specialized() template versions should not have any overlap, otherwise you could get a compiler error declaring that there are multiple candidate overloads to use.

Title: A "catch-all" for SFINAE functions?

Body:
I am trying to make a typed compare function that do some customized comparison for different types.

 #include <type_traits>

template <typename T>
bool typedCompare(const T& lhs, const T& rhs)
{
    return lhs == rhs; // default case, use ==
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typedCompare(const T& lhs, const T& rhs)
{
    return (lhs - rhs) < 1e-10;
}

int main()
{
    typedCompare(1, 1);
    typedCompare(1.0, 1.0);
    return 0;
}

Here I have a special version for double that compare the difference with a small amount (please ignore the fact that I did not use std::abs()). I have a few other custom types that I need to do some special comparison, and I cannot change their == operator for some reason.

Besides, I still want to have a "catch-all" style function that employs the == operator. My problem is that when trying to compile this code snippet the compiler complains about that typedCompare(1.0, 1.0) is ambiguous, it can choose either of the two functions provided.

Why? And how could I resolve this issue?

Thanks.

Body:
I like both the solution from @max66 with a helper template and the multiple solutions from @Edgar Rokyan.

Here is another approach that can be used for what you want using a helper template function.

#include <type_traits>
#include <iostream>
#include <string>

// elipsis version is at the bottom of the overload resolution priority.
// it will only be used if nothing else matches the overload.
void typeCompare_specialized(...)
{
  std::cout << "SHOULD NEVER BE CALLED!!!\n";
}

template <typename T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
typeCompare_specialized(const T& lhs, const T& rhs)
{
  std::cout << "floating-point version\n";
  return (lhs - rhs) < 1e-10;
}

template <typename T>
typename std::enable_if<std::is_integral<T>::value, bool>::type
typeCompare_specialized(const T& lhs, const T& rhs)
{
  std::cout << "integral version\n";
  return lhs == rhs;
}

template <typename T>
auto typedCompare(const T& lhs, const T& rhs)
  -> typename std::enable_if<std::is_same<bool,decltype(typeCompare_specialized(lhs, rhs))>::value,bool>::type
{
  return typeCompare_specialized(lhs, rhs);
}

template <typename T>
auto typedCompare(const T& lhs, const T& rhs)
  -> typename std::enable_if<!std::is_same<bool,decltype(typeCompare_specialized(lhs, rhs))>::value,bool>::type
{
  std::cout << "catch-all version\n";
  return lhs == rhs;
}

int main()
{
  typedCompare(1, 1);
  typedCompare(1.0, 1.0);
  typedCompare(std::string("hello"), std::string("there"));

  return 0;
}

Running the above program will yield the following output:

integral version
floating-point version
catch-all version

Again, I would prefer to use one of the previous answers mentioned.  I include this possibility for completeness.

I would also like to add that you should make sure your typeCompare_specialized() template versions should not have any overlap, otherwise you could get a compiler error declaring that there are multiple candidate overloads to use.


问:
Alphabetical Order for all Localizable Strings
i've a simple table cell with some names in alphabetical order in English.
I managed to localized all in some other language and all works fine.
the question is : There is a method or command to put the localized names in other languages in alphabetical order?

```<code>import UIKit

var animals = [“A1”, “A2”, “A3”, “A4”, “A5”];

class TableViewController: UITableViewController {

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellController;
        cell.textLabel?.font = UIFont(name: "Futura-Bold", size: 18);
        cell.textLabel?.textColor = UIColor.black;
        cell.textLabel?.text = NSLocalizedString(animals[indexPath.row], comment: "");
        cell.smallBird.image = UIImage(named: animals[indexPath.row] + ".png");
        return cell
    }
}
</code>```

Localizable strings

```<code>/* Animals (EN) */

“A1" = “Cat”;
“A2" = “Dog”;
“A3" = “Owl”;
“A4" = “Leon”;
“A5" = “Tiger”;
</code>```

答:
You are ordering them by the keys at the moment, not the values.

Since you need the keys for the images and the value for the labels, and you want to sort the rows by the values, you need more than just the array of keys.

The following creates an array of tuples of keys and localized names, sorted by the localized name.

```<code>let animals = ["A1", "A2", "A3", "A4", "A5"].map { ($0, NSLocalizedString($0, comment: "")) }.sorted { $0.1 < $1.1 }
</code>```

Then update cellForRowAt:

```<code>cell.textLabel?.text = animals[indexPath.row].1
cell.smallBird.image = UIImage(named: animals[indexPath.row].0)
</code>```

You do not need to add the ".png" when using UIImage(named:).

Body:
i've a simple table cell with some names in alphabetical order in English.
I managed to localized all in some other language and all works fine.
the question is : There is a method or command to put the localized names in other languages in alphabetical order?

import UIKit

var animals = [“A1”, “A2”, “A3”, “A4”, “A5”];

class TableViewController: UITableViewController {

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellController;
        cell.textLabel?.font = UIFont(name: "Futura-Bold", size: 18);
        cell.textLabel?.textColor = UIColor.black;
        cell.textLabel?.text = NSLocalizedString(animals[indexPath.row], comment: "");
        cell.smallBird.image = UIImage(named: animals[indexPath.row] + ".png");
        return cell
    }
}

Localizable strings

/* Animals (EN) */

“A1" = “Cat”;
“A2" = “Dog”;
“A3" = “Owl”;
“A4" = “Leon”;
“A5" = “Tiger”;

Body:
You are ordering them by the keys at the moment, not the values.

Since you need the keys for the images and the value for the labels, and you want to sort the rows by the values, you need more than just the array of keys.

The following creates an array of tuples of keys and localized names, sorted by the localized name.

let animals = ["A1", "A2", "A3", "A4", "A5"].map { ($0, NSLocalizedString($0, comment: "")) }.sorted { $0.1 < $1.1 }

Then update cellForRowAt:

cell.textLabel?.text = animals[indexPath.row].1
cell.smallBird.image = UIImage(named: animals[indexPath.row].0)

You do not need to add the ".png" when using UIImage(named:).


问:
Serializing `numpy.dtype` objects: human readable
A bit of background. I'm building an application/schema for an HDF5 database and part of the API is being able to specify the dtype (and part of the shape) of a dataset when you first construct the HDF5 file, but not necessarily having to write those datasets you specify before the file is closed and the wrapper for File object is deleted. So I want to save that data in the HDF5 file so the application programmer doesn't have to pass those specifications around every time they open the file for writing. I also want to be able to support arbitrary numpy.dtypes for those datasets (via the h5py library).

Is there a standard/good way to serialize to plain text a numpy dtype object, besides pickling?

I don't want to use pickling because it is not really readable and was thinking something more like a JSON style format.

e.g. for a datatype like this:

```<code>In [1]: dt
Out[1]: dtype([('one', '<i8'), ('two', '<f8')])
</code>```

答:
My working solution is just to use a JSON string:

```<code>In [1]: dt = numpy.dtype([('one', np.int), ('two', np.float)])
In [2]: dt.descr
Out[2]: [('one', '<i8'), ('two', '<f8')]
In [3]: dt_str = json.dumps(dt.descr)
In [4]: dt_str
Out[4]: '[["one", "<i8"], ["two", "<f8"]]'
</code>```

Which can easily be read back in and converted to a numpy.dtype:

```<code>In [5]: np.dtype([tuple(i) for i in json.loads(dt_str)])
Out[5]: dtype([('one', '<i8'), ('two', '<f8')])
</code>```

Body:
A bit of background. I'm building an application/schema for an HDF5 database and part of the API is being able to specify the dtype (and part of the shape) of a dataset when you first construct the HDF5 file, but not necessarily having to write those datasets you specify before the file is closed and the wrapper for File object is deleted. So I want to save that data in the HDF5 file so the application programmer doesn't have to pass those specifications around every time they open the file for writing. I also want to be able to support arbitrary numpy.dtypes for those datasets (via the h5py library).

Is there a standard/good way to serialize to plain text a numpy dtype object, besides pickling?

I don't want to use pickling because it is not really readable and was thinking something more like a JSON style format.

e.g. for a datatype like this:

In [1]: dt
Out[1]: dtype([('one', '<i8'), ('two', '<f8')])

Body:
My working solution is just to use a JSON string:

In [1]: dt = numpy.dtype([('one', np.int), ('two', np.float)])
In [2]: dt.descr
Out[2]: [('one', '<i8'), ('two', '<f8')]
In [3]: dt_str = json.dumps(dt.descr)
In [4]: dt_str
Out[4]: '[["one", "<i8"], ["two", "<f8"]]'

Which can easily be read back in and converted to a numpy.dtype:

In [5]: np.dtype([tuple(i) for i in json.loads(dt_str)])
Out[5]: dtype([('one', '<i8'), ('two', '<f8')])


问:
Nesting
 and
 tags?

Question:

Which of these is the proper way to nest the
 and
 tags, and what is your reasoning behind it?

Choice A:

```<code><article>
    <h1>Some Title</h1>
    <p>Here's some text and whatnot.</p>
    <p>Here's another paragraph filled with other text and other whatnots.</p>
</article>
</code>```

Choice B:

```<code><div class="post">
    <h1>Here's a Really Awesome Title</h1>
    <article>
        <p>Here's a paragraph with text and whatnot.</p>
        <p>And here's another paragraph. I think this one is pretty awesome too.</p>
    </article>
</div>
</code>```

Opinions seem mixed about this, and I'm not 100% which is the correct answer.

答:
⚠ Warning ⚠

This answer is severely out-of-date and relies on the now-obsolete document outline algorithm.

both are fine

@David Dorward has a great answer, and I was going to comment to expand on it, but when I realized my comment was getting too long I decided I'd just add my own answer instead.

The h# elements semantically belong to their parents.

This h1 is the primary header for the page

```<code><body>
  <h1>Some text</h1>
</body>
</code>```

While this h1 is the primary header for the article

```<code><body>
  <article>
    <h1>Some text</h1>
  </article>
</body>
</code>```

This allows us to expand the usage of h# elements in meaningful ways as follows:

```<code><body>
  <h1>Blag Tottle</h1>
  <article>
    <h1>Article 1 Title</h1>
    <p>Lorem ipsum etc</p>
  </article>
  <article>
    <h1>Article 2 Title</h1>
    <p>Lorem ipsum etc</p>
  </article>
</body>
</code>```

Now you may want to separate your article heading some more, which is a perfect application of the header element:

```<code><body>
  <h1>Blag Tottle</h1>
  <article>
    <header>
      <h1>Article 1 Title</h1>
      <span class="author">And not a mouse</span>
    </header>
    <p>Lorem ipsum etc</p>
  </article>
  <article>
    <header>
      <h1>Article 2 Title</h1>
      <span class="author">Somebody</span>
    </header>
    <p>Lorem ipsum etc</p>
  </article>
</body>
</code>```

Title: Nesting <article> and <h1> tags?

Body:
Question:

Which of these is the proper way to nest the
 and
 tags, and what is your reasoning behind it?

Choice A:

Some Title

Here's some text and whatnot.

Here's another paragraph filled with other text and other whatnots.

Choice B:

Here's a Really Awesome Title

Here's a paragraph with text and whatnot.

And here's another paragraph. I think this one is pretty awesome too.

Opinions seem mixed about this, and I'm not 100% which is the correct answer.

Body:
⚠ Warning ⚠

This answer is severely out-of-date and relies on the now-obsolete document outline algorithm.

both are fine

@David Dorward has a great answer, and I was going to comment to expand on it, but when I realized my comment was getting too long I decided I'd just add my own answer instead.

The h# elements semantically belong to their parents.

This h1 is the primary header for the page

<body>
  <h1>Some text</h1>
</body>

While this h1 is the primary header for the article

<body>
  <article>
    <h1>Some text</h1>
  </article>
</body>

This allows us to expand the usage of h# elements in meaningful ways as follows:

<body>
  <h1>Blag Tottle</h1>
  <article>
    <h1>Article 1 Title</h1>
    <p>Lorem ipsum etc</p>
  </article>
  <article>
    <h1>Article 2 Title</h1>
    <p>Lorem ipsum etc</p>
  </article>
</body>

Now you may want to separate your article heading some more, which is a perfect application of the header element:

<body>
  <h1>Blag Tottle</h1>
  <article>
    <header>
      <h1>Article 1 Title</h1>
      <span class="author">And not a mouse</span>
    </header>
    <p>Lorem ipsum etc</p>
  </article>
  <article>
    <header>
      <h1>Article 2 Title</h1>
      <span class="author">Somebody</span>
    </header>
    <p>Lorem ipsum etc</p>
  </article>
</body>

ContentLicense: CC BY-SA 4.0


问:
What are valid values documented for ec2.images.filter command?
Noob question, where do I get information about valid tags for ec2.images.filter command? IE, it's not in Python API doc strings for boto3

```<code>import boto3
ec2 = boto3.resource('ec2', region_name='us-west-2')
image = list(ec2.images.filter(Filters=[{"Name":"Id", "Values": ["ami-405ade3a"]}]).all())[0]

ClientError: An error occurred (InvalidParameterValue) when calling the DescribeImages operation: The filter 'Id' is invalid
</code>```

答:
They are documented in Boto3 EC2 images section.

See: ec2.images.filter()

Body:
Noob question, where do I get information about valid tags for ec2.images.filter command? IE, it's not in Python API doc strings for boto3

import boto3
ec2 = boto3.resource('ec2', region_name='us-west-2')
image = list(ec2.images.filter(Filters=[{"Name":"Id", "Values": ["ami-405ade3a"]}]).all())[0]

ClientError: An error occurred (InvalidParameterValue) when calling the DescribeImages operation: The filter 'Id' is invalid


问:
Xquery statement to get a value for specific name
I am trying to write a xquery to get the Value for a specific name .Below is the request payload: i.e. if the Name ="ID" then get the
"Value" for that tag (i.e.1000000000.)If the Name="User" get the "Value" for that tag( ie."US").

```<code> <not:Items xmlns:v5="http://www.example.com"
xmlns:com="http://commom.com
xmlns:not="http://services.not.com"
xmlns:com1="http://common1.com">
<not:Array>
<com1:Item>
<v5:List>
<com:extensionsItem>
<com:Name>ID</com:Name>
<com:Value>1000000000</com:Value>
</com:extensionsItem>
<com:extensionsItem>
<com:Name>User</com:Name>
<com:Value>US</com:Value>
</com:extensionsItem>
</v5:List>
</com1:Item>
</not:Array>
</not:Items>
</code>```

I tried the options below:

```<code><ns2:ID>{fn:data($Items/not:Array/com1:Item/v5:List/com:extensionsItem[1]/com:Value)}<ID>
</code>```

This statement works . But I cannot assure that ID will always come in first element in the array of List.So i want a statement that will work even if ID comes in any other
place in the array and I can retrieve the value.
Thanks in advance

答: I think you simply want to apply a predicate $Items/not:Array/com1:Item/v5:List/com:extensionsItem[com:Name = 'ID']/com:Value

Body:
I am trying to write a xquery to get the Value for a specific name .Below is the request payload: i.e. if the Name ="ID" then get the
"Value" for that tag (i.e.1000000000.)If the Name="User" get the "Value" for that tag( ie."US").

 <not:Items xmlns:v5="http://www.example.com"
xmlns:com="http://commom.com
xmlns:not="http://services.not.com"
xmlns:com1="http://common1.com">
<not:Array>
<com1:Item>
<v5:List>
<com:extensionsItem>
<com:Name>ID</com:Name>
<com:Value>1000000000</com:Value>
</com:extensionsItem>
<com:extensionsItem>
<com:Name>User</com:Name>
<com:Value>US</com:Value>
</com:extensionsItem>
</v5:List>
</com1:Item>
</not:Array>
</not:Items>

I tried the options below:

<ns2:ID>{fn:data($Items/not:Array/com1:Item/v5:List/com:extensionsItem[1]/com:Value)}<ID>

This statement works . But I cannot assure that ID will always come in first element in the array of List.So i want a statement that will work even if ID comes in any other
place in the array and I can retrieve the value.
Thanks in advance


问:
Combine mouse-events in JavaScript
I am trying to build a Paint-like web application using javascript. The user is supposed to be able to "draw" shapes with the mouse over a grid of pixels.
How can i get this working using DOM eventlisteners?

with this line the user is able to set single pixels one by one:

```<code>td.addEventlistener("click", setpixel);
</code>```

So i guess I have to combine mousedown and mouseover in one eventlistener. Is that possible?

答:
You can't combine event listeners, per se. But you can use multiple listeners to track the state of the cursor.

```<code>var mouseIsDown = false
el.addEventListener('mousedown', function(){mouseIsDown = true})
el.addEventListener('mouseup', function(){mouseIsDown = false})
</code>```

Then you will need to decide what to do when the mouse is moving.

```<code>el.addEventListener('mousemove', function(){
    if(mouseIsDown){
        // implement drawing logic here
    }
})
</code>```

Title: Combine mouse-events in JavaScript

Body:
I am trying to build a Paint-like web application using javascript. The user is supposed to be able to "draw" shapes with the mouse over a grid of pixels.
How can i get this working using DOM eventlisteners?

with this line the user is able to set single pixels one by one:

td.addEventlistener("click", setpixel);

So i guess I have to combine mousedown and mouseover in one eventlistener. Is that possible?

Body:
You can't combine event listeners, per se. But you can use multiple listeners to track the state of the cursor.

var mouseIsDown = false
el.addEventListener('mousedown', function(){mouseIsDown = true})
el.addEventListener('mouseup', function(){mouseIsDown = false})

Then you will need to decide what to do when the mouse is moving.

el.addEventListener('mousemove', function(){
    if(mouseIsDown){
        // implement drawing logic here
    }
})


问:
Insert query result into table - SQL Server Management Studio
This code works great:

```<code>select month(period)
from fmdr3.dbo.fmdr_2017
</code>```

It returns the number of the month from a date column.

I'm trying to figure out how to insert the results into the table FMDR_2017 in a column called Month.

I've been trying permutations of this:

```<code>insert into fmdr3.dbo.fmdr_2017(Month)
    select month(period)
    from fmdr3.dbo.fmdr_2017
</code>```

but haven't had any success yet.

Thank you.

答:
I'm guessing you'll want to update the Month column based on the period?</p>

```<code>UPDATE fmdr3.dbo.fmdr_2017
SET Month = Month(Period);
</code>```

Body:
This code works great:

select month(period)
from fmdr3.dbo.fmdr_2017

It returns the number of the month from a date column.

I'm trying to figure out how to insert the results into the table FMDR_2017 in a column called Month.

I've been trying permutations of this:

insert into fmdr3.dbo.fmdr_2017(Month)
    select month(period)
    from fmdr3.dbo.fmdr_2017

but haven't had any success yet.

Thank you.

Body:
I'm guessing you'll want to update the Month column based on the period?

UPDATE fmdr3.dbo.fmdr_2017
SET Month = Month(Period);


问:
phantom database in Vista
I have a C++/MFC based application that accesses a Microsoft Access database in the folder c:\Program Files\xxx\yyy.

In literally hundreds of other computers running XP, Vista, and 7; the application works just fine.  But on one Vista machine, the apps reads the data from the database and it is completely different then what is actually in the database if I access it via Microsoft Access.  I delete the database from that folder and the application can still access this "phantom" database.

Does anyone have any recommendations?

Thanks

答: Is the data stored local to the user, or on a server somewhere?  Does the data the program on Vista look like it's coming from somewhere else in your information storage database, or is it just making things up?  Some information about structure might help us give you an answer?</p>

Title: phantom database in Vista


问:
InstrumentedHashset and overriding add & addAll
In Effective Java 2nd edition, Item 16, the author provides a scenario that illustrates "inheritence breaks encapsulation" where InstrumentedHashSet inherits from HashSet and overrides both methods add() and addAll(). My question is why the following alternative would not solve our problem for good? What sort of new problem(s) could occur :

```<code>public class InstrumentedHashSet<E> extends HashSet<E> {

    // The number of attempted element insertions
    private int addCount = 0;

    public InstrumentedHashSet() {
    }

    public InstrumentedHashSet(int initCap, float loadFactor) {
         super(initCap, loadFactor);
    }

    @Override public boolean add(E e) {
         addCount++;
         return super.add(e);
    }
    /* only the add method has been overrided
    @Override public boolean addAll(Collection<? extends E> c) {
         addCount += c.size();
         return super.addAll(c);
    }
    */

    public int getAddCount() {
         return addCount;
    }
}
</code>```

答:
If you remove an override for addAll, your InstrumentedHashSet would become vulnerable to changes in implementation of addAll in HashSet<T>.

Currently, JDK implementation leaves the implementation up to its AbstractCollection base class, which faithfully calls add for each item:

```<code>public boolean addAll(Collection<? extends E> c) {
    boolean modified = false;
    Iterator<? extends E> e = c.iterator();
    while (e.hasNext()) {
        if (add(e.next())) // <<== This will call your override
            modified = true;
    }
    return modified;
}
</code>```

However, an alternative approach is possible: for example, addAll could try optimizing insertions by expanding hash bucket array at once inside addAll method, instead of calling add repeatedly. This would break the code, because addCount would no longer be properly maintained.

[from the comment] What would incite the Java language designers in Oracle to change HashSet<T> implementation? Would not that break many java programs designed with the pre-knowledge that addAll calls add within its implementation?

That is precisely the point that Item 16 is trying to illustrate. Once others start inheriting from your class, you become "locked into" aspects of your implementation that are not explicitly stated in your program's code, such as one requiring addAll to call add on each item. In effect, inheriting broke encapsulation by "freezing" aspects of your code without your explicit acknowledgement.

Body:
In Effective Java 2nd edition, Item 16, the author provides a scenario that illustrates "inheritence breaks encapsulation" where InstrumentedHashSet inherits from HashSet and overrides both methods add() and addAll(). My question is why the following alternative would not solve our problem for good? What sort of new problem(s) could occur :

public class InstrumentedHashSet<E> extends HashSet<E> {

    // The number of attempted element insertions
    private int addCount = 0;

    public InstrumentedHashSet() {
    }

    public InstrumentedHashSet(int initCap, float loadFactor) {
         super(initCap, loadFactor);
    }

    @Override public boolean add(E e) {
         addCount++;
         return super.add(e);
    }
    /* only the add method has been overrided
    @Override public boolean addAll(Collection<? extends E> c) {
         addCount += c.size();
         return super.addAll(c);
    }
    */

    public int getAddCount() {
         return addCount;
    }
}

Body:
If you remove an override for addAll, your InstrumentedHashSet would become vulnerable to changes in implementation of addAll in HashSet<T>.

Currently, JDK implementation leaves the implementation up to its AbstractCollection base class, which faithfully calls add for each item:

public boolean addAll(Collection<? extends E> c) {
    boolean modified = false;
    Iterator<? extends E> e = c.iterator();
    while (e.hasNext()) {
        if (add(e.next())) // <<== This will call your override
            modified = true;
    }
    return modified;
}

However, an alternative approach is possible: for example, addAll could try optimizing insertions by expanding hash bucket array at once inside addAll method, instead of calling add repeatedly. This would break the code, because addCount would no longer be properly maintained.

[from the comment] What would incite the Java language designers in Oracle to change HashSet<T> implementation? Would not that break many java programs designed with the pre-knowledge that addAll calls add within its implementation?

That is precisely the point that Item 16 is trying to illustrate. Once others start inheriting from your class, you become "locked into" aspects of your implementation that are not explicitly stated in your program's code, such as one requiring addAll to call add on each item. In effect, inheriting broke encapsulation by "freezing" aspects of your code without your explicit acknowledgement.


问:
Two MdPaginators for one Md-Table
I am working on creating an md-table for an application.  I can sort and paginate but need to add a paginator on the bottom as well as the top.  They should literally clone each other in functionality.  I've tried to create a second MdPaginator and then reference the first.

For example

```<code>@ViewChild('paginator') paginator: MdPaginator;
@ViewChild('paginator2') paginator2: MdPaginator;
</code>```

Then I set

```<code>this.paginator2 = this.paginator
</code>```

This is in hopes to get them to link together.  As mentioned, I have everything working just need a top and bottom paginator that are connected.

答: I finally developed a solution to this issue.  To achieve this behavior, I created an array of observables that I could pass to the class that extends cdk DataSource.  Next, I created a Subject that would be added to the array and be fired off when one of the paginators page events occurred.  I ended up subscribing to paginatorOne.page event and paginatorTwo.page event and synced up the pageIndex on these paginators then the Subject I created I fired that event by using .next(pageEvent).  Hope this helps anyone else trying to achieve this.</p>

Title: Two MdPaginators for one Md-Table

Body:
I am working on creating an md-table for an application.  I can sort and paginate but need to add a paginator on the bottom as well as the top.  They should literally clone each other in functionality.  I've tried to create a second MdPaginator and then reference the first.

For example

@ViewChild('paginator') paginator: MdPaginator;
@ViewChild('paginator2') paginator2: MdPaginator;

Then I set

this.paginator2 = this.paginator

This is in hopes to get them to link together.  As mentioned, I have everything working just need a top and bottom paginator that are connected.


问:
How to disable skipping in JavaScript console.log()

I'm trying to measure time taken by a function to execute in JS.
When I try to console.log() the elapsed time, some blue numbers appear in the console and some of the logs are gone.

When I counted the appeared number, it matched with the number of lines of skipped log.

I'm sure you can notice the problem at the right part of screenshot.

I would like the console to show all of the logs.

Is there anything I can do? BTW, the browser is Firefox 58.0b8. (Developer Edition)

答:
Not sure, if this will serve your purpose but this is a workaround not a solution provided by any browser.

You can add a wrapper function for console.log like below

```<code>function logToConsole(number) {
  var randomNumber = Math.floor(Math.random() * 6) + 1;
  console.log(number.toString() + Array(randomNumber).join(" "));
}
</code>```

Here, each time console.log is called, it is padded with a random number between 1 and 6. (You can also increase the range, if you feel that there is a chance for error)

Complete example below.

function logToConsole(number) {
  var randomNumber = Math.floor(Math.random() * 6) + 1;
  console.log(number.toString() + Array(randomNumber).join(" "));
}

logToConsole(0.1111);
logToConsole(0.1111);
logToConsole(0.1111);
logToConsole(0.1111);
logToConsole(0.1111);```

Body:
Not sure, if this will serve your purpose but this is a workaround not a solution provided by any browser.

You can add a wrapper function for console.log like below

function logToConsole(number) {
  var randomNumber = Math.floor(Math.random() * 6) + 1;
  console.log(number.toString() + Array(randomNumber).join(" "));
}

Here, each time console.log is called, it is padded with a random number between 1 and 6. (You can also increase the range, if you feel that there is a chance for error)

Complete example below.

function logToConsole(number) {
  var randomNumber = Math.floor(Math.random() * 6) + 1;
  console.log(number.toString() + Array(randomNumber).join(" "));
}

logToConsole(0.1111);
logToConsole(0.1111);
logToConsole(0.1111);
logToConsole(0.1111);
logToConsole(0.1111);


答:
I guess this will work.

```<code>d={}
for index, row in df.iterrows():
  if(d.get(row['state'],0)==0):
    d[row['state']=[].append(str(row['year'])+" : "+ str(row['month']))
  else:
    d[row['state']] = d[row['state']].append(str(row['year'])+" : "+ str(row['month']))
</code>```

This will have it like

```<code>arkansas        ["2017 : 10.0", "2017 : 11.0", "2017 : 12.0"]
</code>```

Title: converting pandas dataframe to contain a dictionary or list of lists

Body:
      state      Year  Month  count
0       alabama  2017.0   10.0     31
1       alabama  2017.0   11.0     30
2       alabama  2017.0   12.0     31
3       alabama  2018.0    1.0     31
4       alabama  2018.0    2.0     28
5       alabama  2018.0    3.0     31
6       alabama  2018.0    4.0     30
7       alabama  2018.0    5.0     31
8       alabama  2018.0    6.0     30
9       alabama  2018.0    7.0     14
10     arkansas  2017.0   10.0     31
11     arkansas  2017.0   11.0     30
12     arkansas  2017.0   12.0     31

Can I convert dataframe above to:

                                                            Month
state
alabama         {2017:10.0, 2017:11.0, 2017:12.0, 2018:1.0, 2018:2.0, 2018:3.0, 2018:4.0, 2018:5.0, 2018:6.0, 2018:7.0}
arkansas        {2017:10.0, 2017:11.0, 2017:12.0}

related to converting pandas dataframe to contain a list

based on @Vaishali's comment below, since dictionary cannot contain duplicate keys, this should be ok too:

                                                            Month
state
alabama         [[2017,10.0], [2017,11.0], [2017,12.0], [2018,1.0], [2018,2.0], [2018,3.0], [2018,4.0], [2018,5.0], [2018,6.0], 2[018,7.0]]
arkansas        [[2017,10.0], [2017,11.0], [2017,12.0]]

Body:
I guess this will work.

d={}
for index, row in df.iterrows():
  if(d.get(row['state'],0)==0):
    d[row['state']=[].append(str(row['year'])+" : "+ str(row['month']))
  else:
    d[row['state']] = d[row['state']].append(str(row['year'])+" : "+ str(row['month']))

This will have it like

arkansas        ["2017 : 10.0", "2017 : 11.0", "2017 : 12.0"]


问:
Angular 2/4 prevent user to leave component if changes not saved
I have this interface that i'm using to prevent the user to leave page

```<code>export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}
</code>```

In one of my component i have the following code

```<code>export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }
</code>```

My problem is that my component -> (component: ComponentCanDeactivate) from PendingChangesGuard  is always null so i get an error saying

Cannot call canDeactivate() of null

I also have this setup in my routing

```<code> path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'
</code>```

Can someone tell me what am i doing wrong?

答:
In your PendingChangesGuard, try to inject the component itself, not the interface:

```<code>export class PendingChangesGuard implements CanDeactivate<DashboardComponent> {
  constructor() {}
  canDeactivate(component: DashboardComponent): boolean {
  ...
  }
</code>```

You cannot inject an interface using Angular DI as interfaces are just Typescript constructs and do not exist in Javascript code produced with the compilation process.

For more information, have a look at this SO question.

Body:
I have this interface that i'm using to prevent the user to leave page

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}

In one of my component i have the following code

export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }

My problem is that my component -> (component: ComponentCanDeactivate) from PendingChangesGuard  is always null so i get an error saying

Cannot call canDeactivate() of null

I also have this setup in my routing

 path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

Can someone tell me what am i doing wrong?

Body:
In your PendingChangesGuard, try to inject the component itself, not the interface:

export class PendingChangesGuard implements CanDeactivate<DashboardComponent> {
  constructor() {}
  canDeactivate(component: DashboardComponent): boolean {
  ...
  }

You cannot inject an interface using Angular DI as interfaces are just Typescript constructs and do not exist in Javascript code produced with the compilation process.

For more information, have a look at this SO question.


问:
Libsodium key exchange (shared secret) in a different ways
I make android implementation of crypto messages for app.

Server side uses crypto_kx_client_session_keys in libsodium library for creating shared secret between client and server.

I use java designed NaCl library, where is no such method (old libsodium API usage).
So I make shared secret within crypto_scalarmult_curve25519 (Diffie Hellman), but final shared secret key does not match with the server's one.

My code:

```<code>// Shared secret generation
crypto_scalarmult_curve25519(result, serverPublicKey: PublicKey, clientSecretKey: PrivateKey)
// Shared secret decrypt (with SecretBox)
crypto_secretbox_xsalsa20poly1305_open(message, ciphertext, ciphertext.length, nonce, sharedkey)
</code>```

Is there any possibility to make identical shared secret key in different ways? Or do I need to write a similar method manually?

答:
The output of crypto_scalarmult() should not be directly used as a key. It has to be hashed, preferably with other data known by both parties, such as the involved public keys. See the libsodium documentation on crypto_scalarmult(), which also describes what crypto_kx() does.

That being said, the scalarmult() + hash + secretbox() sequence already exists in both libraries as a single high-level API, and is called crypto_box().

Body:
I make android implementation of crypto messages for app.

Server side uses crypto_kx_client_session_keys in libsodium library for creating shared secret between client and server.

I use java designed NaCl library, where is no such method (old libsodium API usage).
So I make shared secret within crypto_scalarmult_curve25519 (Diffie Hellman), but final shared secret key does not match with the server's one.

My code:

// Shared secret generation
crypto_scalarmult_curve25519(result, serverPublicKey: PublicKey, clientSecretKey: PrivateKey)
// Shared secret decrypt (with SecretBox)
crypto_secretbox_xsalsa20poly1305_open(message, ciphertext, ciphertext.length, nonce, sharedkey)

Is there any possibility to make identical shared secret key in different ways? Or do I need to write a similar method manually?


问:
Updating a device to iOS 11.2 breaks support with Xcode 9.1
I tried to run my app on a device running iOS 11.2 and received the following error:

Could not locate device supported files.

This iPhone 5s (Model A1457, A1518, A1528, A1530) is running iOS 11.2
  (15C114), which may not be supported by this version of Xcode.

I have used iphone 5s(version 11.1.2) and I want to build my project from xcode 9.1(ios 11.1).

答: Xcode 9.2 has finally been released. You can update it from App Store or just download it here: https://download.developer.apple.com/Developer_Tools/Xcode_9.2/Xcode_9.2.xip</p>


问:
SQL UNION and MERGE
I'm having multiple select statements involving many tables and Joins. All the select statements have the same Headers. I'm trying to combine all this into a single result set. So which approach is better SQL UNION or MERGE?
I know UNION is A+B. So if a column is NULL in Table A and it has a value in TABLE B then UNION will give me two rows right? So if I want to combine all the rows into a single row based on the id should I use MERGE? I have an option to do this in SQL or SSIS.

```<code>SELECT ID, NAME, VitalName as VitalName FROM TABLE A
UNION
SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B
</code>```

TableA

```<code>+----+------+-----------+
| ID | Name | VitalName |
+----+------+-----------+
|  1 | AAA  | HeartRate |
|  2 |      | Systolic  |
|  3 |      | Diastolic |
+----+------+-----------+
</code>```

TableB

```<code>+----+------+---------------+
| ID | Name | VitalReadings |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
+----+------+---------------+
</code>```

Expected Result

```<code>+----+------+---------------+
| ID | Name | VitalName     |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
|  3 |      | Diastolic     |
+----+------+---------------+
</code>```

答:
Use union and then use select distinct to remove duplicate.

e.g. SELECT DISTINCT * FROM (SELECT ID, NAME, VitalName as VitalName FROM TABLE_A
UNION SELECT ID, NAME, VitalReadings as VitalName FROM TABLE_B) as TABLE_C

Title: SQL UNION and MERGE

Body:
I'm having multiple select statements involving many tables and Joins. All the select statements have the same Headers. I'm trying to combine all this into a single result set. So which approach is better SQL UNION or MERGE?
I know UNION is A+B. So if a column is NULL in Table A and it has a value in TABLE B then UNION will give me two rows right? So if I want to combine all the rows into a single row based on the id should I use MERGE? I have an option to do this in SQL or SSIS.

SELECT ID, NAME, VitalName as VitalName FROM TABLE A
UNION
SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B

TableA

+----+------+-----------+
| ID | Name | VitalName |
+----+------+-----------+
|  1 | AAA  | HeartRate |
|  2 |      | Systolic  |
|  3 |      | Diastolic |
+----+------+-----------+

TableB

+----+------+---------------+
| ID | Name | VitalReadings |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
+----+------+---------------+

Expected Result

+----+------+---------------+
| ID | Name | VitalName     |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
|  3 |      | Diastolic     |
+----+------+---------------+


问:
How to move camera using joystick in Unity?
I have a problem with camera movement using joystick in Unity. I wrote this code to my joystick

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler {

private Image bgImg;
private Image joystickImg;
private Vector2 pos;

private void Start()
{
    bgImg = GetComponent<Image>();
    joystickImg = transform.GetChild(0).GetComponent<Image>();
}

public virtual void OnDrag(PointerEventData ped)
{
    Vector2 pos;
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
    {
        pos.x = (pos.x * 2 + 1) / bgImg.rectTransform.sizeDelta.x;
        pos.y = (pos.y * 2 - 1) / bgImg.rectTransform.sizeDelta.y;

        pos = (pos.magnitude > 1.0f) ? pos.normalized : pos;

        // Move Joystrick IMG
        joystickImg.rectTransform.anchoredPosition = new Vector2(pos.x * (bgImg.rectTransform.sizeDelta.x / 3), pos.y * (bgImg.rectTransform.sizeDelta.y / 3));
    }
}

public virtual void OnPointerDown(PointerEventData ped)
{
    OnDrag(ped);
}

public virtual void OnPointerUp(PointerEventData ped)
{
    pos = Vector2.zero;
    joystickImg.rectTransform.anchoredPosition = Vector2.zero;
}

public float Horizontal()
{
    if (pos.x != 0)
    {
        return pos.x;
    }
    else
    {
        return Input.GetAxis("Horizontal");
    }
}

public float Vertical()
{
    if (pos.y != 0)
    {
        return pos.y;
    }
    else
    {
        return Input.GetAxis("Vertical");
    }
}
}
</code>```

This code works well and return dynamicly Vector2(x,y). So, now I want to move camera (change position X,Y) using this joystick and these coordinates. Do you have any idea how to do it? Everyones show how to move cube or sphere and nowhere how to translate a camera...

答:
Camera behave like any other game object in the scene
you translate , rotate , scale (will not be shown ) </p>

<p>cause it is have Transform component . </p>

Body:
I have a problem with camera movement using joystick in Unity. I wrote this code to my joystick

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class VirtualJoystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler {

private Image bgImg;
private Image joystickImg;
private Vector2 pos;

private void Start()
{
    bgImg = GetComponent<Image>();
    joystickImg = transform.GetChild(0).GetComponent<Image>();
}

public virtual void OnDrag(PointerEventData ped)
{
    Vector2 pos;
    if (RectTransformUtility.ScreenPointToLocalPointInRectangle(bgImg.rectTransform, ped.position, ped.pressEventCamera, out pos))
    {
        pos.x = (pos.x * 2 + 1) / bgImg.rectTransform.sizeDelta.x;
        pos.y = (pos.y * 2 - 1) / bgImg.rectTransform.sizeDelta.y;

        pos = (pos.magnitude > 1.0f) ? pos.normalized : pos;

        // Move Joystrick IMG
        joystickImg.rectTransform.anchoredPosition = new Vector2(pos.x * (bgImg.rectTransform.sizeDelta.x / 3), pos.y * (bgImg.rectTransform.sizeDelta.y / 3));
    }
}

public virtual void OnPointerDown(PointerEventData ped)
{
    OnDrag(ped);
}

public virtual void OnPointerUp(PointerEventData ped)
{
    pos = Vector2.zero;
    joystickImg.rectTransform.anchoredPosition = Vector2.zero;
}

public float Horizontal()
{
    if (pos.x != 0)
    {
        return pos.x;
    }
    else
    {
        return Input.GetAxis("Horizontal");
    }
}

public float Vertical()
{
    if (pos.y != 0)
    {
        return pos.y;
    }
    else
    {
        return Input.GetAxis("Vertical");
    }
}
}

This code works well and return dynamicly Vector2(x,y). So, now I want to move camera (change position X,Y) using this joystick and these coordinates. Do you have any idea how to do it? Everyones show how to move cube or sphere and nowhere how to translate a camera...

Body:
Camera behave like any other game object in the scene
you translate , rotate , scale (will not be shown )

cause it is have Transform component .


问:
If statements in Excel
I am trying to write an if statement to further classify my data by type. Basically the cells currently contain the ID number and tissue type, but i want to figure out a way to insert the tissue type classification into the cell below.

So for example the ID # and tissue type (all in the same excel cell) is written 868686 Skin. And in the cell below, I wrote the formula IF(B2="Skin", "Skin", " ") but because I didn't have the whole contents of the cell (the ID#) included, it didn't find it. So is there a way to say IF B2 contains the word skin, then do this...

thanks.

答:
You could use FIND, this will return the number of the starting position of the text String in cell B2.

If 123 Skin was in B2 then =FIND("Skin", B2) would return 5 (Skin starts at the fifth position counting from the left).

Putting together with the IF statement, it would look like:

```<code>=IF(FIND("Skin", B2) > 0, "Skin", " ")
</code>```

(So if the result > 0 then it has been found in the cell)

You would probably want to take it one step further to take into consideration what happens if the cell doesn't contain that text (if you don't do that it will show an error)

```<code>=IF(IFERROR(FIND("Skin", B2), 0) > 0, "Skin", " ")
</code>```

(Above will return 0 if it hasn't been found)

Title: If statements in Excel

Body:
You could use FIND, this will return the number of the starting position of the text String in cell B2.

If 123 Skin was in B2 then =FIND("Skin", B2) would return 5 (Skin starts at the fifth position counting from the left).

Putting together with the IF statement, it would look like:

=IF(FIND("Skin", B2) > 0, "Skin", " ")

(So if the result > 0 then it has been found in the cell)

You would probably want to take it one step further to take into consideration what happens if the cell doesn't contain that text (if you don't do that it will show an error)

=IF(IFERROR(FIND("Skin", B2), 0) > 0, "Skin", " ")

(Above will return 0 if it hasn't been found)


问:
Pandas DataFrame Return Value from Column Index
I have a dataframe that has values of the different column numbers for another dataframe. Is there a way that I can just return the value from the other dataframe instead of just having the column index.

I basically want to match up the index between the Push and df dataframes. The values in the Push dataframe contain what column I want to return from the df dataframe.

Push dataframe:

```<code>    0   1
0   1   2
1   0   3
2   0   3
3   1   3
4   0   2
</code>```

df dataframe:

```<code>    0   1   2   3   4
0   10  11  22  33  44
1   10  11  22  33  44
2   10  11  22  33  44
3   10  11  22  33  44
4   10  11  22  33  44
</code>```

return:

```<code>    0   1
0   11  22
1   10  33
2   10  33
3   11  33
4   10  22
</code>```

答:
We using melt then replace  notice (df1 is your push , df2 is your df)

```<code>df1.astype(str).replace(df2.melt().drop_duplicates().set_index('variable').value.to_dict())
Out[31]:
    0   1
0  11  22
1  10  33
2  10  33
3  11  33
4  10  22
</code>```

Body:
I have a dataframe that has values of the different column numbers for another dataframe. Is there a way that I can just return the value from the other dataframe instead of just having the column index.

I basically want to match up the index between the Push and df dataframes. The values in the Push dataframe contain what column I want to return from the df dataframe.

Push dataframe:

    0   1
0   1   2
1   0   3
2   0   3
3   1   3
4   0   2

df dataframe:

    0   1   2   3   4
0   10  11  22  33  44
1   10  11  22  33  44
2   10  11  22  33  44
3   10  11  22  33  44
4   10  11  22  33  44

return:

    0   1
0   11  22
1   10  33
2   10  33
3   11  33
4   10  22

Body:
We using melt then replace  notice (df1 is your push , df2 is your df)

df1.astype(str).replace(df2.melt().drop_duplicates().set_index('variable').value.to_dict())
Out[31]:
    0   1
0  11  22
1  10  33
2  10  33
3  11  33
4  10  22