问:
Search in MacMail
I am running OS X 10.11.6 and MacMail 9.3 can not search my emails.
I 'rebuilt' my mailboxes and rebuilt my SpotLight indexes.

MacMail always reports 'Zero matches for search'.

Spotlight is saving in 'Store-V2', while the 'Envelope' indexes are in 'V3'.

What could be wrong?

```<code>$ pwd
/Users/davidlaxer/Library/Mail/V3/MailData
(base) MacBook-Pro:MailData davidlaxer$ ls -lrt Env*
-rwxr-xr-x@ 1 davidlaxer  staff  86241280 May 10 10:31 Envelope Index
-rwxr-xr-x@ 1 davidlaxer  staff     32768 May 10 11:20 Envelope Index-shm
-rwxr-xr-x@ 1 davidlaxer  staff   1512072 May 10 11:46 Envelope Index-wal

$ sudo du -g /.Spotlight-V100/
Password:
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.assisted_import_post
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.assisted_import_pre
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.corespotlight
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.health_check
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_priority
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_system
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_user
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.migration
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.migration_secondchance
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.scan
14  /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039
14  /.Spotlight-V100//Store-V2
14  /.Spotlight-V100/

 sudo ls -lRt /.Spotlight-V100/
total 8
drwx------  3 root  wheel   102 May  5 08:27 Store-V2
-rw-------  1 root  wheel  4001 May  5 08:27 VolumeConfiguration.plist

/.Spotlight-V100//Store-V2:
total 0
drwx------  119 root  wheel  4046 May 10 11:50 CD1CE8CA-B264-41BC-909A-ACD3AE66F039

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039:
total 28512848
-rw-------  1 root  wheel   261361664 May 10 11:51 .store.db
-rw-------  1 root  wheel        6554 May 10 11:51 live.4.indexGroups
-rw-------  1 root  wheel       65536 May 10 11:51 live.4.indexIds
-rw-------  1 root  wheel        7452 May 10 11:51 journalAttr.153
-rw-------  1 root  wheel     4614377 May 10 11:50 0.indexGroups
drwx------  3 root  wheel         102 May 10 11:50 journals.health_check
-rw-------  1 root  wheel        4096 May 10 11:50 0.indexHead
-rw-------  1 root  wheel        4096 May 10 11:50 tmp.spotlight.state
drwx------  3 root  wheel         102 May 10 11:46 journals.assisted_import_pre
-rw-------  1 root  wheel          62 May 10 11:45 live.1.indexGroups
-rw-------  1 root  wheel         616 May 10 11:45 live.1.indexIds
-rw-------  1 root  wheel        4096 May 10 11:45 live.1.indexHead
-rw-------  1 root  wheel    33554432 May 10 11:29 0.directoryStoreFile
-rw-------  1 root  wheel     4194304 May 10 11:29 live.0.directoryStoreFile
-rw-------  1 root  wheel        4096 May 10 11:29 live.0.indexHead
-rw-------  1 root  wheel       65536 May 10 11:29 live.1.directoryStoreFile
-rw-------  1 root  wheel     1048576 May 10 11:29 live.3.directoryStoreFile
-rw-------  1 root  wheel        4096 May 10 11:29 live.3.indexHead
-rw-------  1 root  wheel       65536 May 10 11:29 live.4.directoryStoreFile
-rw-------  1 root  wheel    33554432 May 10 11:29 reverseDirectoryStore
-rw-------  1 root  wheel        4096 May 10 11:29 live.4.indexHead
-rw-------  1 root  wheel    25952256 May 10 11:29 0.directoryStoreFile.shadow
-rw-------  1 root  wheel     4614377 May 10 11:29 0.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 0.shadowIndexHead
-rw-------  1 root  wheel          28 May 10 11:29 indexState
drwx------  3 root  wheel         102 May 10 11:29 journals.assisted_import_post
drwx------  3 root  wheel         102 May 10 11:29 journals.live_system
drwx------  3 root  wheel         102 May 10 11:29 journals.live_user
-rw-------  1 root  wheel     2752512 May 10 11:29 live.0.directoryStoreFile.shadow
-rw-------  1 root  wheel     1144320 May 10 11:29 live.0.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 live.0.shadowIndexHead
-rw-------  1 root  wheel        5952 May 10 11:29 live.1.directoryStoreFile.shadow
-rw-------  1 root  wheel          62 May 10 11:29 live.1.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 live.1.shadowIndexHead
-rw-------  1 root  wheel      786432 May 10 11:29 live.3.directoryStoreFile.shadow
-rw-------  1 root  wheel       45288 May 10 11:29 live.3.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 live.3.shadowIndexHead
-rw-------  1 root  wheel       17664 May 10 11:29 live.4.directoryStoreFile.shadow
-rw-------  1 root  wheel           0 May 10 11:29 live.4.indexUpdates
-rw-------  1 root  wheel     8388608 May 10 11:29 live.4.shadowIndexArrays
-rw-------  1 root  wheel        1456 May 10 11:29 live.4.shadowIndexCompactDirectory
-rw-------  1 root  wheel       19532 May 10 11:29 live.4.shadowIndexDirectory
-rw-------  1 root  wheel        2932 May 10 11:29 live.4.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 live.4.shadowIndexHead
-rw-------  1 root  wheel     2501400 May 10 11:29 live.4.shadowIndexPositionTable
-rw-------  1 root  wheel     2501400 May 10 11:29 live.4.shadowIndexTermIds
-rw-------  1 root  wheel    31719424 May 10 11:29 reverseDirectoryStore.shadow
-rw-------  1 root  wheel          33 May 10 11:29 reverseStore.updates
-rw-------  1 root  wheel   261361664 May 10 11:29 store.db
-rw-------  1 root  wheel           3 May 10 11:29 store.updates
-rw-------  1 root  wheel     8388608 May 10 11:29 live.4.indexArrays
-rw-------  1 root  wheel        2048 May 10 11:29 live.4.indexCompactDirectory
-rw-------  1 root  wheel       32896 May 10 11:29 live.4.indexDirectory
-rw-------  1 root  wheel     4194304 May 10 11:29 live.4.indexPositionTable
-rw-------  1 root  wheel    16777216 May 10 11:29 live.4.indexPositions
-rw-------  1 root  wheel     8388608 May 10 11:29 live.4.indexPostings
-rw-------  1 root  wheel     4194304 May 10 11:29 live.4.indexTermIds
-rw-r--r--  1 root  wheel           4 May 10 11:29 shutdown_time
-rw-------  1 root  wheel     1144320 May 10 11:20 live.0.indexGroups
-rw-------  1 root  wheel    11443200 May 10 11:20 live.0.indexIds
-rw-------  1 root  wheel       45288 May 10 10:41 live.3.indexGroups
-rw-------  1 root  wheel      452880 May 10 08:54 live.3.indexIds
-rw-------  1 root  wheel    19262912 May 10 08:50 live.3.indexArrays
-rw-------  1 root  wheel     4022314 May 10 08:50 live.3.indexCompactDirectory
-rw-------  1 root  wheel      460544 May 10 08:50 live.3.indexDirectory
-rw-------  1 root  wheel          31 May 10 08:50 live.3.indexUpdates
-rw-------  1 root  wheel    35174385 May 10 08:50 live.3.indexPositions
-rw-------  1 root  wheel     9377717 May 10 08:50 live.3.indexPostings
-rw-------  1 root  wheel       65536 May 10 08:16 live.2.directoryStoreFile
-rw-------  1 root  wheel        4096 May 10 08:16 live.2.indexHead
-rw-------  1 root  wheel        1792 May 10 08:16 live.2.directoryStoreFile.shadow
-rw-------  1 root  wheel           4 May 10 08:16 live.2.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 08:16 live.2.shadowIndexHead
-rw-------  1 root  wheel     5937408 May 10 08:16 live.1.indexArrays
-rw-------  1 root  wheel      732628 May 10 08:16 live.1.indexCompactDirectory
-rw-------  1 root  wheel      722684 May 10 08:16 live.1.indexDirectory
-rw-------  1 root  wheel          17 May 10 08:16 live.1.indexUpdates
-rw-------  1 root  wheel     1332150 May 10 08:16 live.1.indexPositions
-rw-------  1 root  wheel      381040 May 10 08:16 live.1.indexPostings
-rw-------  1 root  wheel        3277 May 10 08:16 live.2.indexGroups
-rw-------  1 root  wheel        2112 May 10 08:15 live.2.indexArrays
-rw-------  1 root  wheel           8 May 10 08:15 live.2.indexCompactDirectory
-rw-------  1 root  wheel        2056 May 10 08:15 live.2.indexDirectory
-rw-------  1 root  wheel          32 May 10 08:15 live.2.indexIds
-rw-------  1 root  wheel         704 May 10 08:15 live.2.indexPositionTable
-rw-------  1 root  wheel         704 May 10 08:15 live.2.indexTermIds
-rw-------  1 root  wheel        4096 May 10 08:15 live.2.indexPostings
-rw-------  1 root  wheel          13 May 10 08:15 live.2.indexUpdates
-rw-------  1 root  wheel        4096 May 10 08:15 live.2.indexPositions
-rw-------  1 root  wheel   116111616 May 10 06:55 live.0.indexArrays
-rw-------  1 root  wheel    16341676 May 10 06:55 live.0.indexCompactDirectory
-rw-------  1 root  wheel     7297772 May 10 06:55 live.0.indexDirectory
-rw-------  1 root  wheel         125 May 10 06:55 live.0.indexUpdates
-rw-------  1 root  wheel   233745118 May 10 06:55 live.0.indexPositions
-rw-------  1 root  wheel    92373248 May 10 06:55 live.0.indexPostings
-rw-------  1 root  wheel    46143768 May  9 17:44 0.indexIds
drwx------  3 root  wheel         102 May  8 15:29 journals.live_priority
-rw-------  1 root  wheel      814959 May  8 15:29 tmp.spotlight.loc
-rw-------  1 root  wheel  1863674176 May  7 15:28 0.indexArrays
-rw-------  1 root  wheel   421591410 May  7 15:28 0.indexCompactDirectory
-rw-------  1 root  wheel    32731520 May  7 15:28 0.indexDirectory
-rw-------  1 root  wheel        1815 May  7 15:28 0.indexUpdates
-rw-------  1 root  wheel  9492016397 May  7 15:21 0.indexPositions
-rw-------  1 root  wheel  1462613059 May  7 15:21 0.indexPostings
drwx------  3 root  wheel         102 May  7 14:10 journals.scan
-rw-------  1 root  wheel           0 May  5 08:27 Cab.created
-rw-------  1 root  wheel           0 May  5 08:27 Lion.created
-rw-------  1 root  wheel           0 May  5 08:27 journalAttr.1
-rw-------  1 root  wheel           0 May  5 08:27 journalExclusion
drwx------  2 root  wheel          68 May  5 08:27 journals.corespotlight
drwx------  2 root  wheel          68 May  5 08:27 journals.live
drwx------  2 root  wheel          68 May  5 08:27 journals.migration
drwx------  2 root  wheel          68 May  5 08:27 journals.migration_secondchance
-rw-r--r--  1 root  wheel           4 May  5 08:27 store_generation
-rw-------  1 root  wheel           0 May  5 08:27 tmp.Cab
-rw-------  1 root  wheel           0 May  5 08:27 tmp.Lion
-rw-------  1 root  wheel           0 May  5 08:27 tmp.SnowLeopard

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.health_check:
total 0
-rw-------  1 root  wheel  0 May 10 11:50 retire.10586

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.assisted_import_pre:
total 0
-rw-------  1 root  wheel  0 May 10 11:46 retire.155623

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.assisted_import_post:
total 0
-rw-------  1 root  wheel  0 May 10 11:29 retire.372

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_system:
total 0
-rw-------  1 root  wheel  0 May 10 11:29 retire.359623

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_user:
total 0
-rw-------  1 root  wheel  0 May 10 11:29 retire.970891

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_priority:
total 0
-rw-------  1 root  wheel  0 May  8 15:29 retire.272870

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.scan:
total 0
-rw-------  1 root  wheel  0 May  7 14:10 retire.5816751

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.corespotlight:

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live:

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.migration:

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.migration_secondchance:

</code>```

答:
The directory ~/Library/Metadata/CoreSpotlight/ was missing.

/private/var/folders had directories owned by a non-existent user.
Clearly, the disk cloning had issues.
The solution was to do a clean reinstall the OS and use the migration assistant.

Title: Search in MacMail

Body:
I am running OS X 10.11.6 and MacMail 9.3 can not search my emails.
I 'rebuilt' my mailboxes and rebuilt my SpotLight indexes.

MacMail always reports 'Zero matches for search'.

Spotlight is saving in 'Store-V2', while the 'Envelope' indexes are in 'V3'.

What could be wrong?

$ pwd
/Users/davidlaxer/Library/Mail/V3/MailData
(base) MacBook-Pro:MailData davidlaxer$ ls -lrt Env*
-rwxr-xr-x@ 1 davidlaxer  staff  86241280 May 10 10:31 Envelope Index
-rwxr-xr-x@ 1 davidlaxer  staff     32768 May 10 11:20 Envelope Index-shm
-rwxr-xr-x@ 1 davidlaxer  staff   1512072 May 10 11:46 Envelope Index-wal

$ sudo du -g /.Spotlight-V100/
Password:
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.assisted_import_post
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.assisted_import_pre
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.corespotlight
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.health_check
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_priority
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_system
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_user
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.migration
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.migration_secondchance
0   /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.scan
14  /.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039
14  /.Spotlight-V100//Store-V2
14  /.Spotlight-V100/

 sudo ls -lRt /.Spotlight-V100/
total 8
drwx------  3 root  wheel   102 May  5 08:27 Store-V2
-rw-------  1 root  wheel  4001 May  5 08:27 VolumeConfiguration.plist

/.Spotlight-V100//Store-V2:
total 0
drwx------  119 root  wheel  4046 May 10 11:50 CD1CE8CA-B264-41BC-909A-ACD3AE66F039

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039:
total 28512848
-rw-------  1 root  wheel   261361664 May 10 11:51 .store.db
-rw-------  1 root  wheel        6554 May 10 11:51 live.4.indexGroups
-rw-------  1 root  wheel       65536 May 10 11:51 live.4.indexIds
-rw-------  1 root  wheel        7452 May 10 11:51 journalAttr.153
-rw-------  1 root  wheel     4614377 May 10 11:50 0.indexGroups
drwx------  3 root  wheel         102 May 10 11:50 journals.health_check
-rw-------  1 root  wheel        4096 May 10 11:50 0.indexHead
-rw-------  1 root  wheel        4096 May 10 11:50 tmp.spotlight.state
drwx------  3 root  wheel         102 May 10 11:46 journals.assisted_import_pre
-rw-------  1 root  wheel          62 May 10 11:45 live.1.indexGroups
-rw-------  1 root  wheel         616 May 10 11:45 live.1.indexIds
-rw-------  1 root  wheel        4096 May 10 11:45 live.1.indexHead
-rw-------  1 root  wheel    33554432 May 10 11:29 0.directoryStoreFile
-rw-------  1 root  wheel     4194304 May 10 11:29 live.0.directoryStoreFile
-rw-------  1 root  wheel        4096 May 10 11:29 live.0.indexHead
-rw-------  1 root  wheel       65536 May 10 11:29 live.1.directoryStoreFile
-rw-------  1 root  wheel     1048576 May 10 11:29 live.3.directoryStoreFile
-rw-------  1 root  wheel        4096 May 10 11:29 live.3.indexHead
-rw-------  1 root  wheel       65536 May 10 11:29 live.4.directoryStoreFile
-rw-------  1 root  wheel    33554432 May 10 11:29 reverseDirectoryStore
-rw-------  1 root  wheel        4096 May 10 11:29 live.4.indexHead
-rw-------  1 root  wheel    25952256 May 10 11:29 0.directoryStoreFile.shadow
-rw-------  1 root  wheel     4614377 May 10 11:29 0.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 0.shadowIndexHead
-rw-------  1 root  wheel          28 May 10 11:29 indexState
drwx------  3 root  wheel         102 May 10 11:29 journals.assisted_import_post
drwx------  3 root  wheel         102 May 10 11:29 journals.live_system
drwx------  3 root  wheel         102 May 10 11:29 journals.live_user
-rw-------  1 root  wheel     2752512 May 10 11:29 live.0.directoryStoreFile.shadow
-rw-------  1 root  wheel     1144320 May 10 11:29 live.0.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 live.0.shadowIndexHead
-rw-------  1 root  wheel        5952 May 10 11:29 live.1.directoryStoreFile.shadow
-rw-------  1 root  wheel          62 May 10 11:29 live.1.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 live.1.shadowIndexHead
-rw-------  1 root  wheel      786432 May 10 11:29 live.3.directoryStoreFile.shadow
-rw-------  1 root  wheel       45288 May 10 11:29 live.3.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 live.3.shadowIndexHead
-rw-------  1 root  wheel       17664 May 10 11:29 live.4.directoryStoreFile.shadow
-rw-------  1 root  wheel           0 May 10 11:29 live.4.indexUpdates
-rw-------  1 root  wheel     8388608 May 10 11:29 live.4.shadowIndexArrays
-rw-------  1 root  wheel        1456 May 10 11:29 live.4.shadowIndexCompactDirectory
-rw-------  1 root  wheel       19532 May 10 11:29 live.4.shadowIndexDirectory
-rw-------  1 root  wheel        2932 May 10 11:29 live.4.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 11:29 live.4.shadowIndexHead
-rw-------  1 root  wheel     2501400 May 10 11:29 live.4.shadowIndexPositionTable
-rw-------  1 root  wheel     2501400 May 10 11:29 live.4.shadowIndexTermIds
-rw-------  1 root  wheel    31719424 May 10 11:29 reverseDirectoryStore.shadow
-rw-------  1 root  wheel          33 May 10 11:29 reverseStore.updates
-rw-------  1 root  wheel   261361664 May 10 11:29 store.db
-rw-------  1 root  wheel           3 May 10 11:29 store.updates
-rw-------  1 root  wheel     8388608 May 10 11:29 live.4.indexArrays
-rw-------  1 root  wheel        2048 May 10 11:29 live.4.indexCompactDirectory
-rw-------  1 root  wheel       32896 May 10 11:29 live.4.indexDirectory
-rw-------  1 root  wheel     4194304 May 10 11:29 live.4.indexPositionTable
-rw-------  1 root  wheel    16777216 May 10 11:29 live.4.indexPositions
-rw-------  1 root  wheel     8388608 May 10 11:29 live.4.indexPostings
-rw-------  1 root  wheel     4194304 May 10 11:29 live.4.indexTermIds
-rw-r--r--  1 root  wheel           4 May 10 11:29 shutdown_time
-rw-------  1 root  wheel     1144320 May 10 11:20 live.0.indexGroups
-rw-------  1 root  wheel    11443200 May 10 11:20 live.0.indexIds
-rw-------  1 root  wheel       45288 May 10 10:41 live.3.indexGroups
-rw-------  1 root  wheel      452880 May 10 08:54 live.3.indexIds
-rw-------  1 root  wheel    19262912 May 10 08:50 live.3.indexArrays
-rw-------  1 root  wheel     4022314 May 10 08:50 live.3.indexCompactDirectory
-rw-------  1 root  wheel      460544 May 10 08:50 live.3.indexDirectory
-rw-------  1 root  wheel          31 May 10 08:50 live.3.indexUpdates
-rw-------  1 root  wheel    35174385 May 10 08:50 live.3.indexPositions
-rw-------  1 root  wheel     9377717 May 10 08:50 live.3.indexPostings
-rw-------  1 root  wheel       65536 May 10 08:16 live.2.directoryStoreFile
-rw-------  1 root  wheel        4096 May 10 08:16 live.2.indexHead
-rw-------  1 root  wheel        1792 May 10 08:16 live.2.directoryStoreFile.shadow
-rw-------  1 root  wheel           4 May 10 08:16 live.2.shadowIndexGroups
-rw-------  1 root  wheel        4096 May 10 08:16 live.2.shadowIndexHead
-rw-------  1 root  wheel     5937408 May 10 08:16 live.1.indexArrays
-rw-------  1 root  wheel      732628 May 10 08:16 live.1.indexCompactDirectory
-rw-------  1 root  wheel      722684 May 10 08:16 live.1.indexDirectory
-rw-------  1 root  wheel          17 May 10 08:16 live.1.indexUpdates
-rw-------  1 root  wheel     1332150 May 10 08:16 live.1.indexPositions
-rw-------  1 root  wheel      381040 May 10 08:16 live.1.indexPostings
-rw-------  1 root  wheel        3277 May 10 08:16 live.2.indexGroups
-rw-------  1 root  wheel        2112 May 10 08:15 live.2.indexArrays
-rw-------  1 root  wheel           8 May 10 08:15 live.2.indexCompactDirectory
-rw-------  1 root  wheel        2056 May 10 08:15 live.2.indexDirectory
-rw-------  1 root  wheel          32 May 10 08:15 live.2.indexIds
-rw-------  1 root  wheel         704 May 10 08:15 live.2.indexPositionTable
-rw-------  1 root  wheel         704 May 10 08:15 live.2.indexTermIds
-rw-------  1 root  wheel        4096 May 10 08:15 live.2.indexPostings
-rw-------  1 root  wheel          13 May 10 08:15 live.2.indexUpdates
-rw-------  1 root  wheel        4096 May 10 08:15 live.2.indexPositions
-rw-------  1 root  wheel   116111616 May 10 06:55 live.0.indexArrays
-rw-------  1 root  wheel    16341676 May 10 06:55 live.0.indexCompactDirectory
-rw-------  1 root  wheel     7297772 May 10 06:55 live.0.indexDirectory
-rw-------  1 root  wheel         125 May 10 06:55 live.0.indexUpdates
-rw-------  1 root  wheel   233745118 May 10 06:55 live.0.indexPositions
-rw-------  1 root  wheel    92373248 May 10 06:55 live.0.indexPostings
-rw-------  1 root  wheel    46143768 May  9 17:44 0.indexIds
drwx------  3 root  wheel         102 May  8 15:29 journals.live_priority
-rw-------  1 root  wheel      814959 May  8 15:29 tmp.spotlight.loc
-rw-------  1 root  wheel  1863674176 May  7 15:28 0.indexArrays
-rw-------  1 root  wheel   421591410 May  7 15:28 0.indexCompactDirectory
-rw-------  1 root  wheel    32731520 May  7 15:28 0.indexDirectory
-rw-------  1 root  wheel        1815 May  7 15:28 0.indexUpdates
-rw-------  1 root  wheel  9492016397 May  7 15:21 0.indexPositions
-rw-------  1 root  wheel  1462613059 May  7 15:21 0.indexPostings
drwx------  3 root  wheel         102 May  7 14:10 journals.scan
-rw-------  1 root  wheel           0 May  5 08:27 Cab.created
-rw-------  1 root  wheel           0 May  5 08:27 Lion.created
-rw-------  1 root  wheel           0 May  5 08:27 journalAttr.1
-rw-------  1 root  wheel           0 May  5 08:27 journalExclusion
drwx------  2 root  wheel          68 May  5 08:27 journals.corespotlight
drwx------  2 root  wheel          68 May  5 08:27 journals.live
drwx------  2 root  wheel          68 May  5 08:27 journals.migration
drwx------  2 root  wheel          68 May  5 08:27 journals.migration_secondchance
-rw-r--r--  1 root  wheel           4 May  5 08:27 store_generation
-rw-------  1 root  wheel           0 May  5 08:27 tmp.Cab
-rw-------  1 root  wheel           0 May  5 08:27 tmp.Lion
-rw-------  1 root  wheel           0 May  5 08:27 tmp.SnowLeopard

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.health_check:
total 0
-rw-------  1 root  wheel  0 May 10 11:50 retire.10586

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.assisted_import_pre:
total 0
-rw-------  1 root  wheel  0 May 10 11:46 retire.155623

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.assisted_import_post:
total 0
-rw-------  1 root  wheel  0 May 10 11:29 retire.372

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_system:
total 0
-rw-------  1 root  wheel  0 May 10 11:29 retire.359623

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_user:
total 0
-rw-------  1 root  wheel  0 May 10 11:29 retire.970891

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live_priority:
total 0
-rw-------  1 root  wheel  0 May  8 15:29 retire.272870

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.scan:
total 0
-rw-------  1 root  wheel  0 May  7 14:10 retire.5816751

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.corespotlight:

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.live:

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.migration:

/.Spotlight-V100//Store-V2/CD1CE8CA-B264-41BC-909A-ACD3AE66F039/journals.migration_secondchance:


来源: stackexchange

问:
How to configure Visual Studio not to give UAC prompt on each run?
I have switched to Vista recently and I wanted to keep UAC turned on, as I agree it increases computer security a lot. Some developer tools I use regularly require running elevated:

PIX for Windows

Visual Studio 2005 (elevated privileges seem to be needed for debugging and for IncrediBuild to work)

mapped and substed drives: The elevated process does not seem to see the drives I have mapped in my user account. This article describes the problem, but I am not sure how could I implement its final suggestion to "map these drives in the context of the elevated login".

I have experimented with many suggestions I have found, Compatibility Administrator seemed quite promising, but the result was still not what I wanted. When I used RunAsInvoker, there was no UAC prompt, but the Visual Studio did not work. When I used RunAsAdmin or RunAsHighest, it worked, but there was the prompt.

Is there any way how to teach UAC to remember some particular application should always run elevated and never prompt me about this, or some other way how to allow me launching VS elevated without the prompt? If there is no way to do it, does there exist some security reason why it cannot be done?

答:
Try:

Administrative Tools -> Local Security Policy -> Local Policies -> Security Options -> User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode = Elevate without prompting.

OwnerDisplayName: Suma

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Suma

ContentLicense: CC BY-SA 3.0


问:
I get an Error JNA while trying to run my java program from CLI
I get this error when trying to run my program from CLI:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: daniel has been compiled by a more recent version of the Java Runtime (class file version 58.0), this version of the Java Runtime only recognizes class file versions up to 52.0

I have Windows 10
Already tried updating the path following these steps:

Search for Advanced System Settings in your windows Search box. Click on Advanced System Settings.

Click on Environment variables button: Environment Variables popup will open.

Go to system variables session, and click on New button to create new variable (HOME_PATH), then New System Variables popup will open.

Give Variable Name: JAVA_HOME, and Variable value : Your Java SDK home path. Ex: C:\Profram files\java\jdk1.8.0_151 Note: It should not include \bin. Then click on OK button.

Now you are able to see your JAVA_HOME in system variables list.

Select Path (from system variables list) and click on Edit button, A new pop will opens (Edit Environment Variables). It was introduced in windows 10.

Click on New button and give %JAVA_HOME%\bin at highlighted field and click Ok button.

Didn't work, also tried uninstalling the JDK and reinstalling but same issue, I installed the JDK from this link: https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html

Any clue?

答:
Mmhm I remember I tried version 14 but uninstalled then installed Java 8, not sure if that created a conclict.

Also I can use Eclipse and it runs fine, but I want to try using CLI

java -version gives:

java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)

ContentLicense: CC BY-SA 4.0


问:
Using future<> and promise<> for message passing?
I'm trying write a simple program to pass message with future<> and promise<> so I understand how they work.  The intent is to pass 10  objects from the produce to the consumer.  Unfortunately, I'm running into compilation issues.  Does anyone know where I have gone wrong?
Thank you!

Update solution.

```<code>#include <iostream>
#include <thread>
#include <unistd.h>
#include <stdlib.h>
#include <future>
#include <functional>
#include <vector>
using namespace std;
using namespace std::chrono;

struct MSG {
  int val;
};

void consumer(vector<future<MSG>> *futv) {
  for (auto& p : *futv) {
    this_thread::sleep_for(milliseconds{rand() % 25});
    MSG m = p.get();
    cout << m.val << endl;
  }
}

void producer(vector<promise<MSG>> *promv) {
  MSG m = {0};

  for (auto& p : *promv) {
    this_thread::sleep_for(milliseconds{rand() % 25});
    p.set_value(m);
    m.val++;
  }
}

int main(int argc, char *argv[])
{
  vector<promise<MSG>> promv;
  vector<future<MSG>> futv;

  for (int i=0; i<10; i++) {
    promv.push_back(promise<MSG>());
    futv.push_back(promv[i].get_future());
  }

  thread tp {producer, &promv};
  thread tc {consumer, &futv};

  tp.join();
  tc.join();

  return 0;
}
</code>```

Compilation...,

```<code>g++ -lpthread -pedantic -Wall test84.cc && ./a.out
0
1
2
3
4
5
6
7
8
9
</code>```

答:
The error is due to future being only movable but not copyable

for (auto p : futv) - this is an attempt to copy elements fro vector.
Use the following loops to have reference to vector element instead:

for (auto& p : futv)
or
for (decltype(auto) p : futv)

Generally the idea may work as an exercise, but promises/futures are not really designed for that. The problem is that you cannot reuse elements of your array for another run. So for real uses, producer-consumer queues are implemented by using lower level primitives: mutexes, condition variables, atomics, etc.

Body:
I'm trying write a simple program to pass message with future<> and promise<> so I understand how they work.  The intent is to pass 10  objects from the produce to the consumer.  Unfortunately, I'm running into compilation issues.  Does anyone know where I have gone wrong?
Thank you!

Update solution.

#include <iostream>
#include <thread>
#include <unistd.h>
#include <stdlib.h>
#include <future>
#include <functional>
#include <vector>
using namespace std;
using namespace std::chrono;

struct MSG {
  int val;
};

void consumer(vector<future<MSG>> *futv) {
  for (auto& p : *futv) {
    this_thread::sleep_for(milliseconds{rand() % 25});
    MSG m = p.get();
    cout << m.val << endl;
  }
}

void producer(vector<promise<MSG>> *promv) {
  MSG m = {0};

  for (auto& p : *promv) {
    this_thread::sleep_for(milliseconds{rand() % 25});
    p.set_value(m);
    m.val++;
  }
}

int main(int argc, char *argv[])
{
  vector<promise<MSG>> promv;
  vector<future<MSG>> futv;

  for (int i=0; i<10; i++) {
    promv.push_back(promise<MSG>());
    futv.push_back(promv[i].get_future());
  }

  thread tp {producer, &promv};
  thread tc {consumer, &futv};

  tp.join();
  tc.join();

  return 0;
}

Compilation...,

g++ -lpthread -pedantic -Wall test84.cc && ./a.out
0
1
2
3
4
5
6
7
8
9


问:
How to acess the appsettings in blazor webassembly
I currentying trying to save the api url in an appsettings.
However, the configuration.Propertiers seems to be empty. I am not sure how to get the setting.
in program.cs:</p>

```<code>public static async Task Main(string[] args)
{
   var builder = WebAssemblyHostBuilder.CreateDefault(args);
   //string url = builder.Configuration.Properties["APIURL"].ToString();
   foreach (var prop in builder.Configuration.Properties)
      Console.WriteLine($"{prop.Key} : {prop.Value}" );
   //builder.Services.AddSingleton<Service>(new Service(url));
   builder.RootComponents.Add<App>("app");
   await builder.Build().RunAsync();
}
</code>```

答:
Inkkiller nailed it.  You can simplify the call into IConfiguration without the APIHelper class and access it directly in Program.cs from the WebAssemblyHostBuilder.

appsettings:

```<code>{
   "ServerlessBaseURI": "http://localhost:0000/",
}
</code>```

Program.cs:

```<code>public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);

    string serverlessBaseURI = builder.Configuration["ServerlessBaseURI"];
}

</code>```

Body:
I currentying trying to save the api url in an appsettings.
However, the configuration.Propertiers seems to be empty. I am not sure how to get the setting.
in program.cs:

public static async Task Main(string[] args)
{
   var builder = WebAssemblyHostBuilder.CreateDefault(args);
   //string url = builder.Configuration.Properties["APIURL"].ToString();
   foreach (var prop in builder.Configuration.Properties)
      Console.WriteLine($"{prop.Key} : {prop.Value}" );
   //builder.Services.AddSingleton<Service>(new Service(url));
   builder.RootComponents.Add<App>("app");
   await builder.Build().RunAsync();
}

Body:
Inkkiller nailed it.  You can simplify the call into IConfiguration without the APIHelper class and access it directly in Program.cs from the WebAssemblyHostBuilder.

appsettings:

{
   "ServerlessBaseURI": "http://localhost:0000/",
}

Program.cs:

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);

    string serverlessBaseURI = builder.Configuration["ServerlessBaseURI"];
}


问:
Easiest way to share class across all processes in multiprocessing
I have a class that starts multiple threads upon initialization. Originally I was using threading, but I learned the hard way how painfully slow it can get. As I researched this, it seems that multiprocessing would be faster because it actually utilizes multiple cores. The only hard part is the fact that it doesn't automatically share values. How could I make the following code share self across all processes?

Ideally, it would also share across processes outside of the class as well.
Also, I would rather share the entire class than share each individual value, if possible.

import multiprocessing as mp
from time import sleep

class ThreadedClass:
    def __init__(self):
        self.var = 0
        #Here is where I would want to tell multiprocessing to share 'self'
        change_var = mp.Process(target=self.change_var, args=())
        print_var = mp.Process(target=self.print_var, args=())
        change_var.start()
        sleep(0.5)
        print_var.start()

    def change_var(self):
        while True:
            self.var += 1
            print("Changed var to ", self.var)
            sleep(1)

    def print_var(self):
        while True:
            print("Printing var: ", self.var)
            sleep(1)

ThreadedClass()
```

<p>I also included output of the above code below:</p>

```Changed var to  1
Printing var:  0
Changed var to  2
Printing var:  0
Changed var to  3
Printing var:  0
Changed var to  4
Printing var:  0
Changed var to  5
Printing var:  0
Changed var to  6
Printing var:  0
Changed var to  7
Printing var:  0
Changed var to  8
Printing var:  0
Changed var to  9
Printing var:  0
Changed var to  10
```

Thanks in advance.

答:
First of all, multiprocessing means that you are making sub-processes. This means that in general, they have their own space in memory and don't talk to each other. To be clear, when you start a new multiprocessing thread, python copies all your global variables into that thread and then runs that thread separate from everything else. So, when you spawned your two processes, change_var and print_var, each of them received a copy of self, and since their are two copies of self, neither of them is talking to each. One thread is updating it's own copy of self and producing answers that are counting, the other is not updating self. You can easily test this yourself:

```<code>import multiprocessing as mp
LIST = [] # This list is in parent process.
def update(item):
    LIST.append(item)
p = mp.Process(target=update, args=(5,)) # Copies LIST, update, and anything else that is global.
p.start()
p.join()
# The LIST in the sub-process is cleaned up in memory when the process ends.
print(LIST) # The LIST in the parent process is not updated.
</code>```

It would be very dangerous if different processes were updating each other's variables while they were trying to process with them; hence, naturally to isolate them (and prevent "segmentation faults"), the entire namespace is copied. If you want sub-processes to talk to each other, you need to communicate with a manager and Queue that is designed for that.

I personally recommend to write your code around things like a Pool() instead. Very clean, input an array, get back an array, done. But if you want to go down the rabbit hole, here is what I read on the multiprocessing website.

```<code>import multiprocessing as mp

def f(queue):
    queue.put(['stuff',15])
def g(queue):
    queue.put(['other thing'])

queue = mp.Queue()
p = mp.Process(target=f,args=(queue,))
q = mp.Process(target=g,args=(queue,))
p.start()
q.start()
for _ in range(2):
    print(queue.get())
p.join()
q.join()
</code>```

The main idea is that the queue does not get copied and instead allows things to be left in the queue. When the you run queue.get() it waits for something in the queue to be gotten that was left by some other process. queue.get() blocks and waits. This means you could have one process read the contents of the other process, like:

```<code>import multiprocessing as mp

def f(queue):
    obj = queue.get() # Blocks this sub-process until something shows up.
    if obj:
        print('Something was in the queue from some other process.')
        print(obj)
def g(queue):
    queue.put(['leaving information here in queue'])

queue = mp.Queue()
p = mp.Process(target=f,args=(queue,))
q = mp.Process(target=g,args=(queue,))
p.start()
</code>```

This is kindof cool, so I recommend waiting here a second to think about what is waiting to process. Next start the q process.

```<code>q.start()
</code>```

Notice that p didn't get to finish processing until q was started. This is because the Queue blocked and waited for something to show up.

```<code># clean up
p.join()
q.join()
</code>```

You can read more at: https://docs.python.org/3.4/library/multiprocessing.html?highlight=process#multiprocessing.Queue

Body:
I have a class that starts multiple threads upon initialization. Originally I was using threading, but I learned the hard way how painfully slow it can get. As I researched this, it seems that multiprocessing would be faster because it actually utilizes multiple cores. The only hard part is the fact that it doesn't automatically share values. How could I make the following code share self across all processes?

Ideally, it would also share across processes outside of the class as well.
Also, I would rather share the entire class than share each individual value, if possible.

import multiprocessing as mp
from time import sleep

class ThreadedClass:
    def __init__(self):
        self.var = 0
        #Here is where I would want to tell multiprocessing to share 'self'
        change_var = mp.Process(target=self.change_var, args=())
        print_var = mp.Process(target=self.print_var, args=())
        change_var.start()
        sleep(0.5)
        print_var.start()

    def change_var(self):
        while True:
            self.var += 1
            print("Changed var to ", self.var)
            sleep(1)

    def print_var(self):
        while True:
            print("Printing var: ", self.var)
            sleep(1)

ThreadedClass()

I also included output of the above code below:

Changed var to  1
Printing var:  0
Changed var to  2
Printing var:  0
Changed var to  3
Printing var:  0
Changed var to  4
Printing var:  0
Changed var to  5
Printing var:  0
Changed var to  6
Printing var:  0
Changed var to  7
Printing var:  0
Changed var to  8
Printing var:  0
Changed var to  9
Printing var:  0
Changed var to  10

Thanks in advance.

Body:
First of all, multiprocessing means that you are making sub-processes. This means that in general, they have their own space in memory and don't talk to each other. To be clear, when you start a new multiprocessing thread, python copies all your global variables into that thread and then runs that thread separate from everything else. So, when you spawned your two processes, change_var and print_var, each of them received a copy of self, and since their are two copies of self, neither of them is talking to each. One thread is updating it's own copy of self and producing answers that are counting, the other is not updating self. You can easily test this yourself:

import multiprocessing as mp
LIST = [] # This list is in parent process.
def update(item):
    LIST.append(item)
p = mp.Process(target=update, args=(5,)) # Copies LIST, update, and anything else that is global.
p.start()
p.join()
# The LIST in the sub-process is cleaned up in memory when the process ends.
print(LIST) # The LIST in the parent process is not updated.

It would be very dangerous if different processes were updating each other's variables while they were trying to process with them; hence, naturally to isolate them (and prevent "segmentation faults"), the entire namespace is copied. If you want sub-processes to talk to each other, you need to communicate with a manager and Queue that is designed for that.

I personally recommend to write your code around things like a Pool() instead. Very clean, input an array, get back an array, done. But if you want to go down the rabbit hole, here is what I read on the multiprocessing website.

import multiprocessing as mp

def f(queue):
    queue.put(['stuff',15])
def g(queue):
    queue.put(['other thing'])

queue = mp.Queue()
p = mp.Process(target=f,args=(queue,))
q = mp.Process(target=g,args=(queue,))
p.start()
q.start()
for _ in range(2):
    print(queue.get())
p.join()
q.join()

The main idea is that the queue does not get copied and instead allows things to be left in the queue. When the you run queue.get() it waits for something in the queue to be gotten that was left by some other process. queue.get() blocks and waits. This means you could have one process read the contents of the other process, like:

import multiprocessing as mp

def f(queue):
    obj = queue.get() # Blocks this sub-process until something shows up.
    if obj:
        print('Something was in the queue from some other process.')
        print(obj)
def g(queue):
    queue.put(['leaving information here in queue'])

queue = mp.Queue()
p = mp.Process(target=f,args=(queue,))
q = mp.Process(target=g,args=(queue,))
p.start()

This is kindof cool, so I recommend waiting here a second to think about what is waiting to process. Next start the q process.

q.start()

Notice that p didn't get to finish processing until q was started. This is because the Queue blocked and waited for something to show up.

# clean up
p.join()
q.join()

You can read more at: https://docs.python.org/3.4/library/multiprocessing.html?highlight=process#multiprocessing.Queue


问:
What is an easy way to put an element in the middle of a PHP array?
Say you have a 10 element indexed array and you want to place an element somewhere in the middle (say index 3). Then I want to have the rest of the array shift and thus be 11 elements long. Is there an easy way to do this?

I am surprised there is no put() function or something.

I know it would be easy enough to do this with a combination of array_splice and array_merge but I was just wondering if there an easier way.

答: Unfortunately your best bet is what you described in your post.</p>

OwnerDisplayName: Andrew

LastEditorDisplayName: Andrew

OwnerDisplayName: zodeus


问:
Accurate method to add months in PHP 5.1?
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

```<code>date('Y-m-d',strtotime( '+1 month', strtotime('now')));
</code>```

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?

答: You could compare the result of strtotime( 'last day of +1 month', strtotime('now')) with strtotime( '+1 month', strtotime('now')), and use whichever one is earlier.

Body:
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

date('Y-m-d',strtotime( '+1 month', strtotime('now')));

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?


问:
How to convert json output to array/list using Powershell (to json output)
Want to convert json output to array or list using Powershell.

I have tried converting the output using ConvertFrom-Json, then fetching the key Name and Values.  Need suggestion.

json Output:

```<code>{
    "demo1": {
        "type": [
            "tuple",
            [
                [
                    "list",
                    "string"
                ],
                [
                    "list",
                    "string"
                ]
            ]
        ],
        "value": [
            [
                "123"
            ],
            [
                "456"
            ]
        ]
    },
    "demo2": {
        "type": [
            "tuple",
            [
                "string",
                "string"
            ]
        ],
        "value": [
            "abc",
            "xyz"
        ]
    }
}
</code>```

Using Powershell want to convert it as below:

```<code>demo1 = [["123"],["456"]]
demo2 = ["abc","xyz"]
</code>```

Thanks in advance.

答:
Seems like a pretty straightforward use of convertfrom-json:

```<code>$a = get-content file.json | convertfrom-json

$a.demo1.value
123
456

$a.demo2.value
abc
xyz
</code>```

You want it as json?

```<code>$a.demo1.value | ConvertTo-Json -Compress
[["123"],["456"]]

$a.demo2.value | ConvertTo-Json -Compress
["abc","xyz"]
</code>```

Body:
Want to convert json output to array or list using Powershell.

I have tried converting the output using ConvertFrom-Json, then fetching the key Name and Values.  Need suggestion.

json Output:

{
    "demo1": {
        "type": [
            "tuple",
            [
                [
                    "list",
                    "string"
                ],
                [
                    "list",
                    "string"
                ]
            ]
        ],
        "value": [
            [
                "123"
            ],
            [
                "456"
            ]
        ]
    },
    "demo2": {
        "type": [
            "tuple",
            [
                "string",
                "string"
            ]
        ],
        "value": [
            "abc",
            "xyz"
        ]
    }
}

Using Powershell want to convert it as below:

demo1 = [["123"],["456"]]
demo2 = ["abc","xyz"]

Thanks in advance.

Body:
Seems like a pretty straightforward use of convertfrom-json:

$a = get-content file.json | convertfrom-json

$a.demo1.value
123
456

$a.demo2.value
abc
xyz

You want it as json?

$a.demo1.value | ConvertTo-Json -Compress
[["123"],["456"]]

$a.demo2.value | ConvertTo-Json -Compress
["abc","xyz"]


问:
How do I get the 8-hour cumulative TWAP of 1-min candles on Pinescript?
I'm creating an indicator that takes the 8-hour cumulative TWAP of 1-min candles, which will be reset every 8 hours. This should be able to be shown on all time frames. Is this the right way to do so?

```<code>resIn        = input("480", "Resolution")
res          = resIn == "0" ? '1' : resIn
typicalPrice = ohlc4
weight       = barssince(change(security))
price        = 0.0

price       := weight == 0 ? typicalPrice : typicalPrice + nz(price[1])
twap         = price / (weight + 1)
</code>```

Thank you so much.

答:
You were close )

```<code>//@version=4
study("8H VWAP")
resIn        = input("480", "Resolution")
typicalPrice = ohlc4
reset        = change(time(resIn))
weight       = barssince(reset)
price        = 0.0

price       := weight == 0 ? typicalPrice : typicalPrice + nz(price[1])
twap         = price / (weight + 1)

plot(twap)
bgcolor(reset ? color.gray : na)
</code>```

Body:
I'm creating an indicator that takes the 8-hour cumulative TWAP of 1-min candles, which will be reset every 8 hours. This should be able to be shown on all time frames. Is this the right way to do so?

resIn        = input("480", "Resolution")
res          = resIn == "0" ? '1' : resIn
typicalPrice = ohlc4
weight       = barssince(change(security))
price        = 0.0

price       := weight == 0 ? typicalPrice : typicalPrice + nz(price[1])
twap         = price / (weight + 1)

Thank you so much.

Body:
You were close )

//@version=4
study("8H VWAP")
resIn        = input("480", "Resolution")
typicalPrice = ohlc4
reset        = change(time(resIn))
weight       = barssince(reset)
price        = 0.0

price       := weight == 0 ? typicalPrice : typicalPrice + nz(price[1])
twap         = price / (weight + 1)

plot(twap)
bgcolor(reset ? color.gray : na)


问:
Flutter Bloc state does not update no matter what
I am currently trying to learn state management for flutter and i have the below code, but for some reason the state is never updated, am i missing something?

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BlocProvider(
        create: (context) => ItemBloc(),
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Bloc Demo"),
      ),
      body: Lister(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          ItemBloc().add(AddEvent());
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class Lister extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ItemBloc, ListState>(
      builder: (context, state) {
        if (state is ListAdded) {
          return ListView.builder(
            itemCount: state.items.length,
            itemBuilder: (context, index) {
              return Text("item"); // This never increases in count
            },
          );
        }
        return Center(
          child: Text('err'),
        );
      },
    );
  }
}

// BLOC
class ItemBloc extends Bloc<ListEvent, ListState> {
  @override
  get initialState => ListAdded(items: ["initial"]);

  @override
  Stream<ListState> mapEventToState(ListEvent event) async* {
    if (event is AddEvent) {
      final lister = ["first", "second"];
      yield ListAdded(items: lister);
    }
  }
}

abstract class ListEvent extends Equatable {
  @override
  List<Object> get props => [];
}

class AddEvent extends ListEvent {}

abstract class ListState extends Equatable {
  const ListState();

  @override
  List<Object> get props => [];
}

class ListAdded extends ListState {
  final List<String> items;

  const ListAdded({
    this.items,
  });

  @override
  List<Object> get props => [items];

  @override
  String toString() => 'ItemsLoaded { items: ${items.length} }';
}
</code>```

Please note: I have tried separating the code into individual files and importing the bloc.dart package instead of flutter_bloc.dart package in the Bloc file

答:
When you do

```<code>ItemBloc().add(AddEvent())
</code>```

you're creating new bloc instance and add event to it. It isn't connected with one created in MyApp and used in Lister.

You should get the created bloc instead:

```<code>BlocProvider.of<ItemBloc>(context).add(AddEvent())
</code>```

Body:
I am currently trying to learn state management for flutter and i have the below code, but for some reason the state is never updated, am i missing something?

import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: BlocProvider(
        create: (context) => ItemBloc(),
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Bloc Demo"),
      ),
      body: Lister(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          ItemBloc().add(AddEvent());
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class Lister extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ItemBloc, ListState>(
      builder: (context, state) {
        if (state is ListAdded) {
          return ListView.builder(
            itemCount: state.items.length,
            itemBuilder: (context, index) {
              return Text("item"); // This never increases in count
            },
          );
        }
        return Center(
          child: Text('err'),
        );
      },
    );
  }
}

// BLOC
class ItemBloc extends Bloc<ListEvent, ListState> {
  @override
  get initialState => ListAdded(items: ["initial"]);

  @override
  Stream<ListState> mapEventToState(ListEvent event) async* {
    if (event is AddEvent) {
      final lister = ["first", "second"];
      yield ListAdded(items: lister);
    }
  }
}

abstract class ListEvent extends Equatable {
  @override
  List<Object> get props => [];
}

class AddEvent extends ListEvent {}

abstract class ListState extends Equatable {
  const ListState();

  @override
  List<Object> get props => [];
}

class ListAdded extends ListState {
  final List<String> items;

  const ListAdded({
    this.items,
  });

  @override
  List<Object> get props => [items];

  @override
  String toString() => 'ItemsLoaded { items: ${items.length} }';
}

Please note: I have tried separating the code into individual files and importing the bloc.dart package instead of flutter_bloc.dart package in the Bloc file

Body:
When you do

ItemBloc().add(AddEvent())

you're creating new bloc instance and add event to it. It isn't connected with one created in MyApp and used in Lister.

You should get the created bloc instead:

BlocProvider.of<ItemBloc>(context).add(AddEvent())


问:
DropDownList can't bind to DbNull
I have a DropDownList trying to bind to DbNull and it's not happy about it. I've seen advice about creating a ListItem with value=" " but this isn't working.

Any help would be much appreciated.

答:
if you want to add default value to dropdwon list you can do it as below

```<code> mydropdown.DataSource = getdata();
 mydropdown.DataBind();
 mydropdown.Items.Insert(0,new ListItem("N/A","N/A"));
</code>```

Edit

if you know some values of the datasouce is null than y dont you filter out those value at database level and than bind soruce with the drop down.
or
make use of Isnull() in query and assing default value to null values.

Title: DropDownList can't bind to DbNull

Body:
if you want to add default value to dropdwon list you can do it as below

 mydropdown.DataSource = getdata();
 mydropdown.DataBind();
 mydropdown.Items.Insert(0,new ListItem("N/A","N/A"));

Edit

if you know some values of the datasouce is null than y dont you filter out those value at database level and than bind soruce with the drop down.
or
make use of Isnull() in query and assing default value to null values.


问:
OneWayToSource Binding with C# in Xamarin
I created a slider that rotates a label using OneWayToSource binding in XAML to wrap my head around how Binding Modes work.

I got it to work using XAML, but when I tried to achieve the same thing in C#, the slider does not rotate the label.

XAML Approach (which works):

XAML:

```<code><StackLayout x:Name="stackLayout">
    <Label x:Name="Label" Text="XAML" VerticalOptions="CenterAndExpand" HorizontalOptions="Center"></Label>
    <Slider BindingContext="{x:Reference Label}"  Maximum="360.0" Value="{Binding Path=Rotation, Mode=OneWayToSource}"></Slider>
</StackLayout>
</code>```

Code Behind:

```<code>public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
}
</code>```

C# approach (which is not working):

XAML:

```<code><StackLayout x:Name="stackLayout">
</StackLayout>
</code>```

Code Behind:

```<code>public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        Slider rotationSlider = new Slider {Maximum = 360.0};
        Label label = new Label
        {
            Text = "Code",
            VerticalOptions = LayoutOptions.CenterAndExpand,
            HorizontalOptions = LayoutOptions.Center
        };
        rotationSlider.SetBinding(RotationProperty, "Value", BindingMode.OneWayToSource);
        rotationSlider.BindingContext = label;

        stackLayout.Children.Add(label);
        stackLayout.Children.Add(rotationSlider);
    }
}
</code>```

What am I doing wrong in the C# approach?

答:
you have it backwards - you want to bind the Slider's Value to the Label's Rotation

```<code>rotationSlider.SetBinding(Slider.ValueProperty, "Rotation", BindingMode.OneWayToSource);
</code>```

Body:
I created a slider that rotates a label using OneWayToSource binding in XAML to wrap my head around how Binding Modes work.

I got it to work using XAML, but when I tried to achieve the same thing in C#, the slider does not rotate the label.

XAML Approach (which works):

XAML:

<StackLayout x:Name="stackLayout">

    <Slider BindingContext="{x:Reference Label}"  Maximum="360.0" Value="{Binding Path=Rotation, Mode=OneWayToSource}"></Slider>
</StackLayout>

Code Behind:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
}

C# approach (which is not working):

XAML:

<StackLayout x:Name="stackLayout">
</StackLayout>

Code Behind:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        Slider rotationSlider = new Slider {Maximum = 360.0};
        Label label = new Label
        {
            Text = "Code",
            VerticalOptions = LayoutOptions.CenterAndExpand,
            HorizontalOptions = LayoutOptions.Center
        };
        rotationSlider.SetBinding(RotationProperty, "Value", BindingMode.OneWayToSource);
        rotationSlider.BindingContext = label;

        stackLayout.Children.Add(label);
        stackLayout.Children.Add(rotationSlider);
    }
}

What am I doing wrong in the C# approach?

Body:
you have it backwards - you want to bind the Slider's Value to the Label's Rotation

rotationSlider.SetBinding(Slider.ValueProperty, "Rotation", BindingMode.OneWayToSource);


问:
String manipulation within a column (pandas): split, replace, join
I'd like to create a new column based on the following conditions:

if the row contains dogs/dog/chien/chiens, then add -00

if the row contains cats/cat/chat/chats, then add 00-

A sample of data is as follows:

```<code>Animal

22 dogs
1 dog
1 cat
3 dogs
32 chats
</code>```

and so far.

I'd like as output a column with only numbers (numerical):

```<code>Animal        New column

22 dogs       22-00
1 dog         1-00
1 cat         00-1
3 dogs        3-00
32 chats      00-32
</code>```

I think I should use an if condition to check the words, then .split and .join . It's about string manipulation but I'm having trouble breaking down this problem.

答:
Since your data is well-formatted, you can use a basic substitution and apply it to the row:

```<code>import pandas as pd
import re

def replacer(s):
    return re.sub(r" (chiens?|dogs?)", "-00",
                  re.sub(r"(\d+) ch?ats?", r"00-\1", s))

df = pd.DataFrame({"Animal": ["22 dogs", "1 dog", "1 cat", "3 dogs", "32 chats"]})
df["New Column"] = df["Animal"].apply(replacer)
</code>```

Output:

     Animal New Column
0   22 dogs      22-00
1     1 dog       1-00
2     1 cat       00-1
3    3 dogs       3-00
4  32 chats      00-32
```

Body:
I'd like to create a new column based on the following conditions:

if the row contains dogs/dog/chien/chiens, then add -00

if the row contains cats/cat/chat/chats, then add 00-

A sample of data is as follows:

Animal

22 dogs
1 dog
1 cat
3 dogs
32 chats

and so far.

I'd like as output a column with only numbers (numerical):

Animal        New column

22 dogs       22-00
1 dog         1-00
1 cat         00-1
3 dogs        3-00
32 chats      00-32

I think I should use an if condition to check the words, then .split and .join . It's about string manipulation but I'm having trouble breaking down this problem.

Body:
Since your data is well-formatted, you can use a basic substitution and apply it to the row:

import pandas as pd
import re

def replacer(s):
    return re.sub(r" (chiens?|dogs?)", "-00",
                  re.sub(r"(\d+) ch?ats?", r"00-\1", s))

df = pd.DataFrame({"Animal": ["22 dogs", "1 dog", "1 cat", "3 dogs", "32 chats"]})
df["New Column"] = df["Animal"].apply(replacer)

Output:

     Animal New Column
0   22 dogs      22-00
1     1 dog       1-00
2     1 cat       00-1
3    3 dogs       3-00
4  32 chats      00-32


问:
Not able to add custom Header text in WebApi GET
I have a fully working Visual Studio WebApi solution and I'm trying now to add some custom header information in the return response header but on the client side I am able to receive only the standard ones like the following ones:

Here the code of the GetCustomer WebApi:

```<code>    public class CustomerController : ApiController
    {

        [HttpGet]
        public JsonResult<List<Models.Customer>> GetCustomers()
        {

            EntityMapper<DataAccessLayer.Customer, Models.Customer> mapObj = new EntityMapper<DataAccessLayer.Customer, Models.Customer>();
            List<DataAccessLayer.Customer> custList = DAL.GetAllCustomers();
            List<Models.Customer> customers = new List<Models.Customer>();

            foreach (var item in custList)
            {
                customers.Add(mapObj.Translate(item));
            }

            // Setting Header
            HttpContext.Current.Response.Headers.Add("Some-Header", "Some-Text"));

            // Returning List of Customers Collections
            return Json<List<Models.Customer>>(customers);
        }

</code>```

As a result the HttpContext.Current.Response.Headers.Add("Some-Header", "Some-Text")); does not generate error but is completely ignnored.

Any idea on how to resolve this issue?

答:
Ok. I found myself the issue.
Because of the CORS I had to explicit instruct the response to expose custom Headers.

Adding:

HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Some-Header");

solved the issue!

Body:
I have a fully working Visual Studio WebApi solution and I'm trying now to add some custom header information in the return response header but on the client side I am able to receive only the standard ones like the following ones:

Here the code of the GetCustomer WebApi:

    public class CustomerController : ApiController
    {

        [HttpGet]
        public JsonResult<List<Models.Customer>> GetCustomers()
        {

            EntityMapper<DataAccessLayer.Customer, Models.Customer> mapObj = new EntityMapper<DataAccessLayer.Customer, Models.Customer>();
            List<DataAccessLayer.Customer> custList = DAL.GetAllCustomers();
            List<Models.Customer> customers = new List<Models.Customer>();

            foreach (var item in custList)
            {
                customers.Add(mapObj.Translate(item));
            }

            // Setting Header
            HttpContext.Current.Response.Headers.Add("Some-Header", "Some-Text"));

            // Returning List of Customers Collections
            return Json<List<Models.Customer>>(customers);
        }

As a result the HttpContext.Current.Response.Headers.Add("Some-Header", "Some-Text")); does not generate error but is completely ignnored.

Any idea on how to resolve this issue?


问:
remove fields on checkout page in Woocommerce
How do I remove fields on the Woocommerce Checkout page?

I read on this page that it can be done with a filter - tried it but it didn't work (I changed order_comments by billing_phone which is one of the fields I'd like to hide.

// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
     unset($fields['order']['order_comments']);

     return $fields;
}
```

How can I hide the telephone field, for example? Thanks

答:
```<code>// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
     unset($fields['billing']['billing_phone']);

     return $fields;
}
</code>```

That maybe?

Body:
How do I remove fields on the Woocommerce Checkout page?

I read on this page that it can be done with a filter - tried it but it didn't work (I changed order_comments by billing_phone which is one of the fields I'd like to hide.

// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
     unset($fields['order']['order_comments']);

     return $fields;
}

How can I hide the telephone field, for example? Thanks

Body:
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
     unset($fields['billing']['billing_phone']);

     return $fields;
}

That maybe?


答:
Using re:

```<code>import re

list1 = ['dogs', 'dog', 'chien', 'chiens']
list2 = ['cats', 'cat', 'chat', 'chats']

df['New_col'] = [(re.search(r'(\w+)', val).group(1).strip()+"-00") if re.search(r'([a-zA-Z]+)', val).group(1).strip() in list1 else ("00-" + re.search(r'(\w+)', val).group(1).strip()) if re.search(r'([a-zA-Z]+)', val).group(1).strip() in list2 else val for val in list(df['Animal'])]

print(df)
</code>```

Output:

```<code>     Animal New_col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32
</code>```

Title: String manipulation within a column (pandas): split, replace, join

Body:
Using re:

import re

list1 = ['dogs', 'dog', 'chien', 'chiens']
list2 = ['cats', 'cat', 'chat', 'chats']

df['New_col'] = [(re.search(r'(\w+)', val).group(1).strip()+"-00") if re.search(r'([a-zA-Z]+)', val).group(1).strip() in list1 else ("00-" + re.search(r'(\w+)', val).group(1).strip()) if re.search(r'([a-zA-Z]+)', val).group(1).strip() in list2 else val for val in list(df['Animal'])]

print(df)

Output:

     Animal New_col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32


问:
react-native facebook login correct implementation
I am developing a mobile app which has a traditional email/password authentication system.

I want to add the facebook login feature to the app. However I do not know how to proceed after the sdk returns that the user is successfully logged in through facebook.

What am I supposed to do in terms of database ? (I'm using Laravel + mysql + laravel passport for authentication)

How do I return a token to the user? How is the flow supposed to be?

Thanks

答:
Few things to do,

The phone number becomes the primary key.

Email and other user information not being collected at first step in sign up becomes nullable().

You need to return token using JSON response.

In Laravel's route/api.php, you need to create an api route.

In the controller, write the logic and return a JSON response (either add the token in response body or response header. It's preferred to add it in the response header.)


问:
Rest API response 404 Not found when run project with Java Application
I have app with spring boot, i want to run this app with Java Application but when i call rest API it always response 404, but with Tomcat server it's ok. I don't know why

Here is my main app

```<code>package com.secret;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class SecretApplication extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(SecretApplication.class, args);
    }
}
</code>```

here is my file pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.secret</groupId>
    <artifactId>MySecret</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath />
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

    </dependencies>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>11</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

Here is my controller

```<code>package com.secret.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.secret.common.dto.ResponseBodyDto;

@CrossOrigin
@RestController
@RequestMapping("/demo")
public class Demo {

    @GetMapping(value = "/user")
    public ResponseEntity<Object> getUserByUsername() throws Exception{

        ResponseBodyDto<Object> dto = new ResponseBodyDto<>();
        dto.setData("Ok");
        return new ResponseEntity<Object>(dto, HttpStatus.OK);
    }
}
</code>```

And When i run my app by Java Application always get 404 when call rest API http://localhost:8080/MySecret/demo/user

```<code>{
    "timestamp": "2020-05-28T08:03:05.090+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/MySecret/demo/user"
}
</code>```

But when i run my app by Tomcat Server then it still success

```<code>{
    "code": "R_200",
    "message": "Your request has been processed successfully.",
    "totalRecord": 0,
    "data": "Ok"
}
</code>```

I don't want to use Tomcat Server to run my app anymore, Someone help me pls!!!

答:
When you run your project as jar (java application), you should use localhost:8080/demo/user

When you run your application into a server (jboss per example) the name of your war file is the root path.

localhost:8080/MySecret/demo/user

I think your war file is MySecret.war.

That's the reason of the difference between the first and the second. Since you don't have a base path, /demo/user is the path of your endpoint.

Body:
I have app with spring boot, i want to run this app with Java Application but when i call rest API it always response 404, but with Tomcat server it's ok. I don't know why

Here is my main app

package com.secret;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class SecretApplication extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(SecretApplication.class, args);
    }
}

here is my file pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.secret</groupId>
    <artifactId>MySecret</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath />
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

    </dependencies>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>11</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Here is my controller

package com.secret.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.secret.common.dto.ResponseBodyDto;

@CrossOrigin
@RestController
@RequestMapping("/demo")
public class Demo {

    @GetMapping(value = "/user")
    public ResponseEntity<Object> getUserByUsername() throws Exception{

        ResponseBodyDto<Object> dto = new ResponseBodyDto<>();
        dto.setData("Ok");
        return new ResponseEntity<Object>(dto, HttpStatus.OK);
    }
}

And When i run my app by Java Application always get 404 when call rest API http://localhost:8080/MySecret/demo/user

{
    "timestamp": "2020-05-28T08:03:05.090+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/MySecret/demo/user"
}

But when i run my app by Tomcat Server then it still success

{
    "code": "R_200",
    "message": "Your request has been processed successfully.",
    "totalRecord": 0,
    "data": "Ok"
}

I don't want to use Tomcat Server to run my app anymore, Someone help me pls!!!


问:
how to implement R lapply on a data frame object
I am very new to R and especially to R apply family functions.

I have a data frame:

```<code>df <- data.frame(a=c(1,2,3),b=c(3,4,5))
</code>```

And tried:

```<code>lapply(df$a,sum)
</code>```

But this doesn't give the sum of the first column of data frame df.

However, this line of code does:

```<code>lapply(df,sum)
</code>```

Is there something that I am doing wrong here?

答:
For multiple columns, use colSums

```<code>colSums(df, na.rm = TRUE)
</code>```

and single column, it would be

```<code>sum(df$a, na.rm = TRUE)
</code>```

If we loop over a vector, each element of the list have a length of 1, thus the sum would be the element itself

Body:
I am very new to R and especially to R apply family functions.

I have a data frame:

df <- data.frame(a=c(1,2,3),b=c(3,4,5))

And tried:

lapply(df$a,sum)

But this doesn't give the sum of the first column of data frame df.

However, this line of code does:

lapply(df,sum)

Is there something that I am doing wrong here?

Body:
For multiple columns, use colSums

colSums(df, na.rm = TRUE)

and single column, it would be

sum(df$a, na.rm = TRUE)

If we loop over a vector, each element of the list have a length of 1, thus the sum would be the element itself


答:
You can hide the phone field with this filter:

```<code>add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
     unset($fields['billing']['billing_phone']);

     return $fields;
}
</code>```

Be sure to add this in the file function.php of your current theme.

Title: remove fields on checkout page in Woocommerce

Body:
You can hide the phone field with this filter:

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
     unset($fields['billing']['billing_phone']);

     return $fields;
}

Be sure to add this in the file function.php of your current theme.


问:
Graqhql query works but can't use it because of multiimensional arrays
I have this file that I can't seem to get to work My development environment is currently gatsby, and I am having trouble integrating graqhql with gatsby. I know for sure that the graphql query is correct, because it outputs but because the there are two arrays, group[ edges []], I don't know how to call them. Any hehelp would be greatly appreciated, could anyone give me some advice. I am a relatively new programmer so all of this is confusing me a little.

in my tune-awesome.js page

```<code>    import {graphql, StaticQuery } from 'gatsby'

    class BlogRoll extends React.Component {
      render() {
        const { data } = this.props
        const { group} = data.allSongsJson

        return (
            {group.map(({ edges }) =>
                   <p>{node.filesize}</p>
                  </div>
                </div>
              ))}
        )
      }
    }

    export default () => (
      <StaticQuery
        query={graphql`
          query byTuneAwemeQuery {
              allSongsJson {
                group(field: tune) {
                  edges {
                    node {
                      filesize                   }
                }
               }
              }
            }
        `}
        render={(data, count) => <BlogRoll data={data} count={count} />}
      />
    )```

    }
    ~
    ~
    ~
```

答:
You just need to do another loop:

```<code>groups.map(({ edges }) => {
  edges.map(({ node }, index) => {
    <p key={index}>{node.filesize}</p>
  })
})
</code>```

You can simplify this nesting a bit by using nodes instead of edges.node in your query, and by aliasing for brevity/clarity:

```<code>query byTuneAwemeQuery {
  songData: allSongsJson {
    groups: group(field: tune) {
      nodes {
        filesize
      }
    }
  }
}
</code>```

Which you would then access more like this:

```<code>const { data: songData } = this.props

// first node filesize for each group:
songData.groups.map(group => group.nodes[0].filesize)
</code>```

Body:
I have this file that I can't seem to get to work My development environment is currently gatsby, and I am having trouble integrating graqhql with gatsby. I know for sure that the graphql query is correct, because it outputs but because the there are two arrays, group[ edges []], I don't know how to call them. Any hehelp would be greatly appreciated, could anyone give me some advice. I am a relatively new programmer so all of this is confusing me a little.

in my tune-awesome.js page

    import {graphql, StaticQuery } from 'gatsby'

    class BlogRoll extends React.Component {
      render() {
        const { data } = this.props
        const { group} = data.allSongsJson

        return (
            {group.map(({ edges }) =>

{node.filesize}

              ))}
        )
      }
    }

    export default () => (
      <StaticQuery
        query={graphql`
          query byTuneAwemeQuery {
              allSongsJson {
                group(field: tune) {
                  edges {
                    node {
                      filesize                   }
                }
               }
              }
            }
        `}
        render={(data, count) => <BlogRoll data={data} count={count} />}
      />
    )```

    }
    ~
    ~
    ~

Body:
You just need to do another loop:

groups.map(({ edges }) => {
  edges.map(({ node }, index) => {
    <p key={index}>{node.filesize}</p>
  })
})

You can simplify this nesting a bit by using nodes instead of edges.node in your query, and by aliasing for brevity/clarity:

query byTuneAwemeQuery {
  songData: allSongsJson {
    groups: group(field: tune) {
      nodes {
        filesize
      }
    }
  }
}

Which you would then access more like this:

const { data: songData } = this.props

// first node filesize for each group:
songData.groups.map(group => group.nodes[0].filesize)


问:
Manually Parsing a a JSON into an Object of a Struct
I'm a beginner in swift and I'm currently making an app that makes a web request. I've been trying to parse this JSON Data but the nested data is just really hard to wrap my head around:

```<code> "abilities": [
            {
                "ability": {
                    "name": "chlorophyll",
                    "url": "https://pokeapi.co/api/v2/ability/34/"
                },
                "is_hidden": true,
                "slot": 3
            },
            {
                "ability": {
                    "name": "overgrow",
                    "url": "https://pokeapi.co/api/v2/ability/65/"
                },
                "is_hidden": false,
                "slot": 1
            }
        ]
</code>```

JSon Serialization Code

```<code>let jsonAny = try JSONSerialization.jsonObject(with: data, options: [])
            guard let json = jsonAny as? [String: Any] else { return }
</code>```

This is my attempt to manually parse the JSON Data

```<code>    private func parsePokemonManual(json: [String: Any]) -> Pokemon {
        let abilities = json["abilities"] as? [String: Any] ?? [String: Any]()

        return Pokemon(abilities: abilities)
    }
}
</code>```

These are the structs that I made to hold the data.

```<code>struct Abilities {
    let ability : Ability

    struct Ability {
        let name : String
    }
}
</code>```

How do I successfully parse the JSON Data into an object of Pokemon structure?

With this code so fat I am getting the error "Cannot convert the value of type '[String : Any]' to expected argument type '[Abilities]'. My problem is that I don't know what type to cast the abilities as and that my struct 'Abilities' is also incorrect.

答:
There are 3 problems with your attempt although one might argue there is only 1, that you should use Codable instead but lets stay with JSONSerialization here. The problems are

You are reading the json wrong and should cast not to a dictionary but an array of dictionaries when accessing "abilities"

Your struct is to complicated, maybe because of the previous problem

Lastly, you can't cast into a custom type, you need to convert or map the data into your type by telling exactly what values to use and how because the compiler doesn't understand how to do it.

First the struct can be simplified to

```<code>struct Ability {
    let name : String
}
</code>```

And the rest is fixed in the function parsePokemonManual. First get "abilities" and cast to an array of dictionaries. Then map each item in the array by getting "ability" and casting it to a dictionary that is used to get the "name" value that is then used when creating an instance of Ability

```<code>private func parsePokemonManual(json: [String: Any]) -> [Ability] {
    guard let abilities = json["abilities"] as? [[String: Any]] else {
        return []
    }

    return abilities.compactMap { dict in
        guard let ability = dict["ability"] as? [String: String], let name = ability["name"] else { return nil }

        return Ability(name: name)
    }
}
</code>```

Body:
I'm a beginner in swift and I'm currently making an app that makes a web request. I've been trying to parse this JSON Data but the nested data is just really hard to wrap my head around:

 "abilities": [
            {
                "ability": {
                    "name": "chlorophyll",
                    "url": "https://pokeapi.co/api/v2/ability/34/"
                },
                "is_hidden": true,
                "slot": 3
            },
            {
                "ability": {
                    "name": "overgrow",
                    "url": "https://pokeapi.co/api/v2/ability/65/"
                },
                "is_hidden": false,
                "slot": 1
            }
        ]

JSon Serialization Code

let jsonAny = try JSONSerialization.jsonObject(with: data, options: [])
            guard let json = jsonAny as? [String: Any] else { return }

This is my attempt to manually parse the JSON Data

    private func parsePokemonManual(json: [String: Any]) -> Pokemon {
        let abilities = json["abilities"] as? [String: Any] ?? [String: Any]()

        return Pokemon(abilities: abilities)
    }
}

These are the structs that I made to hold the data.

struct Abilities {
    let ability : Ability

    struct Ability {
        let name : String
    }
}

How do I successfully parse the JSON Data into an object of Pokemon structure?

With this code so fat I am getting the error "Cannot convert the value of type '[String : Any]' to expected argument type '[Abilities]'. My problem is that I don't know what type to cast the abilities as and that my struct 'Abilities' is also incorrect.

Body:
There are 3 problems with your attempt although one might argue there is only 1, that you should use Codable instead but lets stay with JSONSerialization here. The problems are

You are reading the json wrong and should cast not to a dictionary but an array of dictionaries when accessing "abilities"

Your struct is to complicated, maybe because of the previous problem

Lastly, you can't cast into a custom type, you need to convert or map the data into your type by telling exactly what values to use and how because the compiler doesn't understand how to do it.

First the struct can be simplified to

struct Ability {
    let name : String
}

And the rest is fixed in the function parsePokemonManual. First get "abilities" and cast to an array of dictionaries. Then map each item in the array by getting "ability" and casting it to a dictionary that is used to get the "name" value that is then used when creating an instance of Ability

private func parsePokemonManual(json: [String: Any]) -> [Ability] {
    guard let abilities = json["abilities"] as? [[String: Any]] else {
        return []
    }

    return abilities.compactMap { dict in
        guard let ability = dict["ability"] as? [String: String], let name = ability["name"] else { return nil }

        return Ability(name: name)
    }
}