问:
Docker: Filesystem is not responding
I have to run 43 containers on the local machine.

Each startup I have warnings

```<code>WARNING: Connection pool is full, discarding connection: localhost
</code>```

Warning don't block my work

But sometimes at containers startup, I got multiple errors below

```<code>Filesystem is not responding
Filesystem mounted at /var/lib/docker/overlay/{hash}/merged is not responding
</code>```

A lot of them pushed as notifications in my manjaro KDE
These errors block my work, containers not working. Only reboot helps me.

I will provide any additional information you need

Filesystem is ext4
Storage driver: overlay2

```<code>docker system df
TYPE                TOTAL               ACTIVE              SIZE                RECLAIMABLE
Images              16                  10                  3.82GB              1.198GB (31%)
Containers          43                  43                  1.138MB             0B (0%)
Local Volumes       20                  10                  1.947GB             955.4MB (49%)
Build Cache         0                   0                   0B                  0B
</code>```

```<code>sudo docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
3e046a2f4038        bridge              bridge              local
8aadcba2673b        dev_default         bridge              local
0f58cf29be50        host                host                local
dace3c787c02        none                null                local
</code>```

```<code>sudo docker network inspect dev_default
[
    {
        "Name": "dev_default",
        "Id": "8aadcba2673b48477a439252f9528493511d63d017acbe7981893e9abc8ef1ce",
        "Created": "2020-02-14T13:40:06.643398755+03:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.20.0.0/16",
                    "Gateway": "172.20.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "016e0d8ec547831d3cb4ed971ccc9d4dd7c21d7bbd17d2295d9b6c2f37250ce1": {
                "Name": "dev_emulator-22800014_1",
                "EndpointID": "4d665c749b325820aac33d415baa8467e49b549c928d730b0fd16a01423f94c9",
                "MacAddress": "02:42:ac:14:00:0a",
                "IPv4Address": "172.20.0.10/16",
                "IPv6Address": ""
            },
            "060a555c3a813188d49c06d22170eab6555b4acf6f532bf3c7dd7ea82f01b5fb": {
                "Name": "dev_emulator-22800038_1",
                "EndpointID": "85a43daca97c55f2ea2c83401468ba64315997f8c817d22fc81a2b54283236dc",
                "MacAddress": "02:42:ac:14:00:10",
                "IPv4Address": "172.20.0.16/16",
                "IPv6Address": ""
            },
            "06aba1b6a003e42388fd4d4feaa66ab8f2fbab853bf32bf74ef50050cba30ae6": {
                "Name": "dev_emulator-22800015_1",
                "EndpointID": "2541a4e7d05c88ea2a6bccc3280b5eac8437646ed07fa13d6bd00a65aae0331d",
                "MacAddress": "02:42:ac:14:00:12",
                "IPv4Address": "172.20.0.18/16",
                "IPv6Address": ""
            },
            "085d84226f8aa471ccbf784f7c34be362371d481d7a157ec87538c631c85868a": {
                "Name": "dev_emulator-19400017_1",
                "EndpointID": "0bef199879d04a55e0916d943cef1e883cf0032a32fc7c6ff6cc71bc2eb5d397",
                "MacAddress": "02:42:ac:14:00:15",
                "IPv4Address": "172.20.0.21/16",
                "IPv6Address": ""
            },
            "09fbe0b08f81f1b30a056bcddbf02bafe50f5367447eea52393d6f85fe9e6e95": {
                "Name": "dev_emulator-19400019_1",
                "EndpointID": "0ab5142fa4f578b23600e0a1b00433009368a82efad15cb7b29273095b4ddb81",
                "MacAddress": "02:42:ac:14:00:20",
                "IPv4Address": "172.20.0.32/16",
                "IPv6Address": ""
            },
            "160f645c05d1a7ca3c7189a24cbd1aa598ae64a0eced259580e5475544556e99": {
                "Name": "dev_emulator-22800016_1",
                "EndpointID": "3b376a61b5bd383b4ac92ad959bce1d51fa8f189bb8dc54c086ad0e7ad0c0ee3",
                "MacAddress": "02:42:ac:14:00:02",
                "IPv4Address": "172.20.0.2/16",
                "IPv6Address": ""
            },
            "18d5f68d2f5d5fc2d39ecad9d16bdb75af91d74626ac77c559fd508c2e75e1e8": {
                "Name": "dev_emulator-19400031_1",
                "EndpointID": "771bb76578e24aba74f4780b5e3f02d7aa03bd1e6c6b0311ca8a4e66fcd00ea3",
                "MacAddress": "02:42:ac:14:00:16",
                "IPv4Address": "172.20.0.22/16",
                "IPv6Address": ""
            },
            "23c427c2b75f27b79f2fe83eb9d361d506786fc2f702d5b854d443d14683b0da": {
                "Name": "dev_tdiRelay_1",
                "EndpointID": "00331149f91abef709e1eb494a937cbe534ef4bfa5da137edb648e748ff800e0",
                "MacAddress": "02:42:ac:14:00:2b",
                "IPv4Address": "172.20.0.43/16",
                "IPv6Address": ""
            },
            "272c718eaa25a45952eceb860d875418b6ba6a68db026733052e67b7efa3ab8d": {
                "Name": "dev_tdiParser_1",
                "EndpointID": "02fecfde12e183c6ece57f1ab96b858fb4e3b0f1977a47a00f61ce9ece7960fa",
                "MacAddress": "02:42:ac:14:00:2c",
                "IPv4Address": "172.20.0.44/16",
                "IPv6Address": ""
            },
            "29e9a0e3fa9eff5185fc6dda092f4358140c4ca852d97f31c31c77055b1ffe60": {
                "Name": "dev_emulator-19400013_1",
                "EndpointID": "4a501dcf83ba64273512a5381c562abbdc5dba0d0b6d01fe68a03499674e2f15",
                "MacAddress": "02:42:ac:14:00:0f",
                "IPv4Address": "172.20.0.15/16",
                "IPv6Address": ""
            },
            "2cb4e8011fa4c338803f546dfb9181936030cae6d3d4eddddd7af0a04137f2b6": {
                "Name": "dev_emulator-22800010_1",
                "EndpointID": "0dc1d7639077e18c511b75638f9995e5a052914da6e14bca174fd6a8217ca2d4",
                "MacAddress": "02:42:ac:14:00:17",
                "IPv4Address": "172.20.0.23/16",
                "IPv6Address": ""
            },
            "408a7b4f1f1c92be7022f514775ebc93fd6359237b74704da73ee51b158cbfe2": {
                "Name": "dev_emulator-22800031_1",
                "EndpointID": "380cfac2b1200c530d5c665b5290d8930448ed39c56710d29fe191af5e748d7d",
                "MacAddress": "02:42:ac:14:00:0d",
                "IPv4Address": "172.20.0.13/16",
                "IPv6Address": ""
            },
            "43bda6ed5698b59d90fa1479547efa2c4bbcec187b03d4990632217bbb4cec9c": {
                "Name": "dev_emulator-22800018_1",
                "EndpointID": "c77dac271dedc5d05968a17fbf665358ba214d03a67dca082c37668410d0f1a2",
                "MacAddress": "02:42:ac:14:00:18",
                "IPv4Address": "172.20.0.24/16",
                "IPv6Address": ""
            },
            "44a1e95f87f1eac91bfc06a16a32b8b478df871af9b9d1d9bf095e6f2b075e5a": {
                "Name": "dev_maintempdb_1",
                "EndpointID": "4021ea4e27729adeaa81b7d0bd6f7c67be17734c4d67b14d660880f7c0531f37",
                "MacAddress": "02:42:ac:14:00:05",
                "IPv4Address": "172.20.0.5/16",
                "IPv6Address": ""
            },
            "554f1a422ece3eb0558a747ef6d63dba6b0e9d019c438d118ded9ff76ef176df": {
                "Name": "dev_emulator-19400040_1",
                "EndpointID": "f2a3bb793ab5be3e7c1276d38b3ad3a922ea0a901fa990e356a722875aa1556a",
                "MacAddress": "02:42:ac:14:00:14",
                "IPv4Address": "172.20.0.20/16",
                "IPv6Address": ""
            },
            "5932a2cb3803e390ce98ef823610e6f3ca12213e52b9812c2d4b5519b473e709": {
                "Name": "dev_emulator-22800023_1",
                "EndpointID": "81b45bb2b1832a83dab9dfc803e44a724ffd5a6a1bc6e11fc4577b6489b090ed",
                "MacAddress": "02:42:ac:14:00:04",
                "IPv4Address": "172.20.0.4/16",
                "IPv6Address": ""
            },
            "596314ba1bebbb5938735e7559a2cad8a3927a0b222c9a42f6a2abab2184779e": {
                "Name": "dev_mainq_1",
                "EndpointID": "9bc8505918c5bef6132172e90c5b50e4801a213e5fb7f18c54f8a841e0deee26",
                "MacAddress": "02:42:ac:14:00:22",
                "IPv4Address": "172.20.0.34/16",
                "IPv6Address": ""
            },
            "61dea1acffa8eb3508bbf4c90d17fc01b32c7da578682555343d053ca65add04": {
                "Name": "dev_outerdb_1",
                "EndpointID": "4613444ab9c6e33dc6eb35ff0d5400a8d34b1ceeb30d8e1bb2f607ec9fb953db",
                "MacAddress": "02:42:ac:14:00:23",
                "IPv4Address": "172.20.0.35/16",
                "IPv6Address": ""
            },
            "666aa5be6401cd4ac2fe34a74789e0a5e210c46fc43a569448f6f51cc255fa61": {
                "Name": "dev_outerOctave_1",
                "EndpointID": "fc3c5b47a330a68e7b0ff494f1fde3926b429158a1846197d31b11b0aae083cd",
                "MacAddress": "02:42:ac:14:00:29",
                "IPv4Address": "172.20.0.41/16",
                "IPv6Address": ""
            },
            "6f3533a85093ddde99cac38201ab379bbba2948f08da50a4a173be982cea7c2a": {
                "Name": "dev_emulator-22800040_1",
                "EndpointID": "9615b87b9cea2f94ba46b0005d4b73c31cf358446cf3bf3ec94894a25a12241a",
                "MacAddress": "02:42:ac:14:00:0e",
                "IPv4Address": "172.20.0.14/16",
                "IPv6Address": ""
            },
            "7100bd89110864bc254023ffb53bab12883897c42ba7cd5adb29a8b894150f20": {
                "Name": "dev_emulator-22800033_1",
                "EndpointID": "2bb75565256cb335c1f076e2e4ef4acc5623e0d0bdf4aa1b7c0514fa4eb04f51",
                "MacAddress": "02:42:ac:14:00:09",
                "IPv4Address": "172.20.0.9/16",
                "IPv6Address": ""
            },
            "801f8d9ddeebf4c1e5f692797cdd65650cd09e05b23eab4e7886cc183c79b6c3": {
                "Name": "dev_emulator-19400016_1",
                "EndpointID": "e0b0f28260a5a03c79b7f41f1bf8db9640848c6d0aed35d6fdd53cba03d61366",
                "MacAddress": "02:42:ac:14:00:0b",
                "IPv4Address": "172.20.0.11/16",
                "IPv6Address": ""
            },
            "809d22241a480f9192f29edc5d03e79db33043cc9bfa763639e67e8cfdd80f0e": {
                "Name": "dev_emulator-19400015_1",
                "EndpointID": "638e6b1cddd1fe78a11de8622ab42ca8ee967303330277e2187261b426aa2f8b",
                "MacAddress": "02:42:ac:14:00:1e",
                "IPv4Address": "172.20.0.30/16",
                "IPv6Address": ""
            },
            "86995a099365f63f6112c25e3e784f6610ae278702c812b61370e186ca53e2ad": {
                "Name": "dev_s3storage_1",
                "EndpointID": "e4c8299d772eaa6a57a63bd351585ec5785c09f6df2e785730ae41d4ff3a25f2",
                "MacAddress": "02:42:ac:14:00:19",
                "IPv4Address": "172.20.0.25/16",
                "IPv6Address": ""
            },
            "8b8e754c99ff6226e8ccd03a150173dfb06e6309c9774c263ae006d9f53f52aa": {
                "Name": "dev_emulator-22800022_1",
                "EndpointID": "dbd31d8e3150192e87b8917927d07729e0603f5288dcc9f296650f34f06c37ee",
                "MacAddress": "02:42:ac:14:00:1c",
                "IPv4Address": "172.20.0.28/16",
                "IPv6Address": ""
            },
            "8cf73e2e2503e52bfcafbc1c9322b994127df20c359ca624be644210abd57dbc": {
                "Name": "dev_tileserver_1",
                "EndpointID": "77374f4cde143d455c0f062e673008c8b41fe4b2977392c9982bc0052217c6c3",
                "MacAddress": "02:42:ac:14:00:03",
                "IPv4Address": "172.20.0.3/16",
                "IPv6Address": ""
            },
            "8e05504ce48d890fa9359938c533b4495814e67f36c8c5b24a736812a5eb0e2f": {
                "Name": "dev_emulator-19400028_1",
                "EndpointID": "9d26d053da0d0945d3ff707bccba3cbb12fb81f295678c3604ad60eb9aa9ef2c",
                "MacAddress": "02:42:ac:14:00:1f",
                "IPv4Address": "172.20.0.31/16",
                "IPv6Address": ""
            },
            "968b41556187c66cb31e623b063d3acf594eb6abac0aa5444bc85d017a807ba6": {
                "Name": "dev_outerWeb_1",
                "EndpointID": "1959455650da340d1d59f8d6011b88657371d7e7e2db02db69462b6747835f97",
                "MacAddress": "02:42:ac:14:00:28",
                "IPv4Address": "172.20.0.40/16",
                "IPv6Address": ""
            },
            "9a12736c89c8005b32ff9f11283dfbd666ad201fbd9a45bb1c5ad0f20b5f52eb": {
                "Name": "dev_emulator-19400011_1",
                "EndpointID": "c23c6ac83769cf06ccc856a47aa0859a9da3f942e7e792384842dde54564e463",
                "MacAddress": "02:42:ac:14:00:25",
                "IPv4Address": "172.20.0.37/16",
                "IPv6Address": ""
            },
            "9d12ef78d15fec44b4fa42878c4268d1ec4ac21db4f694bc02d208acd1b561df": {
                "Name": "dev_emulator-19400012_1",
                "EndpointID": "e0f1c3f68bdfa4e7205b6ea8acad4ec791393139e54fc823b9cc7e079c2e419a",
                "MacAddress": "02:42:ac:14:00:07",
                "IPv4Address": "172.20.0.7/16",
                "IPv6Address": ""
            },
            "b2958a80d70e47692c9ac69314b4fd69acc3e18760f644dceb8142d23d046b3a": {
                "Name": "dev_emulator-22800007_1",
                "EndpointID": "c285a1c6e276ff364bbb72d60ba94eea247aa524d6e9477de8fb92f60b4a8f83",
                "MacAddress": "02:42:ac:14:00:0c",
                "IPv4Address": "172.20.0.12/16",
                "IPv6Address": ""
            },
            "b7f4d47981571d0970c1db4dc065a1c93186287b50938b1f1e5acc972678735b": {
                "Name": "dev_emulator-19400014_1",
                "EndpointID": "8625c39b48c0000b79c13b1d1f21ba07ce16b8813cf786a94ceedc8a84cda55d",
                "MacAddress": "02:42:ac:14:00:06",
                "IPv4Address": "172.20.0.6/16",
                "IPv6Address": ""
            },
            "c08e59d978c478cd6bb8c30b1ff0dc51b10ac10fc616e6fc24d3600391d4b3da": {
                "Name": "dev_emulator-19400020_1",
                "EndpointID": "1b629f69d2364e39375cd4cb4e42bd5e34332e468b04169a7fcaa167d58f3f19",
                "MacAddress": "02:42:ac:14:00:24",
                "IPv4Address": "172.20.0.36/16",
                "IPv6Address": ""
            },
            "c84a447df4e5b632e042e567033d243017b6f0ba58f97be1222110d50b1019b3": {
                "Name": "dev_emulator-19400023_1",
                "EndpointID": "642b31dd4818063828c9889237416aa7b297391fe557530e11959c971278d0dd",
                "MacAddress": "02:42:ac:14:00:26",
                "IPv4Address": "172.20.0.38/16",
                "IPv6Address": ""
            },
            "ca15d4fee3f45b8d8a7552aaa519563d2b1b8ea13c51c0c0d1cd94765cf94512": {
                "Name": "dev_emulator-19400009_1",
                "EndpointID": "8a62973b92ad70a6aad08b717c1ff26fd781cd97e341d2d8ed753a2d2294d00e",
                "MacAddress": "02:42:ac:14:00:11",
                "IPv4Address": "172.20.0.17/16",
                "IPv6Address": ""
            },
            "cb4fd70cdb8dac59bff2c0257224dc1d261df2770b50221132e5a23997afd1d6": {
                "Name": "dev_maineternaldb_1",
                "EndpointID": "d4cec9ce4110dd188bf7c958b89433d40d436b46f212fbdf35c0dcbcdf0831b9",
                "MacAddress": "02:42:ac:14:00:08",
                "IPv4Address": "172.20.0.8/16",
                "IPv6Address": ""
            },
            "e4d60f497831a9c38ebf96a2d48aed8bfb26928a2ed76ba2b8e77139c4b832bc": {
                "Name": "dev_emulator-22800004_1",
                "EndpointID": "61a18f0b561336186ca3bf01a8b3439396f9c76e3ba76b28c7ec355441be2dd9",
                "MacAddress": "02:42:ac:14:00:21",
                "IPv4Address": "172.20.0.33/16",
                "IPv6Address": ""
            },
            "e79451e6ad59896d21fcd88301ce099917ef96ea3d32a3060cb79978b6421fcf": {
                "Name": "dev_emulator-19400036_1",
                "EndpointID": "e3303c42d1b0ebac104762b989229773501b3a8e5b5c7059c765543e3031e8b6",
                "MacAddress": "02:42:ac:14:00:1a",
                "IPv4Address": "172.20.0.26/16",
                "IPv6Address": ""
            },
            "ead3cffd714f12160dde8e35bae0222b521d6264338267edf9c00bbb11b0ebde": {
                "Name": "dev_mainOctave_1",
                "EndpointID": "e5f4c078e4b1ed13fd52eb5740f38c59760388a8bed6b01549841a649db6fb94",
                "MacAddress": "02:42:ac:14:00:2a",
                "IPv4Address": "172.20.0.42/16",
                "IPv6Address": ""
            },
            "ec9aeb9218cef0b8176e3713258812dfcfba5baa691b9639e50fe965b5681cea": {
                "Name": "dev_outerq_1",
                "EndpointID": "69756ebf2b6a1bdceff4f37fe1dad22859983f417bdbe8e4ab82bd23668500fc",
                "MacAddress": "02:42:ac:14:00:13",
                "IPv4Address": "172.20.0.19/16",
                "IPv6Address": ""
            },
            "f2b86f1ae769358a413c94d6bc7c129e50cdf2a6afe12d86be1e5b85fce6cad7": {
                "Name": "dev_web2_1",
                "EndpointID": "0efa83f1aaef42831b312582fbd7ac25c202f7650d237ea30c72de01eaffd1a8",
                "MacAddress": "02:42:ac:14:00:27",
                "IPv4Address": "172.20.0.39/16",
                "IPv6Address": ""
            },
            "f3ed055ec5f6a6bf6ab73b6db24a495e531e2078694ad523723880e9ae7627e7": {
                "Name": "dev_emulator-77700000_1",
                "EndpointID": "a3ecfc5de45ba1bc0dd491f6dc4052034b077d0e3f717f182751b2a29e42e850",
                "MacAddress": "02:42:ac:14:00:1d",
                "IPv4Address": "172.20.0.29/16",
                "IPv6Address": ""
            },
            "fca06c99c6f6140161a007bab98e885f468a40a21318f9b7be2fdec322645db9": {
                "Name": "dev_maincouchdb_1",
                "EndpointID": "45b118cabc4a5ca41a968f3d382045a9a1b62939f0a871cedb64a3f0068a0aec",
                "MacAddress": "02:42:ac:14:00:1b",
                "IPv4Address": "172.20.0.27/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]
</code>```

```<code>sudo docker network inspect bridge
[
    {
        "Name": "bridge",
        "Id": "3e046a2f4038ab5cf2c2989c7c7adb2bb2f75cd75fef18d133cc7d6952b8fa72",
        "Created": "2020-02-14T13:25:50.571033335+03:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]
</code>```

```<code>sudo docker info

Client:
 Debug Mode: false

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 117
 Server Version: 19.03.5-ce
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: d50db0a42053864a270f648048f9a8b4f24eced3.m
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.5.2-1-MANJARO
 Operating System: Manjaro Linux
 OSType: linux
 Architecture: x86_64
 CPUs: 8
 Total Memory: 31.33GiB
 Name: gemini-f5
 ID: EXYX:H5OE:U74F:HHTF:6P4M:B7HJ:YEXR:S34A:PPXJ:W56Z:BI3D:2DXI
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  dockerregistry.smart-dn.ru:5000
  127.0.0.0/8
 Live Restore Enabled: false
</code>```

答:
hi we have same problems sometimes when using nfs share volumes,sometimes on filesystem,all depend on how many volumes you have.

Simple answer is docker is not build to start up lots of containers.

Our production server when we make once per mont maintance (rebooting) starting 100 containers somtimes even 1 hour. producing not only filesystem (IO read/write) errors.

Try to find a way to block these

pushed as notifications in my manjaro KDE

containers will eventualy start up
we didnt find any solution

our stable workaround was rancher.com and another servers. Rancher helped in way of self distributing containers to server with low resource usage.

Title: Docker: Filesystem is not responding

Body:
I have to run 43 containers on the local machine.

Each startup I have warnings

WARNING: Connection pool is full, discarding connection: localhost

Warning don't block my work

But sometimes at containers startup, I got multiple errors below

Filesystem is not responding
Filesystem mounted at /var/lib/docker/overlay/{hash}/merged is not responding

A lot of them pushed as notifications in my manjaro KDE
These errors block my work, containers not working. Only reboot helps me.

I will provide any additional information you need

Filesystem is ext4
Storage driver: overlay2

docker system df
TYPE                TOTAL               ACTIVE              SIZE                RECLAIMABLE
Images              16                  10                  3.82GB              1.198GB (31%)
Containers          43                  43                  1.138MB             0B (0%)
Local Volumes       20                  10                  1.947GB             955.4MB (49%)
Build Cache         0                   0                   0B                  0B

sudo docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
3e046a2f4038        bridge              bridge              local
8aadcba2673b        dev_default         bridge              local
0f58cf29be50        host                host                local
dace3c787c02        none                null                local

sudo docker network inspect dev_default
[
    {
        "Name": "dev_default",
        "Id": "8aadcba2673b48477a439252f9528493511d63d017acbe7981893e9abc8ef1ce",
        "Created": "2020-02-14T13:40:06.643398755+03:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.20.0.0/16",
                    "Gateway": "172.20.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "016e0d8ec547831d3cb4ed971ccc9d4dd7c21d7bbd17d2295d9b6c2f37250ce1": {
                "Name": "dev_emulator-22800014_1",
                "EndpointID": "4d665c749b325820aac33d415baa8467e49b549c928d730b0fd16a01423f94c9",
                "MacAddress": "02:42:ac:14:00:0a",
                "IPv4Address": "172.20.0.10/16",
                "IPv6Address": ""
            },
            "060a555c3a813188d49c06d22170eab6555b4acf6f532bf3c7dd7ea82f01b5fb": {
                "Name": "dev_emulator-22800038_1",
                "EndpointID": "85a43daca97c55f2ea2c83401468ba64315997f8c817d22fc81a2b54283236dc",
                "MacAddress": "02:42:ac:14:00:10",
                "IPv4Address": "172.20.0.16/16",
                "IPv6Address": ""
            },
            "06aba1b6a003e42388fd4d4feaa66ab8f2fbab853bf32bf74ef50050cba30ae6": {
                "Name": "dev_emulator-22800015_1",
                "EndpointID": "2541a4e7d05c88ea2a6bccc3280b5eac8437646ed07fa13d6bd00a65aae0331d",
                "MacAddress": "02:42:ac:14:00:12",
                "IPv4Address": "172.20.0.18/16",
                "IPv6Address": ""
            },
            "085d84226f8aa471ccbf784f7c34be362371d481d7a157ec87538c631c85868a": {
                "Name": "dev_emulator-19400017_1",
                "EndpointID": "0bef199879d04a55e0916d943cef1e883cf0032a32fc7c6ff6cc71bc2eb5d397",
                "MacAddress": "02:42:ac:14:00:15",
                "IPv4Address": "172.20.0.21/16",
                "IPv6Address": ""
            },
            "09fbe0b08f81f1b30a056bcddbf02bafe50f5367447eea52393d6f85fe9e6e95": {
                "Name": "dev_emulator-19400019_1",
                "EndpointID": "0ab5142fa4f578b23600e0a1b00433009368a82efad15cb7b29273095b4ddb81",
                "MacAddress": "02:42:ac:14:00:20",
                "IPv4Address": "172.20.0.32/16",
                "IPv6Address": ""
            },
            "160f645c05d1a7ca3c7189a24cbd1aa598ae64a0eced259580e5475544556e99": {
                "Name": "dev_emulator-22800016_1",
                "EndpointID": "3b376a61b5bd383b4ac92ad959bce1d51fa8f189bb8dc54c086ad0e7ad0c0ee3",
                "MacAddress": "02:42:ac:14:00:02",
                "IPv4Address": "172.20.0.2/16",
                "IPv6Address": ""
            },
            "18d5f68d2f5d5fc2d39ecad9d16bdb75af91d74626ac77c559fd508c2e75e1e8": {
                "Name": "dev_emulator-19400031_1",
                "EndpointID": "771bb76578e24aba74f4780b5e3f02d7aa03bd1e6c6b0311ca8a4e66fcd00ea3",
                "MacAddress": "02:42:ac:14:00:16",
                "IPv4Address": "172.20.0.22/16",
                "IPv6Address": ""
            },
            "23c427c2b75f27b79f2fe83eb9d361d506786fc2f702d5b854d443d14683b0da": {
                "Name": "dev_tdiRelay_1",
                "EndpointID": "00331149f91abef709e1eb494a937cbe534ef4bfa5da137edb648e748ff800e0",
                "MacAddress": "02:42:ac:14:00:2b",
                "IPv4Address": "172.20.0.43/16",
                "IPv6Address": ""
            },
            "272c718eaa25a45952eceb860d875418b6ba6a68db026733052e67b7efa3ab8d": {
                "Name": "dev_tdiParser_1",
                "EndpointID": "02fecfde12e183c6ece57f1ab96b858fb4e3b0f1977a47a00f61ce9ece7960fa",
                "MacAddress": "02:42:ac:14:00:2c",
                "IPv4Address": "172.20.0.44/16",
                "IPv6Address": ""
            },
            "29e9a0e3fa9eff5185fc6dda092f4358140c4ca852d97f31c31c77055b1ffe60": {
                "Name": "dev_emulator-19400013_1",
                "EndpointID": "4a501dcf83ba64273512a5381c562abbdc5dba0d0b6d01fe68a03499674e2f15",
                "MacAddress": "02:42:ac:14:00:0f",
                "IPv4Address": "172.20.0.15/16",
                "IPv6Address": ""
            },
            "2cb4e8011fa4c338803f546dfb9181936030cae6d3d4eddddd7af0a04137f2b6": {
                "Name": "dev_emulator-22800010_1",
                "EndpointID": "0dc1d7639077e18c511b75638f9995e5a052914da6e14bca174fd6a8217ca2d4",
                "MacAddress": "02:42:ac:14:00:17",
                "IPv4Address": "172.20.0.23/16",
                "IPv6Address": ""
            },
            "408a7b4f1f1c92be7022f514775ebc93fd6359237b74704da73ee51b158cbfe2": {
                "Name": "dev_emulator-22800031_1",
                "EndpointID": "380cfac2b1200c530d5c665b5290d8930448ed39c56710d29fe191af5e748d7d",
                "MacAddress": "02:42:ac:14:00:0d",
                "IPv4Address": "172.20.0.13/16",
                "IPv6Address": ""
            },
            "43bda6ed5698b59d90fa1479547efa2c4bbcec187b03d4990632217bbb4cec9c": {
                "Name": "dev_emulator-22800018_1",
                "EndpointID": "c77dac271dedc5d05968a17fbf665358ba214d03a67dca082c37668410d0f1a2",
                "MacAddress": "02:42:ac:14:00:18",
                "IPv4Address": "172.20.0.24/16",
                "IPv6Address": ""
            },
            "44a1e95f87f1eac91bfc06a16a32b8b478df871af9b9d1d9bf095e6f2b075e5a": {
                "Name": "dev_maintempdb_1",
                "EndpointID": "4021ea4e27729adeaa81b7d0bd6f7c67be17734c4d67b14d660880f7c0531f37",
                "MacAddress": "02:42:ac:14:00:05",
                "IPv4Address": "172.20.0.5/16",
                "IPv6Address": ""
            },
            "554f1a422ece3eb0558a747ef6d63dba6b0e9d019c438d118ded9ff76ef176df": {
                "Name": "dev_emulator-19400040_1",
                "EndpointID": "f2a3bb793ab5be3e7c1276d38b3ad3a922ea0a901fa990e356a722875aa1556a",
                "MacAddress": "02:42:ac:14:00:14",
                "IPv4Address": "172.20.0.20/16",
                "IPv6Address": ""
            },
            "5932a2cb3803e390ce98ef823610e6f3ca12213e52b9812c2d4b5519b473e709": {
                "Name": "dev_emulator-22800023_1",
                "EndpointID": "81b45bb2b1832a83dab9dfc803e44a724ffd5a6a1bc6e11fc4577b6489b090ed",
                "MacAddress": "02:42:ac:14:00:04",
                "IPv4Address": "172.20.0.4/16",
                "IPv6Address": ""
            },
            "596314ba1bebbb5938735e7559a2cad8a3927a0b222c9a42f6a2abab2184779e": {
                "Name": "dev_mainq_1",
                "EndpointID": "9bc8505918c5bef6132172e90c5b50e4801a213e5fb7f18c54f8a841e0deee26",
                "MacAddress": "02:42:ac:14:00:22",
                "IPv4Address": "172.20.0.34/16",
                "IPv6Address": ""
            },
            "61dea1acffa8eb3508bbf4c90d17fc01b32c7da578682555343d053ca65add04": {
                "Name": "dev_outerdb_1",
                "EndpointID": "4613444ab9c6e33dc6eb35ff0d5400a8d34b1ceeb30d8e1bb2f607ec9fb953db",
                "MacAddress": "02:42:ac:14:00:23",
                "IPv4Address": "172.20.0.35/16",
                "IPv6Address": ""
            },
            "666aa5be6401cd4ac2fe34a74789e0a5e210c46fc43a569448f6f51cc255fa61": {
                "Name": "dev_outerOctave_1",
                "EndpointID": "fc3c5b47a330a68e7b0ff494f1fde3926b429158a1846197d31b11b0aae083cd",
                "MacAddress": "02:42:ac:14:00:29",
                "IPv4Address": "172.20.0.41/16",
                "IPv6Address": ""
            },
            "6f3533a85093ddde99cac38201ab379bbba2948f08da50a4a173be982cea7c2a": {
                "Name": "dev_emulator-22800040_1",
                "EndpointID": "9615b87b9cea2f94ba46b0005d4b73c31cf358446cf3bf3ec94894a25a12241a",
                "MacAddress": "02:42:ac:14:00:0e",
                "IPv4Address": "172.20.0.14/16",
                "IPv6Address": ""
            },
            "7100bd89110864bc254023ffb53bab12883897c42ba7cd5adb29a8b894150f20": {
                "Name": "dev_emulator-22800033_1",
                "EndpointID": "2bb75565256cb335c1f076e2e4ef4acc5623e0d0bdf4aa1b7c0514fa4eb04f51",
                "MacAddress": "02:42:ac:14:00:09",
                "IPv4Address": "172.20.0.9/16",
                "IPv6Address": ""
            },
            "801f8d9ddeebf4c1e5f692797cdd65650cd09e05b23eab4e7886cc183c79b6c3": {
                "Name": "dev_emulator-19400016_1",
                "EndpointID": "e0b0f28260a5a03c79b7f41f1bf8db9640848c6d0aed35d6fdd53cba03d61366",
                "MacAddress": "02:42:ac:14:00:0b",
                "IPv4Address": "172.20.0.11/16",
                "IPv6Address": ""
            },
            "809d22241a480f9192f29edc5d03e79db33043cc9bfa763639e67e8cfdd80f0e": {
                "Name": "dev_emulator-19400015_1",
                "EndpointID": "638e6b1cddd1fe78a11de8622ab42ca8ee967303330277e2187261b426aa2f8b",
                "MacAddress": "02:42:ac:14:00:1e",
                "IPv4Address": "172.20.0.30/16",
                "IPv6Address": ""
            },
            "86995a099365f63f6112c25e3e784f6610ae278702c812b61370e186ca53e2ad": {
                "Name": "dev_s3storage_1",
                "EndpointID": "e4c8299d772eaa6a57a63bd351585ec5785c09f6df2e785730ae41d4ff3a25f2",
                "MacAddress": "02:42:ac:14:00:19",
                "IPv4Address": "172.20.0.25/16",
                "IPv6Address": ""
            },
            "8b8e754c99ff6226e8ccd03a150173dfb06e6309c9774c263ae006d9f53f52aa": {
                "Name": "dev_emulator-22800022_1",
                "EndpointID": "dbd31d8e3150192e87b8917927d07729e0603f5288dcc9f296650f34f06c37ee",
                "MacAddress": "02:42:ac:14:00:1c",
                "IPv4Address": "172.20.0.28/16",
                "IPv6Address": ""
            },
            "8cf73e2e2503e52bfcafbc1c9322b994127df20c359ca624be644210abd57dbc": {
                "Name": "dev_tileserver_1",
                "EndpointID": "77374f4cde143d455c0f062e673008c8b41fe4b2977392c9982bc0052217c6c3",
                "MacAddress": "02:42:ac:14:00:03",
                "IPv4Address": "172.20.0.3/16",
                "IPv6Address": ""
            },
            "8e05504ce48d890fa9359938c533b4495814e67f36c8c5b24a736812a5eb0e2f": {
                "Name": "dev_emulator-19400028_1",
                "EndpointID": "9d26d053da0d0945d3ff707bccba3cbb12fb81f295678c3604ad60eb9aa9ef2c",
                "MacAddress": "02:42:ac:14:00:1f",
                "IPv4Address": "172.20.0.31/16",
                "IPv6Address": ""
            },
            "968b41556187c66cb31e623b063d3acf594eb6abac0aa5444bc85d017a807ba6": {
                "Name": "dev_outerWeb_1",
                "EndpointID": "1959455650da340d1d59f8d6011b88657371d7e7e2db02db69462b6747835f97",
                "MacAddress": "02:42:ac:14:00:28",
                "IPv4Address": "172.20.0.40/16",
                "IPv6Address": ""
            },
            "9a12736c89c8005b32ff9f11283dfbd666ad201fbd9a45bb1c5ad0f20b5f52eb": {
                "Name": "dev_emulator-19400011_1",
                "EndpointID": "c23c6ac83769cf06ccc856a47aa0859a9da3f942e7e792384842dde54564e463",
                "MacAddress": "02:42:ac:14:00:25",
                "IPv4Address": "172.20.0.37/16",
                "IPv6Address": ""
            },
            "9d12ef78d15fec44b4fa42878c4268d1ec4ac21db4f694bc02d208acd1b561df": {
                "Name": "dev_emulator-19400012_1",
                "EndpointID": "e0f1c3f68bdfa4e7205b6ea8acad4ec791393139e54fc823b9cc7e079c2e419a",
                "MacAddress": "02:42:ac:14:00:07",
                "IPv4Address": "172.20.0.7/16",
                "IPv6Address": ""
            },
            "b2958a80d70e47692c9ac69314b4fd69acc3e18760f644dceb8142d23d046b3a": {
                "Name": "dev_emulator-22800007_1",
                "EndpointID": "c285a1c6e276ff364bbb72d60ba94eea247aa524d6e9477de8fb92f60b4a8f83",
                "MacAddress": "02:42:ac:14:00:0c",
                "IPv4Address": "172.20.0.12/16",
                "IPv6Address": ""
            },
            "b7f4d47981571d0970c1db4dc065a1c93186287b50938b1f1e5acc972678735b": {
                "Name": "dev_emulator-19400014_1",
                "EndpointID": "8625c39b48c0000b79c13b1d1f21ba07ce16b8813cf786a94ceedc8a84cda55d",
                "MacAddress": "02:42:ac:14:00:06",
                "IPv4Address": "172.20.0.6/16",
                "IPv6Address": ""
            },
            "c08e59d978c478cd6bb8c30b1ff0dc51b10ac10fc616e6fc24d3600391d4b3da": {
                "Name": "dev_emulator-19400020_1",
                "EndpointID": "1b629f69d2364e39375cd4cb4e42bd5e34332e468b04169a7fcaa167d58f3f19",
                "MacAddress": "02:42:ac:14:00:24",
                "IPv4Address": "172.20.0.36/16",
                "IPv6Address": ""
            },
            "c84a447df4e5b632e042e567033d243017b6f0ba58f97be1222110d50b1019b3": {
                "Name": "dev_emulator-19400023_1",
                "EndpointID": "642b31dd4818063828c9889237416aa7b297391fe557530e11959c971278d0dd",
                "MacAddress": "02:42:ac:14:00:26",
                "IPv4Address": "172.20.0.38/16",
                "IPv6Address": ""
            },
            "ca15d4fee3f45b8d8a7552aaa519563d2b1b8ea13c51c0c0d1cd94765cf94512": {
                "Name": "dev_emulator-19400009_1",
                "EndpointID": "8a62973b92ad70a6aad08b717c1ff26fd781cd97e341d2d8ed753a2d2294d00e",
                "MacAddress": "02:42:ac:14:00:11",
                "IPv4Address": "172.20.0.17/16",
                "IPv6Address": ""
            },
            "cb4fd70cdb8dac59bff2c0257224dc1d261df2770b50221132e5a23997afd1d6": {
                "Name": "dev_maineternaldb_1",
                "EndpointID": "d4cec9ce4110dd188bf7c958b89433d40d436b46f212fbdf35c0dcbcdf0831b9",
                "MacAddress": "02:42:ac:14:00:08",
                "IPv4Address": "172.20.0.8/16",
                "IPv6Address": ""
            },
            "e4d60f497831a9c38ebf96a2d48aed8bfb26928a2ed76ba2b8e77139c4b832bc": {
                "Name": "dev_emulator-22800004_1",
                "EndpointID": "61a18f0b561336186ca3bf01a8b3439396f9c76e3ba76b28c7ec355441be2dd9",
                "MacAddress": "02:42:ac:14:00:21",
                "IPv4Address": "172.20.0.33/16",
                "IPv6Address": ""
            },
            "e79451e6ad59896d21fcd88301ce099917ef96ea3d32a3060cb79978b6421fcf": {
                "Name": "dev_emulator-19400036_1",
                "EndpointID": "e3303c42d1b0ebac104762b989229773501b3a8e5b5c7059c765543e3031e8b6",
                "MacAddress": "02:42:ac:14:00:1a",
                "IPv4Address": "172.20.0.26/16",
                "IPv6Address": ""
            },
            "ead3cffd714f12160dde8e35bae0222b521d6264338267edf9c00bbb11b0ebde": {
                "Name": "dev_mainOctave_1",
                "EndpointID": "e5f4c078e4b1ed13fd52eb5740f38c59760388a8bed6b01549841a649db6fb94",
                "MacAddress": "02:42:ac:14:00:2a",
                "IPv4Address": "172.20.0.42/16",
                "IPv6Address": ""
            },
            "ec9aeb9218cef0b8176e3713258812dfcfba5baa691b9639e50fe965b5681cea": {
                "Name": "dev_outerq_1",
                "EndpointID": "69756ebf2b6a1bdceff4f37fe1dad22859983f417bdbe8e4ab82bd23668500fc",
                "MacAddress": "02:42:ac:14:00:13",
                "IPv4Address": "172.20.0.19/16",
                "IPv6Address": ""
            },
            "f2b86f1ae769358a413c94d6bc7c129e50cdf2a6afe12d86be1e5b85fce6cad7": {
                "Name": "dev_web2_1",
                "EndpointID": "0efa83f1aaef42831b312582fbd7ac25c202f7650d237ea30c72de01eaffd1a8",
                "MacAddress": "02:42:ac:14:00:27",
                "IPv4Address": "172.20.0.39/16",
                "IPv6Address": ""
            },
            "f3ed055ec5f6a6bf6ab73b6db24a495e531e2078694ad523723880e9ae7627e7": {
                "Name": "dev_emulator-77700000_1",
                "EndpointID": "a3ecfc5de45ba1bc0dd491f6dc4052034b077d0e3f717f182751b2a29e42e850",
                "MacAddress": "02:42:ac:14:00:1d",
                "IPv4Address": "172.20.0.29/16",
                "IPv6Address": ""
            },
            "fca06c99c6f6140161a007bab98e885f468a40a21318f9b7be2fdec322645db9": {
                "Name": "dev_maincouchdb_1",
                "EndpointID": "45b118cabc4a5ca41a968f3d382045a9a1b62939f0a871cedb64a3f0068a0aec",
                "MacAddress": "02:42:ac:14:00:1b",
                "IPv4Address": "172.20.0.27/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {}
    }
]

sudo docker network inspect bridge
[
    {
        "Name": "bridge",
        "Id": "3e046a2f4038ab5cf2c2989c7c7adb2bb2f75cd75fef18d133cc7d6952b8fa72",
        "Created": "2020-02-14T13:25:50.571033335+03:00",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.17.0.0/16",
                    "Gateway": "172.17.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]

sudo docker info

Client:
 Debug Mode: false

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 117
 Server Version: 19.03.5-ce
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: false
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: d50db0a42053864a270f648048f9a8b4f24eced3.m
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.5.2-1-MANJARO
 Operating System: Manjaro Linux
 OSType: linux
 Architecture: x86_64
 CPUs: 8
 Total Memory: 31.33GiB
 Name: gemini-f5
 ID: EXYX:H5OE:U74F:HHTF:6P4M:B7HJ:YEXR:S34A:PPXJ:W56Z:BI3D:2DXI
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  dockerregistry.smart-dn.ru:5000
  127.0.0.0/8
 Live Restore Enabled: false


来源: stackexchange

问:
ReactJS: Saving a value in localStorage with useReducer
Hello I have a problem saving my current theme. Basically I can change the theme normally, but when I update the page it goes back to my light theme.

I can't find a solution to save my state type in localstorage.

Code:

```<code>export default function App() {
  const [theme, setTheme] = usePersistedState('light');
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? { type: 'dark' } : { type: 'light' });
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />
      <div className="App">
        <button onClick={toggleTheme}>a</button>
      </div>
    </ThemeProvider>
  );
}
</code>```

My hook:

```<code>    function usePersistedState(key) {
      const getTheme = themeType => () => {
        switch (themeType) {
          case 'dark':
            return darkTheme;
          case 'light':
            return lightTheme;
          default:
            return lightTheme;
        }
      };

      const reducer = (state, action) => {
        // this will run on every state change (on every dispatch call)
        return getTheme(action.type)();
      };

      const [state, dispatch] = useReducer(reducer, null, getTheme(key)); // first argument is the reducer function. second argument is the initial state. third argument is an init function (for complex initialization)

      console.log(state);
        useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(state.type));
  }, [key, state]);
</code>```

Example:

答:
Another approach to implementing a persisted state hook would be to extend the regular setState hook with persistence logic "wrapped" around the setter method that setState provides.

This added persistence logic would store the most recent state value (provided by client code) to localStorage, effectivly synchronizing your persistance layer with the most recent state value set:

function usePersistedState(key, mapper, defaultKey) {

  const [state, setState] = useState();

  useEffect(() => {

    /* Called once on component mount. Load persisted JSON
    once, parse JSON, and apply to the hook's local runtime state */
    const persistKey = localStorage.getItem(key);

    setState(mapper(persistKey || defaultKey));
  }, []);

  const setStateAndPersist = (newKey) => {

    /* Intercept setState, at which point we update local storage on
    the nominated key to reflect the most recent state value set by
    client code */
    localStorage.setItem(key, newKey);

    setState(mapper(newKey));
  }

  /* Expose theme state, and intercepted setter function */
  return [state, setStateAndPersist];
}
```

<p>The <code>useEffect</code> hook is also used to load any previously persisted state for the <code>key</code>, into the <code>usePersistedState</code> hooks local state. Note that <code>useEffect</code> has a <code>[]</code> passed as the second argument, which ensure that the effect is only run once (seeing we only want to load persisted state once during the <code>usePersistedState</code> hooks lifecycle). </p>

<p>This hook would then require the following changes in your code:</p>

```const [themeKey, setTheme] = usePersistedState('theme-key', (themeType) => {
 switch (themeType) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
}, 'light');
```

Hope that helps!

ContentLicense: CC BY-SA 4.0

Body:
Hello I have a problem saving my current theme. Basically I can change the theme normally, but when I update the page it goes back to my light theme.

I can't find a solution to save my state type in localstorage.

Code:

export default function App() {
  const [theme, setTheme] = usePersistedState('light');
  const toggleTheme = () => {
    setTheme(theme.type === 'light' ? { type: 'dark' } : { type: 'light' });
  };
  return (
    <ThemeProvider theme={theme}>
      <GlobalStyle />

        <button onClick={toggleTheme}>a</button>

    </ThemeProvider>
  );
}

My hook:

    function usePersistedState(key) {
      const getTheme = themeType => () => {
        switch (themeType) {
          case 'dark':
            return darkTheme;
          case 'light':
            return lightTheme;
          default:
            return lightTheme;
        }
      };

      const reducer = (state, action) => {
        // this will run on every state change (on every dispatch call)
        return getTheme(action.type)();
      };

      const [state, dispatch] = useReducer(reducer, null, getTheme(key)); // first argument is the reducer function. second argument is the initial state. third argument is an init function (for complex initialization)

      console.log(state);
        useEffect(() => {
    localStorage.setItem('theme', JSON.stringify(state.type));
  }, [key, state]);

Example:

Body:
Another approach to implementing a persisted state hook would be to extend the regular setState hook with persistence logic "wrapped" around the setter method that setState provides.

This added persistence logic would store the most recent state value (provided by client code) to localStorage, effectivly synchronizing your persistance layer with the most recent state value set:

function usePersistedState(key, mapper, defaultKey) {

  const [state, setState] = useState();

  useEffect(() => {

    /* Called once on component mount. Load persisted JSON
    once, parse JSON, and apply to the hook's local runtime state */
    const persistKey = localStorage.getItem(key);

    setState(mapper(persistKey || defaultKey));
  }, []);

  const setStateAndPersist = (newKey) => {

    /* Intercept setState, at which point we update local storage on
    the nominated key to reflect the most recent state value set by
    client code */
    localStorage.setItem(key, newKey);

    setState(mapper(newKey));
  }

  /* Expose theme state, and intercepted setter function */
  return [state, setStateAndPersist];
}

The useEffect hook is also used to load any previously persisted state for the key, into the usePersistedState hooks local state. Note that useEffect has a [] passed as the second argument, which ensure that the effect is only run once (seeing we only want to load persisted state once during the usePersistedState hooks lifecycle).

This hook would then require the following changes in your code:

const [themeKey, setTheme] = usePersistedState('theme-key', (themeType) => {
 switch (themeType) {
      case 'dark':
        return darkTheme;
      case 'light':
        return lightTheme;
      default:
        return lightTheme;
    }
}, 'light');

Hope that helps!


问:
Three.js 2D object collision with raycaster
I'm trying to detect collision of two 2D object (for example, two THREE.CircleGeometry) on a plane.

My question: is there a recommended method to detect 2D objet collision? I have 2 attempts below but they are both bad. If anyone has experience on this before, would you please help? Thank you in advance.

Here is my 1st attempt:

```<code>//'player' is the Circle that I'm controlling. In the scene, there is another position-fixed circle, called 'target'.
// I hope to cast a ray from player to the target and detect collision.
// 'mouse' is a normalized direction THREE.Vector3()

raycaster.set(player.position, mouse);
var intersects = raycaster.intersectObjects( scene.children );
for ( var i = 0; i < intersects.length; i++ ) {
    console.log("TEST");
    intersects[ i ].object.material.color.set( 0xff0000 );
}
</code>```

Obviously that didn't work. I already realized raycaster does not seem to work on 2D object. (I tested with 3D object, and it worked perfectly fine).

Here comes the 2nd attempt:

```<code>var dis = distance(target.position, player.position);
if (dis < 1) {
target.material.color.set(0xff0000);
}
</code>```

This method works and I can detect collision between the two circles: player and target. HOWEVER, it leads to really bad performance, because it's absolutely non-necessary to check thousands of targets per render().

If anyone has any thoughts or any recommended reading, would you please advise? I tried to search online but most tutorial and examples are for 3D collision. Thanks in advance.

答:
I know this is a old post, but maybe other person need.

I recommend the second methods thats you propos, but using a subset of the circles.

In a hypotetical map, you have 1000000 obstacles, of course, if you check the collision to every obstacle, you go to end few years later, but if you have a grid on the map, and place this circles in cells corresponding to the posicitions, the you can compare onlie the circles around the player, comparing onli the circles of the cells occuped for the player.

In thas ways is fast if you do a simple collision verification for this circles.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to detect collision of two 2D object (for example, two THREE.CircleGeometry) on a plane.

My question: is there a recommended method to detect 2D objet collision? I have 2 attempts below but they are both bad. If anyone has experience on this before, would you please help? Thank you in advance.

Here is my 1st attempt:

//'player' is the Circle that I'm controlling. In the scene, there is another position-fixed circle, called 'target'.
// I hope to cast a ray from player to the target and detect collision.
// 'mouse' is a normalized direction THREE.Vector3()

raycaster.set(player.position, mouse);
var intersects = raycaster.intersectObjects( scene.children );
for ( var i = 0; i < intersects.length; i++ ) {
    console.log("TEST");
    intersects[ i ].object.material.color.set( 0xff0000 );
}

Obviously that didn't work. I already realized raycaster does not seem to work on 2D object. (I tested with 3D object, and it worked perfectly fine).

Here comes the 2nd attempt:

var dis = distance(target.position, player.position);
if (dis < 1) {
target.material.color.set(0xff0000);
}

This method works and I can detect collision between the two circles: player and target. HOWEVER, it leads to really bad performance, because it's absolutely non-necessary to check thousands of targets per render().

If anyone has any thoughts or any recommended reading, would you please advise? I tried to search online but most tutorial and examples are for 3D collision. Thanks in advance.


问:
Upgrading Doctrine Migrations
I am getting this warning on my codebase, here's my composer

```<code>Package zendframework/zend-eventmanager is abandoned, you should avoid using it. Use laminas/laminas-eventmanager instead.
</code>```

So I needed to upgrade Doctrine Migrations bundle, but I can't seem to upgrade it, and I can't find an upgrade log.
First I get errors about Doctrine\DBAL\Migrations\AbstractMigration, so I replaced them all to Doctrine\Migrations\AbstractMigration. Now I'm getting

```<code>Compile Error: Declaration of Application\Migrations\Version20170927104049::up(Doctrine\DBAL\Schema\Schema $schema) must be compatible with Doctrine\Migrations\AbstractMigration::up(Doctrine\DB
  AL\Schema\Schema $schema): void
</code>```

I asked for a CHANGELOG https://github.com/doctrine/DoctrineMigrationsBundle/issues/296

But anyhelp would be greatly appreciated

答:
You should start by upgrading your packages through composer upgrade - for example, in your composer.lock, you are using ocramius/proxy-manager in a version of that bundle that is nearly three years old, and this requires the abandoned package. The name change from zendframework/zend-eventmanager to laminas/laminas-eventmanager has happened in 2019.

A next step might be to upgrade the constraints such that you require even newer packages. For example, there are much more recent versions of doctrine/doctrine-migrations-bundle or symfony/swiftmailer-bundle, and updating them from time to time helps to avoid problems. As the gap between the installed version and a more recent version gets larger and larger, the upgrading process gets more complex too.

On the other hand: if your code is still working properly, you can simply ignore that warning. It tells you that the given package will not receive any updates after all, but that does not mean you are in danger immediately

Title: Upgrading Doctrine Migrations

Body:
I am getting this warning on my codebase, here's my composer

Package zendframework/zend-eventmanager is abandoned, you should avoid using it. Use laminas/laminas-eventmanager instead.

So I needed to upgrade Doctrine Migrations bundle, but I can't seem to upgrade it, and I can't find an upgrade log.
First I get errors about Doctrine\DBAL\Migrations\AbstractMigration, so I replaced them all to Doctrine\Migrations\AbstractMigration. Now I'm getting

Compile Error: Declaration of Application\Migrations\Version20170927104049::up(Doctrine\DBAL\Schema\Schema $schema) must be compatible with Doctrine\Migrations\AbstractMigration::up(Doctrine\DB
  AL\Schema\Schema $schema): void

I asked for a CHANGELOG https://github.com/doctrine/DoctrineMigrationsBundle/issues/296

But anyhelp would be greatly appreciated


问:
Where is the executable zplug file in Ubuntu after apt install zplug?
I'm trying to test my dotfiles in ubuntu (in a docker container);

I'm using zplug, I already installed it via sudo apt install zplug, but the path isn't set properly (zsh: command not found: zplug).

So which directory has to be added to path to run zplug?

答:
I found init.zsh in /usr/share/zplug/init.zsh
So, after $ source /usr/share/zplug/init.zsh I have zplug available


问:
Can a dask.distributed cluster autoscale different workers independently?
I'd like to set up a dask cluster with a number of different types of workers e.g. normal workers, high-memory workers, GPU workers, ...

As I understand it I can manually create the workers and tag them with resources. What I'd like to do is create a cluster, specifying the min/max number of each type of worker and have it autoscale the exact number of each type of worker based on the number of tasks requesting each type of worker/resource.

Is this possible now or is this something which is on the roadmap (issue I can subscribe to)?

答:
Is this possible now

As of 2020-02-15 this is not a supported behavior

or is this something which is on the roadmap (issue I can subscribe to)?

Dask isn't centrally managed, and so doesn't have a roadmap.  I don't know of any issue about this today, but I wouldn't be surprised if one already existed.


问:
Cypress test fails for asserting equal to DOM title
Working on a project created with the @vue/cli 4.2.2 and Vue CLI Electron Plugin Builder. Vue CLI uses the HtmlWebpackPlugin that automatically generates the index.html in the public directory. The </title> of the relevant index.html page has the <%= htmlWebpackPlugin.options.title %> syntax that automatically detects the title of the page from the vue.config.js file.

vue.config.js

module.exports = {
  pluginOptions: {
    electronBuilder: {
      chainWebpackRendererProcess: config => {
        config.plugin("html").tap(args => {
          args[0].title = "Stack Overflow";
          return args;
        });
      }
    }
  }
};
```

<p>The problem is that when the app starts, there's a millisecond flash where the page title changes from <strong>stackoverflow</strong> to <strong>Stack Overflow</strong>. To prevent this, I used the Electron <code>page-title-updated</code> hook like the following to make sure the app title loads correctly.</p>

<p><code>main.js</code></p>

<pre class="lang-js prettyprint-override"><code>var win = new BrowserWindow({
  width: 800,
  height: 600,
  title: 'Stack Overflow'
});

win.on('page-title-updated', (evt) => {
  evt.preventDefault();
});
</code>```

It works great and there's no window flashing in the </title> now but when running e2e test using the Cypress, it just can't find the correct title Stack Overflow and test fails.
test.js

describe("My First Test", () => {
  it("ensures the correct title", () => {
    cy.visit('/').title().should('eq', 'Stack Overflow')
  })
});
```

The result of Cypress test expected stackoverflow to equal Stack Overflow. So, the million dollar question is, how do I get the Cypress test pass?

答:
If you are testing via Vue's script test:e2e, it looks like the test target is the Vue app in the browser, not the electron app.

Of course, you can set title in the Vue app as per this question How can I bind the html  content in vuejs (as well as your mod to the Electon startup) and your Electron app still looks ok.

Title.vue

```

<p><strong>App.vue</strong></p>

<pre class="lang-js prettyprint-override"><code><template>
  <div id="app">
    <Title title="Stack Overflow"></Title>
    ...
  </div>
</template>

<script>
import Title from './components/Title.vue'

export default {
  name: 'App',
  components: {
    Title
  },
}
</script>
</code>```

Now the test passes, but you are still just testing Vue code, not as running in Electron.

See Testing Electron.js applications using Cypress - alpha release for some info that may help you.

Body:
Working on a project created with the @vue/cli 4.2.2 and Vue CLI Electron Plugin Builder. Vue CLI uses the HtmlWebpackPlugin that automatically generates the index.html in the public directory. The </title> of the relevant index.html page has the <%= htmlWebpackPlugin.options.title %> syntax that automatically detects the title of the page from the vue.config.js file.

vue.config.js

module.exports = {
  pluginOptions: {
    electronBuilder: {
      chainWebpackRendererProcess: config => {
        config.plugin("html").tap(args => {
          args[0].title = "Stack Overflow";
          return args;
        });
      }
    }
  }
};

The problem is that when the app starts, there's a millisecond flash where the page title changes from stackoverflow to Stack Overflow. To prevent this, I used the Electron page-title-updated hook like the following to make sure the app title loads correctly.

main.js

var win = new BrowserWindow({
  width: 800,
  height: 600,
  title: 'Stack Overflow'
});

win.on('page-title-updated', (evt) => {
  evt.preventDefault();
});

It works great and there's no window flashing in the </title> now but when running e2e test using the Cypress, it just can't find the correct title Stack Overflow and test fails.
test.js

describe("My First Test", () => {
  it("ensures the correct title", () => {
    cy.visit('/').title().should('eq', 'Stack Overflow')
  })
});

The result of Cypress test expected stackoverflow to equal Stack Overflow. So, the million dollar question is, how do I get the Cypress test pass?

Body:
If you are testing via Vue's script test:e2e, it looks like the test target is the Vue app in the browser, not the electron app.

Of course, you can set title in the Vue app as per this question How can I bind the html  content in vuejs (as well as your mod to the Electon startup) and your Electron app still looks ok.

Title.vue

<script>
  export default {
    name: 'vue-title',
    props: ['title'],
    watch: {
      title: {
        immediate: true,
        handler() {
          document.title = this.title;
        }
      }
    },
    render () {
      return null;
    },
  }
</script>

App.vue

<template>
  <div id="app">
    <Title title="Stack Overflow"></Title>
    ...
  </div>
</template>

<script>
import Title from './components/Title.vue'

export default {
  name: 'App',
  components: {
    Title
  },
}
</script>

Now the test passes, but you are still just testing Vue code, not as running in Electron.

See Testing Electron.js applications using Cypress - alpha release for some info that may help you.


问:
Location updates update only the marker but not the map. Flutter
I'm receiving a stream of Positions , I than update a _positionvariable that is used both in center: to set the map position, and in the Marker I use to show user position.
The problem is that the marker gets updated, but not the map position.
The expected behaviour is that the Marker, stays steady on the centre of the screen while the map moves underneath it, but it happen the opposite. Can you see where I set things wrong?
many thanks for your time and help.

```<code>class HomeScreen extends StatefulWidget {
  final String name;

  HomeScreen({
    Key key,
    @required this.name,
  }) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Geolocator _geolocator;
  Position _position;

  FlutterMap _flutterMap;
  MapOptions _mapOptions;
  MapController _controller;
  void checkPermission() {
    _geolocator.checkGeolocationPermissionStatus().then((status) {
      print('status: $status');
    });
    _geolocator
        .checkGeolocationPermissionStatus(
            locationPermission: GeolocationPermission.locationAlways)
        .then((status) {
      print('always status: $status');
    });
    _geolocator.checkGeolocationPermissionStatus(
        locationPermission: GeolocationPermission.locationWhenInUse)
      ..then((status) {
        print('whenInUse status: $status');
      });
  }

  @override
  void initState() {
    super.initState();
    _geolocator = Geolocator();
    checkPermission();
    updateLocation();
  }

  void setMap() {
    _controller = MapController();
    _mapOptions = MapOptions(
      center: LatLng(_position.latitude, _position.longitude),
      minZoom: 16.0,
      maxZoom: 19.0,
    );
    _flutterMap = FlutterMap(
      options: _mapOptions,
      mapController: _controller,
      layers: [
//        PolygonLayer(polygonOpts, map, stream)
//                    PolygonLayerOptions(
//                      polygons:
//                    ),
        TileLayerOptions(
//        urlTemplate:'https://api.openrouteservice.org/mapsurfer/{z}/{x}/{y}.png?api_key=5b3ce3597851110001cf62484c4b65d85bc844eca3a2c6b9f300ddf4',
            urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            subdomains: ['a', 'b', 'c'],
            keepBuffer: 20),
        new MarkerLayerOptions(
          markers: [
            Marker(
              point: LatLng(_position.latitude, _position.longitude),
              height: 200,
              width: 200,
              builder: (context) => IconButton(
                icon: Icon(Icons.location_on),
                color: Colors.red,
                iconSize: 60,
                onPressed: () {
                  print('icon tapped');
                },
              ),
            ),
          ],
        ),
      ],
    );
  }

  void startTracking() {
    LocationOptions locationOptions =
        LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 0);

    StreamSubscription positionStream = _geolocator
        .getPositionStream(locationOptions)
        .listen((Position position) {
      setState(() {
        _position = position;
        if (_position != null) {
//          _controller.move(LatLng(_position.latitude, _position.longitude), 16);
          setMap();
        }
      });
      print(
          _position.latitude.toString() + ',' + _position.longitude.toString());
    });
  }

  void updateLocation() async {
    try {
      Position newPosition = await _geolocator
          .getCurrentPosition(
            desiredAccuracy: LocationAccuracy.bestForNavigation,
          )
          .timeout(new Duration(seconds: 5));
      print(
          'updateLocation(): ${newPosition.latitude.toString() + ',' + newPosition.longitude.toString()}');

      setState(() {
        _position = newPosition;
        setMap();
      });
    } catch (error) {
      print('Error updating location: ${error.toString()}');
    }
  }

  void postRequest() async {
    print('postRequest called');

    // working properly
//    final request =
//    'http://router.project-osrm.org/trip/v1/driving/44.5018645003438,11.340018709036542;44.501342559233315,11.336182647230146?exclude=motorway';
//    final request = 'http://router.project-osrm.org/trip/v1/driving/44.5018645003438,11.340018709036542;44.501342559233315,11.33618264723014?source=first&destination=last&roundtrip=false&exclude=motorway&generate_hints=false&geometries=geojson&overview=full';
//    final request =
//        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.501342559233315&tlon=11.336182647230146&geometry=1&instructions=1&lang=it';

    // GOOOD
    final request =
        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it';

    // only driving
//    final request =
//        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik';

//    final request =
//        'https://routing.openstreetmap.de/routed-foot/route/v1/driving/13.7807085453224,51.0536161;13.7835429,51.0515885?overview=false&geometries=polyline&steps=true';

    // Await the http get response, then decode the json-formatted response.
    var response = await get(request);
    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body);
      print('${jsonResponse.runtimeType} : $jsonResponse');
      List<dynamic> coordinates = jsonResponse['coordinates'];
      print('coordinates are : $coordinates');
      print('coordinates are: ${coordinates.length}');
      Map<String, dynamic> properties = jsonResponse['properties'];
//      print('properties are $properties');
      String distance = properties['distance'];
      print('Route is $distance Km long.');
      String instructions = properties['description'];
      print('instructions are $instructions');

      List<LatLng> suggestedRoute = [];
      for (int i = 0; i < (coordinates.length); i++) {
        dynamic coordinate = coordinates[i];
        LatLng position = LatLng(coordinate[1], coordinate[0]);
        suggestedRoute.add(position);
        print('position is $position');
        print(i);
      }
      print('suggestedRoute is $suggestedRoute');
    } else {
      print('Request failed with status: ${response.statusCode}.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text(
          'Home',
          style: TextStyle(color: Colors.orangeAccent, fontSize: 40),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.exit_to_app,
              color: Colors.orange,
              size: 35,
            ),
            onPressed: () {
              BlocProvider.of<AuthenticationBloc>(context).add(
                LoggedOut(),
              );
            },
          ),
        ],
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        minimum: EdgeInsets.symmetric(horizontal: 20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 670,
                width: 370,
                child: _flutterMap,

              ),
              SizedBox(
                height: 10,
              ),
              RaisedButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5)),
                onPressed: () {
                  startTracking();
//                  setState(() {
////                    updateLocation();
//                  });
//
                },
                color: Colors.red,
                child: Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    'alert',
                    style: TextStyle(color: Colors.white, fontSize: 30),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
I found the error.
_controller is initialised inside setMap() instead that inside initState(), so when I call _controller.move(LatLng(_position.latitude, _position.longitude), 16); inside startTracking() it thrown the error not having a connection to the map..and didn't move the map.
Having it initialised inside initState() works as expected.
Many thanks

Body:
I'm receiving a stream of Positions , I than update a _positionvariable that is used both in center: to set the map position, and in the Marker I use to show user position.
The problem is that the marker gets updated, but not the map position.
The expected behaviour is that the Marker, stays steady on the centre of the screen while the map moves underneath it, but it happen the opposite. Can you see where I set things wrong?
many thanks for your time and help.

class HomeScreen extends StatefulWidget {
  final String name;

  HomeScreen({
    Key key,
    @required this.name,
  }) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Geolocator _geolocator;
  Position _position;

  FlutterMap _flutterMap;
  MapOptions _mapOptions;
  MapController _controller;
  void checkPermission() {
    _geolocator.checkGeolocationPermissionStatus().then((status) {
      print('status: $status');
    });
    _geolocator
        .checkGeolocationPermissionStatus(
            locationPermission: GeolocationPermission.locationAlways)
        .then((status) {
      print('always status: $status');
    });
    _geolocator.checkGeolocationPermissionStatus(
        locationPermission: GeolocationPermission.locationWhenInUse)
      ..then((status) {
        print('whenInUse status: $status');
      });
  }

  @override
  void initState() {
    super.initState();
    _geolocator = Geolocator();
    checkPermission();
    updateLocation();
  }

  void setMap() {
    _controller = MapController();
    _mapOptions = MapOptions(
      center: LatLng(_position.latitude, _position.longitude),
      minZoom: 16.0,
      maxZoom: 19.0,
    );
    _flutterMap = FlutterMap(
      options: _mapOptions,
      mapController: _controller,
      layers: [
//        PolygonLayer(polygonOpts, map, stream)
//                    PolygonLayerOptions(
//                      polygons:
//                    ),
        TileLayerOptions(
//        urlTemplate:'https://api.openrouteservice.org/mapsurfer/{z}/{x}/{y}.png?api_key=5b3ce3597851110001cf62484c4b65d85bc844eca3a2c6b9f300ddf4',
            urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            subdomains: ['a', 'b', 'c'],
            keepBuffer: 20),
        new MarkerLayerOptions(
          markers: [
            Marker(
              point: LatLng(_position.latitude, _position.longitude),
              height: 200,
              width: 200,
              builder: (context) => IconButton(
                icon: Icon(Icons.location_on),
                color: Colors.red,
                iconSize: 60,
                onPressed: () {
                  print('icon tapped');
                },
              ),
            ),
          ],
        ),
      ],
    );
  }

  void startTracking() {
    LocationOptions locationOptions =
        LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 0);

    StreamSubscription positionStream = _geolocator
        .getPositionStream(locationOptions)
        .listen((Position position) {
      setState(() {
        _position = position;
        if (_position != null) {
//          _controller.move(LatLng(_position.latitude, _position.longitude), 16);
          setMap();
        }
      });
      print(
          _position.latitude.toString() + ',' + _position.longitude.toString());
    });
  }

  void updateLocation() async {
    try {
      Position newPosition = await _geolocator
          .getCurrentPosition(
            desiredAccuracy: LocationAccuracy.bestForNavigation,
          )
          .timeout(new Duration(seconds: 5));
      print(
          'updateLocation(): ${newPosition.latitude.toString() + ',' + newPosition.longitude.toString()}');

      setState(() {
        _position = newPosition;
        setMap();
      });
    } catch (error) {
      print('Error updating location: ${error.toString()}');
    }
  }

  void postRequest() async {
    print('postRequest called');

    // working properly
//    final request =
//    'http://router.project-osrm.org/trip/v1/driving/44.5018645003438,11.340018709036542;44.501342559233315,11.336182647230146?exclude=motorway';
//    final request = 'http://router.project-osrm.org/trip/v1/driving/44.5018645003438,11.340018709036542;44.501342559233315,11.33618264723014?source=first&destination=last&roundtrip=false&exclude=motorway&generate_hints=false&geometries=geojson&overview=full';
//    final request =
//        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.501342559233315&tlon=11.336182647230146&geometry=1&instructions=1&lang=it';

    // GOOOD
    final request =
        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it';

    // only driving
//    final request =
//        'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik';

//    final request =
//        'https://routing.openstreetmap.de/routed-foot/route/v1/driving/13.7807085453224,51.0536161;13.7835429,51.0515885?overview=false&geometries=polyline&steps=true';

    // Await the http get response, then decode the json-formatted response.
    var response = await get(request);
    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body);
      print('${jsonResponse.runtimeType} : $jsonResponse');
      List<dynamic> coordinates = jsonResponse['coordinates'];
      print('coordinates are : $coordinates');
      print('coordinates are: ${coordinates.length}');
      Map<String, dynamic> properties = jsonResponse['properties'];
//      print('properties are $properties');
      String distance = properties['distance'];
      print('Route is $distance Km long.');
      String instructions = properties['description'];
      print('instructions are $instructions');

      List<LatLng> suggestedRoute = [];
      for (int i = 0; i < (coordinates.length); i++) {
        dynamic coordinate = coordinates[i];
        LatLng position = LatLng(coordinate[1], coordinate[0]);
        suggestedRoute.add(position);
        print('position is $position');
        print(i);
      }
      print('suggestedRoute is $suggestedRoute');
    } else {
      print('Request failed with status: ${response.statusCode}.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: Text(
          'Home',
          style: TextStyle(color: Colors.orangeAccent, fontSize: 40),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.exit_to_app,
              color: Colors.orange,
              size: 35,
            ),
            onPressed: () {
              BlocProvider.of<AuthenticationBloc>(context).add(
                LoggedOut(),
              );
            },
          ),
        ],
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        minimum: EdgeInsets.symmetric(horizontal: 20),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 670,
                width: 370,
                child: _flutterMap,

              ),
              SizedBox(
                height: 10,
              ),
              RaisedButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5)),
                onPressed: () {
                  startTracking();
//                  setState(() {
////                    updateLocation();
//                  });
//
                },
                color: Colors.red,
                child: Padding(
                  padding: EdgeInsets.all(8.0),
                  child: Text(
                    'alert',
                    style: TextStyle(color: Colors.white, fontSize: 30),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


问:
How to transform position from one object to the current player position?
So i have this little particlesystem attached on my player so if he dies he explodes. But i cant simply attach the particlesystem under the player because if i destroy my player the childs of the gameobjects get destroyed as well. The animation runs if he dies but not on his current spot so some ideas for that? Maybe to transform the position to the current position of the player while he dies?
Here my code:</p>

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

public class playerdeath : MonoBehaviour
{

    public ParticleSystem death_explosion;

    // Start is called before the first frame update
    void Start()
    {

        death_explosion.Stop();
    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "deathcube")
            Destroy(gameObject);
        Debug.Log("collision detected");
        death_explosion.Play();
    }
}
</code>```

答: got it :) --> add death_explosion.transform.position = GameObject.Find("player").transform.position;

Body:
So i have this little particlesystem attached on my player so if he dies he explodes. But i cant simply attach the particlesystem under the player because if i destroy my player the childs of the gameobjects get destroyed as well. The animation runs if he dies but not on his current spot so some ideas for that? Maybe to transform the position to the current position of the player while he dies?
Here my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playerdeath : MonoBehaviour
{

    public ParticleSystem death_explosion;

    // Start is called before the first frame update
    void Start()
    {

        death_explosion.Stop();
    }

    // Update is called once per frame
    void Update()
    {

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "deathcube")
            Destroy(gameObject);
        Debug.Log("collision detected");
        death_explosion.Play();
    }
}


问:
How to properly declare an N-dimensional queue inline in SystemVerilog?
If I have 2D queue of ints, I would expect to be able to declare it inline like so:

```<code>int my_queue[$][$] = {{1, 2}, {3, 4}};
</code>```

I have also seen

```<code>typedef int int_queue[$];
int_queue my_queue[$] = {{1, 2}, {3, 4}};
</code>```

Instead, when I compile, VCS provides me with an Incompatible Complex Type error:

```<code>  Type of source expression is incompatible with type of target expression.
  Mismatching types cannot be used in assignments, initializations and
  instantiations. The type of the target is 'int$[$][$]', while the type of
  the source is 'bit[63:0]'.
</code>```

Which implies to me that VCS expects the right hand side of the equation to be cast properly. The way around this that I have been using is:

```<code>typedef int int_queue[$];
typedef int_queue int_queue_of_queues[$];
int_queue_of_queues my_queue = int_queue_of_queues'{{1, 2}, {3, 4}};
</code>```

But this adds N extra typedefs and lines for N dimensions, and I would rather do this in one line. If I had a way to cast the right hand side of the declaration without a typedef, then this would be simple, but I don't know if that is possible.

答:
The array concatenation syntax only works on a single dimension.  You cannot nest the {}'s because of cases where there is ambiguity between array {} and integral {} concatenation. You need to use array assignment pattern in the outer, or both dimensions. I prefer using assignment patterns for both dimensions making it clearer that these are array elements, not integral concatenations.

```<code>int my_queue[$][$] = '{'{1, 2}, '{3, 4}};
</code>```

See section 10.10 Unpacked array concatenation in the IEEE 1800-2017
LRM.

Body:
If I have 2D queue of ints, I would expect to be able to declare it inline like so:

int my_queue[$][$] = {{1, 2}, {3, 4}};

I have also seen

typedef int int_queue[$];
int_queue my_queue[$] = {{1, 2}, {3, 4}};

Instead, when I compile, VCS provides me with an Incompatible Complex Type error:

  Type of source expression is incompatible with type of target expression.
  Mismatching types cannot be used in assignments, initializations and
  instantiations. The type of the target is 'int$[$][$]', while the type of
  the source is 'bit[63:0]'.

Which implies to me that VCS expects the right hand side of the equation to be cast properly. The way around this that I have been using is:

typedef int int_queue[$];
typedef int_queue int_queue_of_queues[$];
int_queue_of_queues my_queue = int_queue_of_queues'{{1, 2}, {3, 4}};

But this adds N extra typedefs and lines for N dimensions, and I would rather do this in one line. If I had a way to cast the right hand side of the declaration without a typedef, then this would be simple, but I don't know if that is possible.

Body:
The array concatenation syntax only works on a single dimension.  You cannot nest the {}'s because of cases where there is ambiguity between array {} and integral {} concatenation. You need to use array assignment pattern in the outer, or both dimensions. I prefer using assignment patterns for both dimensions making it clearer that these are array elements, not integral concatenations.

int my_queue[$][$] = '{'{1, 2}, '{3, 4}};

See section 10.10 Unpacked array concatenation in the IEEE 1800-2017
LRM.


问:
regex match line in which the first word repeats elsewhere in the line
I am looking for a way to match a line that has two or more occurrences of a pattern (a word). Example:

```<code>abc cde abc dd
</code>```

should be matched because the sequence abc is present twice. The sequences are always separated by a space. If it helps, it is enough to test for multiple presence of the first word.

答:
Here it is

^(\w{2,}(?=\s)).*\1.*$
```

Explanation

^ means to search the start of a line

(\w*(?=\s)) this part is the first capturing group, \w checks for word characters of any quantity and (?=\s) is a positive lookahead to see if it ends with a whitespace.

The following .* means there can be any characters of any quantity.

Fianlly, \1 matches the same text as most recently matched by the 1st capturing group.

.*$ at the end matches the rest of the line

Body:
I am looking for a way to match a line that has two or more occurrences of a pattern (a word). Example:

abc cde abc dd

should be matched because the sequence abc is present twice. The sequences are always separated by a space. If it helps, it is enough to test for multiple presence of the first word.

Body:
Here it is

^(\w{2,}(?=\s)).*\1.*$

Explanation

^ means to search the start of a line

(\w*(?=\s)) this part is the first capturing group, \w checks for word characters of any quantity and (?=\s) is a positive lookahead to see if it ends with a whitespace.

The following .* means there can be any characters of any quantity.

Fianlly, \1 matches the same text as most recently matched by the 1st capturing group.

.*$ at the end matches the rest of the line


问:
How to add text size to a ListView?
How can I add a text size code here to reduce the default size. Thanks in advance.</p>

```<code>package com.xxx;

public class Score extends AppCompatActivity {
    ListView lstView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score_main);

        mainView = (ListView)findViewById(R.id.mainRanking);
        DbHelper db = new DbHelper(this);
        List<Ranking> mainRanking = db.getRanking();
        if(mainRanking.size() > 0)
        {
            CustomAdapter adapter = new CustomAdapter(this,mainRanking);
            lstView.setAdapter(adapter);
        }
    }
}
</code>```

答:
Add this to your styles.xml:

```<code><style name="ListViewTheme">
    <item name="android:textSize">12sp</item>
</style>
</code>```

And then add this to your ListView tag:

```<code><ListView
    android:id="@+id/mainRanking"
    android:theme="@style/ListViewTheme"
    .../>
</code>```

Title: How to add text size to a ListView?

Body:
How can I add a text size code here to reduce the default size. Thanks in advance.

package com.xxx;

public class Score extends AppCompatActivity {
    ListView lstView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score_main);

        mainView = (ListView)findViewById(R.id.mainRanking);
        DbHelper db = new DbHelper(this);
        List<Ranking> mainRanking = db.getRanking();
        if(mainRanking.size() > 0)
        {
            CustomAdapter adapter = new CustomAdapter(this,mainRanking);
            lstView.setAdapter(adapter);
        }
    }
}

Body:
Add this to your styles.xml:

<style name="ListViewTheme">
    <item name="android:textSize">12sp</item>
</style>

And then add this to your ListView tag:

<ListView
    android:id="@+id/mainRanking"
    android:theme="@style/ListViewTheme"
    .../>


问:
Aerospike - command execution timed out on client
Using the following code to load data in Aerospike. data is a list of maps of type BinMap

```<code>for _, binMap := range data {
   id, ok := binMap["id"].(string)
   key, _ := as.NewKey("test", "myset", id)
   err := shared.Client.Put(nil, key, binMap)
   if err !=nil {
        fmt.Println(err)
 }
</code>```

After loading few records, the following error message is received.

```<code>command execution timed out on client: Exceeded number of retries.
See `Policy.MaxRetries`. (last error: Node not found for partition
test:711 in partition table.)
</code>```

For each iteration, the partition test number changes.
The error continues even after waiting for 5 seconds after each Put command. I am not sure what timeout is reported in the error message.What client configuration is required for go client?

Using MacOs 10.15.3; go client; Aerospike running on docker 2.2.0.3

答: There's a good chance your cluster hasn't formed correctly, or that its networking isn't properly set up to give clients access to all the nodes. Since you're using Docker, take a look at Lucien's Medium post How do I get a 2 nodes Aerospike cluster running quickly in Docker without editing a single file?.</p>

Body:
Using the following code to load data in Aerospike. data is a list of maps of type BinMap

for _, binMap := range data {
   id, ok := binMap["id"].(string)
   key, _ := as.NewKey("test", "myset", id)
   err := shared.Client.Put(nil, key, binMap)
   if err !=nil {
        fmt.Println(err)
 }

After loading few records, the following error message is received.

command execution timed out on client: Exceeded number of retries.
See `Policy.MaxRetries`. (last error: Node not found for partition
test:711 in partition table.)

For each iteration, the partition test number changes.
The error continues even after waiting for 5 seconds after each Put command. I am not sure what timeout is reported in the error message.What client configuration is required for go client?

Using MacOs 10.15.3; go client; Aerospike running on docker 2.2.0.3


问:
How to create ObjectID from its string representation [pyarrow]
I am saving a Python object to the Plasma store in one client, and want to load it in another.  My idea was to pass the ObjectID as part of an HTTP request.  So I have something like:

```<code>import pyarrow.plasma as plasma

client = plasma.connect("/tmp/plasma")
payload = {"a": 1}
object_id = client.put(payload)
object_str = str(object_id)
print(object_str)  # outputs: "ObjectID(8d8e54e5cb547962a6d16ff2869c2c3282ff6550)"
</code>```

In my destination client, I expected that I would be able to do something like:

```<code>import pyarrow.plasma as plasma
client = plasma.connect("/tmp/plasma")

data = client.get("8d8e54e5cb547962a6d16ff2869c2c3282ff6550")
</code>```

But this doesn't work, as client.get is expecting a plasma.ObjectID object, not a string identifier.  But then I cannot find any way to create an plasma.ObjectID object using this identifier.  It says I need to pass in 20-bytes, but I'm not sure how to get the right 20 bytes from this ID.  I have tried things like plasma.ObjectID(b'8d8e54e5cb547962a6d16ff2869c2c3282ff6550') to no avail.

The only thing I've found that works is a hacky solution of listing all the objects in the store like "client.list()", and then string-matching the string representation of the ObjectID keys in the returned dictionary.

If I'm not following the intended design, how do I:

save a python object to Plasma in server 1

pass a reference over HTTP from one server to another

access this object in server 2?

答:
Found the solution.  The printed ObjectID is a hexcode.  You can convert it to bytes like this:</p>

```<code># source
import pyarrow.plasma as plasma
client = plasma.connect("/tmp/plasma")

payload = {"a": 1}
object_id = client.put(payload)
object_str = str(object_id)
print(object_str)  # outputs: "ObjectID(8d8e54e5cb547962a6d16ff2869c2c3282ff6550)"

# client
id_str = "8d8e54e5cb547962a6d16ff2869c2c3282ff6550"
object = plasma.ObjectID(bytes.fromhex(id_str))
data = client.get(object)
</code>```

Body:
I am saving a Python object to the Plasma store in one client, and want to load it in another.  My idea was to pass the ObjectID as part of an HTTP request.  So I have something like:

import pyarrow.plasma as plasma

client = plasma.connect("/tmp/plasma")
payload = {"a": 1}
object_id = client.put(payload)
object_str = str(object_id)
print(object_str)  # outputs: "ObjectID(8d8e54e5cb547962a6d16ff2869c2c3282ff6550)"

In my destination client, I expected that I would be able to do something like:

import pyarrow.plasma as plasma
client = plasma.connect("/tmp/plasma")

data = client.get("8d8e54e5cb547962a6d16ff2869c2c3282ff6550")

But this doesn't work, as client.get is expecting a plasma.ObjectID object, not a string identifier.  But then I cannot find any way to create an plasma.ObjectID object using this identifier.  It says I need to pass in 20-bytes, but I'm not sure how to get the right 20 bytes from this ID.  I have tried things like plasma.ObjectID(b'8d8e54e5cb547962a6d16ff2869c2c3282ff6550') to no avail.

The only thing I've found that works is a hacky solution of listing all the objects in the store like "client.list()", and then string-matching the string representation of the ObjectID keys in the returned dictionary.

If I'm not following the intended design, how do I:

save a python object to Plasma in server 1

pass a reference over HTTP from one server to another

access this object in server 2?

Body:
Found the solution.  The printed ObjectID is a hexcode.  You can convert it to bytes like this:

# source
import pyarrow.plasma as plasma
client = plasma.connect("/tmp/plasma")

payload = {"a": 1}
object_id = client.put(payload)
object_str = str(object_id)
print(object_str)  # outputs: "ObjectID(8d8e54e5cb547962a6d16ff2869c2c3282ff6550)"

# client
id_str = "8d8e54e5cb547962a6d16ff2869c2c3282ff6550"
object = plasma.ObjectID(bytes.fromhex(id_str))
data = client.get(object)


问:
CATransiton Flicker w/ background animations
I am using a CATransition to shuffle CALayer's in and out of a UIView (the UIView isn't fullscreen.)  The new layer enters from the right and the old layer leaves to the left.  The CAlayer's have their contents properties set to CGImageRefs.  Here is what I believe to be the pertinent code:

```<code>CATransition *transition = [CATransition animation];

transition.duration = transitionTime;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;

transition.delegate = self;
[view.layer addAnimation:transition forKey:nil];

// onDeck is the layer stage-right and is about to enter
[view.layer addSublayer:onDeck];

// onStage is the layer currently in the middle of the view and is exiting
if (onStage)
   [onStage removeFromSuperlayer];
</code>```

This animation occurs, there is a 1 second pause, and then a new image is animated in etc, etc.  This works beautifully in the simulator but on my 2nd generation iPod Touch, there are occasional hiccups in the animation.  Specifically, the layer being animated in will flicker on top of the currently displayed layer.  These flickers are not consistent but are noticeable.

What I've narrowed down to be the likely culprit(s) are the background animations I have going on behind this transition.  There are a few dozen CAlayer's flying in and out of the full-screen view in the background.  When I remove these background animations or set the animation duration for the transition to a much higher duration (2 seconds +) the animation performs fine (I'd like the animation time to be 0.75 seconds.)

My first thought (which seems to be backed up by the above observations) is that I am pushing CoreAnimation (at least for my iPod) too hard and need to compromise.  Why I am having trouble accepting this is that the scene renders very nicely (little to no lag) aside from this occasional flicker.

If anyone has any input on this issue, or CoreAnimation optimization in general, I'd be very much appreciative!

Thanks for reading

Update:

Had a chance to test this on an iPhone 4 and the flickering never occurred.  Additionally, CoreAnimation instrument confirmed that, on my 2nd generation iPod Touch, I am consistently getting high 40s to low/mid 50s in FPS.

答: I would get rid of all shadows (if you have any) and then check if performance improves. I've seen that shadows, particularly shadows on CAShapeLayers, have a great impact on the smoothness of animations.</p>

Body:
I am using a CATransition to shuffle CALayer's in and out of a UIView (the UIView isn't fullscreen.)  The new layer enters from the right and the old layer leaves to the left.  The CAlayer's have their contents properties set to CGImageRefs.  Here is what I believe to be the pertinent code:

CATransition *transition = [CATransition animation];

transition.duration = transitionTime;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;

transition.delegate = self;
[view.layer addAnimation:transition forKey:nil];

// onDeck is the layer stage-right and is about to enter
[view.layer addSublayer:onDeck];

// onStage is the layer currently in the middle of the view and is exiting
if (onStage)
   [onStage removeFromSuperlayer];

This animation occurs, there is a 1 second pause, and then a new image is animated in etc, etc.  This works beautifully in the simulator but on my 2nd generation iPod Touch, there are occasional hiccups in the animation.  Specifically, the layer being animated in will flicker on top of the currently displayed layer.  These flickers are not consistent but are noticeable.

What I've narrowed down to be the likely culprit(s) are the background animations I have going on behind this transition.  There are a few dozen CAlayer's flying in and out of the full-screen view in the background.  When I remove these background animations or set the animation duration for the transition to a much higher duration (2 seconds +) the animation performs fine (I'd like the animation time to be 0.75 seconds.)

My first thought (which seems to be backed up by the above observations) is that I am pushing CoreAnimation (at least for my iPod) too hard and need to compromise.  Why I am having trouble accepting this is that the scene renders very nicely (little to no lag) aside from this occasional flicker.

If anyone has any input on this issue, or CoreAnimation optimization in general, I'd be very much appreciative!

Thanks for reading

Update:

Had a chance to test this on an iPhone 4 and the flickering never occurred.  Additionally, CoreAnimation instrument confirmed that, on my 2nd generation iPod Touch, I am consistently getting high 40s to low/mid 50s in FPS.