问:
How to write length function for all Monoids
I'm playing around with rewriting simple functions in different ways and I clearly misunderstand some core concepts. Is there a better way to work with limited types like these?

```<code>mlength :: Monoid m => m -> Int
mlength mempty   = 0
mlength (l <> r) = mlength l + mlength r
</code>```

It fails compilation with the following error:

```<code>Parse error in pattern: l <> r
</code>```

I can see that my usage of <> is misguided because there are multiple correct matches for l and r. Even though it looks like it doesn't matter which value is assigned, a value still has to be assigned in the end. Maybe there's a way for me to assert this decision for specific Monoid instances?

```<code>"ab" == ""   <> "ab"
"ab" == "a"  <> "b"
"ab" == "ab" <> ""
</code>```

答:
A monoid, in the general case, has no notion of length. Take for instance Sum Int, which is Int equipped with addition for its monoidal operation. We have

```<code>Sum 3 <> Sum 4 = Sum 7 = Sum (-100) <> Sum 7 <> Sum (100)
</code>```

What should be its "length"? There is no real notion of length here, since the underlying type is Int, which is not a list-like type.

Another example: Endo Int which is Int -> Int equipped with composition. E.g.

```<code>Endo (\x -> x+1) <> Endo (\x -> x*2) = Endo (\x -> 2*x+1)
</code>```

Again, no meaningful "length" can be defined here.

You can browse Data.Monoid and see other examples where there is no notion of "length".

Const a is also a (boring) monoid with no length.

Now, it is true that lists [a] form a monoid (the free monoid over a), and length can indeed be defined there. Still, this is only a particular case, which does not generalize.

Body:
I'm playing around with rewriting simple functions in different ways and I clearly misunderstand some core concepts. Is there a better way to work with limited types like these?

mlength :: Monoid m => m -> Int
mlength mempty   = 0
mlength (l <> r) = mlength l + mlength r

It fails compilation with the following error:

Parse error in pattern: l <> r

I can see that my usage of <> is misguided because there are multiple correct matches for l and r. Even though it looks like it doesn't matter which value is assigned, a value still has to be assigned in the end. Maybe there's a way for me to assert this decision for specific Monoid instances?

"ab" == ""   <> "ab"
"ab" == "a"  <> "b"
"ab" == "ab" <> ""

Body:
A monoid, in the general case, has no notion of length. Take for instance Sum Int, which is Int equipped with addition for its monoidal operation. We have

Sum 3 <> Sum 4 = Sum 7 = Sum (-100) <> Sum 7 <> Sum (100)

What should be its "length"? There is no real notion of length here, since the underlying type is Int, which is not a list-like type.

Another example: Endo Int which is Int -> Int equipped with composition. E.g.

Endo (\x -> x+1) <> Endo (\x -> x*2) = Endo (\x -> 2*x+1)

Again, no meaningful "length" can be defined here.

You can browse Data.Monoid and see other examples where there is no notion of "length".

Const a is also a (boring) monoid with no length.

Now, it is true that lists [a] form a monoid (the free monoid over a), and length can indeed be defined there. Still, this is only a particular case, which does not generalize.


来源: stackexchange

问:
Trouble connecting to mysql in docker using jdbc
I am new to both Docker and Java.I am trying to connect to mysql server inside a docker using JDBC from my local Ubuntu machine.The command that I use to start the mysql server in docker is:

```<code>docker network create --subnet=172.18.0.0/16 master_network
docker run --net master_network --ip 172.18.0.22 --name docker-mysql -e MYSQL_ROOT_PASSWORD=password -d -p=3306:3306   mysql:latest
</code>```

The command that I am using to connect to mysql server from docker is as follows:

```<code>String connectionUrl = "jdbc:mysql://172.18.0.22:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
Connection conn =  DriverManager.getConnection(connectionUrl,user,password);
</code>```

But I am getting the below error:

```<code>java.sql.SQLException: Access denied for user 'hbstudent'@'172.18.0.1' (using password: YES)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at HibernateBasics.TestingConnectionToMysql.main(TestingConnectionToMysql.java:15)
</code>```

The docker inspect command gives me the following information

```<code>[
{
    "Id": "90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5",
    "Created": "2020-02-15T01:19:14.021480835Z",
    "Path": "docker-entrypoint.sh",
    "Args": [
        "mysqld"
    ],
    "State": {
        "Status": "running",
        "Running": true,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 5105,
        "ExitCode": 0,
        "Error": "",
        "StartedAt": "2020-02-15T01:19:14.526528758Z",
        "FinishedAt": "0001-01-01T00:00:00Z"
    },
    "Image": "sha256:791b6e40940cd550af522eb4ffe995226798204504fe495743445b900e417a51",
    "ResolvConfPath": "/var/lib/docker/containers/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5/resolv.conf",
    "HostnamePath": "/var/lib/docker/containers/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5/hostname",
    "HostsPath": "/var/lib/docker/containers/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5/hosts",
    "LogPath": "/var/lib/docker/containers/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5-json.log",
    "Name": "/docker-mysql",
    "RestartCount": 0,
    "Driver": "overlay2",
    "Platform": "linux",
    "MountLabel": "",
    "ProcessLabel": "",
    "AppArmorProfile": "docker-default",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": null,
        "ContainerIDFile": "",
        "LogConfig": {
            "Type": "json-file",
            "Config": {}
        },
        "NetworkMode": "master_network",
        "PortBindings": {
            "3306/tcp": [
                {
                    "HostIp": "",
                    "HostPort": "3306"
                }
            ]
        },
        "RestartPolicy": {
            "Name": "no",
            "MaximumRetryCount": 0
        },
        "AutoRemove": false,
        "VolumeDriver": "",
        "VolumesFrom": null,
        "CapAdd": null,
        "CapDrop": null,
        "Capabilities": null,
        "Dns": [],
        "DnsOptions": [],
        "DnsSearch": [],
        "ExtraHosts": null,
        "GroupAdd": null,
        "IpcMode": "private",
        "Cgroup": "",
        "Links": null,
        "OomScoreAdj": 0,
        "PidMode": "",
        "Privileged": false,
        "PublishAllPorts": false,
        "ReadonlyRootfs": false,
        "SecurityOpt": null,
        "UTSMode": "",
        "UsernsMode": "",
        "ShmSize": 67108864,
        "Runtime": "runc",
        "ConsoleSize": [
            0,
            0
        ],
        "Isolation": "",
        "CpuShares": 0,
        "Memory": 0,
        "NanoCpus": 0,
        "CgroupParent": "",
        "BlkioWeight": 0,
        "BlkioWeightDevice": [],
        "BlkioDeviceReadBps": null,
        "BlkioDeviceWriteBps": null,
        "BlkioDeviceReadIOps": null,
        "BlkioDeviceWriteIOps": null,
        "CpuPeriod": 0,
        "CpuQuota": 0,
        "CpuRealtimePeriod": 0,
        "CpuRealtimeRuntime": 0,
        "CpusetCpus": "",
        "CpusetMems": "",
        "Devices": [],
        "DeviceCgroupRules": null,
        "DeviceRequests": null,
        "KernelMemory": 0,
        "KernelMemoryTCP": 0,
        "MemoryReservation": 0,
        "MemorySwap": 0,
        "MemorySwappiness": null,
        "OomKillDisable": false,
        "PidsLimit": null,
        "Ulimits": null,
        "CpuCount": 0,
        "CpuPercent": 0,
        "IOMaximumIOps": 0,
        "IOMaximumBandwidth": 0,
        "MaskedPaths": [
            "/proc/asound",
            "/proc/acpi",
            "/proc/kcore",
            "/proc/keys",
            "/proc/latency_stats",
            "/proc/timer_list",
            "/proc/timer_stats",
            "/proc/sched_debug",
            "/proc/scsi",
            "/sys/firmware"
        ],
        "ReadonlyPaths": [
            "/proc/bus",
            "/proc/fs",
            "/proc/irq",
            "/proc/sys",
            "/proc/sysrq-trigger"
        ]
    },
    "GraphDriver": {
        "Data": {
            "LowerDir": "/var/lib/docker/overlay2/794c33dc3dba3bd3f3b59c2fa0751abb4a08d256716791442e048eba8dad4718-init/diff:/var/lib/docker/overlay2/08cff1074288c594a797ee81fc4f8e6d65e56e3815ed779c59d6a12b69c4bef3/diff:/var/lib/docker/overlay2/d4965f2d4dc55cc40e6b33b7370ea8f735e06ba02bc6e9d9f302a023e2f0ab40/diff:/var/lib/docker/overlay2/2c4fa859d3bf60b43e2ad97889fa850cc02d82e55a3c61d951a1fa7fa8a37a23/diff:/var/lib/docker/overlay2/e0f465f72028a167ef41bf541b693e70c004053d429ee8c8992e690a7138d419/diff:/var/lib/docker/overlay2/28b6d7f4d734c945bc670e4d9741012bcf0a4e779e1797e0687f76969c413a95/diff:/var/lib/docker/overlay2/3d0721a625aca9d5a9c11d2d07a9ce365f0d03cf8033975557435ed43a6f0465/diff:/var/lib/docker/overlay2/58393e75098f068ca6b95c79f62f31f0774af97ebe53dc191b8b34c9c79b0ce4/diff:/var/lib/docker/overlay2/c656f68c525873355be411b15e2af708f47758f0efcc55e0dcf0de87f4f3859a/diff:/var/lib/docker/overlay2/a9b4a61a797212e7ebc6816a7b2f94fbfe74a9572e61fbf803748590eee89a5a/diff:/var/lib/docker/overlay2/e2db5f0234d764243d37f466e65b2e87913ece5744d806ecafcb596c937094ce/diff:/var/lib/docker/overlay2/06cc3c7e20d47b12dffed61bb7b95bf8055468bc65c981cb4f0d0a7080cc9880/diff:/var/lib/docker/overlay2/72eb0da71371fe94e46795d36ad0d103b92c6ee0e0aec48ee3888c16a1e72837/diff",
            "MergedDir": "/var/lib/docker/overlay2/794c33dc3dba3bd3f3b59c2fa0751abb4a08d256716791442e048eba8dad4718/merged",
            "UpperDir": "/var/lib/docker/overlay2/794c33dc3dba3bd3f3b59c2fa0751abb4a08d256716791442e048eba8dad4718/diff",
            "WorkDir": "/var/lib/docker/overlay2/794c33dc3dba3bd3f3b59c2fa0751abb4a08d256716791442e048eba8dad4718/work"
        },
        "Name": "overlay2"
    },
    "Mounts": [
        {
            "Type": "volume",
            "Name": "63948ece9ac10c7e0f6a5761684a5861051cfad101dec1374529ba016bb6973a",
            "Source": "/var/lib/docker/volumes/63948ece9ac10c7e0f6a5761684a5861051cfad101dec1374529ba016bb6973a/_data",
            "Destination": "/var/lib/mysql",
            "Driver": "local",
            "Mode": "",
            "RW": true,
            "Propagation": ""
        }
    ],
    "Config": {
        "Hostname": "90c8f3d5191f",
        "Domainname": "",
        "User": "",
        "AttachStdin": false,
        "AttachStdout": false,
        "AttachStderr": false,
        "ExposedPorts": {
            "3306/tcp": {},
            "33060/tcp": {}
        },
        "Tty": false,
        "OpenStdin": false,
        "StdinOnce": false,
        "Env": [
            "MYSQL_ROOT_PASSWORD=password",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
            "GOSU_VERSION=1.7",
            "MYSQL_MAJOR=8.0",
            "MYSQL_VERSION=8.0.19-1debian9"
        ],
        "Cmd": [
            "mysqld"
        ],
        "Image": "mysql:latest",
        "Volumes": {
            "/var/lib/mysql": {}
        },
        "WorkingDir": "",
        "Entrypoint": [
            "docker-entrypoint.sh"
        ],
        "OnBuild": null,
        "Labels": {}
    },
    "NetworkSettings": {
        "Bridge": "",
        "SandboxID": "45769ba1596268ba02b3d6f2e50eaadd950b1113faed28f25f981408370272ab",
        "HairpinMode": false,
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "Ports": {
            "3306/tcp": [
                {
                    "HostIp": "0.0.0.0",
                    "HostPort": "3306"
                }
            ],
            "33060/tcp": null
        },
        "SandboxKey": "/var/run/docker/netns/45769ba15962",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null,
        "EndpointID": "",
        "Gateway": "",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "",
        "IPPrefixLen": 0,
        "IPv6Gateway": "",
        "MacAddress": "",
        "Networks": {
            "master_network": {
                "IPAMConfig": {
                    "IPv4Address": "172.18.0.22"
                },
                "Links": null,
                "Aliases": [
                    "90c8f3d5191f"
                ],
                "NetworkID": "25371b13fc9c6f11c23e1d795364bbd5cc5a160de866335b058b807c9f6ce552",
                "EndpointID": "b3cb70c1cbee99170886dd9a60f2ca87534831694f947949fed596919712d668",
                "Gateway": "172.18.0.1",
                "IPAddress": "172.18.0.22",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:12:00:16",
                "DriverOpts": null
            }
        }
    }
}
</code>```

]

I am connected to mysql running in the docker from mysql workbench application using the ip 172.18.0.22 and port 3306.This is the script I am using to create the users in mysql using mysql workbench application.

```<code>CREATE USER 'hbstudent'@'localhost' IDENTIFIED BY 'hbstudent';
GRANT ALL PRIVILEGES ON * . * TO 'hbstudent'@'localhost';
ALTER USER 'hbstudent'@'localhost' IDENTIFIED WITH mysql_native_password BY 'hbstudent';
</code>```

Also ,my-sql server in docker is running at 172.18.0.22.But the error says that user is denied access at 172.18.0.1 although my connection string in jdbc is 172.18.0.22

I have already referred to similar stackoverflow questions and yet not able to figure out what my mistake is.

答:
java.sql.SQLException: Access denied for user 'hbstudent'@'172.18.0.1' (using password: YES)

There is no such user hbstudent, or the credentials are defined improperly,  after MySQL starts

ContentLicense: CC BY-SA 4.0

Body:
I am new to both Docker and Java.I am trying to connect to mysql server inside a docker using JDBC from my local Ubuntu machine.The command that I use to start the mysql server in docker is:

docker network create --subnet=172.18.0.0/16 master_network
docker run --net master_network --ip 172.18.0.22 --name docker-mysql -e MYSQL_ROOT_PASSWORD=password -d -p=3306:3306   mysql:latest

The command that I am using to connect to mysql server from docker is as follows:

String connectionUrl = "jdbc:mysql://172.18.0.22:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
Connection conn =  DriverManager.getConnection(connectionUrl,user,password);

But I am getting the below error:

java.sql.SQLException: Access denied for user 'hbstudent'@'172.18.0.1' (using password: YES)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at HibernateBasics.TestingConnectionToMysql.main(TestingConnectionToMysql.java:15)

The docker inspect command gives me the following information

[
{
    "Id": "90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5",
    "Created": "2020-02-15T01:19:14.021480835Z",
    "Path": "docker-entrypoint.sh",
    "Args": [
        "mysqld"
    ],
    "State": {
        "Status": "running",
        "Running": true,
        "Paused": false,
        "Restarting": false,
        "OOMKilled": false,
        "Dead": false,
        "Pid": 5105,
        "ExitCode": 0,
        "Error": "",
        "StartedAt": "2020-02-15T01:19:14.526528758Z",
        "FinishedAt": "0001-01-01T00:00:00Z"
    },
    "Image": "sha256:791b6e40940cd550af522eb4ffe995226798204504fe495743445b900e417a51",
    "ResolvConfPath": "/var/lib/docker/containers/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5/resolv.conf",
    "HostnamePath": "/var/lib/docker/containers/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5/hostname",
    "HostsPath": "/var/lib/docker/containers/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5/hosts",
    "LogPath": "/var/lib/docker/containers/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5/90c8f3d5191fd207578a0b40e8a2369de949dc3a9c6fd2fdcf2ba044c32bdca5-json.log",
    "Name": "/docker-mysql",
    "RestartCount": 0,
    "Driver": "overlay2",
    "Platform": "linux",
    "MountLabel": "",
    "ProcessLabel": "",
    "AppArmorProfile": "docker-default",
    "ExecIDs": null,
    "HostConfig": {
        "Binds": null,
        "ContainerIDFile": "",
        "LogConfig": {
            "Type": "json-file",
            "Config": {}
        },
        "NetworkMode": "master_network",
        "PortBindings": {
            "3306/tcp": [
                {
                    "HostIp": "",
                    "HostPort": "3306"
                }
            ]
        },
        "RestartPolicy": {
            "Name": "no",
            "MaximumRetryCount": 0
        },
        "AutoRemove": false,
        "VolumeDriver": "",
        "VolumesFrom": null,
        "CapAdd": null,
        "CapDrop": null,
        "Capabilities": null,
        "Dns": [],
        "DnsOptions": [],
        "DnsSearch": [],
        "ExtraHosts": null,
        "GroupAdd": null,
        "IpcMode": "private",
        "Cgroup": "",
        "Links": null,
        "OomScoreAdj": 0,
        "PidMode": "",
        "Privileged": false,
        "PublishAllPorts": false,
        "ReadonlyRootfs": false,
        "SecurityOpt": null,
        "UTSMode": "",
        "UsernsMode": "",
        "ShmSize": 67108864,
        "Runtime": "runc",
        "ConsoleSize": [
            0,
            0
        ],
        "Isolation": "",
        "CpuShares": 0,
        "Memory": 0,
        "NanoCpus": 0,
        "CgroupParent": "",
        "BlkioWeight": 0,
        "BlkioWeightDevice": [],
        "BlkioDeviceReadBps": null,
        "BlkioDeviceWriteBps": null,
        "BlkioDeviceReadIOps": null,
        "BlkioDeviceWriteIOps": null,
        "CpuPeriod": 0,
        "CpuQuota": 0,
        "CpuRealtimePeriod": 0,
        "CpuRealtimeRuntime": 0,
        "CpusetCpus": "",
        "CpusetMems": "",
        "Devices": [],
        "DeviceCgroupRules": null,
        "DeviceRequests": null,
        "KernelMemory": 0,
        "KernelMemoryTCP": 0,
        "MemoryReservation": 0,
        "MemorySwap": 0,
        "MemorySwappiness": null,
        "OomKillDisable": false,
        "PidsLimit": null,
        "Ulimits": null,
        "CpuCount": 0,
        "CpuPercent": 0,
        "IOMaximumIOps": 0,
        "IOMaximumBandwidth": 0,
        "MaskedPaths": [
            "/proc/asound",
            "/proc/acpi",
            "/proc/kcore",
            "/proc/keys",
            "/proc/latency_stats",
            "/proc/timer_list",
            "/proc/timer_stats",
            "/proc/sched_debug",
            "/proc/scsi",
            "/sys/firmware"
        ],
        "ReadonlyPaths": [
            "/proc/bus",
            "/proc/fs",
            "/proc/irq",
            "/proc/sys",
            "/proc/sysrq-trigger"
        ]
    },
    "GraphDriver": {
        "Data": {
            "LowerDir": "/var/lib/docker/overlay2/794c33dc3dba3bd3f3b59c2fa0751abb4a08d256716791442e048eba8dad4718-init/diff:/var/lib/docker/overlay2/08cff1074288c594a797ee81fc4f8e6d65e56e3815ed779c59d6a12b69c4bef3/diff:/var/lib/docker/overlay2/d4965f2d4dc55cc40e6b33b7370ea8f735e06ba02bc6e9d9f302a023e2f0ab40/diff:/var/lib/docker/overlay2/2c4fa859d3bf60b43e2ad97889fa850cc02d82e55a3c61d951a1fa7fa8a37a23/diff:/var/lib/docker/overlay2/e0f465f72028a167ef41bf541b693e70c004053d429ee8c8992e690a7138d419/diff:/var/lib/docker/overlay2/28b6d7f4d734c945bc670e4d9741012bcf0a4e779e1797e0687f76969c413a95/diff:/var/lib/docker/overlay2/3d0721a625aca9d5a9c11d2d07a9ce365f0d03cf8033975557435ed43a6f0465/diff:/var/lib/docker/overlay2/58393e75098f068ca6b95c79f62f31f0774af97ebe53dc191b8b34c9c79b0ce4/diff:/var/lib/docker/overlay2/c656f68c525873355be411b15e2af708f47758f0efcc55e0dcf0de87f4f3859a/diff:/var/lib/docker/overlay2/a9b4a61a797212e7ebc6816a7b2f94fbfe74a9572e61fbf803748590eee89a5a/diff:/var/lib/docker/overlay2/e2db5f0234d764243d37f466e65b2e87913ece5744d806ecafcb596c937094ce/diff:/var/lib/docker/overlay2/06cc3c7e20d47b12dffed61bb7b95bf8055468bc65c981cb4f0d0a7080cc9880/diff:/var/lib/docker/overlay2/72eb0da71371fe94e46795d36ad0d103b92c6ee0e0aec48ee3888c16a1e72837/diff",
            "MergedDir": "/var/lib/docker/overlay2/794c33dc3dba3bd3f3b59c2fa0751abb4a08d256716791442e048eba8dad4718/merged",
            "UpperDir": "/var/lib/docker/overlay2/794c33dc3dba3bd3f3b59c2fa0751abb4a08d256716791442e048eba8dad4718/diff",
            "WorkDir": "/var/lib/docker/overlay2/794c33dc3dba3bd3f3b59c2fa0751abb4a08d256716791442e048eba8dad4718/work"
        },
        "Name": "overlay2"
    },
    "Mounts": [
        {
            "Type": "volume",
            "Name": "63948ece9ac10c7e0f6a5761684a5861051cfad101dec1374529ba016bb6973a",
            "Source": "/var/lib/docker/volumes/63948ece9ac10c7e0f6a5761684a5861051cfad101dec1374529ba016bb6973a/_data",
            "Destination": "/var/lib/mysql",
            "Driver": "local",
            "Mode": "",
            "RW": true,
            "Propagation": ""
        }
    ],
    "Config": {
        "Hostname": "90c8f3d5191f",
        "Domainname": "",
        "User": "",
        "AttachStdin": false,
        "AttachStdout": false,
        "AttachStderr": false,
        "ExposedPorts": {
            "3306/tcp": {},
            "33060/tcp": {}
        },
        "Tty": false,
        "OpenStdin": false,
        "StdinOnce": false,
        "Env": [
            "MYSQL_ROOT_PASSWORD=password",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
            "GOSU_VERSION=1.7",
            "MYSQL_MAJOR=8.0",
            "MYSQL_VERSION=8.0.19-1debian9"
        ],
        "Cmd": [
            "mysqld"
        ],
        "Image": "mysql:latest",
        "Volumes": {
            "/var/lib/mysql": {}
        },
        "WorkingDir": "",
        "Entrypoint": [
            "docker-entrypoint.sh"
        ],
        "OnBuild": null,
        "Labels": {}
    },
    "NetworkSettings": {
        "Bridge": "",
        "SandboxID": "45769ba1596268ba02b3d6f2e50eaadd950b1113faed28f25f981408370272ab",
        "HairpinMode": false,
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "Ports": {
            "3306/tcp": [
                {
                    "HostIp": "0.0.0.0",
                    "HostPort": "3306"
                }
            ],
            "33060/tcp": null
        },
        "SandboxKey": "/var/run/docker/netns/45769ba15962",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null,
        "EndpointID": "",
        "Gateway": "",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "",
        "IPPrefixLen": 0,
        "IPv6Gateway": "",
        "MacAddress": "",
        "Networks": {
            "master_network": {
                "IPAMConfig": {
                    "IPv4Address": "172.18.0.22"
                },
                "Links": null,
                "Aliases": [
                    "90c8f3d5191f"
                ],
                "NetworkID": "25371b13fc9c6f11c23e1d795364bbd5cc5a160de866335b058b807c9f6ce552",
                "EndpointID": "b3cb70c1cbee99170886dd9a60f2ca87534831694f947949fed596919712d668",
                "Gateway": "172.18.0.1",
                "IPAddress": "172.18.0.22",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:12:00:16",
                "DriverOpts": null
            }
        }
    }
}

]

I am connected to mysql running in the docker from mysql workbench application using the ip 172.18.0.22 and port 3306.This is the script I am using to create the users in mysql using mysql workbench application.

CREATE USER 'hbstudent'@'localhost' IDENTIFIED BY 'hbstudent';
GRANT ALL PRIVILEGES ON * . * TO 'hbstudent'@'localhost';
ALTER USER 'hbstudent'@'localhost' IDENTIFIED WITH mysql_native_password BY 'hbstudent';

Also ,my-sql server in docker is running at 172.18.0.22.But the error says that user is denied access at 172.18.0.1 although my connection string in jdbc is 172.18.0.22

I have already referred to similar stackoverflow questions and yet not able to figure out what my mistake is.


问:
Alter WordPress theme nav bar positioning
I am attempting to move a WP theme's nav bar next to its designated logo area to no avail (like this: http://screencast.com/t/UsPhTZ3SM) Any ideas? Here is the header.php code: http://pastebin.com/mr7mtpMG

Many thanks,

Alex

答:
I would re-format the html and cleanup the css(way too many unnecessary floats), but if you want a quick fix, try the following:

```
- #top-header, add position: absolute and margin-left: 26em
- #nav-pages li, add display: inline-block
```

remove the following properties:

```
#top-header, width: 930px;
#top-header-left, float: left, display: inline;
#nav-pages, #nav-pages ul, float: left
#nav-pages li, float: left
```

NOTE: Not tested on everyones favorite, IE

Hope this makes sense

ContentLicense: CC BY-SA 3.0

Body:
I would re-format the html and cleanup the css(way too many unnecessary floats), but if you want a quick fix, try the following:

- #top-header, add position: absolute and margin-left: 26em
- #nav-pages li, add display: inline-block

remove the following properties:

#top-header, width: 930px;
#top-header-left, float: left, display: inline;
#nav-pages, #nav-pages ul, float: left
#nav-pages li, float: left

NOTE: Not tested on everyones favorite, IE

Hope this makes sense


问:
Isolating/indexing/ranging through a list object tuple set
So basically I have a tuple set kind of like this.

```<code>tuple_set = [('name1', 'score'), ('name2', 'score'), ('name3', 'score')]
</code>```

It basically is a specific list in a larger dictionary of names/scores. I need to isolate name1, name2 and name3 in something that I can iterate through like a list.

It also might work if I can range through it but I can't take the range of the list object/tupleset.

Also appending to a list like this won't work cause it will only put a list of name1s

```<code>a_list = []

for stuff in tuple_set:
    a_list.append(tuple_set[0][0])
</code>```

output: a_list = ["name1", "name1", "name1"]

Does someone know the solution?

答:
your code will work with a small change if you think that while you are iterating over your tuple_list you have access to each element, one by iteration, so over one iteration you can grab your first element from variable stuff which is the name you want:

```<code>a_list = []

for stuff in tuple_set:
    a_list.append(stuff[0])
</code>```

maybe you got confused because you can use each element index to the job:

```<code>a_list = []

for index in range(tuple_set):
    a_list.append(tuple_set[index][0])
</code>```

you can also unpack each element in other 2 (the name and the score) like @ShadowRanger was suggesting:

```<code>for name, score in tuple_set:
    a_list.append(name)
</code>```

if you like the job to be done in one line you can use a list comprehension:

```<code>a_list = [s[0] for s in tuple_set]
</code>```

or:

```<code>a_list = [n for n, _ in tuple_set]
</code>```

Body:
So basically I have a tuple set kind of like this.

tuple_set = [('name1', 'score'), ('name2', 'score'), ('name3', 'score')]

It basically is a specific list in a larger dictionary of names/scores. I need to isolate name1, name2 and name3 in something that I can iterate through like a list.

It also might work if I can range through it but I can't take the range of the list object/tupleset.

Also appending to a list like this won't work cause it will only put a list of name1s

a_list = []

for stuff in tuple_set:
    a_list.append(tuple_set[0][0])

output: a_list = ["name1", "name1", "name1"]

Does someone know the solution?

Body:
your code will work with a small change if you think that while you are iterating over your tuple_list you have access to each element, one by iteration, so over one iteration you can grab your first element from variable stuff which is the name you want:

a_list = []

for stuff in tuple_set:
    a_list.append(stuff[0])

maybe you got confused because you can use each element index to the job:

a_list = []

for index in range(tuple_set):
    a_list.append(tuple_set[index][0])

you can also unpack each element in other 2 (the name and the score) like @ShadowRanger was suggesting:

for name, score in tuple_set:
    a_list.append(name)

if you like the job to be done in one line you can use a list comprehension:

a_list = [s[0] for s in tuple_set]

or:

a_list = [n for n, _ in tuple_set]


问:
Traefik/Portainer - ERR_TOO_MANY_REDIRECTS
I'm trying to setup Traefik and Portainer but seem to be hitting some issues. I think mainly around Traefik and setting up new containers.

Everything looks correct to me but I seem to be getting an error when I point to my subdomain

```<code>ERR_TOO_MANY_REDIRECTS
</code>```

If I point to the IP address and Port, the Portainer dashboard is displayed, it just seems to be that when pointing to my sub-domain, there is some recursive redirection I'm assuming.

My docker compose looks like this:-

```<code>version: '3'

services:
  portainer:
    image: portainer/portainer:latest
    container_name: portainer-new
   restart: unless-stopped
    security_opt:
      - no-new-privileges:true
    networks:
      - proxy
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./data:/data
    ports:
      - 8000:8000
      - 9000:9000
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.portainer.entrypoints=http"
      - "traefik.http.routers.portainer.rule=Host(`MY_URL`)"
      - "traefik.http.middlewares.portainer-https-redirect.redirectscheme.scheme=https"
      - "traefik.http.routers.portainer.middlewares=portainer-https-redirect"
      - "traefik.http.routers.portainer-secure.entrypoints=https"
      - "traefik.http.routers.portainer-secure.rule=Host(`MY_URL`)"
      - "traefik.http.routers.portainer-secure.tls=true"
      - "traefik.http.routers.portainer-secure.tls.certresolver=http"
      - "traefik.http.routers.portainer-secure.service=portainer"
      - "traefik.http.services.portainer.loadbalancer.server.port=9000"
      - "traefik.docker.network=proxy"

networks:
  proxy:
    external: true
</code>```

Any ideas?

答:
Okay, so I figured out my issue.

The above is correct and valid. I use CloudFlare for proxy/DNS etc... I had added my subdomain to my DNS settings, but my Proxy Status was Proxied rather than DNS ONLY. After setting DNS only the above worked.

Body:
I'm trying to setup Traefik and Portainer but seem to be hitting some issues. I think mainly around Traefik and setting up new containers.

Everything looks correct to me but I seem to be getting an error when I point to my subdomain

ERR_TOO_MANY_REDIRECTS

If I point to the IP address and Port, the Portainer dashboard is displayed, it just seems to be that when pointing to my sub-domain, there is some recursive redirection I'm assuming.

My docker compose looks like this:-

version: '3'

services:
  portainer:
    image: portainer/portainer:latest
    container_name: portainer-new
   restart: unless-stopped
    security_opt:
      - no-new-privileges:true
    networks:
      - proxy
    volumes:
      - /etc/localtime:/etc/localtime:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./data:/data
    ports:
      - 8000:8000
      - 9000:9000
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.portainer.entrypoints=http"
      - "traefik.http.routers.portainer.rule=Host(`MY_URL`)"
      - "traefik.http.middlewares.portainer-https-redirect.redirectscheme.scheme=https"
      - "traefik.http.routers.portainer.middlewares=portainer-https-redirect"
      - "traefik.http.routers.portainer-secure.entrypoints=https"
      - "traefik.http.routers.portainer-secure.rule=Host(`MY_URL`)"
      - "traefik.http.routers.portainer-secure.tls=true"
      - "traefik.http.routers.portainer-secure.tls.certresolver=http"
      - "traefik.http.routers.portainer-secure.service=portainer"
      - "traefik.http.services.portainer.loadbalancer.server.port=9000"
      - "traefik.docker.network=proxy"

networks:
  proxy:
    external: true

Any ideas?


问:
IndexErrors in python
```<code>#To Find the first occurance of a substring
def getIndex(string, sequence):
    for i in range(len(string)):
        if string[i] == sequence[0]:
            try:
                if string[i+1:(i+1+len(sequence)-1)] == sequence[1:]:
                    return i
                else:
                    continue
            except IndexError:
                print('Array out of bounds substring doesnt exist')
    else:
        return 'not found'

print(getIndex('skyscrapper', 'erss'))
</code>```

In the above code the letter e is present at index 9 so when I do string[i+1:(i+1+len(sequence)-1)] equivalent to string[10:13] shouldn't it be throwing an IndexError since the index 12 doesnt exist in the string?

答:
Python doesn't throw error when ranging in string. One way you can achieve your goal by adding ck = string[i+len(sequence)] inside the try block.

Try this one...

def getIndex(string, sequence):
    for i in range(len(string)):
        if string[i] == sequence[0]:
            try:
                # this will result IndexError if index out of range
                ck = string[i+len(sequence)]
                if string[i+1:(i+1+len(sequence)-1)] == sequence[1:]:
                    return i
                else:
                    continue
            except IndexError:
                print('Array out of bounds substring doesnt exist')
    else:
        return 'not found'

print(getIndex('skyscrapper', 'erss'))
```

Title: IndexErrors in python

Body:
#To Find the first occurance of a substring
def getIndex(string, sequence):
    for i in range(len(string)):
        if string[i] == sequence[0]:
            try:
                if string[i+1:(i+1+len(sequence)-1)] == sequence[1:]:
                    return i
                else:
                    continue
            except IndexError:
                print('Array out of bounds substring doesnt exist')
    else:
        return 'not found'

print(getIndex('skyscrapper', 'erss'))

In the above code the letter e is present at index 9 so when I do string[i+1:(i+1+len(sequence)-1)] equivalent to string[10:13] shouldn't it be throwing an IndexError since the index 12 doesnt exist in the string?


问:
Add an animation to a simple carousel
I have a very simple banner change script:

```<code>document.getElementById("car_head").innerHTML = carousel[carousel_num][0];
document.getElementById("car_text").innerHTML = carousel[carousel_num][1];
document.getElementById("car_pic").src = carousel[carousel_num][2];
</code>```

This changes the content of my header on a timer.

How can I add a simple animation to it? Would adding a fade in/out animation be different than adding a slide in/out animation?

Thanks,

答:
You would need to loop through it with some form of an animation loop that gradually changes the value you want (alpha, x/y, whatever). For example:

```<code>var change = function() {
    x -= 10;
    y -= 2;
    styleThese();
    if (x > 10 && y > 0) {
        setTimeout(change, 20);
    }
}

change();
</code>```

Obviously this code doesn't really work. Just work off of that basic idea.

Title: Add an animation to a simple carousel

Body:
I have a very simple banner change script:

document.getElementById("car_head").innerHTML = carousel[carousel_num][0];
document.getElementById("car_text").innerHTML = carousel[carousel_num][1];
document.getElementById("car_pic").src = carousel[carousel_num][2];

This changes the content of my header on a timer.

How can I add a simple animation to it? Would adding a fade in/out animation be different than adding a slide in/out animation?

Thanks,

Body:
You would need to loop through it with some form of an animation loop that gradually changes the value you want (alpha, x/y, whatever). For example:

var change = function() {
    x -= 10;
    y -= 2;
    styleThese();
    if (x > 10 && y > 0) {
        setTimeout(change, 20);
    }
}

change();

Obviously this code doesn't really work. Just work off of that basic idea.


问:
Is there a screen problem with stack in flutter
My problem is because
I have a image at the top of the screen and under the image is the rest of body scaffold, but that has a rounded corners

I used the Stack with positioned to appbar floating and transparent, the container below appbar, but I can't do the rounded corners of the container with this stack, this is what I'm doing

Scaffold(
    body: Stack(
        children: <Widget>[
            SingleChildScrollView(
                child: ...
            )
            Positioned(
                top: 0.0,
                left: 0.0,
                right: 0.0,
                child: AppBar(
                    ...
                ),
            ),
        ],
    ),
)
```

After tried this, I could not do this container with rounded corners and I got this

答:
You can use Stack and Position widget to achieve so.</p>

```<code>import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: MyHomePage(),
    ));

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  final upperbodypartheight = 230;
  final double rounded = 30;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/crown.png"),
              fit: BoxFit.cover,
            ),
          ),
          height: 230,
          child: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0.0,
            title: Text("title"),
          ),
        ),
        Positioned(
          bottom: 0,
          child: Container(
            height: MediaQuery.of(context).size.height -
                upperbodypartheight +
                rounded,
            width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(
                color: Colors.amber,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(rounded),
                    topRight: Radius.circular(rounded))),
          ),
        ),
      ],
    );
  }
}
</code>```

Body:
My problem is because
I have a image at the top of the screen and under the image is the rest of body scaffold, but that has a rounded corners

I used the Stack with positioned to appbar floating and transparent, the container below appbar, but I can't do the rounded corners of the container with this stack, this is what I'm doing

Scaffold(
    body: Stack(
        children: <Widget>[
            SingleChildScrollView(
                child: ...
            )
            Positioned(
                top: 0.0,
                left: 0.0,
                right: 0.0,
                child: AppBar(
                    ...
                ),
            ),
        ],
    ),
)

After tried this, I could not do this container with rounded corners and I got this

Body:
You can use Stack and Position widget to achieve so.

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      home: MyHomePage(),
    ));

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  final upperbodypartheight = 230;
  final double rounded = 30;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/crown.png"),
              fit: BoxFit.cover,
            ),
          ),
          height: 230,
          child: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0.0,
            title: Text("title"),
          ),
        ),
        Positioned(
          bottom: 0,
          child: Container(
            height: MediaQuery.of(context).size.height -
                upperbodypartheight +
                rounded,
            width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(
                color: Colors.amber,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(rounded),
                    topRight: Radius.circular(rounded))),
          ),
        ),
      ],
    );
  }
}


问:
Spring boot cannot find my template view There was an unexpected error (type=Not Found, status=404)
I spent almost a day trying to fix this without any luck

i am integrating spring boot mongodb and thymeleaf

Here is my controller

```<code>@Controller
public class ItemController {
  @Autowired
  private ItemService itemService;

  @GetMapping("/items")
  public String home(Model model) {
    model.addAttribute("items", new ItemEntity());
    List<ItemEntity> items = itemService.findAll();
    model.addAttribute("items", items);
    return "item";
  }
}
</code>```

this is my html template

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <h2>FileUpload</h2>
            <form action="" th:action="@{'/fileupload'}" th:object="${item}" method="post"
                  enctype='multipart/form-data'>
                <div class="form-group">
                    <label for="fileupload">File Upload(excel or csv)</label>
                    <input type="file" class="form-control" id="file" name="file" th:field="*{file}"/>
                </div>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>
        </div>
        <div class="col-md-12">
            <h2>All items</h2>
            <table class="table table-bordered">
                <thead>
                <tr>
                    <th>height</th>
                    <th>width</th>
                    <th>length</th>
                    <th>weight</th>
                    <th>securityLevel</th>
                    <th>file type</th>
                </tr>
                </thead>
                <tbody>
                <tr th:each="item : ${items}">
                    <td th:text="${item.height}">John</td>
                    <td th:text="${item.width}">Doe</td>
                    <td th:text="${item.length}">john@example.com</td>
                    <td th:text="${item.weight}">john@example.com</td>
                    <td th:text="${item.securityLevel}">john@example.com</td>
                    <td th:text="${item.fileType}">john@example.com</td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</body>
</html>
</code>```

build.gradle

```<code>plugins {
    id 'org.springframework.boot' version '2.2.4.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'com.vending'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-devtools'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compile group: 'com.opencsv', name: 'opencsv', version: '4.4'
    compile group: 'org.apache.poi', name: 'poi', version: '3.9'
    compile group: 'commons-io', name: 'commons-io', version: '2.6'
    compile group: 'org.thymeleaf', name: 'thymeleaf', version: '2.0.5'
    compile group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '1.2'
}

test {
    useJUnitPlatform()
}
</code>```

i also have these for mongod inside application.properties

```<code>spring.data.mongodb.database=vending
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
</code>```

when i run VendingApplication and go to http://localhost:8080/items i get this

Whitelabel Error Page
  This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sat Feb 15 03:26:41 EST 2020
  There was an unexpected error (type=Not Found, status=404).
  No message available

it looks like spring is failing to resolve templates view for some reason

UPDATE:

The problem came from the database name which did not map mine

```<code>application.properties
spring.data.mongodb.database=your_db_name
</code>```

答:
In template you are using method as post

```<code><form action="" th:action="@{'/fileupload'}" th:object="${item}" method="post"
</code>```

Change it to get and try

```<code><form action="" th:action="@{'/fileupload'}" th:object="${item}" method="get"
</code>```

Or in controller change mapping to @PostMapping

Body:
I spent almost a day trying to fix this without any luck

i am integrating spring boot mongodb and thymeleaf

Here is my controller

@Controller
public class ItemController {
  @Autowired
  private ItemService itemService;

  @GetMapping("/items")
  public String home(Model model) {
    model.addAttribute("items", new ItemEntity());
    List<ItemEntity> items = itemService.findAll();
    model.addAttribute("items", items);
    return "item";
  }
}

this is my html template

<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>Title</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

FileUpload

            <form action="" th:action="@{'/fileupload'}" th:object="${item}" method="post"
                  enctype='multipart/form-data'>

                    File Upload(excel or csv)
                    <input type="file" class="form-control" id="file" name="file" th:field="*{file}"/>

                <button type="submit" class="btn btn-default">Submit</button>
            </form>

All items

                    height
                    width
                    length
                    weight
                    securityLevel
                    file type

                    John
                    Doe
                    john@example.com
                    john@example.com
                    john@example.com
                    john@example.com

build.gradle

plugins {
    id 'org.springframework.boot' version '2.2.4.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'com.vending'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-devtools'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compile group: 'com.opencsv', name: 'opencsv', version: '4.4'
    compile group: 'org.apache.poi', name: 'poi', version: '3.9'
    compile group: 'commons-io', name: 'commons-io', version: '2.6'
    compile group: 'org.thymeleaf', name: 'thymeleaf', version: '2.0.5'
    compile group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '1.2'
}

test {
    useJUnitPlatform()
}

i also have these for mongod inside application.properties

spring.data.mongodb.database=vending
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017

when i run VendingApplication and go to http://localhost:8080/items i get this

Whitelabel Error Page
  This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sat Feb 15 03:26:41 EST 2020
  There was an unexpected error (type=Not Found, status=404).
  No message available

it looks like spring is failing to resolve templates view for some reason

UPDATE:

The problem came from the database name which did not map mine

application.properties
spring.data.mongodb.database=your_db_name

Body:
In template you are using method as post

<form action="" th:action="@{'/fileupload'}" th:object="${item}" method="post"

Change it to get and try

<form action="" th:action="@{'/fileupload'}" th:object="${item}" method="get"

Or in controller change mapping to @PostMapping


问:
Wordpress How to make a custom walllet system in wordpress?
I am working on a college project which is a website in which i am buying some products from customer or user. So i want to pay them for the stuff that i buy from them.
But directly providing them cash instead i want a wallet system in which i can transfer money in their wallet so that there will be a proof of our transaction.
Is there any plugin in wordpress which can solve my above problem. Since i am new in wordpress so i don't know how to achieve this.
Please tell me that whether should i be able to achieve this type of wallet system or not?</p>

答:
So essentially you want to buy products from customers and pay them for that but without actually giving them cash.

Here are my thoughts about this and possible solutions:

Without a website:
You can easily use Paypal to do this without any website and therefore you will be able to send money using your Paypal account to their Paypal account with any cash transaction (Paypal keep all records of the transaction so you can use it for finance).

With a website:
You install some plugins that will turn your website into a multi vendors market Where users can sell their products directly inside your website. This solution will offer functionalities similar to famous sites like Amazon and eBay. Choosing this solution will allow your customers to sell you services or products and they get paid to their Paypal account despite the payment method you use (except cash), this way the transactions will be happening using electronic wallets which in this example PayPal and all records for transactions will be logged.

The last note is, depending on how much manual work you want to do the solutions will vary.

You may need some assistance o building such a website. Contact me if you need help.

Thanks.


问:
Why && in return and casting?
I was looking at the core Java book and the equality test part confused me a bit

What is the meaning of this specific return line, especially with the &&

Why does it need to cast otherObject to Employee when it already know if it's of the same class?

```<code>class Employee
{
...
    public boolean equals(Object otherObject)
    {
        // a quick test to see if the objects are identical
        if (this == otherObject) return true;

        // must return false if the explicit parameter is null
        if (otherObject == null) return false;

        // if the classes don't match, they can't be equal
        if (getClass() != otherObject.getClass())
           return false;
        // now we know otherObject is a non-null Employee
        Employee other = (Employee) otherObject;

        // test whether the fields have identical values
        return name.equals(other.name)
           && salary == other.salary
           && hireDay.equals(other.hireDay);
    }
}
</code>```

答:
&& is a type of Logical Operator and is read as “AND AND” or “Logical AND“. This operator is used to perform “logical AND” operation, i.e. the function similar to AND gate in digital electronics.

One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensively to test for several conditions for making a decision.

Title: Why && in return and casting?

Body:
I was looking at the core Java book and the equality test part confused me a bit

What is the meaning of this specific return line, especially with the &&

Why does it need to cast otherObject to Employee when it already know if it's of the same class?

class Employee
{
...
    public boolean equals(Object otherObject)
    {
        // a quick test to see if the objects are identical
        if (this == otherObject) return true;

        // must return false if the explicit parameter is null
        if (otherObject == null) return false;

        // if the classes don't match, they can't be equal
        if (getClass() != otherObject.getClass())
           return false;
        // now we know otherObject is a non-null Employee
        Employee other = (Employee) otherObject;

        // test whether the fields have identical values
        return name.equals(other.name)
           && salary == other.salary
           && hireDay.equals(other.hireDay);
    }
}


问:
How to save a png using Unity WebCamTexture
I want to save a picture using the device native camera. Currently I cannot get the image to save to file. I have a rawimage which's texture is the native device camera image. I am taking the bytes from that rawimage and encoding to png. Then I write the png to file on my computer.</p>

```<code>    public WebCamTexture webCamTexture;
    public RawImage myImage;

    public void start () {
        webCamTexture = new WebCamTexture ();
        myImage.texture = webCamTexture;
        myImage.transform.localScale = new Vector3 (1,-1,1);
        webCamTexture.Play ();

        int width =  (int)GameObject.Find("myImage").GetComponent<Rect>      ().width;
        int height = (int)GameObject.Find("myImage").GetComponent<Rect>().height;
        Texture2D tex = new Texture2D (width, height, TextureFormat.RGB24, false);

        tex.ReadPixels (new Rect (0, 0, width, height), 0, 0);
        tex.Apply ();

        byte[] bytes = tex.EncodeToPNG ();
        System.IO.File.WriteAllBytes(Application.dataPath + "/"+"imgcap.png",bytes);

        Object.Destroy (tex);
    }
</code>```

答:
using System;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;

public class WebCamScreenShot : MonoBehaviour
{
    public static int fileCounter = 0;

    WebCamTexture webCamTexture;

    public string path = "C:/temp/UnityScreenShots";

    public string fileNamePrefix = "image_";

    void Start()
    {
        var devices = WebCamTexture.devices;

        if (devices.Length < 1) throw new System.Exception("No webcams was found");

        var device = devices[0];

        webCamTexture = new WebCamTexture(device.name);
        webCamTexture.requestedFPS = 30;
        webCamTexture.requestedWidth = 320;
        webCamTexture.requestedHeight = 240;
        webCamTexture.Play();

        if (webCamTexture.width < 1 || webCamTexture.height < 1) throw new System.Exception("Invalid resolution");
    }

    public void SaveToPNG()
    {
        string zeros =
            (fileCounter < 10000 ? "0000" :
                (fileCounter < 1000 ? "000" :
                    (fileCounter < 100 ? "00" :
                        (fileCounter < 10 ? "0" : ""))));

        string image_path = path + $"/{ fileNamePrefix + zeros + fileCounter }.png";

        byte[] data = ScreenshotWebcam( webCamTexture );

        File.WriteAllBytes(image_path, data);

        fileCounter ++ ;
    }
    static byte[] ScreenshotWebcam(WebCamTexture wct)
    {
        Texture2D colorTex = new Texture2D(wct.width, wct.height, TextureFormat.RGBA32, false);

        byte[] colorByteData = Color32ArrayToByteArray(wct.GetPixels32());

        colorTex.LoadRawTextureData(colorByteData);
        colorTex.Apply();

        return colorTex.EncodeToPNG();
    }

    static byte[] Color32ArrayToByteArray(Color32[] colors)
    {
        // https://stackoverflow.com/a/21575147/2496170

        if (colors == null || colors.Length == 0) return null;

        int lengthOfColor32 = Marshal.SizeOf(typeof(Color32));

        int length = lengthOfColor32 * colors.Length;

        byte[] bytes = new byte[length];

        GCHandle handle = default(GCHandle);

        try
        {
            handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
            IntPtr ptr = handle.AddrOfPinnedObject();
            Marshal.Copy(ptr, bytes, 0, length);
        }
        finally
        {
            if (handle != default(GCHandle)) handle.Free();
        }

        return bytes;
    }
}

```

Body:
I want to save a picture using the device native camera. Currently I cannot get the image to save to file. I have a rawimage which's texture is the native device camera image. I am taking the bytes from that rawimage and encoding to png. Then I write the png to file on my computer.

    public WebCamTexture webCamTexture;
    public RawImage myImage;

    public void start () {
        webCamTexture = new WebCamTexture ();
        myImage.texture = webCamTexture;
        myImage.transform.localScale = new Vector3 (1,-1,1);
        webCamTexture.Play ();

        int width =  (int)GameObject.Find("myImage").GetComponent<Rect>      ().width;
        int height = (int)GameObject.Find("myImage").GetComponent<Rect>().height;
        Texture2D tex = new Texture2D (width, height, TextureFormat.RGB24, false);

        tex.ReadPixels (new Rect (0, 0, width, height), 0, 0);
        tex.Apply ();

        byte[] bytes = tex.EncodeToPNG ();
        System.IO.File.WriteAllBytes(Application.dataPath + "/"+"imgcap.png",bytes);

        Object.Destroy (tex);
    }


问:
calling back (a notification) from a thread that runs in a service
After starting my app it starts the main activity that starts a service. This service has its basic starting notifications, icon ect. and starts a thread that runs some business logic periodically. How can i make this thread be able to call the service back (which started it) to do some notification about the results? How can i reference the service? I just cant figure it out. Pls help me! thx!</p>

答: Your service will run on the main thread of the application. Have a handler in it and pass the reference of that handler to your thread. The thread can post back messages to the handler. For details about passing data between threads see this.</p>


问:
Filename too long when using keyword_search to detect pdf?
I am trying to do some text mining of a pdf by searching for certain keywords.

This is my code:

```<code>library(pdftools)
library(tidyverse)
library(pdfsearch)

UC_text <- pdf_text("https://wilmar-iframe.todayir.com/attachment/20190411162436345449392_en.pdf")

result <- keyword_search(UC_text,
                         keyword = c('SUBSTANTIAL SHAREHOLDERS'),
                         path = TRUE, surround_lines = 1)
</code>```

However, I got the error message of a filename too long. How can I get over this issue?

答:
Given the explanation in the cran manual of pdfsearch, you can directly pass the PDF link to the keyword_search(). In this way, I do not see the error message you provided. I rather got the following result.

```<code>result <- keyword_search("https://wilmar-iframe.todayir.com/attachment/20190411162436345449392_en.pdf",
                         keyword = c('SUBSTANTIAL SHAREHOLDERS'),
                         path = TRUE, surround_lines = 1)

  keyword                  page_num line_num line_text token_text
  <chr>                       <int>    <int> <list>    <list>
1 SUBSTANTIAL SHAREHOLDERS       49     2010 <chr [3]> <list [3]>
</code>```

Body:
I am trying to do some text mining of a pdf by searching for certain keywords.

This is my code:

library(pdftools)
library(tidyverse)
library(pdfsearch)

UC_text <- pdf_text("https://wilmar-iframe.todayir.com/attachment/20190411162436345449392_en.pdf")

result <- keyword_search(UC_text,
                         keyword = c('SUBSTANTIAL SHAREHOLDERS'),
                         path = TRUE, surround_lines = 1)

However, I got the error message of a filename too long. How can I get over this issue?

Body:
Given the explanation in the cran manual of pdfsearch, you can directly pass the PDF link to the keyword_search(). In this way, I do not see the error message you provided. I rather got the following result.

result <- keyword_search("https://wilmar-iframe.todayir.com/attachment/20190411162436345449392_en.pdf",
                         keyword = c('SUBSTANTIAL SHAREHOLDERS'),
                         path = TRUE, surround_lines = 1)

  keyword                  page_num line_num line_text token_text
  <chr>                       <int>    <int> <list>    <list>
1 SUBSTANTIAL SHAREHOLDERS       49     2010 <chr [3]> <list [3]>


问:
Can a geometry shader access OpenGL culling and front face settings?
Is it possible for a OpenGL geometry shader to access the current settings for glFrontFace and glCullFace, and whether face culling is enabled? I have a geometry shader that renders normals for vertexes of triangles, and would like to render them only for triangles that will not be culled. What I would like to have is global variables, similar to built-in uniform variables, that tell whether glFrontFace was given GL_CCW or CL_CW, and whether glCullFace is set to GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK, and whether face culling is enabled.

A workaround is for my C++ program to set the values as uniform variables in the shader program, but it would be more general, and make the shader program more easily usable, if it could query the status of culling, glFrontFace and glCullFace settings from OpenGL.

Please note, I do not want the gl_FrontFacing variable that is available to the fragment shader. Instead, the geometry shader needs to be able to access the values to know whether to generate a line representing a normal at the vertices of the triangle.

答:
No, these are all the inputs you have in geometry shaders: https://www.khronos.org/opengl/wiki/Geometry_Shader#Inputs

You will have to use use a uniform.


问:
Test explorer visual studio 2015 not discovering specflow tests
Not sure if it's a visual studio bug or if I am missing the obvious, but it's a bit of hit and miss.

Sometimes Visual Studio discovers the tests, most of the times I can only see the marquee progress bar and nothing else.

Any ideas about why ?

EDITED

What happens is this:

Sometimes tests do not show
Most of the time tests show but when building/rebuilding solution than marquee progress bar goes in a infinite loop and the run Selected test and Debug selected test are both DISABLED and therefore cannot run test.The output windows shows nothing.

答:
There is a bug in Specflow.Tools.MSBuild.Generation Version=2.3.2.

A short summary of it goes like this: Specflow finds .feature files
and if any of the corresponding .feature.cs files are missing or
out of date, it will generate them and add them to a list of files
called SpecFlowGeneratedFiles. The .csproj contains a section which
compiles the SpecFlowGeneratedFiles into the assembly. If the files
are not included, then there are no tests in the assembly, therefore
no tests are discovered.

In the event that all the .feature.cs files are already present and
up-to-date, the SpecFlowGeneratedFiles are not set, and you get
an infuriating situation where the tests have mysteriously disappeared.
You can verify this bug by deleting any one of the generated .feature.cs
files from the disk and build again.

A workaround is to edit your .csproj and add a section after AfterUpdateFeatureFilesInProject.

```<code><Target Name="AfterUpdateFeatureFilesInProject">
  <ItemGroup>
    <Compile Include="@(SpecFlowGeneratedFiles)" />
  </ItemGroup>
</Target>

<!-- Workaround Specflow 2.3 MSBuild bug. SpecFlowGeneratedFiles is not set if UpdateFeatureFilesInProject is up-to-date
   causing tests not to be discovered, as they are not included in the project -->
<ItemGroup>
  <Compile Include="**/*.feature.cs" Exclude="@(SpecFlowGeneratedFiles)">
    <DependentUpon>%(Filename)</DependentUpon>
  </Compile>
</ItemGroup>
</code>```

Body:
There is a bug in Specflow.Tools.MSBuild.Generation Version=2.3.2.

A short summary of it goes like this: Specflow finds .feature files
and if any of the corresponding .feature.cs files are missing or
out of date, it will generate them and add them to a list of files
called SpecFlowGeneratedFiles. The .csproj contains a section which
compiles the SpecFlowGeneratedFiles into the assembly. If the files
are not included, then there are no tests in the assembly, therefore
no tests are discovered.

In the event that all the .feature.cs files are already present and
up-to-date, the SpecFlowGeneratedFiles are not set, and you get
an infuriating situation where the tests have mysteriously disappeared.
You can verify this bug by deleting any one of the generated .feature.cs
files from the disk and build again.

A workaround is to edit your .csproj and add a section after AfterUpdateFeatureFilesInProject.

<Target Name="AfterUpdateFeatureFilesInProject">
  <ItemGroup>
    <Compile Include="@(SpecFlowGeneratedFiles)" />
  </ItemGroup>
</Target>

<!-- Workaround Specflow 2.3 MSBuild bug. SpecFlowGeneratedFiles is not set if UpdateFeatureFilesInProject is up-to-date
   causing tests not to be discovered, as they are not included in the project -->
<ItemGroup>
  <Compile Include="**/*.feature.cs" Exclude="@(SpecFlowGeneratedFiles)">
    <DependentUpon>%(Filename)</DependentUpon>
  </Compile>
</ItemGroup>


问:
What can I add to this Script to paste rows as values only in reverse order
The script I found in this thread works perfectly. It pastes the 18 rows from the one sheet that uses importxml into a values-only sheet, at the bottom, so that I can keep records of all the imports.

Is there something I could add to it that would paste the rows in reverse order? I don't mean pasting at the top of my values-only sheet, I mean pasting at the bottom but in reverse-order.

Here is the script that is referenced in that link (modified for my usage):

```<code>function copyPaste() {
  var ss=SpreadsheetApp.getActive();
  var srcsh=ss.getSheetByName('Imported');
  var dessh=ss.getSheetByName('ImportedValues');
  var srcrg=srcsh.getRange('A6:P23');
  var data=srcrg.getValues();
  var desrg=dessh.getRange(dessh.getLastRow() + 1,1,18,16);
  desrg.setValues(data);}
</code>```

Background: The import gets the info I need in a newest first order, and I would like my Values-only sheet to maintain an oldest-first order.

答:
```<code>function copyPaste() {
  var ss=SpreadsheetApp.getActive();
  var srcsh=ss.getSheetByName('Imported');
  var dessh=ss.getSheetByName('ImportedValues');
  var srcrg=srcsh.getRange('A6:P23');
  var data=srcrg.getValues();
  var rdata=data.map(function(r){return r;}).reverse();
  var desrg=dessh.getRange(dessh.getLastRow() + 1,1,18,16);
  desrg.setValues(rdata);
}
</code>```

Body:
The script I found in this thread works perfectly. It pastes the 18 rows from the one sheet that uses importxml into a values-only sheet, at the bottom, so that I can keep records of all the imports.

Is there something I could add to it that would paste the rows in reverse order? I don't mean pasting at the top of my values-only sheet, I mean pasting at the bottom but in reverse-order.

Here is the script that is referenced in that link (modified for my usage):

function copyPaste() {
  var ss=SpreadsheetApp.getActive();
  var srcsh=ss.getSheetByName('Imported');
  var dessh=ss.getSheetByName('ImportedValues');
  var srcrg=srcsh.getRange('A6:P23');
  var data=srcrg.getValues();
  var desrg=dessh.getRange(dessh.getLastRow() + 1,1,18,16);
  desrg.setValues(data);}

Background: The import gets the info I need in a newest first order, and I would like my Values-only sheet to maintain an oldest-first order.


问:
Unselect and Select Event
I am using this fiddle - https://jsfiddle.net/BlackLabel/3tqkjLoh/6/

Here the issue - When I select other point from the previous point of the pie (without unselecting the previous one). It shows the status of unselect event of the previous point. I want the status of both 'selected the current one and unselected the previous one'

```<code>const content = document.getElementById('content');
const chart = Highcharts.chart('container', {
  chart: {
    type: 'pie'
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      point: {
        events: {
          select: function(event) {
            const selected = this;
            if (selected) {
              content.textContent = selected.options.name
              /* do something */
              // fetch(`/api?id=${ selected.options.id }`)
            } else {
              content.textContent = 'nothing'
            }
          },
          unselect: function () {
            content.textContent = 'unselect event: ' + this.options.name
          }
        }
      }
    },
  },

  series: [{
    data: [{
      y: 20,
      "name": "click me",
    }, {
      y: 60,
      "name": "click me foo",
      selected: true,
      sliced: true,
    }, {
      y: 100,
      "name": "click me bar",
    }, {
      y: 100,
      "name": "click me baz",
    }, ]
  }]
});
</code>```

答:
Here's the problem, selected event triggers before unselect event
So basically, content.textContent is first set to selected.options.name, and then again sets to 'unselect event: ' + this.options.name and then the latest value is appeared onto the DOM.

https://jsfiddle.net/devatquarxps/5yb0wehd/7/

const content = document.getElementById('content');
const chart = Highcharts.chart('container', {
  chart: {
    type: 'pie'
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      point: {

        events: {
          select: function(event) {
            const selected = this;
   selected ? content.textContent ='select event: ' + selected.options.name + ' | ' : content.textContent = ''

          },
          unselect: function () {
           content.textContent =content.textContent + '  unselect event: ' + this.options.name
          }
        }
      }
    },
  },

  series: [{
    data: [{
      y: 20,
      "name": "click me",
    }, {
      y: 60,
      "name": "click me foo",
      selected: true,
      sliced: true,
    }, {
      y: 100,
      "name": "click me bar",
    }, {
      y: 100,
      "name": "click me baz",
    }, ]
  }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<h3 style="color: red">open console panel</h3>
<p>
  After clicking, [selected and sliced] status is not synchronized update；
</p>
<div>
  <h5>Show to users</h5>
  <h6>You have chosen :</h6>
  <p id="content"></p>
</div>
<div id="container" style="height: 400px"></div></code>```

Title: Unselect and Select Event

Body:
I am using this fiddle - https://jsfiddle.net/BlackLabel/3tqkjLoh/6/

Here the issue - When I select other point from the previous point of the pie (without unselecting the previous one). It shows the status of unselect event of the previous point. I want the status of both 'selected the current one and unselected the previous one'

const content = document.getElementById('content');
const chart = Highcharts.chart('container', {
  chart: {
    type: 'pie'
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      point: {
        events: {
          select: function(event) {
            const selected = this;
            if (selected) {
              content.textContent = selected.options.name
              /* do something */
              // fetch(`/api?id=${ selected.options.id }`)
            } else {
              content.textContent = 'nothing'
            }
          },
          unselect: function () {
            content.textContent = 'unselect event: ' + this.options.name
          }
        }
      }
    },
  },

  series: [{
    data: [{
      y: 20,
      "name": "click me",
    }, {
      y: 60,
      "name": "click me foo",
      selected: true,
      sliced: true,
    }, {
      y: 100,
      "name": "click me bar",
    }, {
      y: 100,
      "name": "click me baz",
    }, ]
  }]
});

Body:
Here's the problem, selected event triggers before unselect event
So basically, content.textContent is first set to selected.options.name, and then again sets to 'unselect event: ' + this.options.name and then the latest value is appeared onto the DOM.

https://jsfiddle.net/devatquarxps/5yb0wehd/7/

const content = document.getElementById('content');
const chart = Highcharts.chart('container', {
  chart: {
    type: 'pie'
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      point: {

        events: {
          select: function(event) {
            const selected = this;
   selected ? content.textContent ='select event: ' + selected.options.name + ' | ' : content.textContent = ''

          },
          unselect: function () {
           content.textContent =content.textContent + '  unselect event: ' + this.options.name
          }
        }
      }
    },
  },

  series: [{
    data: [{
      y: 20,
      "name": "click me",
    }, {
      y: 60,
      "name": "click me foo",
      selected: true,
      sliced: true,
    }, {
      y: 100,
      "name": "click me bar",
    }, {
      y: 100,
      "name": "click me baz",
    }, ]
  }]
});

<script src="https://code.highcharts.com/highcharts.js"></script>
<h3 style="color: red">open console panel</h3>
<p>
  After clicking, [selected and sliced] status is not synchronized update；
</p>
<div>
  <h5>Show to users</h5>
  <h6>You have chosen :</h6>
  <p id="content"></p>
</div>
<div id="container" style="height: 400px"></div>


问:
How to split a items inside a list, surrounded by brackets, seperated by ,
I have a string of plot ploints such as:

```<code>plots = [(0, 1), (0, 2), (1, 4), ... (0.4, 0.8) etc
</code>```

But I want to split them into respective x and y's:

```<code>x = (0, 0, 1, ... 0.4)
y = (1, 2, 4, ... 0.8)
</code>```

I am unsure how to do this.

答:
python provides you with the zip() function

```<code>x, y = zip(*plots)
</code>```

which would provide your exact need, the asterisk would unpack the list into tuples, than the zip function "zips" the tuples together, that is creates a tuple for each index of the tuples

Body:
I have a string of plot ploints such as:

plots = [(0, 1), (0, 2), (1, 4), ... (0.4, 0.8) etc

But I want to split them into respective x and y's:

x = (0, 0, 1, ... 0.4)
y = (1, 2, 4, ... 0.8)

I am unsure how to do this.

Body:
python provides you with the zip() function

x, y = zip(*plots)

which would provide your exact need, the asterisk would unpack the list into tuples, than the zip function "zips" the tuples together, that is creates a tuple for each index of the tuples


问:
Use of scheduler with self-ajusting optimizers in PyTorch
In PyTorch, the weight adjustment policy is determined by the optimizer, and the learning rate is adjusted with a scheduler. When the optimizer is SGD, there is only one learning rate and this is straightforward. When using Adagrad, Adam, or any similar optimizer which inherently adjusts the learning rate on a per-parameter basis, is there something in particular to look out for? Can I ignore the scheduler completely since the algorithm adjusts its own learning rates? Should I parameterize it very differently than if I'm using SGD?</p>

答:
The learning rate you define for optimizers like ADAM are upper bounds. You can see this in the paper in Section 2.1. The stepsize α in the paper is the learning rate.

The effective magnitude of the steps taken in parameter space at each are approximately bounded by the stepsize setting α

Also this stepsize α is directly used and multiplied with the step size correction, which is learned. So changing the learning rate e.g. reducing it will reduce all individual learning rates and reduces the upper bound. This can be helpful during the "end" of an training, to reduce the overall step sizes, so only smaller steps occur and might help the network to find a minima in the loss function.

I saw learning rate decay in some papers using ADAM and used it myself and it did help. What I found is that you should do it slower than e.g. with SGD. With one model I just multiply it with 0.8 every 10 epochs. So it is a gradual decay which I think works better than more drastic steps since you don't "invalidate" the estimated momentums to much. But this is just my theory.


问:
Reading a file with a read method using Scanner (InputMismatchException)
I'm new to java and I have a problem with reading a file using the scanner class.

My objective is to read the following .txt file:

```<code>3
Emmalaan 23
3051JC Rotterdam
7 rooms
price 300000
Javastraat 88
4078KB Eindhoven
3 rooms
price 50000
Javastraat 93
4078KB Eindhoven
4 rooms
price 55000
</code>```

The "3" on top of the file should be read as an integer that tells how many houses the file has. The following four lines after the "3" determine one house.

I try to read this file using a read method in the class portefeuille:

```<code>public static Portefeuille read(String infile)
    {
        Portefeuille returnvalue = new Portefeuille();

        try
        {
            Scanner scan = new Scanner(new File(infile)).useDelimiter(" |/n");
            int aantalwoningen = scan.nextInt();
            for(int i = 0; i<aantalwoningen; ++i)
            {

                Woning.read(scan);
            }

        }

        catch (FileNotFoundException e)
        {
            System.out.println("File could not be found");
        }

        catch (IOException e)
        {
            System.out.println("Exception while reading the file");
        }

        return returnvalue;
    }
</code>```

The read method in the  Woning class looks like this:

```<code>public static Woning read(Scanner sc)
    {

        String token_adres = sc.next();
        String token_dr = sc.next();
        String token_postcd = sc.next();
        String token_plaats = sc.next();
        int token_vraagPrijs = sc.nextInt();
        String token_kamerstxt = sc.next();
        String token_prijstxt = sc.next();
        int token_kamers = sc.nextInt();

        return new Woning(adresp, token_vraagPrijs, token_kamers);

    }
</code>```

When I try to execute the following code:

```<code>Portefeuille port1 = Portefeuille.read("woningen.txt");
</code>```

I get the following error:

```<code>Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at Portefeuille.read(Portefeuille.java:48)
    at Portefeuille.main(Portefeuille.java:112)
</code>```

However if I use the read method from the Woning class to read one adres in a string format:

```<code>Emmalaan 23
3051JC Rotterdam
7 Rooms
price 300000
</code>```

It works fine.

I tried to change the .txt file into only one address without the "3" on top so that it is exactly formatted like the address that should work. But when I call the read method from Woning class it still gives me the error.

Could anyone please help me with this?

Thank you!

答:
I was also facing a similar issue, so I put my answer so that it could help in future:

There are two possible modifications which I did to make this code run.

First option: Change the use of useDelimiter method to  .useDelimiter("\\r\\n") when creating the Scanner class, I was in windows so we might need \\r for Windows compatibility.

Using this modification, there will be no exception.But the code will again fail at int token_vraagPrijs = sc.nextInt();.

Because in the public static Woning read(Scanner sc), you are suing sc.next();.Actually this method finds and returns the next complete token from this scanner.A complete token is preceded and followed by input that matches the delimiter pattern.

So, every sc.next() is actually reading a line not a token.
So as per your code sc.nextInt() is trying to read something like  Javastraat 88.So again it will give you the same exception.

Second option (Preferred):Don't use any delimiter, Scanner class will default whitespace and your code will work fine.I modified your code and It worked fine for me.

Code:

```<code>public class Test3{
  public static void main(String... s)
    {
    read("test.txt");
    }

public static void read(String infile)
{
    try (Scanner scan = new Scanner(new File(infile)))
    {
        int aantalwoningen = scan.nextInt();
        System.out.println(aantalwoningen);
        for (int i = 0; i < aantalwoningen; ++i)
        {
            read(scan);
        }
    }
    catch (FileNotFoundException e)
    {
        System.out.println("File could not be found");
    }
}

public static void read(Scanner sc)
{

    String token_adres = sc.next();
    String token_dr = sc.next();
    String token_postcd = sc.next();
    String token_plaats = sc.next();
    int token_vraagPrijs = sc.nextInt();
    String token_kamerstxt = sc.next();
    String token_prijstxt = sc.next();
    int token_kamers = sc.nextInt();
    System.out.println(token_adres + " " + token_dr + " " + token_postcd + " " + token_plaats + " "
        + token_vraagPrijs + " " + token_kamerstxt + " " + token_prijstxt + " " + token_kamers);

} }
</code>```

Body:
I'm new to java and I have a problem with reading a file using the scanner class.

My objective is to read the following .txt file:

3
Emmalaan 23
3051JC Rotterdam
7 rooms
price 300000
Javastraat 88
4078KB Eindhoven
3 rooms
price 50000
Javastraat 93
4078KB Eindhoven
4 rooms
price 55000

The "3" on top of the file should be read as an integer that tells how many houses the file has. The following four lines after the "3" determine one house.

I try to read this file using a read method in the class portefeuille:

public static Portefeuille read(String infile)
    {
        Portefeuille returnvalue = new Portefeuille();

        try
        {
            Scanner scan = new Scanner(new File(infile)).useDelimiter(" |/n");
            int aantalwoningen = scan.nextInt();
            for(int i = 0; i<aantalwoningen; ++i)
            {

                Woning.read(scan);
            }

        }

        catch (FileNotFoundException e)
        {
            System.out.println("File could not be found");
        }

        catch (IOException e)
        {
            System.out.println("Exception while reading the file");
        }

        return returnvalue;
    }

The read method in the  Woning class looks like this:

public static Woning read(Scanner sc)
    {

        String token_adres = sc.next();
        String token_dr = sc.next();
        String token_postcd = sc.next();
        String token_plaats = sc.next();
        int token_vraagPrijs = sc.nextInt();
        String token_kamerstxt = sc.next();
        String token_prijstxt = sc.next();
        int token_kamers = sc.nextInt();

        return new Woning(adresp, token_vraagPrijs, token_kamers);

    }

When I try to execute the following code:

Portefeuille port1 = Portefeuille.read("woningen.txt");

I get the following error:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at Portefeuille.read(Portefeuille.java:48)
    at Portefeuille.main(Portefeuille.java:112)

However if I use the read method from the Woning class to read one adres in a string format:

Emmalaan 23
3051JC Rotterdam
7 Rooms
price 300000

It works fine.

I tried to change the .txt file into only one address without the "3" on top so that it is exactly formatted like the address that should work. But when I call the read method from Woning class it still gives me the error.

Could anyone please help me with this?

Thank you!

Body:
I was also facing a similar issue, so I put my answer so that it could help in future:

There are two possible modifications which I did to make this code run.

First option: Change the use of useDelimiter method to  .useDelimiter("\\r\\n") when creating the Scanner class, I was in windows so we might need \\r for Windows compatibility.

Using this modification, there will be no exception.But the code will again fail at int token_vraagPrijs = sc.nextInt();.

Because in the public static Woning read(Scanner sc), you are suing sc.next();.Actually this method finds and returns the next complete token from this scanner.A complete token is preceded and followed by input that matches the delimiter pattern.

So, every sc.next() is actually reading a line not a token.
So as per your code sc.nextInt() is trying to read something like  Javastraat 88.So again it will give you the same exception.

Second option (Preferred):Don't use any delimiter, Scanner class will default whitespace and your code will work fine.I modified your code and It worked fine for me.

Code:

public class Test3{
  public static void main(String... s)
    {
    read("test.txt");
    }

public static void read(String infile)
{
    try (Scanner scan = new Scanner(new File(infile)))
    {
        int aantalwoningen = scan.nextInt();
        System.out.println(aantalwoningen);
        for (int i = 0; i < aantalwoningen; ++i)
        {
            read(scan);
        }
    }
    catch (FileNotFoundException e)
    {
        System.out.println("File could not be found");
    }
}

public static void read(Scanner sc)
{

    String token_adres = sc.next();
    String token_dr = sc.next();
    String token_postcd = sc.next();
    String token_plaats = sc.next();
    int token_vraagPrijs = sc.nextInt();
    String token_kamerstxt = sc.next();
    String token_prijstxt = sc.next();
    int token_kamers = sc.nextInt();
    System.out.println(token_adres + " " + token_dr + " " + token_postcd + " " + token_plaats + " "
        + token_vraagPrijs + " " + token_kamerstxt + " " + token_prijstxt + " " + token_kamers);

} }


问:
Move TextField up when the keyboard has appeared in SwiftUI
I have seven TextField inside my main ContentView. When user open keyboard some of the TextField are hidden under the keyboard frame. So I want to move all TextField up respectively when the keyboard has appeared.

I have used the below code to add TextField on the screen.

```<code>struct ContentView : View {
    @State var textfieldText: String = ""

    var body: some View {
            VStack {
                TextField($textfieldText, placeholder: Text("TextField1"))
                TextField($textfieldText, placeholder: Text("TextField2"))
                TextField($textfieldText, placeholder: Text("TextField3"))
                TextField($textfieldText, placeholder: Text("TextField4"))
                TextField($textfieldText, placeholder: Text("TextField5"))
                TextField($textfieldText, placeholder: Text("TextField6"))
                TextField($textfieldText, placeholder: Text("TextField6"))
                TextField($textfieldText, placeholder: Text("TextField7"))
            }
    }
}
</code>```

Output:

答:
Or
You can just use IQKeyBoardManagerSwift

and can optionally add this to your app delegate to hide the toolbar and enable hiding of keyboard on click on any view other then keyboard.

```<code>IQKeyboardManager.shared.enableAutoToolbar = false
IQKeyboardManager.shared.shouldShowToolbarPlaceholder = false
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.previousNextDisplayMode = .alwaysHide
</code>```

Body:
I have seven TextField inside my main ContentView. When user open keyboard some of the TextField are hidden under the keyboard frame. So I want to move all TextField up respectively when the keyboard has appeared.

I have used the below code to add TextField on the screen.

struct ContentView : View {
    @State var textfieldText: String = ""

    var body: some View {
            VStack {
                TextField($textfieldText, placeholder: Text("TextField1"))
                TextField($textfieldText, placeholder: Text("TextField2"))
                TextField($textfieldText, placeholder: Text("TextField3"))
                TextField($textfieldText, placeholder: Text("TextField4"))
                TextField($textfieldText, placeholder: Text("TextField5"))
                TextField($textfieldText, placeholder: Text("TextField6"))
                TextField($textfieldText, placeholder: Text("TextField6"))
                TextField($textfieldText, placeholder: Text("TextField7"))
            }
    }
}

Output:

Body:
Or
You can just use IQKeyBoardManagerSwift

and can optionally add this to your app delegate to hide the toolbar and enable hiding of keyboard on click on any view other then keyboard.

IQKeyboardManager.shared.enableAutoToolbar = false
IQKeyboardManager.shared.shouldShowToolbarPlaceholder = false
IQKeyboardManager.shared.shouldResignOnTouchOutside = true
IQKeyboardManager.shared.previousNextDisplayMode = .alwaysHide


问:
Create a WCF Proxy for a Rest Web Service
I have a complex WCF Rest service which take multiple inputs and objects. I cannot simply call it by doing an HTTP POST in Fiddler because there is too much data to provide (I could, but it will take me forever). So I would like to do it in code using a proxy. Is there a way to generate a proxy for a .NET 4 WCF Rest Service? Otherwise, what do you propose to allow me to easily test the service?

Thanks.

答:
There's no standard way of creating a proxy for a WCF REST service (there's no WSDL for REST, one emerging standard, WADL, isn't widely adopted, and WCF doesn't support it). For testing purposes, you should share the interface with the client, and either use the ChannelFactory<T> - and set the appropriate behavior in the factory's Endpoint property, or use the helper class WebChannelFactory<T> which does it for you.

Assuming that the interface is called ITest, this is what you'd have:

```<code>Uri serviceUri = new Uri("http://my.service.com/endpoint");
WebChannelFactory<ITest> factory = new WebChannelFactory<ITest>(serviceUri);
ITest proxy = factory.CreateChannel();
Assert.AreEqual(9, proxy.Add(4, 5));
</code>```

Body:
There's no standard way of creating a proxy for a WCF REST service (there's no WSDL for REST, one emerging standard, WADL, isn't widely adopted, and WCF doesn't support it). For testing purposes, you should share the interface with the client, and either use the ChannelFactory<T> - and set the appropriate behavior in the factory's Endpoint property, or use the helper class WebChannelFactory<T> which does it for you.

Assuming that the interface is called ITest, this is what you'd have:

Uri serviceUri = new Uri("http://my.service.com/endpoint");
WebChannelFactory<ITest> factory = new WebChannelFactory<ITest>(serviceUri);
ITest proxy = factory.CreateChannel();
Assert.AreEqual(9, proxy.Add(4, 5));