问:
High query response time for find operation in mongo 4.0.27 with mmap storage engine
Scenario:

We have application which is doing CRUD operations on database. For past 2 years we have been using mongo 3.6.9 and system has been working fine without any issues. When we upgraded the database from 3.6.9 to 4.0.27, we started getting high query response time for find operation but it is not consistent in nature. Sometimes we are getting high query response in 5 hours or 7 hours or even 11 hours.

Testing environment:

java client driver on application side - 3.12.9

mongo version - 4.0.27

Storage Engine - mmap

Replica-set: 7 members (4 non-arbiter and 3 arbiter, all voting members)

One of the member CMD as an example:

```<code>mongod --keyFile=/mongodb.key --storageEngine mmapv1 --nojournal --noprealloc --smallfiles --ipv6 --bind_ip_all --port 27035 --dbpath=/mmapv1-tmpfs-27035 --replSet rs-app_shardAB-ipv6-7 --quiet --slowms 500 --logpath /data/db/mongo-27035.log --oplogSize 3221 --setParameter diagnosticDataCollectionEnabled=true --logappend --logRotate reopen
</code>```

Messages:
As a sample, we got these kind of messages on mongo secondary logs given below:

2022-02-02T02:55:54.392+0000 I COMMAND [conn554] command drasessions_1.drasessions command: find { find: “drasessions”, filter: { _id: { sessionid: “ClpGx3:172.16.241.40:15124:1643368779:0080300316” } }, limit: 1, singleBatch: true, $db: “drasessions_1”, $clusterTime: { clusterTime: Timestamp(1643770525, 464), signature: { hash: BinData(0, A9E0739EB1E3BBA9EF776A9FCEC9342E9457D221), keyId: 7042384422720503811 } }, lsid: { id: UUID(“8b321501-be08-4fa8-ada5-367cc1eb555e”) }, $readPreference: { mode: “nearest” } } planSummary: IDHACK keysExamined:0 docsExamined:0 cursorExhausted:1 numYields:0 nreturned:0 reslen:239 locks:{ Global: { acquireCount: { r: 2 }, acquireWaitCount: { r: 1 }, timeAcquiringMicros: { r: 28911648 } }, MMAPV1Journal: { acquireCount: { r: 1 } }, Database: { acquireCount: { r: 1 } }, Collection: { acquireCount: { R: 1 } } } protocol:op_msg 28911ms

Troubleshooting performed so far:

We have already checked network latency/CPU/RAM/disk space on VM and blade level, so there was no issue also we tested mongo 3.6.9 in same environment and configuration but there is no issue observed.

We enabled mongostat and also attached it as a reference and found below suspect point:

For one of the secondary there are no CRUD operation for 26 sec (*0 *0 *0 *0 in mongostat observed), then suddenly high CRUD operation(*2444 110 *5781 *1816 in mongostat observed) were found on that secondary, there is no connection lost message found in mongostat for that secondary. This pattern is common whenever we are getting high response time (28 sec) on that secondary.

Additional Observation:

For Primary it is always showing *0 for insert operation for all the time but on secondary’s replication is happening for insert like given below:[Mongostat output in rawformat given below: can look into table format snapshot for more clarity]

host insert query update delete getmore command flushes mapped vsize res faults qrw arw net_in net_out conn set repl time

```<code>[2606:ae00:3001:8311:172:16:244:59]:27032 *245 36 *595 *155 0 65|0 0 6.63G 4.49G 0 0|0 0|0 24.9k 124k 144 rs-app_shardAB-ipv6-4 SEC Feb 3 17:06:46.063
[2606:ae00:3001:8311:172:16:244:60]:27032 *0 *0 *0 *0 0 63|0 0 6.61G 4.49G 0 0|0 0|0 11.3k 71.9k 184 rs-app_shardAB-ipv6-4 SEC Feb 3 17:06:46.068
[2606:ae00:3001:8311:172:16:244:b]:27032 *227 40 *589 *155 0 64|0 0 6.75G 4.48G 0 0|0 0|0 26.6k 157k 144 rs-app_shardAB-ipv6-4 SEC Feb 3 17:06:46.075
[2606:ae00:3001:8311:172:16:244:c]:27032 ***0** 39 827 150 68 119|0 0 6.79G 4.49G 0 0|0 0|0 592k 1.49m 371 rs-app_shardAB-ipv6-4 PRI Feb 3 17:06:45.627
localhost:27032 *0 41 795 162 70 120|0 0 6.79G 4.49G **0** 0|0 1|0 589k 1.50m 371 rs-app_shardAB-ipv6-4 PRI Feb 3 17:06:47.584
</code>```

Queries:

There is no CRUD on one of the secondary for 26 sec when there is no connection lost between primary and secondaries,

Always 0 insert operation is showing in Primary in mongostat and even replication for insert is happening on secondaries.

This behavior is not observed in 3.6.9 where same configuration and environment was used.

Attachments:

Mongostat: From 26 sec we observer 0 CRUD values for [2606:ae00:3001:8311:172:16:244:60]:27032 and suddenly it got increased and there is no connection issues between members.

Mongostat showing zero value for CRUD for [2606:ae00:3001:8311:172:16:244:60]:27032

Mongostat showing zero value for CRUD for [2606:ae00:3001:8311:172:16:244:60]:27032

Mongostat showing sudden high  value for CRUD for [2606:ae00:3001:8311:172:16:244:60]:27032

rs.status output from one of the member:

```<code>rs-app_shardAB-ipv6-8:SECONDARY> rs.status()
{
        "set" : "rs-app_shardAB-ipv6-8",
        "date" : ISODate("2022-02-04T12:22:38.647Z"),
        "myState" : 2,
        "term" : NumberLong(33),
        "syncingTo" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
        "syncSourceHost" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
        "syncSourceId" : 3,
        "heartbeatIntervalMillis" : NumberLong(300),
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(1643977358, 530),
                        "t" : NumberLong(33)
                },
                "readConcernMajorityOpTime" : {
                        "ts" : Timestamp(1643977358, 526),
                        "t" : NumberLong(33)
                },
                "appliedOpTime" : {
                        "ts" : Timestamp(1643977358, 589),
                        "t" : NumberLong(33)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(0, 0),
                        "t" : NumberLong(-1)
                }
        },
        "members" : [
                {
                        "_id" : 0,
                        "name" : "[2606:ae00:3001:8311:172:16:244:c]:27040",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 12732,
                        "optime" : {
                                "ts" : Timestamp(1643977358, 464),
                                "t" : NumberLong(33)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("2022-02-04T12:22:38Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.560Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.526Z"),
                        "pingMs" : NumberLong(40),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceHost" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceId" : 3,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 1,
                        "name" : "[2606:ae00:3001:8311:172:16:244:b]:27040",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 12732,
                        "optime" : {
                                "ts" : Timestamp(1643977358, 252),
                                "t" : NumberLong(33)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("2022-02-04T12:22:38Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.308Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.479Z"),
                        "pingMs" : NumberLong(40),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceHost" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceId" : 3,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 3,
                        "name" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 12732,
                        "optime" : {
                                "ts" : Timestamp(1643977358, 526),
                                "t" : NumberLong(33)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("2022-02-04T12:22:38Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.538Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.507Z"),
                        "pingMs" : NumberLong(40),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1643964608, 1),
                        "electionDate" : ISODate("2022-02-04T08:50:08Z"),
                        "configVersion" : 10
                },
                {
                        "_id" : 4,
                        "name" : "[2606:ae00:3001:8311:172:16:244:a9]:27040",
                        "health" : 1,
                        "state" : 7,
                        "stateStr" : "ARBITER",
                        "uptime" : 12732,
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.608Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.569Z"),
                        "pingMs" : NumberLong(20),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 5,
                        "name" : "[2606:ae00:3001:8311:172:16:244:b9]:27040",
                        "health" : 1,
                        "state" : 7,
                        "stateStr" : "ARBITER",
                        "uptime" : 12732,
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.644Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.396Z"),
                        "pingMs" : NumberLong(20),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 6,
                        "name" : "[2606:ae00:3001:8311:172:16:244:bc]:27040",
                        "health" : 1,
                        "state" : 7,
                        "stateStr" : "ARBITER",
                        "uptime" : 12732,
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.574Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.430Z"),
                        "pingMs" : NumberLong(75),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 7,
                        "name" : "[2606:ae00:3001:8311:172:16:244:59]:27040",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 12734,
                        "optime" : {
                                "ts" : Timestamp(1643977358, 589),
                                "t" : NumberLong(33)
                        },
                        "optimeDate" : ISODate("2022-02-04T12:22:38Z"),
                        "syncingTo" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceHost" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceId" : 3,
                        "infoMessage" : "",
                        "configVersion" : 10,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                }
        ],
        "ok" : 1,
        "operationTime" : Timestamp(1643977358, 589),
        "$clusterTime" : {
                "clusterTime" : Timestamp(1643977358, 595),
                "signature" : {
                        "hash" : BinData(0,"B/K0J5a7Pl3Ht0ZZ9/ETQ3Ri29M="),
                        "keyId" : NumberLong("7042384439900372995")
                }
        }
}
</code>```

答:
Solution:

Init sync your members one by one to wiredTiger. ( this will boost your performance due to the document locking & multithreding and will get rid of the annoying mmapv1 space preallocation issue where you need to init sync from time to time to optimize the storage utilization  )

Your query is not using index , since sessionid is nested field in _id,
to get advantage of the default _id index better you insert the sessionId directly in the _id , otherways you need to created one more index :

```<code> db.drasessions.createIndex({"_id.sessionid":-1})
</code>```

but this is not recommended since you already have the default index on _id

Body:
Scenario:

We have application which is doing CRUD operations on database. For past 2 years we have been using mongo 3.6.9 and system has been working fine without any issues. When we upgraded the database from 3.6.9 to 4.0.27, we started getting high query response time for find operation but it is not consistent in nature. Sometimes we are getting high query response in 5 hours or 7 hours or even 11 hours.

Testing environment:

java client driver on application side - 3.12.9

mongo version - 4.0.27

Storage Engine - mmap

Replica-set: 7 members (4 non-arbiter and 3 arbiter, all voting members)

One of the member CMD as an example:

mongod --keyFile=/mongodb.key --storageEngine mmapv1 --nojournal --noprealloc --smallfiles --ipv6 --bind_ip_all --port 27035 --dbpath=/mmapv1-tmpfs-27035 --replSet rs-app_shardAB-ipv6-7 --quiet --slowms 500 --logpath /data/db/mongo-27035.log --oplogSize 3221 --setParameter diagnosticDataCollectionEnabled=true --logappend --logRotate reopen

Messages:
As a sample, we got these kind of messages on mongo secondary logs given below:

2022-02-02T02:55:54.392+0000 I COMMAND [conn554] command drasessions_1.drasessions command: find { find: “drasessions”, filter: { _id: { sessionid: “ClpGx3:172.16.241.40:15124:1643368779:0080300316” } }, limit: 1, singleBatch: true, $db: “drasessions_1”, $clusterTime: { clusterTime: Timestamp(1643770525, 464), signature: { hash: BinData(0, A9E0739EB1E3BBA9EF776A9FCEC9342E9457D221), keyId: 7042384422720503811 } }, lsid: { id: UUID(“8b321501-be08-4fa8-ada5-367cc1eb555e”) }, $readPreference: { mode: “nearest” } } planSummary: IDHACK keysExamined:0 docsExamined:0 cursorExhausted:1 numYields:0 nreturned:0 reslen:239 locks:{ Global: { acquireCount: { r: 2 }, acquireWaitCount: { r: 1 }, timeAcquiringMicros: { r: 28911648 } }, MMAPV1Journal: { acquireCount: { r: 1 } }, Database: { acquireCount: { r: 1 } }, Collection: { acquireCount: { R: 1 } } } protocol:op_msg 28911ms

Troubleshooting performed so far:

We have already checked network latency/CPU/RAM/disk space on VM and blade level, so there was no issue also we tested mongo 3.6.9 in same environment and configuration but there is no issue observed.

We enabled mongostat and also attached it as a reference and found below suspect point:

For one of the secondary there are no CRUD operation for 26 sec (*0 *0 *0 *0 in mongostat observed), then suddenly high CRUD operation(*2444 110 *5781 *1816 in mongostat observed) were found on that secondary, there is no connection lost message found in mongostat for that secondary. This pattern is common whenever we are getting high response time (28 sec) on that secondary.

Additional Observation:

For Primary it is always showing *0 for insert operation for all the time but on secondary’s replication is happening for insert like given below:[Mongostat output in rawformat given below: can look into table format snapshot for more clarity]

host insert query update delete getmore command flushes mapped vsize res faults qrw arw net_in net_out conn set repl time

[2606:ae00:3001:8311:172:16:244:59]:27032 *245 36 *595 *155 0 65|0 0 6.63G 4.49G 0 0|0 0|0 24.9k 124k 144 rs-app_shardAB-ipv6-4 SEC Feb 3 17:06:46.063
[2606:ae00:3001:8311:172:16:244:60]:27032 *0 *0 *0 *0 0 63|0 0 6.61G 4.49G 0 0|0 0|0 11.3k 71.9k 184 rs-app_shardAB-ipv6-4 SEC Feb 3 17:06:46.068
[2606:ae00:3001:8311:172:16:244:b]:27032 *227 40 *589 *155 0 64|0 0 6.75G 4.48G 0 0|0 0|0 26.6k 157k 144 rs-app_shardAB-ipv6-4 SEC Feb 3 17:06:46.075
[2606:ae00:3001:8311:172:16:244:c]:27032 ***0** 39 827 150 68 119|0 0 6.79G 4.49G 0 0|0 0|0 592k 1.49m 371 rs-app_shardAB-ipv6-4 PRI Feb 3 17:06:45.627
localhost:27032 *0 41 795 162 70 120|0 0 6.79G 4.49G **0** 0|0 1|0 589k 1.50m 371 rs-app_shardAB-ipv6-4 PRI Feb 3 17:06:47.584

Queries:

There is no CRUD on one of the secondary for 26 sec when there is no connection lost between primary and secondaries,

Always 0 insert operation is showing in Primary in mongostat and even replication for insert is happening on secondaries.

This behavior is not observed in 3.6.9 where same configuration and environment was used.

Attachments:

Mongostat: From 26 sec we observer 0 CRUD values for [2606:ae00:3001:8311:172:16:244:60]:27032 and suddenly it got increased and there is no connection issues between members.

Mongostat showing zero value for CRUD for [2606:ae00:3001:8311:172:16:244:60]:27032

Mongostat showing zero value for CRUD for [2606:ae00:3001:8311:172:16:244:60]:27032

Mongostat showing sudden high  value for CRUD for [2606:ae00:3001:8311:172:16:244:60]:27032

rs.status output from one of the member:

rs-app_shardAB-ipv6-8:SECONDARY> rs.status()
{
        "set" : "rs-app_shardAB-ipv6-8",
        "date" : ISODate("2022-02-04T12:22:38.647Z"),
        "myState" : 2,
        "term" : NumberLong(33),
        "syncingTo" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
        "syncSourceHost" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
        "syncSourceId" : 3,
        "heartbeatIntervalMillis" : NumberLong(300),
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(1643977358, 530),
                        "t" : NumberLong(33)
                },
                "readConcernMajorityOpTime" : {
                        "ts" : Timestamp(1643977358, 526),
                        "t" : NumberLong(33)
                },
                "appliedOpTime" : {
                        "ts" : Timestamp(1643977358, 589),
                        "t" : NumberLong(33)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(0, 0),
                        "t" : NumberLong(-1)
                }
        },
        "members" : [
                {
                        "_id" : 0,
                        "name" : "[2606:ae00:3001:8311:172:16:244:c]:27040",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 12732,
                        "optime" : {
                                "ts" : Timestamp(1643977358, 464),
                                "t" : NumberLong(33)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("2022-02-04T12:22:38Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.560Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.526Z"),
                        "pingMs" : NumberLong(40),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceHost" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceId" : 3,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 1,
                        "name" : "[2606:ae00:3001:8311:172:16:244:b]:27040",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 12732,
                        "optime" : {
                                "ts" : Timestamp(1643977358, 252),
                                "t" : NumberLong(33)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("2022-02-04T12:22:38Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.308Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.479Z"),
                        "pingMs" : NumberLong(40),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceHost" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceId" : 3,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 3,
                        "name" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 12732,
                        "optime" : {
                                "ts" : Timestamp(1643977358, 526),
                                "t" : NumberLong(33)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(0, 0),
                                "t" : NumberLong(-1)
                        },
                        "optimeDate" : ISODate("2022-02-04T12:22:38Z"),
                        "optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.538Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.507Z"),
                        "pingMs" : NumberLong(40),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1643964608, 1),
                        "electionDate" : ISODate("2022-02-04T08:50:08Z"),
                        "configVersion" : 10
                },
                {
                        "_id" : 4,
                        "name" : "[2606:ae00:3001:8311:172:16:244:a9]:27040",
                        "health" : 1,
                        "state" : 7,
                        "stateStr" : "ARBITER",
                        "uptime" : 12732,
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.608Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.569Z"),
                        "pingMs" : NumberLong(20),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 5,
                        "name" : "[2606:ae00:3001:8311:172:16:244:b9]:27040",
                        "health" : 1,
                        "state" : 7,
                        "stateStr" : "ARBITER",
                        "uptime" : 12732,
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.644Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.396Z"),
                        "pingMs" : NumberLong(20),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 6,
                        "name" : "[2606:ae00:3001:8311:172:16:244:bc]:27040",
                        "health" : 1,
                        "state" : 7,
                        "stateStr" : "ARBITER",
                        "uptime" : 12732,
                        "lastHeartbeat" : ISODate("2022-02-04T12:22:38.574Z"),
                        "lastHeartbeatRecv" : ISODate("2022-02-04T12:22:38.430Z"),
                        "pingMs" : NumberLong(75),
                        "lastHeartbeatMessage" : "",
                        "syncingTo" : "",
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "configVersion" : 10
                },
                {
                        "_id" : 7,
                        "name" : "[2606:ae00:3001:8311:172:16:244:59]:27040",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 12734,
                        "optime" : {
                                "ts" : Timestamp(1643977358, 589),
                                "t" : NumberLong(33)
                        },
                        "optimeDate" : ISODate("2022-02-04T12:22:38Z"),
                        "syncingTo" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceHost" : "[2606:ae00:3001:8311:172:16:244:60]:27040",
                        "syncSourceId" : 3,
                        "infoMessage" : "",
                        "configVersion" : 10,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                }
        ],
        "ok" : 1,
        "operationTime" : Timestamp(1643977358, 589),
        "$clusterTime" : {
                "clusterTime" : Timestamp(1643977358, 595),
                "signature" : {
                        "hash" : BinData(0,"B/K0J5a7Pl3Ht0ZZ9/ETQ3Ri29M="),
                        "keyId" : NumberLong("7042384439900372995")
                }
        }
}

Body:
Solution:

Init sync your members one by one to wiredTiger. ( this will boost your performance due to the document locking & multithreding and will get rid of the annoying mmapv1 space preallocation issue where you need to init sync from time to time to optimize the storage utilization  )

Your query is not using index , since sessionid is nested field in _id,
to get advantage of the default _id index better you insert the sessionId directly in the _id , otherways you need to created one more index :

 db.drasessions.createIndex({"_id.sessionid":-1})

but this is not recommended since you already have the default index on _id


来源: stackexchange

问:
How to fix position image on another image
I have the following code (also pasted below), where I want to make a layout of two columns. In the first one I am putting two images, and in the second displaying some text.

In the first column, I want to have the first image with width:70% and the second one with position:absolute on it. The final result should be like this

As you see the second image partially located in first one in every screens above to 768px.

I can partially locate second image on first one, but that is not dynamic, if you change screen dimensions you can see how that collapse.

But no matter how hard I try, I can not achieve this result.

.checkoutWrapper {
  display: grid;
  grid-template-columns: 50% 50%;
}

.coverIMGLast {
  width: 70%;
  height: 100vh;
}

/* this .phone class should be dynamically  located partially on first image */
.phone {
  position: absolute;
  height: 90%;
  top: 5%;
  bottom: 5%;
  margin-left: 18%;
}

.CheckoutProcess {
  padding: 5.8rem 6.4rem;
}

.someContent {
  border: 1px solid red;
}

/* removing for demo purposes
@media screen and (max-width: 768px) {
  .checkoutWrapper {
    display: grid;
    grid-template-columns: 100%;
  }
  img {
    display: none;
  }
  .CheckoutProcess {
    padding: 0;
  }
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checkoutWrapper">
  <img src="https://via.placeholder.com/300" class="coverIMGLast" />
  <img src="https://via.placeholder.com/300/ff0000" class="phone" />

  <div class="CheckoutProcess">
    <Content />
  </div>
</div></code>```

答:
check out this code, I created this design for you, may it help...

enter image description here

    body {
        padding: 0;
        margin: 0;
    }

    .parent {
        display: flex;
        position: relative;
        align-items: center;
    }

    .left {
        width: 37%;
        background-color: blue;
        height: 100vh;
    }

    .right {
        width: 63%;
        background-color: red;
        height: 100vh;

        display: flex;
        justify-content: center;
        align-items: center;
    }

    .image-container {
        position: absolute;
        height: 60%;
        width: 100%;
        display: flex;
        align-items: center;
    }

    .image {
        height: 500px;
        width: 250px;
        background-color: grey;
        margin-left: 30%;
        border-radius: 20px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

    <div class='parent'>
        <div class='left'></div>
        <div class='right'>
            <div>
                <h3>THis is a heading</h3>
                <p>this is a para</p>
                <p>this is a para</p>
                <p>this is a para</p>
            </div>
        </div>

        <div class="image-container">
            <div class="image"></div>
        </div>
    </div>

</body></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following code (also pasted below), where I want to make a layout of two columns. In the first one I am putting two images, and in the second displaying some text.

In the first column, I want to have the first image with width:70% and the second one with position:absolute on it. The final result should be like this

As you see the second image partially located in first one in every screens above to 768px.

I can partially locate second image on first one, but that is not dynamic, if you change screen dimensions you can see how that collapse.

But no matter how hard I try, I can not achieve this result.

.checkoutWrapper {
  display: grid;
  grid-template-columns: 50% 50%;
}

.coverIMGLast {
  width: 70%;
  height: 100vh;
}

/* this .phone class should be dynamically  located partially on first image */
.phone {
  position: absolute;
  height: 90%;
  top: 5%;
  bottom: 5%;
  margin-left: 18%;
}

.CheckoutProcess {
  padding: 5.8rem 6.4rem;
}

.someContent {
  border: 1px solid red;
}

/* removing for demo purposes
@media screen and (max-width: 768px) {
  .checkoutWrapper {
    display: grid;
    grid-template-columns: 100%;
  }
  img {
    display: none;
  }
  .CheckoutProcess {
    padding: 0;
  }
}
*/

    <Content />

Body:
check out this code, I created this design for you, may it help...

enter image description here

    body {
        padding: 0;
        margin: 0;
    }

    .parent {
        display: flex;
        position: relative;
        align-items: center;
    }

    .left {
        width: 37%;
        background-color: blue;
        height: 100vh;
    }

    .right {
        width: 63%;
        background-color: red;
        height: 100vh;

        display: flex;
        justify-content: center;
        align-items: center;
    }

    .image-container {
        position: absolute;
        height: 60%;
        width: 100%;
        display: flex;
        align-items: center;
    }

    .image {
        height: 500px;
        width: 250px;
        background-color: grey;
        margin-left: 30%;
        border-radius: 20px;
    }

<body>

    <div class='parent'>
        <div class='left'></div>
        <div class='right'>
            <div>
                <h3>THis is a heading</h3>
                <p>this is a para</p>
                <p>this is a para</p>
                <p>this is a para</p>
            </div>
        </div>

        <div class="image-container">
            <div class="image"></div>
        </div>
    </div>

</body>


问:
I want to implement a image croper for web using flutter
Here I have a blocker in development. I want to create a UI by which I can change my profile picture after croping image, and this is a web application So how can I achieve this task like crop image and chang dp for web using flutter.</p>

答:
I haven't tested it yet, but this looks very promising:

https://pub.dev/packages/extended_image


问:
How to pass form text value as a c# parameter on Razor Pages
I have a function that fetch the data based on the user's registration number on the active directory and print it to the textbox fields on the modal. In that case I need to send as a parameter whatever is written in the textbox instead of the field numbered 31919 in the code below.

```<code><center>
    <image style="margin-top: 20px; width: 25%;" src="/images/adduser.png"></image>
    <div style="margin-top: 25px;">
          <form method="post">
                <label class="control-label"><b>Reg. No</b></label>
                <input type="text" name="RegNo" id="RegNo" value="">
                <button onclick="created(1)" style="margin-left: 15px; height: 60%;" data-toggle="modal" data-target="#AddUser1" type="button" class="btn btn-light-primary px-6 font-weight-bold">Fetch</button>
                <span id="spin"><i style="position: relative; display: inline-block;" class="fas fa-sync fa-spin"></i></span>
          </form>
      @{
            FetchDataFromAD("31919");
      }
        <hr />
    </div>
</center>
</code>```

So, basically I'm trying to do something like this:

```<code> @{
     FetchDataFromAD(RegNo.Text);
 }
</code>```

P.S.: FetchDataFromAD just a function that modifying string expressions like that:

```<code>public void FetchDataFromAD(string RegNo)
{
    System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(directoryEntry);
    search.Filter = "(postalCode=" + RegNo + ")";
    foreach (System.DirectoryServices.SearchResult sResultSet in search.FindAll())
    {
        // Ad
        FetchADPersonelName = GetProperty(sResultSet, "cn");
        FetchADTitle = GetProperty(sResultSet, "title");
        FetchADNetworkN = GetProperty(sResultSet, "samaccountname");
        FetchADEmail = GetProperty(sResultSet, "mail");
        FetchADAdress = "2";
        // FetchADDepartman = GetProperty(sResultSet, "department");

    }
}
</code>```

How can I achieve that? Thank you for any suggestions.

答:
Consider to use the following:

```<code><script>
    function ApplyFilter() {
        var regno = document.getElementById("RegNo").value;
        $.ajax({
            type: "GET",
            url: '@Url.Action("FetchDataFromAD", "Home")',
            contentType: "application/json;charset=utf-8",
            data: { regno },
            dataType: "json",
            success: function (data) {
            }
        });
    };
</script>

<div style="margin-top: 25px;">
    <form method="post">
        <label class="control-label"><b>Reg. No</b></label>
        <input type="text" name="RegNo" id="RegNo" value="">
        <button onclick="ApplyFilter()" style="margin-left: 15px; height: 60%;" data-toggle="modal" data-target="#AddUser1" type="button" class="btn btn-light-primary px-6 font-weight-bold">Fetch</button>
        <span id="spin"><i style="position: relative; display: inline-block;" class="fas fa-sync fa-spin"></i></span>
    </form>
    <hr />
</div>
</code>```

And the FetchDataFromAD() method signature update to be called from JavaScript:

public JsonResult FetchDataFromAD(string RegNo)
{
    ... your code here

    return Json("Filter is applied", JsonRequestBehavior.AllowGet);
}
```

Body:
I have a function that fetch the data based on the user's registration number on the active directory and print it to the textbox fields on the modal. In that case I need to send as a parameter whatever is written in the textbox instead of the field numbered 31919 in the code below.

    <image style="margin-top: 20px; width: 25%;" src="/images/adduser.png"></image>

          <form method="post">
                Reg. No
                <input type="text" name="RegNo" id="RegNo" value="">
                <button onclick="created(1)" style="margin-left: 15px; height: 60%;" data-toggle="modal" data-target="#AddUser1" type="button" class="btn btn-light-primary px-6 font-weight-bold">Fetch</button>

          </form>
      @{
            FetchDataFromAD("31919");
      }

So, basically I'm trying to do something like this:

 @{
     FetchDataFromAD(RegNo.Text);
 }

P.S.: FetchDataFromAD just a function that modifying string expressions like that:

public void FetchDataFromAD(string RegNo)
{
    System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(directoryEntry);
    search.Filter = "(postalCode=" + RegNo + ")";
    foreach (System.DirectoryServices.SearchResult sResultSet in search.FindAll())
    {
        // Ad
        FetchADPersonelName = GetProperty(sResultSet, "cn");
        FetchADTitle = GetProperty(sResultSet, "title");
        FetchADNetworkN = GetProperty(sResultSet, "samaccountname");
        FetchADEmail = GetProperty(sResultSet, "mail");
        FetchADAdress = "2";
        // FetchADDepartman = GetProperty(sResultSet, "department");

    }
}

How can I achieve that? Thank you for any suggestions.

Body:
Consider to use the following:

<script>
    function ApplyFilter() {
        var regno = document.getElementById("RegNo").value;
        $.ajax({
            type: "GET",
            url: '@Url.Action("FetchDataFromAD", "Home")',
            contentType: "application/json;charset=utf-8",
            data: { regno },
            dataType: "json",
            success: function (data) {
            }
        });
    };
</script>

<div style="margin-top: 25px;">
    <form method="post">
        <label class="control-label"><b>Reg. No</b></label>
        <input type="text" name="RegNo" id="RegNo" value="">
        <button onclick="ApplyFilter()" style="margin-left: 15px; height: 60%;" data-toggle="modal" data-target="#AddUser1" type="button" class="btn btn-light-primary px-6 font-weight-bold">Fetch</button>
        <span id="spin"><i style="position: relative; display: inline-block;" class="fas fa-sync fa-spin"></i></span>
    </form>
    <hr />
</div>

And the FetchDataFromAD() method signature update to be called from JavaScript:

public JsonResult FetchDataFromAD(string RegNo)
{
    ... your code here

    return Json("Filter is applied", JsonRequestBehavior.AllowGet);
}


问:
How do I return single orderid having same rank?
I have the following output:

Orderid
Time
State
Order_rank

1
10.15
mfr
1

1
10.15
delivered
1

2
12.10
picked
1

2
12.10
mfr
1

Here I have ranked the order ids wrt to the latest time and put the condition in where clause "where order_rank = 1", but I want to return a single entry for one orderjobid, i.e. for orderid 1 I want to return the delivered state entry and for orderid 2 I want mfr state entry etc.

This is just a sample data, I have more than 1000s of orderids, how do I return single entry for the same rank?

答:
Assuming you code looks something like this:

```<code>SELECT * FROM (
  SELECT
     order_id,
     time,
     state,
     RANK() over (partition by order_id order by time) as order_rank
  FROM VALUES
    (1,'10.15','mfr'),
    (1,'10.15','delivered'),
    (2,'12.10','picked'),
    (2,'12.10','mfr')
    v(order_id, time, state)
)
WHERE order_rank = 1;
</code>```

which gives the output you have.

Not the solution you are looking for, but you can move from the RANK and sub-select and WHERE to use QUALIFY and hide the order_rank line:

```<code>SELECT
   order_id,
   time,
   state
FROM VALUES
  (1,'10.15','mfr'),
  (1,'10.15','delivered'),
  (2,'12.10','picked'),
  (2,'12.10','mfr')
  v(order_id, time, state)
QUALIFY RANK() over (partition by order_id order by time) = 1;
</code>```

But as userMT notes, you want to put a numeric ranking into the selection

like:

```<code>     case state
        when 'delivered' then 1
        when 'mfr' then 2
        when 'picked' then 3
        else 4
    end as state_rank,
</code>```

so if you have it as a separate field, it's easier to read:

```<code> SELECT
     order_id,
     time,
     state,
     case state
        when 'delivered' then 1
        when 'mfr' then 2
        when 'picked' then 3
        else 4
    end as state_rank
  FROM VALUES
    (1,'10.15','mfr'),
    (1,'10.15','delivered'),
    (2,'12.10','picked'),
    (2,'12.10','mfr')
    v(order_id, time, state)
  QUALIFY RANK() over (partition by order_id order by time,state_rank) = 1;
</code>```

giving:

ORDER_ID
TIME
STATE
STATE_RANK

1
10.15
delivered
1

2
12.10
mfr
2

but you can mash the case into the rank also:

```<code>  SELECT
     order_id,
     time,
     state
  FROM VALUES
    (1,'10.15','mfr'),
    (1,'10.15','delivered'),
    (2,'12.10','picked'),
    (2,'12.10','mfr')
    v(order_id, time, state)
  QUALIFY RANK() over (partition by order_id order by time, case state when 'delivered' then 1 when 'mfr' then 2 when 'picked' then 3 else 4 end) = 1;
</code>```

gives:

ORDER_ID
TIME
STATE

1
10.15
delivered

2
12.10
mfr

Body:
Assuming you code looks something like this:

SELECT * FROM (
  SELECT
     order_id,
     time,
     state,
     RANK() over (partition by order_id order by time) as order_rank
  FROM VALUES
    (1,'10.15','mfr'),
    (1,'10.15','delivered'),
    (2,'12.10','picked'),
    (2,'12.10','mfr')
    v(order_id, time, state)
)
WHERE order_rank = 1;

which gives the output you have.

Not the solution you are looking for, but you can move from the RANK and sub-select and WHERE to use QUALIFY and hide the order_rank line:

SELECT
   order_id,
   time,
   state
FROM VALUES
  (1,'10.15','mfr'),
  (1,'10.15','delivered'),
  (2,'12.10','picked'),
  (2,'12.10','mfr')
  v(order_id, time, state)
QUALIFY RANK() over (partition by order_id order by time) = 1;

But as userMT notes, you want to put a numeric ranking into the selection

like:

     case state
        when 'delivered' then 1
        when 'mfr' then 2
        when 'picked' then 3
        else 4
    end as state_rank,

so if you have it as a separate field, it's easier to read:

 SELECT
     order_id,
     time,
     state,
     case state
        when 'delivered' then 1
        when 'mfr' then 2
        when 'picked' then 3
        else 4
    end as state_rank
  FROM VALUES
    (1,'10.15','mfr'),
    (1,'10.15','delivered'),
    (2,'12.10','picked'),
    (2,'12.10','mfr')
    v(order_id, time, state)
  QUALIFY RANK() over (partition by order_id order by time,state_rank) = 1;

giving:

ORDER_ID
TIME
STATE
STATE_RANK

1
10.15
delivered
1

2
12.10
mfr
2

but you can mash the case into the rank also:

  SELECT
     order_id,
     time,
     state
  FROM VALUES
    (1,'10.15','mfr'),
    (1,'10.15','delivered'),
    (2,'12.10','picked'),
    (2,'12.10','mfr')
    v(order_id, time, state)
  QUALIFY RANK() over (partition by order_id order by time, case state when 'delivered' then 1 when 'mfr' then 2 when 'picked' then 3 else 4 end) = 1;

gives:

ORDER_ID
TIME
STATE

1
10.15
delivered

2
12.10
mfr


问:
__DoPostback javascript event handlers don't work after deploy to Azure websites
In my ASPX (MVC) page, I set up a JS function:

```<code>        <script language="javascript" type="text/javascript">
        function changehref(param) {
        __doPostBack('i2e',  param);
        }
</code>```

In the codebehind, I check for the value of i2e as follows:

```<code>        public void Page_Load(object sender, System.EventArgs e)
    {
        PostBackStr = Page.ClientScript.GetPostBackEventReference(this, "i2e");
        PostBackStr = "";
        if (Page.IsPostBack)
        {
            bool is_i2e = Request["__EVENTTARGET"] == "i2e"; // btnSave
            string i2e_val = Request["__EVENTARGUMENT"];
            if (is_i2e)
            {
                PostBackStr = i2e_val;
            }
</code>```

Well, the code above works great in Visual Studio 2019 using the local (dev) Web server, but when I deploy the solution in toto to Azure Web hosting, it is as though IIS is ignoring the Postbacks.

Anyone run into this issue? I checked to see if Content-Security-Policy or Strict-Transport-Security was coming back in the response headers from the (IIS 10.0) web server, there are some cookies being set that may be 'neutralizing' __DoPostback:

```<code>('Set-Cookie', 'ASP.NET_SessionId=gqu1kx3kg4pibjl2hr1ot0iw; path=/; HttpOnly; SameSite=Lax, ARRAffinity=5ecc95fa5ba7d2943961f71828ad79ba0870393e24b3a564ea7999feae92443f;Path=/;HttpOnly;Secure;Domain=xxxx.azurewebsites.net, ARRAffinitySameSite=5ecc95fa5ba7d2943961f71828ad79ba0870393e24b3a564ea7999feae92443f;Path=/;HttpOnly;SameSite=None;Secure;Domain=xxxx.azurewebsites.net')
</code>```

答: oopsie, forgot that I was running NoScript on my default browser (Firefox), locally I used Chrome which doesn't have NoScript extension.</p>


问:
Game not printing or updating when AI is thinking
I have a game I am developing in Unity where AI is doing large calculations when it is its turn. It searches the position to depth 1, then 2, then 3 etc. Between each depth I want to instantiate a Gameobject with info about the depth to UI. The problem is that nothing happens until the AI is completely finished, then all items are added at once. Here is some code to explain better:

```<code>private void AIMakeMove()
{
    for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
    {
        SearchPosition(currentDepth);
    }
}

private void SearchPosition(int _currentDepth)
{
    // Search the position to the given depth
    score = Negamax(_currentDepth);

     // Print things   PROBLEM HERE
    GameObject printItem = Instantiate(printItemPrefab, printItemParent.transform);
    Debug.Log(_currentDepth);
}
</code>```

I also tried just a simple Debug.Log instead of Instantiate but same thing happens then, all prints to console happens after the AI is done with its thinking process.

Why is my UI not updating with information? I tell it to create some things after it run the first iteration with depth 0 but it skips this step and goes on depth 2 instead. Can someone please let me know how to get information out between each depth?

答:
The problem is that nothing happens until the AI is completely finished

well the UI is only updated if the Unity main-thread is allowed to finish a frame.

You, however, block the main thread until all iterations are finished.

If it is okey for you to block between each instantiation then you could simply use a Coroutine and do something like

```<code>private void AIMakeMove()
{
    StartCoroutine(AIMakeMoveRoutine());
}

private IEnuemrator AIMakeMoveRoutine()
{
    for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
    {
        SearchPosition(currentDepth);

        // This now tells Unity to "interrupt" this routine here
        // render the current frame and continue from here in the next frame
        yield return null;
    }
}

private void SearchPosition(int _currentDepth)
{
    score = Negamax(_currentDepth);

    GameObject printItem = Instantiate(printItemPrefab, printItemParent.transform);
    Debug.Log(_currentDepth);
}
</code>```

This will finish a frame and start a new one (thus refresh the UI) after each finished iteration.

However, if this still blocks the rest of your application too much you should additionally actually run the calculation async e.g.  using a Task like

```<code>private void AIMakeMove()
{
    StartCoroutine(AIMakeMoveRoutine());
}

private IEnuemrator AIMakeMoveRoutine()
{
    for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
    {
        // you can yield another IEnuemrator -> executes this and waits for it to finish
        yield return SearchPosition(currentDepth);

        // This now tells Unity to "interrupt" this routine here
        // render the current frame and continue from here in the next frame
        yield return null;
    }
}

private IEnumerator SearchPosition(int _currentDepth)
{
    // run the NegamaxTask asynchronously in the background
    var task = Task.Run(() => Negamax(_currentDepth));
    // wait for the task to finish
    while(!task.IsCompleted)
    {
        // do nothing but skip frames to allow the rest of the application to run smoothly
        yield return null;
    }
    // If you do nothing else inside the loop this could also be written as
    //yield return new WaitWhile(() => !task.IsComoleted);
    // or
    //yield return new WaitUntil(() => task.IsCompleted);

    // since the task is already finished it is save / non-blocking to access the result now
    score = task.Result;

    var printItem = Instantiate(printItemPrefab, printItemParent.transform);
    Debug.Log(_currentDepth);
}
</code>```

Now this allows your application to continue with a normal frame-rate while in the background you do the heavy calculations and once in a while get a result back when an iteration is finished.

Body:
I have a game I am developing in Unity where AI is doing large calculations when it is its turn. It searches the position to depth 1, then 2, then 3 etc. Between each depth I want to instantiate a Gameobject with info about the depth to UI. The problem is that nothing happens until the AI is completely finished, then all items are added at once. Here is some code to explain better:

private void AIMakeMove()
{
    for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
    {
        SearchPosition(currentDepth);
    }
}

private void SearchPosition(int _currentDepth)
{
    // Search the position to the given depth
    score = Negamax(_currentDepth);

     // Print things   PROBLEM HERE
    GameObject printItem = Instantiate(printItemPrefab, printItemParent.transform);
    Debug.Log(_currentDepth);
}

I also tried just a simple Debug.Log instead of Instantiate but same thing happens then, all prints to console happens after the AI is done with its thinking process.

Why is my UI not updating with information? I tell it to create some things after it run the first iteration with depth 0 but it skips this step and goes on depth 2 instead. Can someone please let me know how to get information out between each depth?

Body:
The problem is that nothing happens until the AI is completely finished

well the UI is only updated if the Unity main-thread is allowed to finish a frame.

You, however, block the main thread until all iterations are finished.

If it is okey for you to block between each instantiation then you could simply use a Coroutine and do something like

private void AIMakeMove()
{
    StartCoroutine(AIMakeMoveRoutine());
}

private IEnuemrator AIMakeMoveRoutine()
{
    for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
    {
        SearchPosition(currentDepth);

        // This now tells Unity to "interrupt" this routine here
        // render the current frame and continue from here in the next frame
        yield return null;
    }
}

private void SearchPosition(int _currentDepth)
{
    score = Negamax(_currentDepth);

    GameObject printItem = Instantiate(printItemPrefab, printItemParent.transform);
    Debug.Log(_currentDepth);
}

This will finish a frame and start a new one (thus refresh the UI) after each finished iteration.

However, if this still blocks the rest of your application too much you should additionally actually run the calculation async e.g.  using a Task like

private void AIMakeMove()
{
    StartCoroutine(AIMakeMoveRoutine());
}

private IEnuemrator AIMakeMoveRoutine()
{
    for (int currentDepth = 1; currentDepth < maxDepth + 1; currentDepth++)
    {
        // you can yield another IEnuemrator -> executes this and waits for it to finish
        yield return SearchPosition(currentDepth);

        // This now tells Unity to "interrupt" this routine here
        // render the current frame and continue from here in the next frame
        yield return null;
    }
}

private IEnumerator SearchPosition(int _currentDepth)
{
    // run the NegamaxTask asynchronously in the background
    var task = Task.Run(() => Negamax(_currentDepth));
    // wait for the task to finish
    while(!task.IsCompleted)
    {
        // do nothing but skip frames to allow the rest of the application to run smoothly
        yield return null;
    }
    // If you do nothing else inside the loop this could also be written as
    //yield return new WaitWhile(() => !task.IsComoleted);
    // or
    //yield return new WaitUntil(() => task.IsCompleted);

    // since the task is already finished it is save / non-blocking to access the result now
    score = task.Result;

    var printItem = Instantiate(printItemPrefab, printItemParent.transform);
    Debug.Log(_currentDepth);
}

Now this allows your application to continue with a normal frame-rate while in the background you do the heavy calculations and once in a while get a result back when an iteration is finished.


问:
If a parallel branch fails in aws step function, then how can i revert the changes of other branch that is done
I have a aws step function workflow and in that i have a parallel task which executes 3 tasks "A","B" and "C" all are running in parallel , then "A" successfully completes it's executeion, "B" and "C" both are still running then if "B" fails , then how can i revert changes of "A" and of "C"(which run partially.).</p>

答:
As @Riz mentioned, Step Functions does not have any built in rollback options.
One option will be for your parallel state to have a catch which will catch if A B or C fail. If it does, the catch will direct to a cleanup/rollback step within your state machine.</p>


问:
Material Container Transform animation not working in Java
Im trying to use Material Container Transform in Recyclerview Adapter as described by this post MaterialContainerTransform transition is not Working on Return , but after implementing this in my project im getting null pointer exception error.
As everyone know Material Container Transform animation tutorials are in kotlin and im doing it in java.
So if anyone know how to properly use material container transform animation in recyclerview and point out my mistakes i will be very much thankful to him.

RecyclerView Adapter Class(source)

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {

    private Context context;
    private List<Astadhyayi> wordList;
    private List<Astadhyayi> filwordList;
    private DictionaryDB dictionaryDB;

    private OnclickListenerInterface listener;

    public RecyclerViewAdapter(Context context, List<Astadhyayi> itemList, DictionaryDB dictionaryDB) {

        this.context = context;
        this.wordList = itemList;
        this.dictionaryDB = dictionaryDB;
        filwordList = new ArrayList<Astadhyayi>(itemList);

    }

    public void setClickListener(OnclickListenerInterface onclickListener) {

        this.listener = onclickListener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        Astadhyayi word = wordList.get(position);
        holder.rsutras.setText(word.mSutras);

        // Animation******

        holder.rsutras.setTransitionName(word.getMSutras());

        if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {

            holder.bookmark.setImageResource(R.drawable.cards_heart);
        } else {

            holder.bookmark.setImageDrawable(null);
        }
    }

    @Override
    public Filter getFilter() {
        return Searched_Filter;
    }

    private Filter Searched_Filter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<Astadhyayi> filteredList = new ArrayList<>();
            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(filwordList);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();
                for (Astadhyayi item : filwordList) {
                    if (item.getMSutras().toLowerCase().contains(filterPattern)) {
                        filteredList.add(item);
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = filteredList;
            return results;
        }
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            wordList.clear();
            wordList.addAll((ArrayList<Astadhyayi>)results.values);
            notifyDataSetChanged();
        }
    };

    @Override
    public int getItemCount() {
        return wordList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private TextView rsutras;
        private ImageView bookmark;

        public ViewHolder(View itemView) {
            super(itemView);

            itemView.setOnClickListener(this);

            rsutras =  itemView.findViewById(R.id.tvSansTerm);
            bookmark = itemView.findViewById(R.id.bookmarkBtn);

        }

        /*
         @Override
         public void onClick(View view) {

         if(listener!=null) listener.onItemClicked(getAbsoluteAdapterPosition(), rsutras);

         }
         */

        @Override
        public void onClick(View view) {

            int position = this.getAbsoluteAdapterPosition();
            Astadhyayi word = wordList.get(position);

            //*************** Bundle  **************\\
            Bundle bundle = new Bundle();

            bundle.putParcelable("allData", word);

            bundle.putString("transition_name", word.getMSutras());

            Fragment detailsFragment = new TermThreeDetailsFragment();
            detailsFragment.setSharedElementEnterTransition(new MaterialContainerTransform());
            detailsFragment.setArguments(bundle);

            FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
            fT.setReorderingAllowed(true);
            fT.addSharedElement(rsutras, rsutras.getTransitionName()); // Shared element!
            fT.replace(R.id.fragment_container, detailsFragment);
            fT.addToBackStack(null);
            fT.commit();

        }

    }

}
</code>```

RecyclerView Fragment Class(source)

```<code>public class ShowtermsTwoFragment extends Fragment {

    private RecyclerView rv;
    private EditText tV;

    private Toolbar toolbar;
    private LinearLayoutManager layoutManager;
    private static DictionaryDB db;
    private RecyclerViewAdapter rvAdapter;

    private SearchView searchView = null;
    private SearchView.OnQueryTextListener queryTextListener;
    private List<Astadhyayi> wordsList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setExitTransition(new MaterialElevationScale(false));
        setReenterTransition(new MaterialElevationScale(true));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_terms_recyclerview, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        toolbar = ((Toolbar) view.findViewById(R.id.toolbar_rv));
        rv = view.findViewById(R.id.rvTerms);
        tV = view.findViewById(R.id.tVinput);

        //*********** TOOLBAR
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        setHasOptionsMenu(true);

        // new Get_DbData().execute();

        databaseCheck();
        recyclerCheck1();

        postponeEnterTransition();
        ((ViewGroup) view.getParent()).getViewTreeObserver()

            .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                public boolean onPreDraw() {
                    startPostponedEnterTransition();
                    return true;
                }
            });

        }

    private void databaseCheck() {

        String sanskritWord = getActivity().getIntent().getStringExtra("sanskritWord");

        //*********** @@@ DATABASE OPENING @@@ ***********\\
        db = DictionaryDB.getInstance(this.getActivity());

        wordsList = db.getWords((sanskritWord));
    }

    private void recyclerCheck1() {

        layoutManager = new LinearLayoutManager(getContext());
        rv.setLayoutManager(layoutManager);
        rv.setHasFixedSize(true);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rv.getContext(), layoutManager.getOrientation());
        rv.addItemDecoration(dividerItemDecoration);
        rvAdapter = new RecyclerViewAdapter(getContext(), wordsList, db);

        rv.setAdapter(rvAdapter);
     /////**********   rvAdapter.setClickListener(this);
        rvAdapter.notifyDataSetChanged();
    }
}
</code>```

Details Fragment Class(destination)

```<code>public class TermThreeDetailsFragment extends Fragment {

    private TextView sutraTV,vrittiTV,padaTv,adhyayTV,sutraIdTV ;
    private CoordinatorLayout coordinatorLayout;
    private FloatingActionButton fabBtn;
    private static DictionaryDB db;
    private Astadhyayi word;
    private BottomAppBar bottomAppBar;

    private TextToSpeech pronunciation;
    private AudioManager audio;
    private String ttsID , trans;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MaterialContainerTransform transform = new MaterialContainerTransform();
        transform.setScrimColor(Color.TRANSPARENT);
        setSharedElementEnterTransition(transform);
        setSharedElementReturnTransition(transform);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.show_three_details, container, false);

        view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        sutraTV = view.findViewById(R.id.tvSutra);
        adhyayTV = view.findViewById(R.id.tVAdhyay);
        padaTv = view.findViewById(R.id.tVPada);
        sutraIdTV = view.findViewById(R.id.tVSutraId);
        vrittiTV = view.findViewById(R.id.tvVritti);

        fabBtn = view.findViewById(R.id.favFAB);
        coordinatorLayout = view.findViewById(R.id.parentCordlayout);
        bottomAppBar = view.findViewById(R.id.bottom_app_bar);

        bundleCheckWithDb();
        WordCheck();

    }

    private void bundleCheckWithDb() {

                            //***********  Geting Parcelable Data
        word = new Astadhyayi(Parcel.obtain());
        Bundle bundle = this.getArguments();

        if (bundle != null) {
            word = bundle.getParcelable("allData");
            trans = bundle.getString("transition_name");

            adhyayTV.setText(word.getMAdhyay());
            padaTv.setText(word.getMPada());
            sutraIdTV.setText(word.getMSutra_id());
            sutraTV.setText(word.getMSutras());
            vrittiTV.setText(word.getMVritti());
        }

                           //*********** DATABASE OPENING
        db = DictionaryDB.getInstance(this.getActivity());
    }

    private void WordCheck() {

        if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
            fabBtn.setImageResource(R.drawable.cards_heart);
        } else {
            fabBtn.setImageResource(R.drawable.cards_heart_white);
        }

        fabBtn.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    bookMarkWord(word, fabBtn);
                }
            });
    }
}
</code>```

Error im getting

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sanskrit.mysearcher.models.Astadhyayi.getMSutras()' on a null object reference
at com.sanskrit.mysearcher.fragments.TermThreeDetailsFragment.onCreateView(TermThreeDetailsFragment.java:69)

答:
From the current given information, I think you should do something like this:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    word = new Astadhyayi(Parcel.obtain());
    Bundle bundle = this.getArguments();
    if (bundle != null) {
        word = bundle.getParcelable("allData");
    }

    View view = inflater.inflate(R.layout.show_three_details, container, false);
    view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
    return view;
}
</code>```

Again, I am not sure what getMSutras() actually returns and if it's right to use that here.

Body:
Im trying to use Material Container Transform in Recyclerview Adapter as described by this post MaterialContainerTransform transition is not Working on Return , but after implementing this in my project im getting null pointer exception error.
As everyone know Material Container Transform animation tutorials are in kotlin and im doing it in java.
So if anyone know how to properly use material container transform animation in recyclerview and point out my mistakes i will be very much thankful to him.

RecyclerView Adapter Class(source)

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {

    private Context context;
    private List<Astadhyayi> wordList;
    private List<Astadhyayi> filwordList;
    private DictionaryDB dictionaryDB;

    private OnclickListenerInterface listener;

    public RecyclerViewAdapter(Context context, List<Astadhyayi> itemList, DictionaryDB dictionaryDB) {

        this.context = context;
        this.wordList = itemList;
        this.dictionaryDB = dictionaryDB;
        filwordList = new ArrayList<Astadhyayi>(itemList);

    }

    public void setClickListener(OnclickListenerInterface onclickListener) {

        this.listener = onclickListener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        Astadhyayi word = wordList.get(position);
        holder.rsutras.setText(word.mSutras);

        // Animation******

        holder.rsutras.setTransitionName(word.getMSutras());

        if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {

            holder.bookmark.setImageResource(R.drawable.cards_heart);
        } else {

            holder.bookmark.setImageDrawable(null);
        }
    }

    @Override
    public Filter getFilter() {
        return Searched_Filter;
    }

    private Filter Searched_Filter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<Astadhyayi> filteredList = new ArrayList<>();
            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(filwordList);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();
                for (Astadhyayi item : filwordList) {
                    if (item.getMSutras().toLowerCase().contains(filterPattern)) {
                        filteredList.add(item);
                    }
                }
            }
            FilterResults results = new FilterResults();
            results.values = filteredList;
            return results;
        }
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            wordList.clear();
            wordList.addAll((ArrayList<Astadhyayi>)results.values);
            notifyDataSetChanged();
        }
    };

    @Override
    public int getItemCount() {
        return wordList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private TextView rsutras;
        private ImageView bookmark;

        public ViewHolder(View itemView) {
            super(itemView);

            itemView.setOnClickListener(this);

            rsutras =  itemView.findViewById(R.id.tvSansTerm);
            bookmark = itemView.findViewById(R.id.bookmarkBtn);

        }

        /*
         @Override
         public void onClick(View view) {

         if(listener!=null) listener.onItemClicked(getAbsoluteAdapterPosition(), rsutras);

         }
         */

        @Override
        public void onClick(View view) {

            int position = this.getAbsoluteAdapterPosition();
            Astadhyayi word = wordList.get(position);

            //*************** Bundle  **************\\
            Bundle bundle = new Bundle();

            bundle.putParcelable("allData", word);

            bundle.putString("transition_name", word.getMSutras());

            Fragment detailsFragment = new TermThreeDetailsFragment();
            detailsFragment.setSharedElementEnterTransition(new MaterialContainerTransform());
            detailsFragment.setArguments(bundle);

            FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
            fT.setReorderingAllowed(true);
            fT.addSharedElement(rsutras, rsutras.getTransitionName()); // Shared element!
            fT.replace(R.id.fragment_container, detailsFragment);
            fT.addToBackStack(null);
            fT.commit();

        }

    }

}

RecyclerView Fragment Class(source)

public class ShowtermsTwoFragment extends Fragment {

    private RecyclerView rv;
    private EditText tV;

    private Toolbar toolbar;
    private LinearLayoutManager layoutManager;
    private static DictionaryDB db;
    private RecyclerViewAdapter rvAdapter;

    private SearchView searchView = null;
    private SearchView.OnQueryTextListener queryTextListener;
    private List<Astadhyayi> wordsList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setExitTransition(new MaterialElevationScale(false));
        setReenterTransition(new MaterialElevationScale(true));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_terms_recyclerview, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        toolbar = ((Toolbar) view.findViewById(R.id.toolbar_rv));
        rv = view.findViewById(R.id.rvTerms);
        tV = view.findViewById(R.id.tVinput);

        //*********** TOOLBAR
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        setHasOptionsMenu(true);

        // new Get_DbData().execute();

        databaseCheck();
        recyclerCheck1();

        postponeEnterTransition();
        ((ViewGroup) view.getParent()).getViewTreeObserver()

            .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                public boolean onPreDraw() {
                    startPostponedEnterTransition();
                    return true;
                }
            });

        }

    private void databaseCheck() {

        String sanskritWord = getActivity().getIntent().getStringExtra("sanskritWord");

        //*********** @@@ DATABASE OPENING @@@ ***********\\
        db = DictionaryDB.getInstance(this.getActivity());

        wordsList = db.getWords((sanskritWord));
    }

    private void recyclerCheck1() {

        layoutManager = new LinearLayoutManager(getContext());
        rv.setLayoutManager(layoutManager);
        rv.setHasFixedSize(true);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rv.getContext(), layoutManager.getOrientation());
        rv.addItemDecoration(dividerItemDecoration);
        rvAdapter = new RecyclerViewAdapter(getContext(), wordsList, db);

        rv.setAdapter(rvAdapter);
     /////**********   rvAdapter.setClickListener(this);
        rvAdapter.notifyDataSetChanged();
    }
}

Details Fragment Class(destination)

public class TermThreeDetailsFragment extends Fragment {

    private TextView sutraTV,vrittiTV,padaTv,adhyayTV,sutraIdTV ;
    private CoordinatorLayout coordinatorLayout;
    private FloatingActionButton fabBtn;
    private static DictionaryDB db;
    private Astadhyayi word;
    private BottomAppBar bottomAppBar;

    private TextToSpeech pronunciation;
    private AudioManager audio;
    private String ttsID , trans;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MaterialContainerTransform transform = new MaterialContainerTransform();
        transform.setScrimColor(Color.TRANSPARENT);
        setSharedElementEnterTransition(transform);
        setSharedElementReturnTransition(transform);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.show_three_details, container, false);

        view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        sutraTV = view.findViewById(R.id.tvSutra);
        adhyayTV = view.findViewById(R.id.tVAdhyay);
        padaTv = view.findViewById(R.id.tVPada);
        sutraIdTV = view.findViewById(R.id.tVSutraId);
        vrittiTV = view.findViewById(R.id.tvVritti);

        fabBtn = view.findViewById(R.id.favFAB);
        coordinatorLayout = view.findViewById(R.id.parentCordlayout);
        bottomAppBar = view.findViewById(R.id.bottom_app_bar);

        bundleCheckWithDb();
        WordCheck();

    }

    private void bundleCheckWithDb() {

                            //***********  Geting Parcelable Data
        word = new Astadhyayi(Parcel.obtain());
        Bundle bundle = this.getArguments();

        if (bundle != null) {
            word = bundle.getParcelable("allData");
            trans = bundle.getString("transition_name");

            adhyayTV.setText(word.getMAdhyay());
            padaTv.setText(word.getMPada());
            sutraIdTV.setText(word.getMSutra_id());
            sutraTV.setText(word.getMSutras());
            vrittiTV.setText(word.getMVritti());
        }

                           //*********** DATABASE OPENING
        db = DictionaryDB.getInstance(this.getActivity());
    }

    private void WordCheck() {

        if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
            fabBtn.setImageResource(R.drawable.cards_heart);
        } else {
            fabBtn.setImageResource(R.drawable.cards_heart_white);
        }

        fabBtn.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    bookMarkWord(word, fabBtn);
                }
            });
    }
}

Error im getting

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sanskrit.mysearcher.models.Astadhyayi.getMSutras()' on a null object reference
at com.sanskrit.mysearcher.fragments.TermThreeDetailsFragment.onCreateView(TermThreeDetailsFragment.java:69)

Body:
From the current given information, I think you should do something like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    word = new Astadhyayi(Parcel.obtain());
    Bundle bundle = this.getArguments();
    if (bundle != null) {
        word = bundle.getParcelable("allData");
    }

    View view = inflater.inflate(R.layout.show_three_details, container, false);
    view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
    return view;
}

Again, I am not sure what getMSutras() actually returns and if it's right to use that here.


问:
Closing Processes represented by CheckedItems in c#
I am wanting to close processes that a user selects in a ListView box in another form. the ListView box uses checkboxes for selecting which processes to close. Unfortunately, i dont know how to convert the checked processes into processes....any help?</p>

```<code>public void Form4_Load(object sender, EventArgs e)
{
    Process[] prs = Process.GetProcesses();
    listView1.Items.Clear();
    foreach (Process proces in prs)
    {
        if (!string.IsNullOrEmpty(proces.MainWindowTitle))
            listView1.Items.Add(proces.MainWindowTitle);
    }
    foreach (Process PRC in listView1.CheckedItems)
    {
        \\Idk what to put here.
    }
</code>```

答:
In order to kill a process you either need it's name or process id, so change your above code that adds process to ListView1 to some thing like this:

```<code>private void Form4_Load(object sender, EventArgs e)
        {
            Process[] prs = Process.GetProcesses();
            listView1.Items.Clear();
            foreach (Process proces in prs)
            {
                if (!string.IsNullOrEmpty(proces.MainWindowTitle))
                {
                    ListViewItem item = new ListViewItem();
                    item.Tag = proces.Id; //it will be used to kill this process
                    item.Text = proces.MainWindowTitle;
                    listView1.Items.Add(item);
                }
            }
        }
</code>```

Note the tag field, which we will use later to kill the selected process.. Now loop through all selected ListViewItems, get the corresponding process id from tag field and get the reference to the process using System.Diagnostics.Process.GetProcessById. This method returns an object of Process, which exposes a Kill method using which one can stop the process this object refers to.

```<code>private void button1_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem list in listView1.CheckedItems)
            {
                Process p = System.Diagnostics.Process.GetProcessById(Convert.ToInt32(list.Tag));
                if (p != null)
                    p.Kill();
            }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am wanting to close processes that a user selects in a ListView box in another form. the ListView box uses checkboxes for selecting which processes to close. Unfortunately, i dont know how to convert the checked processes into processes....any help?

public void Form4_Load(object sender, EventArgs e)
{
    Process[] prs = Process.GetProcesses();
    listView1.Items.Clear();
    foreach (Process proces in prs)
    {
        if (!string.IsNullOrEmpty(proces.MainWindowTitle))
            listView1.Items.Add(proces.MainWindowTitle);
    }
    foreach (Process PRC in listView1.CheckedItems)
    {
        \\Idk what to put here.
    }

Body:
In order to kill a process you either need it's name or process id, so change your above code that adds process to ListView1 to some thing like this:

private void Form4_Load(object sender, EventArgs e)
        {
            Process[] prs = Process.GetProcesses();
            listView1.Items.Clear();
            foreach (Process proces in prs)
            {
                if (!string.IsNullOrEmpty(proces.MainWindowTitle))
                {
                    ListViewItem item = new ListViewItem();
                    item.Tag = proces.Id; //it will be used to kill this process
                    item.Text = proces.MainWindowTitle;
                    listView1.Items.Add(item);
                }
            }
        }

Note the tag field, which we will use later to kill the selected process.. Now loop through all selected ListViewItems, get the corresponding process id from tag field and get the reference to the process using System.Diagnostics.Process.GetProcessById. This method returns an object of Process, which exposes a Kill method using which one can stop the process this object refers to.

private void button1_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem list in listView1.CheckedItems)
            {
                Process p = System.Diagnostics.Process.GetProcessById(Convert.ToInt32(list.Tag));
                if (p != null)
                    p.Kill();
            }
    }


问:
ERROR: Preparation failed: getting Kubernetes config: invalid configuration: no configuration has been provided Gitlab
Hey guys this is blocking my flow! I have my gitlab runner installed on my Windows machine.

I registered a runner with a kubernetes executor. It previously used to work, but not any more.

I have a kubernetes cluster (the one provided by docker desktop) and the log of my jobs show this error:

```<code>ERROR: Preparation failed: getting Kubernetes config: invalid configuration: no configuration has been provided
</code>```

I have checked a few other resources regarding this issue, such as: this gitlab runner issue , this other gitlab issue and this SO questions but no solution has worked.

The runner on my Runners setting is Running (Green)

The config.toml file looks correct:

```<code>concurrent = 5
check_interval = 0

[session_server]
  session_timeout = 1800

[[runners]]
  name = "kubernetes runner"
  url = "https://gitlab.com/"
  token = "My_Token"
  executor = "kubernetes"
  [runners.custom_build_dir]
  [runners.cache]
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]
  [runners.kubernetes]
    host = ""
    bearer_token_overwrite_allowed = false
    image = ""
    namespace = ""
    namespace_overwrite_allowed = ""
    privileged = false
    service_account_overwrite_allowed = ""
    pod_annotations_overwrite_allowed = ""
    [runners.kubernetes.affinity]
    [runners.kubernetes.pod_security_context]
    [runners.kubernetes.volumes]
    [runners.kubernetes.dns_config]

</code>```

and the config file is definitely in my home directory $HOME/.kube

I'm not sure how things work on windows, maybe the code is not able configured to find this path in windows? The thing is, it used to work before!

Also running:

```<code>kubectl get pods
</code>```

returns results

Any one knows what might be the reason?

答:
I had the same Problem.

What I found is that when you run kubectl you run it with root or some user.
For the gitlab-runner however there is a seperate user.

Running kubectl works because there is a Kubernetes config dir for this user /home/<kubectl-user>/.kube.
It doesn't work for your gitlab runner since there is no config dir for the user.

Copying /home/<kubectl-user>/.kube/ into /home/<gitlab-runner-user>/ should solve your issue

Body:
Hey guys this is blocking my flow! I have my gitlab runner installed on my Windows machine.

I registered a runner with a kubernetes executor. It previously used to work, but not any more.

I have a kubernetes cluster (the one provided by docker desktop) and the log of my jobs show this error:

ERROR: Preparation failed: getting Kubernetes config: invalid configuration: no configuration has been provided

I have checked a few other resources regarding this issue, such as: this gitlab runner issue , this other gitlab issue and this SO questions but no solution has worked.

The runner on my Runners setting is Running (Green)

The config.toml file looks correct:

concurrent = 5
check_interval = 0

[session_server]
  session_timeout = 1800

[[runners]]
  name = "kubernetes runner"
  url = "https://gitlab.com/"
  token = "My_Token"
  executor = "kubernetes"
  [runners.custom_build_dir]
  [runners.cache]
    [runners.cache.s3]
    [runners.cache.gcs]
    [runners.cache.azure]
  [runners.kubernetes]
    host = ""
    bearer_token_overwrite_allowed = false
    image = ""
    namespace = ""
    namespace_overwrite_allowed = ""
    privileged = false
    service_account_overwrite_allowed = ""
    pod_annotations_overwrite_allowed = ""
    [runners.kubernetes.affinity]
    [runners.kubernetes.pod_security_context]
    [runners.kubernetes.volumes]
    [runners.kubernetes.dns_config]

and the config file is definitely in my home directory $HOME/.kube

I'm not sure how things work on windows, maybe the code is not able configured to find this path in windows? The thing is, it used to work before!

Also running:

kubectl get pods

returns results

Any one knows what might be the reason?


问:
C# Entity Framework Core: unable to resolve service
I'm trying to use Entity Framework Core for C# for the first time. My project does compile, but my add-migration does not run.

I get the error:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceDependencies' while attempting to activate 'MySql.EntityFrameworkCore.Storage.Internal.MySQLTypeMappingSource'.

My project file:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BCrypt.Net-Next" Version="4.0.2" />
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="MySql.EntityFrameworkCore" Version="6.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>
</code>```

My DbContext:

```<code>internal class DbModelContext : DbContext
{
    public DbSet<DbUser> Users { get; set; }
    public DbModelContext(DbContextOptions<DbModelContext> options)
        : base(options) { }
}
</code>```

My user table:

```<code>internal class DbUser
{
    [Key]
    public string? Email { get; set; }
    public string? PasswordHash { get; set; }
    public Guid UserId { get; set; }
}
</code>```

Here is my Program.cs (im using net6 so i dont have a startup.cs)

```<code>//Init DbConnectorClass
DatabaseConnector dbConnector = new();

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//TODO: move to appsettings.json
var connString = "server=192.168.178.XXX;user=XXX;database=XXX;password=XXX;port=3306";

builder.Services.AddDbContext<DbModelContext>(options => options.UseMySQL(connString));
builder.Services.AddScoped<IAuthenticationHandler>(ah => new AuthenticationHandler(dbConnector));

WebApplication app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
</code>```

答:
<PackageReference Include="EntityFramework" Version="6.4.4" />
```
<p>This is <strong>not</strong> Entity Framework core, but the old EF 6.
You need to install/replace it with</p>
<pre class="lang-xml prettyprint-override"><code><PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.1" />
</code>```

Or the version of your liking.

Also, the MySql provider you are using is not so great. You might want to switch to Pomelo

Body:
I'm trying to use Entity Framework Core for C# for the first time. My project does compile, but my add-migration does not run.

I get the error:

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceDependencies' while attempting to activate 'MySql.EntityFrameworkCore.Storage.Internal.MySQLTypeMappingSource'.

My project file:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BCrypt.Net-Next" Version="4.0.2" />
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="MySql.EntityFrameworkCore" Version="6.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>
</Project>

My DbContext:

internal class DbModelContext : DbContext
{
    public DbSet<DbUser> Users { get; set; }
    public DbModelContext(DbContextOptions<DbModelContext> options)
        : base(options) { }
}

My user table:

internal class DbUser
{
    [Key]
    public string? Email { get; set; }
    public string? PasswordHash { get; set; }
    public Guid UserId { get; set; }
}

Here is my Program.cs (im using net6 so i dont have a startup.cs)

//Init DbConnectorClass
DatabaseConnector dbConnector = new();

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//TODO: move to appsettings.json
var connString = "server=192.168.178.XXX;user=XXX;database=XXX;password=XXX;port=3306";

builder.Services.AddDbContext<DbModelContext>(options => options.UseMySQL(connString));
builder.Services.AddScoped<IAuthenticationHandler>(ah => new AuthenticationHandler(dbConnector));

WebApplication app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Body:
<PackageReference Include="EntityFramework" Version="6.4.4" />

This is not Entity Framework core, but the old EF 6.
You need to install/replace it with

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.1" />

Or the version of your liking.

Also, the MySql provider you are using is not so great. You might want to switch to Pomelo


问:
Bold particular text in string on runtime jQuery
My requirement is : Thers's an input field. When user is going to filled it,
on runtime i searched for #tag and make text bold. And wants to separate both groups of #tags

For Example: "I am more #FromSide #FromSide  and would like to speak with someone more #ToSide"
Group1: #FromSide #FromSide
Group2: #ToSide

Here's my code:

```<code> `$('#custm-field').keyup(function(){`
            `let str = $(this).val();`
            `let arr = str.split(" ");`
            `$(arr).each((i,e)=>{`
                `if(e=="#")`
                `{ // $(e).css('font-weight','bold');`
                    `arr[i].replace(e,"<strong>"+e+"</strong>");}
                    `let newStr = arr.join(" ");`
            `$('#custm-field').val(newStr)`
            `});`
</code>```

答:
This can be achieved using RegEx:

$('#custm-field').keyup(function(){
  let str = $(this).val();
  str = str.replace(/#(.+?)\s/, '$1');
  $('#custm-field').val(str);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="custm-field"></input></code>```

However, the bold effect won't be displayed in input fields, you need a contenteditable element for this.

Body:
My requirement is : Thers's an input field. When user is going to filled it,
on runtime i searched for #tag and make text bold. And wants to separate both groups of #tags

For Example: "I am more #FromSide #FromSide  and would like to speak with someone more #ToSide"
Group1: #FromSide #FromSide
Group2: #ToSide

Here's my code:

 `$('#custm-field').keyup(function(){`
            `let str = $(this).val();`
            `let arr = str.split(" ");`
            `$(arr).each((i,e)=>{`
                `if(e=="#")`
                `{ // $(e).css('font-weight','bold');`
                    `arr[i].replace(e,""+e+"");}
                    `let newStr = arr.join(" ");`
            `$('#custm-field').val(newStr)`
            `});`

Body:
This can be achieved using RegEx:

$('#custm-field').keyup(function(){
  let str = $(this).val();
  str = str.replace(/#(.+?)\s/, '<strong>$1</strong>');
  $('#custm-field').val(str);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="custm-field"></input>

However, the bold effect won't be displayed in input fields, you need a contenteditable element for this.