问:
Problems Installing Mongodb on Ubuntu 20.04
Will give a quick context. I was strict to the manual:
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/

wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

sudo apt-get update

sudo apt-get install -y mongodb-org

sudo systemctl start mongod

sudo systemctl status mongod

```<code>● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Thu 2020-11-12 03:11:07 EET; 1min 8s ago
Docs: https://docs.mongodb.org/manual
Process: 6780 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=14)
Main PID: 6780 (code=exited, status=14)
systemd[1]: Started MongoDB Database Server.
systemd[1]: mongod.service: Main process exited, code=exited, status=14/n/a
systemd[1]: mongod.service: Failed with result 'exit-code'.
</code>```

mongo

```<code>MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:374:17
@(connect):2:6
exception: connect failed
exiting with code 1
</code>```

Then tried to fix this status=14/n/a with:

```<code>sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock
</code>```

and other stuff

Then deleted mongodb with:

```<code>sudo apt-get purge mongodb-org*
sudo apt remove mongodb
sudo apt purge mongodb
sudo apt autoremove
</code>```

And install it the same way from above with the same result. I need help.

That's the etc/mongod.conf

```<code># mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1

# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:
</code>```

Here is the mongod logs from var/log/mongodb/mongod.log the file is 550 liner and I copied only the last log:

```<code>{"t":{"$date":"2020-11-12T15:30:35.643+02:00"},"s":"W",  "c":"CONTROL",  "id":20698,   "ctx":"main","msg":"***** SERVER RESTARTED *****","tags":["startupWarnings"]}
{"t":{"$date":"2020-11-12T15:30:35.645+02:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"main","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2020-11-12T15:30:35.655+02:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2020-11-12T15:30:35.655+02:00"},"s":"I",  "c":"NETWORK",  "id":4648601, "ctx":"main","msg":"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize."}
{"t":{"$date":"2020-11-12T15:30:35.656+02:00"},"s":"I",  "c":"STORAGE",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":9759,"port":27017,"dbPath":"/var/lib/mongodb","architecture":"64-bit","host":"lubo"}}
{"t":{"$date":"2020-11-12T15:30:35.656+02:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"4.4.1","gitVersion":"ad91a93a5a31e175f5cbf8c69561e788bbc55ce1","openSSLVersion":"OpenSSL 1.1.1f  31 Mar 2020","modules":[],"allocator":"tcmalloc","environment":{"distmod":"ubuntu2004","distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2020-11-12T15:30:35.656+02:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Ubuntu","version":"20.04"}}}
{"t":{"$date":"2020-11-12T15:30:35.656+02:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{"config":"/etc/mongod.conf","net":{"bindIp":"127.0.0.1","port":27017},"processManagement":{"timeZoneInfo":"/usr/share/zoneinfo"},"storage":{"dbPath":"/var/lib/mongodb","journal":{"enabled":true}},"systemLog":{"destination":"file","logAppend":true,"path":"/var/log/mongodb/mongod.log"}}}}
{"t":{"$date":"2020-11-12T15:30:35.657+02:00"},"s":"F",  "c":"STORAGE",  "id":50922,   "ctx":"initandlisten","msg":"An incomplete repair has been detected! This is likely because a repair operation unexpectedly failed before completing. MongoDB will not start up again without --repair."}
{"t":{"$date":"2020-11-12T15:30:35.657+02:00"},"s":"F",  "c":"-",        "id":23091,   "ctx":"initandlisten","msg":"Fatal assertion","attr":{"msgid":50922,"file":"src/mongo/db/storage/storage_engine_init.cpp","line":86}}
{"t":{"$date":"2020-11-12T15:30:35.657+02:00"},"s":"F",  "c":"-",        "id":23092,   "ctx":"initandlisten","msg":"\n\n***aborting after fassert() failure\n\n"}
</code>```

Update ATM I tried another reinstall this time with guide from stackoverflow:

sudo apt-get install --reinstall mongodb
(had error - Errors were encountered while processing)

sudo systemctl daemon-reload

sudo apt update/upgrate

sudo apt install mongodb
(The following package was automatically installed and is no longer required)

sudo apt autoremove

sudo systemctl status mongodb
(Main process exited, code=exited, status=100/n/a)

sudo mongo

```<code>MongoDB shell version v3.6.8
connecting to: mongodb://127.0.0.1:27017
Implicit session: session { "id" : UUID("667c92c8-0a10-4adb-bcf6-ba045f280034") }
MongoDB server version: 3.6.8
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    http://docs.mongodb.org/
Questions? Try the support group
    http://groups.google.com/group/mongodb-user
Server has startup warnings:
2020-11-12T17:33:37.780+0200 I STORAGE  [initandlisten]
2020-11-12T17:33:37.780+0200 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2020-11-12T17:33:37.780+0200 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2020-11-12T17:33:38.722+0200 I CONTROL  [initandlisten]
2020-11-12T17:33:38.722+0200 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-11-12T17:33:38.722+0200 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-11-12T17:33:38.722+0200 I CONTROL  [initandlisten]
</code>```

sudo apt-get install libc6
(libc6 is already the newest version (2.31-0ubuntu9.1))

sudo systemctl status mongod

```<code> mongod.service
     Loaded: not-found (Reason: Unit mongod.service not found.)
     Active: active (running) since Thu 2020-11-12 17:33:37 EET; 7min ago
   Main PID: 16038 (mongod)
     CGroup: /system.slice/mongod.service
             └─16038 /usr/bin/mongod --config /etc/mongod.conf

ное 12 17:33:37 lubo systemd[1]: Started MongoDB Database Server.
ное 12 17:34:03 lubo systemd[1]: mongod.service: Current command vanished from the unit file, execution of the command list won't be resumed.

</code>```

Now I belive we have working mongod, only to connect it with mongod.service

答:
MongoDB is already included in Ubuntu package repositories, but the official MongoDB repository provides the most up-to-date version and is the recommended way of installing the software. In this step, we will add this official repository to our server.

Ubuntu ensures the authenticity of software packages by verifying that they are signed with GPG keys, so we first have to import the key for the official MongoDB repository.

```<code>sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
</code>```

Next, we’ll add MongoDB repository details so apt will know where to download the packages. Issue the following command to create a list file for MongoDB.

```<code>echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
</code>```

Finally, we’ll update the packages list.

```<code>sudo apt-get update

</code>```

We’ll install the mongodb-org meta-package, which includes the daemon, configuration and init scripts, shell, and management tools on the server.

```<code>sudo apt-get install mongodb-org
</code>```

:)

Body:
Will give a quick context. I was strict to the manual:
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/

wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

sudo apt-get update

sudo apt-get install -y mongodb-org

sudo systemctl start mongod

sudo systemctl status mongod

● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Thu 2020-11-12 03:11:07 EET; 1min 8s ago
Docs: https://docs.mongodb.org/manual
Process: 6780 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=14)
Main PID: 6780 (code=exited, status=14)
systemd[1]: Started MongoDB Database Server.
systemd[1]: mongod.service: Main process exited, code=exited, status=14/n/a
systemd[1]: mongod.service: Failed with result 'exit-code'.

mongo

MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:374:17
@(connect):2:6
exception: connect failed
exiting with code 1

Then tried to fix this status=14/n/a with:

sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock

and other stuff

Then deleted mongodb with:

sudo apt-get purge mongodb-org*
sudo apt remove mongodb
sudo apt purge mongodb
sudo apt autoremove

And install it the same way from above with the same result. I need help.

That's the etc/mongod.conf

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1

# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

Here is the mongod logs from var/log/mongodb/mongod.log the file is 550 liner and I copied only the last log:

{"t":{"$date":"2020-11-12T15:30:35.643+02:00"},"s":"W",  "c":"CONTROL",  "id":20698,   "ctx":"main","msg":"***** SERVER RESTARTED *****","tags":["startupWarnings"]}
{"t":{"$date":"2020-11-12T15:30:35.645+02:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"main","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2020-11-12T15:30:35.655+02:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2020-11-12T15:30:35.655+02:00"},"s":"I",  "c":"NETWORK",  "id":4648601, "ctx":"main","msg":"Implicit TCP FastOpen unavailable. If TCP FastOpen is required, set tcpFastOpenServer, tcpFastOpenClient, and tcpFastOpenQueueSize."}
{"t":{"$date":"2020-11-12T15:30:35.656+02:00"},"s":"I",  "c":"STORAGE",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":9759,"port":27017,"dbPath":"/var/lib/mongodb","architecture":"64-bit","host":"lubo"}}
{"t":{"$date":"2020-11-12T15:30:35.656+02:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"4.4.1","gitVersion":"ad91a93a5a31e175f5cbf8c69561e788bbc55ce1","openSSLVersion":"OpenSSL 1.1.1f  31 Mar 2020","modules":[],"allocator":"tcmalloc","environment":{"distmod":"ubuntu2004","distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2020-11-12T15:30:35.656+02:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Ubuntu","version":"20.04"}}}
{"t":{"$date":"2020-11-12T15:30:35.656+02:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{"config":"/etc/mongod.conf","net":{"bindIp":"127.0.0.1","port":27017},"processManagement":{"timeZoneInfo":"/usr/share/zoneinfo"},"storage":{"dbPath":"/var/lib/mongodb","journal":{"enabled":true}},"systemLog":{"destination":"file","logAppend":true,"path":"/var/log/mongodb/mongod.log"}}}}
{"t":{"$date":"2020-11-12T15:30:35.657+02:00"},"s":"F",  "c":"STORAGE",  "id":50922,   "ctx":"initandlisten","msg":"An incomplete repair has been detected! This is likely because a repair operation unexpectedly failed before completing. MongoDB will not start up again without --repair."}
{"t":{"$date":"2020-11-12T15:30:35.657+02:00"},"s":"F",  "c":"-",        "id":23091,   "ctx":"initandlisten","msg":"Fatal assertion","attr":{"msgid":50922,"file":"src/mongo/db/storage/storage_engine_init.cpp","line":86}}
{"t":{"$date":"2020-11-12T15:30:35.657+02:00"},"s":"F",  "c":"-",        "id":23092,   "ctx":"initandlisten","msg":"\n\n***aborting after fassert() failure\n\n"}

Update ATM I tried another reinstall this time with guide from stackoverflow:

sudo apt-get install --reinstall mongodb
(had error - Errors were encountered while processing)

sudo systemctl daemon-reload

sudo apt update/upgrate

sudo apt install mongodb
(The following package was automatically installed and is no longer required)

sudo apt autoremove

sudo systemctl status mongodb
(Main process exited, code=exited, status=100/n/a)

sudo mongo

MongoDB shell version v3.6.8
connecting to: mongodb://127.0.0.1:27017
Implicit session: session { "id" : UUID("667c92c8-0a10-4adb-bcf6-ba045f280034") }
MongoDB server version: 3.6.8
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    http://docs.mongodb.org/
Questions? Try the support group
    http://groups.google.com/group/mongodb-user
Server has startup warnings:
2020-11-12T17:33:37.780+0200 I STORAGE  [initandlisten]
2020-11-12T17:33:37.780+0200 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2020-11-12T17:33:37.780+0200 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2020-11-12T17:33:38.722+0200 I CONTROL  [initandlisten]
2020-11-12T17:33:38.722+0200 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-11-12T17:33:38.722+0200 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-11-12T17:33:38.722+0200 I CONTROL  [initandlisten]

sudo apt-get install libc6
(libc6 is already the newest version (2.31-0ubuntu9.1))

sudo systemctl status mongod

 mongod.service
     Loaded: not-found (Reason: Unit mongod.service not found.)
     Active: active (running) since Thu 2020-11-12 17:33:37 EET; 7min ago
   Main PID: 16038 (mongod)
     CGroup: /system.slice/mongod.service
             └─16038 /usr/bin/mongod --config /etc/mongod.conf

ное 12 17:33:37 lubo systemd[1]: Started MongoDB Database Server.
ное 12 17:34:03 lubo systemd[1]: mongod.service: Current command vanished from the unit file, execution of the command list won't be resumed.

Now I belive we have working mongod, only to connect it with mongod.service

Body:
MongoDB is already included in Ubuntu package repositories, but the official MongoDB repository provides the most up-to-date version and is the recommended way of installing the software. In this step, we will add this official repository to our server.

Ubuntu ensures the authenticity of software packages by verifying that they are signed with GPG keys, so we first have to import the key for the official MongoDB repository.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

Next, we’ll add MongoDB repository details so apt will know where to download the packages. Issue the following command to create a list file for MongoDB.

echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

Finally, we’ll update the packages list.

sudo apt-get update

We’ll install the mongodb-org meta-package, which includes the daemon, configuration and init scripts, shell, and management tools on the server.

sudo apt-get install mongodb-org

:)


来源: stackexchange

问:
How to Automatically adjust TextArea Height in GWT or Smart GWT
I'm having a problem that others have talked about here. ie How to auto adjust TextArea Height. I saw this answer: Creating a textarea with auto-resize

but I was hoping someone here can translate how to do this in GWT or Smart GWT.

答: Take a look at SimpleLayoutPanel. It enables you to respond to the browser's resize events.</p>

ContentLicense: CC BY-SA 3.0


答:
Two problems in this line x.loc[1030:1036,'Priority order':'median_idle_time'] = x.loc[157:330,'Priority order':'median_idle_time']

#1, their shapes do not match. L.H.S. has 7 rows but R.H.S. has 174 rows. Please match them.

#2, pandas assigns value index-wise, and because there is no index-overlap between the L.H.S. and the R.H.S., you see all those NaN. You may convert the R.H.S. to an array by x.loc[157:330,'Priority order':'median_idle_time'].values

ContentLicense: CC BY-SA 4.0

Title: NaN coming on overwriting subset of dataframe from another subset of same dataframe in pandas

Body:
I have a  subset of dataframe x

>> x.loc[1030:1036,'Priority order':]
      Priority order|bike_id|    lat|       lon|        median_idle_time
|    |              |
|1030|  1           | 52447|    13.027514   77.723228   31.904444
|1031|  1           | 52447|    13.027514   77.723228   31.904444
|1032|  1           | 52447|    13.027514   77.723228   31.904444
|1033|  1           | 52447|    13.027514   77.723228   31.904444
|1034|  1           | 52447|    13.027514   77.723228   31.904444
|1035|  1           | 52447|    13.027514   77.723228   31.904444
|1036|  1           | 52447|    13.027514   77.723228   31.904444

when i try to change it with another subset of same parent Dataframe x

>> x.loc[157:330,'Priority order':'median_idle_time']
|   |Priority |bike_id  |lat       |lon       |median_idle_time
      order
|157    |158    51281   13.053876   77.550079   2.017778
|158    |159    53283   12.975240   77.479927   2.004306
|159    |160    48387   12.824695   77.673805   2.000556
|160    |161    52320   12.993121   77.576515   1.984722
|161    |162    35281   12.934137   77.686356   1.958333
|...    |...    ... ... ... ...
|326    |327    48103   12.985148   77.618721   0.464167
|327    |328    48577   12.959455   77.651382   0.443611
|328    |329    54039   12.982092   77.639412   0.311944
|329    |330    49586   13.011577   77.607353   0.213889
|330    |331    53100   12.971110   77.640602   0.199167

x.loc[1030:1036,'Priority order':'median_idle_time'] = x.loc[157:330,'Priority order':'median_idle_time']

is giving me NaN value at subset location of dataframe x

    |Priority   |drop hex   |avg_daily_sessions |idle_bike_count    |drop lat   |drop lon   |avg_daily_sessions/supply  |Priority order |bike_id    |lat    |lon    |median_idle_time
|0      | 1 |8960144b4dbffff    |122.071429 |0  |13.084574  |77.48569   |122.071429 |1.0    |52447.0    |13.027514  |77.723228  |31.904444
|1030   |1  |8960144b4dbffff    |122.071429 |0  |13.084574  |77.48569   |122.071429 |NaN    |NaN    |NaN    |NaN    |NaN
|1031   |1  |8960144b4dbffff    |122.071429 |0  |13.084574  |77.48569   |122.071429 |NaN    |NaN    |NaN    |NaN    |NaN
|1032   |1  |8960144b4dbffff    |122.071429 |0  |13.084574  |77.48569   |122.071429 |NaN    |NaN    |NaN    |NaN    |NaN
|1033   |1  |8960144b4dbffff    |122.071429 |0  |13.084574  |77.48569   |122.071429 |NaN    |NaN    |NaN    |NaN    |NaN
|1034   |1  |8960144b4dbffff    |122.071429 |0  |13.084574  |77.48569   |122.071429 |NaN    |NaN    |NaN    |NaN    |NaN
|1035   |1  |8960144b4dbffff    |122.071429 |0  |13.084574  |77.48569   |122.071429 |NaN    |NaN    |NaN    |NaN    |NaN
|1036   |1  |8960144b4dbffff    |122.071429 |0  |13.084574  |77.48569   |122.071429 |NaN    |NaN    |NaN    |NaN    |NaN

Would appreciate if  anyone could point out where i am messing up the things?


问:
Generate array with foreach PDO / MySQL
I am doing a SELECT from MySQL that brings me a different number of rows for the same column. Then I:

foreach to create an array

merge the resulting arraywith another array

echo using json_encode

My problem: I need to remove the extra array and the keys
when generating my result. I tried different things but those didn't worked, could you tell me what I am doing wrong?

Here's my code:

```<code>    $dados2 = [
        'id' => $_POST['id_profissional']
    ];

    $sql2 = "
    SELECT nome
    FROM areas_de_atuacao_dos_advogados_e_escritorios
    LEFT JOIN areas_de_atuacao ON areas_de_atuacao_dos_advogados_e_escritorios.id_areas_de_atuacao = areas_de_atuacao.id
    WHERE id_advogados_e_escritorios=:id
    ORDER BY principal DESC
    ";

    $stmt2 = $pdo->prepare($sql2);
    $stmt2->execute($dados2);
    $areas_de_atuacao = $stmt2->fetchAll();

    $i = '0';
    foreach ($areas_de_atuacao as $row) {

        $aAreas_de_atuacao [] = array(
            'area_de_atuacao_'.$i   =>  $row["nome"]
        );
        $i++;

    }
</code>```

With this output:

```<code>Array ( [0] => Array ( [area_de_atuacao_0] => Direito Civil ) [1] => Array ( [area_de_atuacao_1] => Direito Criminal ) [2] => Array ( [area_de_atuacao_2] => Direito Empresarial ) [3] => Array ( [area_de_atuacao_3] => Direito de Família ) [4] => Array ( [area_de_atuacao_4] => Direito das Sucessões ) [5] => Array ( [area_de_atuacao_5] => Direito do Trabalho ) )
</code>```

But this is my desire output:

```<code>Array ( [area_de_atuacao_0] => Direito Civil [area_de_atuacao_1] => Direito Criminal [area_de_atuacao_2] => Direito Empresarial [area_de_atuacao_3] => Direito de Família [area_de_atuacao_4] => Direito das Sucessões [area_de_atuacao_5] => Direito do Trabalho )
</code>```

Thank you for your time ;)

答:
Doing this functionally without the foreach loop, this an solution  using array_walk to build the array with index number added to the key. use the sprintf for a little cleaner look than the concat 'area_de_atuacao_'. $key, but that would work too.

```<code>  $aAreas_de_atuacao = []; //Output array
  $names = array_columns($areas_de_atuacao, 'name'); //array of names
  array_walk($names, function ($name, $key) USE (&$aAreas_de_atuacao)  {//passing output array by reference
      $i = sprintf('area_de_atuacao_%d', $key);
      $aAreas_de_atuacao[$i] = $name;
    });

</code>```

Side note: In our code reviews we want developers to be consistent. In your code you started using brackets arrays [], then at the end you used array(), you want your code to flow I'd suggest you stick with one. Just something that stuck out to me, and it works the same, but it doesn't read the same.

Title: Generate array with foreach PDO / MySQL

Body:
I am doing a SELECT from MySQL that brings me a different number of rows for the same column. Then I:

foreach to create an array

merge the resulting arraywith another array

echo using json_encode

My problem: I need to remove the extra array and the keys
when generating my result. I tried different things but those didn't worked, could you tell me what I am doing wrong?

Here's my code:

    $dados2 = [
        'id' => $_POST['id_profissional']
    ];

    $sql2 = "
    SELECT nome
    FROM areas_de_atuacao_dos_advogados_e_escritorios
    LEFT JOIN areas_de_atuacao ON areas_de_atuacao_dos_advogados_e_escritorios.id_areas_de_atuacao = areas_de_atuacao.id
    WHERE id_advogados_e_escritorios=:id
    ORDER BY principal DESC
    ";

    $stmt2 = $pdo->prepare($sql2);
    $stmt2->execute($dados2);
    $areas_de_atuacao = $stmt2->fetchAll();

    $i = '0';
    foreach ($areas_de_atuacao as $row) {

        $aAreas_de_atuacao [] = array(
            'area_de_atuacao_'.$i   =>  $row["nome"]
        );
        $i++;

    }

With this output:

Array ( [0] => Array ( [area_de_atuacao_0] => Direito Civil ) [1] => Array ( [area_de_atuacao_1] => Direito Criminal ) [2] => Array ( [area_de_atuacao_2] => Direito Empresarial ) [3] => Array ( [area_de_atuacao_3] => Direito de Família ) [4] => Array ( [area_de_atuacao_4] => Direito das Sucessões ) [5] => Array ( [area_de_atuacao_5] => Direito do Trabalho ) )

But this is my desire output:

Array ( [area_de_atuacao_0] => Direito Civil [area_de_atuacao_1] => Direito Criminal [area_de_atuacao_2] => Direito Empresarial [area_de_atuacao_3] => Direito de Família [area_de_atuacao_4] => Direito das Sucessões [area_de_atuacao_5] => Direito do Trabalho )

Thank you for your time ;)

Body:
Doing this functionally without the foreach loop, this an solution  using array_walk to build the array with index number added to the key. use the sprintf for a little cleaner look than the concat 'area_de_atuacao_'. $key, but that would work too.

  $aAreas_de_atuacao = []; //Output array
  $names = array_columns($areas_de_atuacao, 'name'); //array of names
  array_walk($names, function ($name, $key) USE (&$aAreas_de_atuacao)  {//passing output array by reference
      $i = sprintf('area_de_atuacao_%d', $key);
      $aAreas_de_atuacao[$i] = $name;
    });

Side note: In our code reviews we want developers to be consistent. In your code you started using brackets arrays [], then at the end you used array(), you want your code to flow I'd suggest you stick with one. Just something that stuck out to me, and it works the same, but it doesn't read the same.


问:
Filter Java Stream to 1 and only 1 element
I am trying to use Java 8 Streams to find elements in a LinkedList. I want to guarantee, however, that there is one and only one match to the filter criteria.

Take this code:

```<code>public static void main(String[] args) {

    LinkedList<User> users = new LinkedList<>();
    users.add(new User(1, "User1"));
    users.add(new User(2, "User2"));
    users.add(new User(3, "User3"));

    User match = users.stream().filter((user) -> user.getId() == 1).findAny().get();
    System.out.println(match.toString());
}
</code>```

```<code>static class User {

    @Override
    public String toString() {
        return id + " - " + username;
    }

    int id;
    String username;

    public User() {
    }

    public User(int id, String username) {
        this.id = id;
        this.username = username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public int getId() {
        return id;
    }
}
</code>```

This code finds a User based on their ID. But there are no guarantees how many Users matched the filter.

Changing the filter line to:

```<code>User match = users.stream().filter((user) -> user.getId() < 0).findAny().get();
</code>```

Will throw a NoSuchElementException (good!)

I would like it to throw an error if there are multiple matches, though. Is there a way to do this?

答:
```<code>public List<state> getAllActiveState() {
    List<Master> master = masterRepository.getActiveExamMasters();
    Master activeMaster = new Master();
    try {
        activeMaster = master.stream().filter(status -> status.getStatus() == true).reduce((u, v) -> {
            throw new IllegalStateException();
        }).get();
        return stateRepository.getAllStateActiveId(activeMaster.getId());
    } catch (IllegalStateException e) {
        logger.info(":More than one status found TRUE in Master");
        return null;
    }
}
</code>```

In this above code, As per the condition if its find more than one true in the list then it will through the exception.

When it through the error will showing custom message because it easy maintain the logs on server side.

From Nth number of element present in list just want only one element have true condition if in list there are more than one elements having true status at that moment it will through an exception.

after getting all the this we using get(); to taking that one element from list and stored it into another object.

If you want you added optional like Optional<activeMaster > = master.stream().filter(status -> status.getStatus() == true).reduce((u, v) -> {throw new IllegalStateException();}).get();

Body:
I am trying to use Java 8 Streams to find elements in a LinkedList. I want to guarantee, however, that there is one and only one match to the filter criteria.

Take this code:

public static void main(String[] args) {

    LinkedList<User> users = new LinkedList<>();
    users.add(new User(1, "User1"));
    users.add(new User(2, "User2"));
    users.add(new User(3, "User3"));

    User match = users.stream().filter((user) -> user.getId() == 1).findAny().get();
    System.out.println(match.toString());
}

static class User {

    @Override
    public String toString() {
        return id + " - " + username;
    }

    int id;
    String username;

    public User() {
    }

    public User(int id, String username) {
        this.id = id;
        this.username = username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public int getId() {
        return id;
    }
}

This code finds a User based on their ID. But there are no guarantees how many Users matched the filter.

Changing the filter line to:

User match = users.stream().filter((user) -> user.getId() < 0).findAny().get();

Will throw a NoSuchElementException (good!)

I would like it to throw an error if there are multiple matches, though. Is there a way to do this?

Body:
public List<state> getAllActiveState() {
    List<Master> master = masterRepository.getActiveExamMasters();
    Master activeMaster = new Master();
    try {
        activeMaster = master.stream().filter(status -> status.getStatus() == true).reduce((u, v) -> {
            throw new IllegalStateException();
        }).get();
        return stateRepository.getAllStateActiveId(activeMaster.getId());
    } catch (IllegalStateException e) {
        logger.info(":More than one status found TRUE in Master");
        return null;
    }
}

In this above code, As per the condition if its find more than one true in the list then it will through the exception.

When it through the error will showing custom message because it easy maintain the logs on server side.

From Nth number of element present in list just want only one element have true condition if in list there are more than one elements having true status at that moment it will through an exception.

after getting all the this we using get(); to taking that one element from list and stored it into another object.

If you want you added optional like Optional<activeMaster > = master.stream().filter(status -> status.getStatus() == true).reduce((u, v) -> {throw new IllegalStateException();}).get();


问:
Difficulty Applying Conditional Rendering to Multiple Array Items
I am trying to set up a quiz questions page (using an API) where, if you select the correct answer for the specific question, the text will show green and the score will increment by one and, if the incorrect answer is selected, the text will show red and the score will remain unchanged.

I am able to apply the logic if there is only one question but, when trying to apply it to ten questions, it applies the changes to each question.

Please see the console and application screenshots below:

For one question:

For ten questions:

My code is as follows:

```<code>import React, { useState } from "react";
import { useLocation } from "react-router-dom";
import "../App.css";
import { Row, Col, Card, Button } from "react-bootstrap";

const Questionnaire = () => {
  const [selectedAnswer, setSelectedAnswer] = useState("");
  const [style, setStyle] = useState("");
  const [score, setScore] = useState(0);

  const location = useLocation();
  const quiz = location.state.quiz;

  // Added:_______________________________//
  const answerOptions = {
    a: "answer_a",
    b: "answer_b",
    c: "answer_c",
    d: "answer_d",
    e: "answer_e",
    f: "answer_f",
  };

  const answerOptionsArray = Array.from(
    { length: quiz.length },
    () => answerOptions
  );

  const questionIndex = Array.from({ length: quiz.length }, (_, i) => i + 1);

  const masterData = questionIndex.map((index, i) => {
    return {
      questionIndex: index,
      answerOptions: answerOptionsArray[i],
      quiz: quiz[i],
    };
  });

  const setAnswer = (e) => {
    const optionValues = answerOptionsArray.map((option) => Object.values(option.a))
    const optionExists = Object.values(answerOptionsArray).includes("answer_a");

    if (optionExists == true) {
      setSelectedAnswer(e.target.value);
    }
    console.log(optionValues);
    // Returns: [ 'answer_a', 'answer_b', 'answer_c', 'answer_d', 'answer_e', 'answer_f' ]
    console.log(e.target.value);
    // Returns: answer_a (If button with "answer_a" is clicked on).
    console.log(optionExists);
    // Returns: false
    console.log(selectedAnswer);
    // Returns: Empty log
  };
  //______________________________________//

  const checkAnswers = (e) => {
    const correctAnswers = masterData.map(
      (answer) => answer.quiz.correct_answers
    );

    const answerCheckA = correctAnswers.map(
      (answer) => answer.answer_a_correct
    );
    const answerCheckB = correctAnswers.map(
      (answer) => answer.answer_b_correct
    );
    const answerCheckC = correctAnswers.map(
      (answer) => answer.answer_c_correct
    );
    const answerCheckD = correctAnswers.map(
      (answer) => answer.answer_d_correct
    );
    const answerCheckE = correctAnswers.map(
      (answer) => answer.answer_e_correct
    );
    const answerCheckF = correctAnswers.map(
      (answer) => answer.answer_f_correct
    );

    if (answerCheckA == "true" && selectedAnswer == "answer_a") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckB == "true" && selectedAnswer == "answer_b") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckC == "true" && selectedAnswer == "answer_c") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckD == "true" && selectedAnswer == "answer_d") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckE == "true" && selectedAnswer == "answer_e") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckF == "true" && selectedAnswer == "answer_f") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else {
      setStyle("incorrect-answer");
      setScore(score);
    }
    console.log("Score: " + score);
  };

  // Adjusted buttons to accommodate the above changes and moved "checkAnswers()" button to the bottom.

  return (
    <div>
      <Row>
        <Col>
          <h3 className="quiz-component-header">
            Quiz: {quiz[0].category} ❨ {quiz[0].difficulty} ❩
          </h3>
        </Col>
      </Row>
      {Object.values(masterData).length !== 0 ? (
        <div>
          <Row>
            <Col>
              {masterData.map((content, i) => (
                <Card
                  key={i}
                  className="col-md-11 question-card"
                  content={content}
                >
                  <Card.Title>QUESTION {content.questionIndex}</Card.Title>
                  <Card.Body>
                    <Card.Text>{content.quiz.question}</Card.Text>
                  </Card.Body>
                  <Card.Title>SELECT YOUR ANSWER</Card.Title>
                  {content.quiz.answers.answer_a !== null ? (
                    <Button
                      value="answer_a"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_a" ? style : undefined
                      }
                    >
                      a. {content.quiz.answers.answer_a}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_b !== null ? (
                    <Button
                      value="answer_b"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_b" ? style : undefined
                      }
                    >
                      b. {content.quiz.answers.answer_b}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_c !== null ? (
                    <Button
                      value="answer_c"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_c" ? style : undefined
                      }
                    >
                      c. {content.quiz.answers.answer_c}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_d !== null ? (
                    <Button
                      value="answer_d"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_d" ? style : undefined
                      }
                    >
                      d. {content.quiz.answers.answer_d}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_e !== null ? (
                    <Button
                      value="answer_e"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_e" ? style : undefined
                      }
                    >
                      e. {content.quiz.answers.answer_e}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                  {content.quiz.answers.answer_f !== null ? (
                    <Button
                      value="answer_f"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_f" ? style : undefined
                      }
                    >
                      f. {content.quiz.answers.answer_f}
                    </Button>
                  ) : (
                    <div></div>
                  )}
                </Card>
              ))}
            </Col>
          </Row>
          <Button type="submit" onClick={checkAnswers}>
            Check Score
          </Button>
          <h3>Score: {score} / 10</h3>
        </div>
      ) : (
        <div>
          <h3>There are Currently No Questions For Your Query</h3>
          <h4>Watch This Space For Added Questions</h4>
        </div>
      )}
    </div>
  );
};

export default Questionnaire;
</code>```

Please may someone assist? I would appreciate any help that anyone is willing to offer.

答:
This may be one possible approach / method to try resolving the issue described in the question.

The below is not a working example. It is merely an approach.

```<code>const Questionnaire = () => {
  .
  .
  const [selectedAnswer, setSelectedAnswer] = useState({});
  .
  .
  const [style, setStyle] = useState({});
  .
  .
  const setAnswerForQuestion = (qIdx, answerKey) => {
    setSelectedAnswer(prev => ({...prev, [qIdx]: answerKey}));
  };
  .
  .
  const checkAnswers = () => {
    const correctAnswers = quiz[0].correct_answers; // quiz[0] only
    // see <h3 className="quiz-component-header">
    // only quiz[0] is rendered in this component
    const tempScore = correctAnswers.reduce((total, ans, qIdx) => (
      total + ( ans === selectedAnswers[qIdx] ? 1 || 0)
    ), 0);
    setScore(tempScore);
    // Now, set style for each question's answer
    setStyle(correctAnswers.reduce((fin, ans, qIdx) => ({
      ...fin,
      [qIdx]:
        ans === selectedAnswers[qIdx]
          ? 'correct-answer'
          : 'incorrect-answer'
    }), {}));
  };
  .
  .
  .
  return (
    .
    .
    {masterData.map((content, i) => (
      <Card key={i} className="col-md-11 question-card" content={content}>
        <Card.Title>QUESTION {content.questionIndex}</Card.Title>
        <Card.Body>
          <Card.Text>{content.quiz.question}</Card.Text>
        </Card.Body>
        <Card.Title>SELECT YOUR ANSWER</Card.Title>
        { Object.entries(content.quiz.answers).map(([k, v], aIdx) => (
            v !== null &&
            <Button
              value={k}
              className={style[i] || undefined}
              onClick={() => setAnswerForQuestion(i, k)}
            >
              {String.fromCharCode(97 + aIdx)}. {v}
            </Button>
          ))
        }

        .
        .
        .
      </Card>
      .
      .
      .
      <Button type="submit" onClick={checkAnswers}>
        Check Score
      </Button>
      <h3>Score: {score} / 10</h3>
      .
      .
    )}
    .
    .
  );
}
</code>```

Body:
I am trying to set up a quiz questions page (using an API) where, if you select the correct answer for the specific question, the text will show green and the score will increment by one and, if the incorrect answer is selected, the text will show red and the score will remain unchanged.

I am able to apply the logic if there is only one question but, when trying to apply it to ten questions, it applies the changes to each question.

Please see the console and application screenshots below:

For one question:

For ten questions:

My code is as follows:

import React, { useState } from "react";
import { useLocation } from "react-router-dom";
import "../App.css";
import { Row, Col, Card, Button } from "react-bootstrap";

const Questionnaire = () => {
  const [selectedAnswer, setSelectedAnswer] = useState("");
  const [style, setStyle] = useState("");
  const [score, setScore] = useState(0);

  const location = useLocation();
  const quiz = location.state.quiz;

  // Added:_______________________________//
  const answerOptions = {
    a: "answer_a",
    b: "answer_b",
    c: "answer_c",
    d: "answer_d",
    e: "answer_e",
    f: "answer_f",
  };

  const answerOptionsArray = Array.from(
    { length: quiz.length },
    () => answerOptions
  );

  const questionIndex = Array.from({ length: quiz.length }, (_, i) => i + 1);

  const masterData = questionIndex.map((index, i) => {
    return {
      questionIndex: index,
      answerOptions: answerOptionsArray[i],
      quiz: quiz[i],
    };
  });

  const setAnswer = (e) => {
    const optionValues = answerOptionsArray.map((option) => Object.values(option.a))
    const optionExists = Object.values(answerOptionsArray).includes("answer_a");

    if (optionExists == true) {
      setSelectedAnswer(e.target.value);
    }
    console.log(optionValues);
    // Returns: [ 'answer_a', 'answer_b', 'answer_c', 'answer_d', 'answer_e', 'answer_f' ]
    console.log(e.target.value);
    // Returns: answer_a (If button with "answer_a" is clicked on).
    console.log(optionExists);
    // Returns: false
    console.log(selectedAnswer);
    // Returns: Empty log
  };
  //______________________________________//

  const checkAnswers = (e) => {
    const correctAnswers = masterData.map(
      (answer) => answer.quiz.correct_answers
    );

    const answerCheckA = correctAnswers.map(
      (answer) => answer.answer_a_correct
    );
    const answerCheckB = correctAnswers.map(
      (answer) => answer.answer_b_correct
    );
    const answerCheckC = correctAnswers.map(
      (answer) => answer.answer_c_correct
    );
    const answerCheckD = correctAnswers.map(
      (answer) => answer.answer_d_correct
    );
    const answerCheckE = correctAnswers.map(
      (answer) => answer.answer_e_correct
    );
    const answerCheckF = correctAnswers.map(
      (answer) => answer.answer_f_correct
    );

    if (answerCheckA == "true" && selectedAnswer == "answer_a") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckB == "true" && selectedAnswer == "answer_b") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckC == "true" && selectedAnswer == "answer_c") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckD == "true" && selectedAnswer == "answer_d") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckE == "true" && selectedAnswer == "answer_e") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else if (answerCheckF == "true" && selectedAnswer == "answer_f") {
      setStyle("correct-answer");
      setScore(score + 1);
    } else {
      setStyle("incorrect-answer");
      setScore(score);
    }
    console.log("Score: " + score);
  };

  // Adjusted buttons to accommodate the above changes and moved "checkAnswers()" button to the bottom.

  return (

      <Row>
        <Col>

            Quiz: {quiz[0].category} ❨ {quiz[0].difficulty} ❩

        </Col>
      </Row>
      {Object.values(masterData).length !== 0 ? (

          <Row>
            <Col>
              {masterData.map((content, i) => (
                <Card
                  key={i}
                  className="col-md-11 question-card"
                  content={content}
                >
                  <Card.Title>QUESTION {content.questionIndex}</Card.Title>
                  <Card.Body>
                    <Card.Text>{content.quiz.question}</Card.Text>
                  </Card.Body>
                  <Card.Title>SELECT YOUR ANSWER</Card.Title>
                  {content.quiz.answers.answer_a !== null ? (
                    <Button
                      value="answer_a"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_a" ? style : undefined
                      }
                    >
                      a. {content.quiz.answers.answer_a}
                    </Button>
                  ) : (

                  )}
                  {content.quiz.answers.answer_b !== null ? (
                    <Button
                      value="answer_b"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_b" ? style : undefined
                      }
                    >
                      b. {content.quiz.answers.answer_b}
                    </Button>
                  ) : (

                  )}
                  {content.quiz.answers.answer_c !== null ? (
                    <Button
                      value="answer_c"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_c" ? style : undefined
                      }
                    >
                      c. {content.quiz.answers.answer_c}
                    </Button>
                  ) : (

                  )}
                  {content.quiz.answers.answer_d !== null ? (
                    <Button
                      value="answer_d"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_d" ? style : undefined
                      }
                    >
                      d. {content.quiz.answers.answer_d}
                    </Button>
                  ) : (

                  )}
                  {content.quiz.answers.answer_e !== null ? (
                    <Button
                      value="answer_e"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_e" ? style : undefined
                      }
                    >
                      e. {content.quiz.answers.answer_e}
                    </Button>
                  ) : (

                  )}
                  {content.quiz.answers.answer_f !== null ? (
                    <Button
                      value="answer_f"
                      onClick={(e) => setAnswer(e)}
                      className={
                        selectedAnswer === "answer_f" ? style : undefined
                      }
                    >
                      f. {content.quiz.answers.answer_f}
                    </Button>
                  ) : (

                  )}
                </Card>
              ))}
            </Col>
          </Row>
          <Button type="submit" onClick={checkAnswers}>
            Check Score
          </Button>

Score: {score} / 10

      ) : (

There are Currently No Questions For Your Query

Watch This Space For Added Questions

      )}

  );
};

export default Questionnaire;

Please may someone assist? I would appreciate any help that anyone is willing to offer.

Body:
This may be one possible approach / method to try resolving the issue described in the question.

The below is not a working example. It is merely an approach.

const Questionnaire = () => {
  .
  .
  const [selectedAnswer, setSelectedAnswer] = useState({});
  .
  .
  const [style, setStyle] = useState({});
  .
  .
  const setAnswerForQuestion = (qIdx, answerKey) => {
    setSelectedAnswer(prev => ({...prev, [qIdx]: answerKey}));
  };
  .
  .
  const checkAnswers = () => {
    const correctAnswers = quiz[0].correct_answers; // quiz[0] only
    // see <h3 className="quiz-component-header">
    // only quiz[0] is rendered in this component
    const tempScore = correctAnswers.reduce((total, ans, qIdx) => (
      total + ( ans === selectedAnswers[qIdx] ? 1 || 0)
    ), 0);
    setScore(tempScore);
    // Now, set style for each question's answer
    setStyle(correctAnswers.reduce((fin, ans, qIdx) => ({
      ...fin,
      [qIdx]:
        ans === selectedAnswers[qIdx]
          ? 'correct-answer'
          : 'incorrect-answer'
    }), {}));
  };
  .
  .
  .
  return (
    .
    .
    {masterData.map((content, i) => (
      <Card key={i} className="col-md-11 question-card" content={content}>
        <Card.Title>QUESTION {content.questionIndex}</Card.Title>
        <Card.Body>
          <Card.Text>{content.quiz.question}</Card.Text>
        </Card.Body>
        <Card.Title>SELECT YOUR ANSWER</Card.Title>
        { Object.entries(content.quiz.answers).map(([k, v], aIdx) => (
            v !== null &&
            <Button
              value={k}
              className={style[i] || undefined}
              onClick={() => setAnswerForQuestion(i, k)}
            >
              {String.fromCharCode(97 + aIdx)}. {v}
            </Button>
          ))
        }

        .
        .
        .
      </Card>
      .
      .
      .
      <Button type="submit" onClick={checkAnswers}>
        Check Score
      </Button>
      <h3>Score: {score} / 10</h3>
      .
      .
    )}
    .
    .
  );
}


问:
How do I resolve an Entity Framework error creating the db context
I have created my first (Blazer) project with Entity Framework.  I got enable-migrations and update-database to work.  Now, I get the following build error:

Error while validating the service descriptor 'ServiceType: Timesheet.Models.DatabaseContext Lifetime: Singleton

ImplementationType: Timesheet.Models.DatabaseContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Timesheet.Models.DatabaseContext]' while attempting to activate 'Timesheet.Models.DatabaseContext'.

The error is thrown at this point:

I've tried reading the error multiple times but I'm not sure what it's referring to. I'm hoping someone can point me in the right direction.  Here is the db service in my startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(p =>
           p.GetRequiredService<IDbContextFactory<DatabaseContext>>().CreateDbContext());
}
</code>```

I just have no idea where to go next. Any suggestions are appreciated.

Edit 1: Adding the full Program.cs file

```<code>using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Timesheet.Data;
using Timesheet.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<DatabaseContext>();

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
//builder.Services.AddSingleton<WeatherForecastService>();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();
</code>```

答:
If you see an error like

"Unable to resolve service for type"

you must search the given unresolved type.

Unresolved type means, your middleware cannot identify what is the type given to him.

In this example Your services are in wrong order. Your builder cannot identify what is "Timesheet.Models.DatabaseContext".

So the solution seems you must call builder.Build() operation after builder.Configuration().

I suppose it helps when you see the same error at other times.

Body:
I have created my first (Blazer) project with Entity Framework.  I got enable-migrations and update-database to work.  Now, I get the following build error:

Error while validating the service descriptor 'ServiceType: Timesheet.Models.DatabaseContext Lifetime: Singleton

ImplementationType: Timesheet.Models.DatabaseContext': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Timesheet.Models.DatabaseContext]' while attempting to activate 'Timesheet.Models.DatabaseContext'.

The error is thrown at this point:

I've tried reading the error multiple times but I'm not sure what it's referring to. I'm hoping someone can point me in the right direction.  Here is the db service in my startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(p =>
           p.GetRequiredService<IDbContextFactory<DatabaseContext>>().CreateDbContext());
}

I just have no idea where to go next. Any suggestions are appreciated.

Edit 1: Adding the full Program.cs file

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Timesheet.Data;
using Timesheet.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<DatabaseContext>();

// Add services to the container.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews()
    .AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddMicrosoftIdentityConsentHandler();
//builder.Services.AddSingleton<WeatherForecastService>();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DatabaseContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();


问:
Convet this sql query to php laravel?
SELECT project_name, (CHAR_LENGTH(company_id) - CHAR_LENGTH(REPLACE(company_id, ',', '')) + 1) as total FROM project_management;</p>

答:
```<code>$getData = DB::table('')
    ->selectRaw('write your query here')
    ->where('')
    ->get();
</code>```

Title: Convet this sql query to php laravel?


问:
paste()ing columns whose names are stored in a variable
How do I create a new column from columns whose names are contained in a character vector?

Given these two variables:

```<code>data <- tibble(numbers = 1:10, letters = letters[1:10])
columns <- c("numbers","letters")
</code>```

What command would produce this output?

```<code># A tibble: 10 x 3
   numbers letters combined
     <int> <chr>   <chr>
 1       1 a       1-a
 2       2 b       2-b
 3       3 c       3-c
 4       4 d       4-d
 5       5 e       5-e
 6       6 f       6-f
 7       7 g       7-g
 8       8 h       8-h
 9       9 i       9-i
10      10 j       10-j
</code>```

My first thought was mutate(data, combined = paste(!!columns, sep = "-")) but this does not work.

```<code>Error: Problem with `mutate()` input `combined`.
x Input `combined` can't be recycled to size 10.
ℹ Input `combined` is `paste(c("numbers", "letters"))`.
ℹ Input `combined` must be size 10 or 1, not 2.
</code>```

答:
not the prettiest but this should work</p>
```<code>do.call(
  paste,
  c(data[, columns], list(sep = '-'))
)
</code>```

Body:
How do I create a new column from columns whose names are contained in a character vector?

Given these two variables:

data <- tibble(numbers = 1:10, letters = letters[1:10])
columns <- c("numbers","letters")

What command would produce this output?

# A tibble: 10 x 3
   numbers letters combined
     <int> <chr>   <chr>
 1       1 a       1-a
 2       2 b       2-b
 3       3 c       3-c
 4       4 d       4-d
 5       5 e       5-e
 6       6 f       6-f
 7       7 g       7-g
 8       8 h       8-h
 9       9 i       9-i
10      10 j       10-j

My first thought was mutate(data, combined = paste(!!columns, sep = "-")) but this does not work.

Error: Problem with `mutate()` input `combined`.
x Input `combined` can't be recycled to size 10.
ℹ Input `combined` is `paste(c("numbers", "letters"))`.
ℹ Input `combined` must be size 10 or 1, not 2.

Body:
not the prettiest but this should work

do.call(
  paste,
  c(data[, columns], list(sep = '-'))
)


问:
Declare a SystemVerilog variable with type depending on a parameter
I want to write reusable SystemVerilog code so I need to have in module one variable with type, depending on a parameter (not different bus WIDTH, but different structs). Maybe it is possible to have one parametrized structure or to have different structures but in this case how to declare variable selecting needed struct as a type. Different structs could be declared in generte-if blocks, but they will be local to it blocks, so outside can't to get them. Maybe type conversion might help somehow.

P. S. Interfaces are not allowed to use as well as defines (macros are allowed).

Code example, I want to achieve:

```<code>typedef struct packed
{
  logic a;
  logic b;
} str_s;

typedef struct packed
{
  logic a;
  logic b;
  logic c;
} str_s_with_c;

// A is a parameter
generate
if (A == "ON")
   str_s_with_c array;

if (A == "OFF")
   str_s array;
endgenerate

assign array.a = 1'b1;

logic t;

assign t = array.a;
</code>```

or

```<code>generate
if (A == "ON")
begin
   typedef struct packed
   {
     logic a;
     logic b;
   } str_s;
end

if (A == "OFF")
begin
   typedef struct packed
   {
     logic a;
     logic b;
     logic c;
   } str_s;
end
endhenerate

str_s array;

array.a = 1.b1;
</code>```

答:
You can declare variables local to generate blocks and access them with a block name.

```<code>typedef struct packed
{
  logic a;
  logic b;
} str_s;

typedef struct packed
{
  logic a;
  logic b;
  logic c;
} str_s_with_c;

// A is a parameter
if (A == "ON") begin : bname
   str_s_with_c array;
end
else if (A == "OFF") begin :  bname
   str_s array;
end

assign bname.array.a = 1'b1;

logic t;

assign t = bname.array.a;
</code>```

Note that if you want to access array.c, that will have to be guarded with a generate-if as well.

```<code>if (A == "ON") begin
  always @(posedge clk)
    x = bname.array.c;
end
else if (A == "OFF") begin
  always @(posedge clk)
     x = something_else;
end
</code>```

Body:
I want to write reusable SystemVerilog code so I need to have in module one variable with type, depending on a parameter (not different bus WIDTH, but different structs). Maybe it is possible to have one parametrized structure or to have different structures but in this case how to declare variable selecting needed struct as a type. Different structs could be declared in generte-if blocks, but they will be local to it blocks, so outside can't to get them. Maybe type conversion might help somehow.

P. S. Interfaces are not allowed to use as well as defines (macros are allowed).

Code example, I want to achieve:

typedef struct packed
{
  logic a;
  logic b;
} str_s;

typedef struct packed
{
  logic a;
  logic b;
  logic c;
} str_s_with_c;

// A is a parameter
generate
if (A == "ON")
   str_s_with_c array;

if (A == "OFF")
   str_s array;
endgenerate

assign array.a = 1'b1;

logic t;

assign t = array.a;

or

generate
if (A == "ON")
begin
   typedef struct packed
   {
     logic a;
     logic b;
   } str_s;
end

if (A == "OFF")
begin
   typedef struct packed
   {
     logic a;
     logic b;
     logic c;
   } str_s;
end
endhenerate

str_s array;

array.a = 1.b1;

Body:
You can declare variables local to generate blocks and access them with a block name.

typedef struct packed
{
  logic a;
  logic b;
} str_s;

typedef struct packed
{
  logic a;
  logic b;
  logic c;
} str_s_with_c;

// A is a parameter
if (A == "ON") begin : bname
   str_s_with_c array;
end
else if (A == "OFF") begin :  bname
   str_s array;
end

assign bname.array.a = 1'b1;

logic t;

assign t = bname.array.a;

Note that if you want to access array.c, that will have to be guarded with a generate-if as well.

if (A == "ON") begin
  always @(posedge clk)
    x = bname.array.c;
end
else if (A == "OFF") begin
  always @(posedge clk)
     x = something_else;
end


问:
Getting null for lambda asyncinvoke function in php
I am trying to call an async lamda function inside of my Php file. But here i am getting null as output.I am not sure about the structure of my below code for calling a async lamda function.</p>
```<code><?php

/**
 * [getMOOCCouponListDetails description].
 *
 * @param [type] $data          [description]
 * @param [type] $vendorDetails [description]
 *
 * @return [type] [description]
 */

require_once 'vendor/autoload.php';
use Aws\Lambda\LambdaClient;
function addRewardsPoints($vendorid, $data)
{

    if(empty($data) || empty($vendorid)){
        HTTPFailWithCode(401,VBOXLITE_HTTP_MISSING_PARAMS);
    }
    $Payload = [
        "subscriberid" => isset($data['subscriberid']) ? $data['subscriberid']:" ",
        "videocompletion" =>  isset($data['videocompletion']) ? $data['videocompletion']:" ",
        "profileid" =>  isset($data['profileid']) ? $data['profileid']:" ",
        "contentid" =>  isset($data['contentid']) ? $data['contentid']:" ",
        "courseid" => isset($data['courseid']) ? $data['courseid']:" ",
        "vendorid" =>  $vendorid,
        "paymentId" =>  isset($data['paymentId']) ? $data['paymentId']:" " ,
        "planId" => isset($data['planId']) ? $data['planId']:" " ,
    ];

$client = LambdaClient::factory(
    array(
        'version' => 'latest',
        'region'  => 'us-east-1'
    )
);
$result = $client->invokeAsync([
  'FunctionName' => 'actuator-jsonruleengine-dev',
  'InvokeArgs' => $Payload
]);
var_dump($result->get('Payload'));

$finalResult = json_decode($result);
errorlog_withlevel('addRewardsPoints POST  output=======>' . json_encode($finalResult), 3);
return $finalResult;
</code>```

答:
```<code><?php

/**
 * [getMOOCCouponListDetails description].
 *
 * @param [type] $data          [description]
 * @param [type] $vendorDetails [description]
 *
 * @return [type] [description]
 */

require_once 'vendor/autoload.php';
function addRewardsPoints($vendorid, $data)
{
    $Payload = [
        "subscriberid" => isset($data['subscriberid']) ? $data['subscriberid']:" ",
        "videocompletion" =>  isset($data['videocompletion']) ? $data['videocompletion']:" ",
        "profileid" =>  isset($data['profileid']) ? $data['profileid']:" ",
        "contentid" =>  isset($data['contentid']) ? $data['contentid']:" ",
        "courseid" => isset($data['courseid']) ? $data['courseid']:" ",
        "vendorid" =>  $vendorid,
        "paymentId" =>  isset($data['paymentId']) ? $data['paymentId']:" " ,
        "planId" => isset($data['planId']) ? $data['planId']:" " ,
        "profilename" => isset($data['profilename']) ? $data['profilename']:" " ,
    ];
    try {

        $client = new Aws\Lambda\LambdaClient(
            array(
                'version' => 'latest',
                'region'  => 'us-east-1'
            )
        );

        $result = $client->invoke([
            'FunctionName' => 'actuator-jsonruleengine-dev',
            'Payload' => json_encode($Payload)
        ]);

        errorlog_withlevel('addRewardsPoints POST  output=======>' . json_encode($result), 3);

        return $result;
    }
    catch(Exception $e)
    {
        $errorData = formatError(1078);
        $errorData['reason'] = $e->getMessage();
        errorlog_withlevel('exception=======>' . json_encode($e->getMessage()), 3);
    }
}
</code>```

Body:
I am trying to call an async lamda function inside of my Php file. But here i am getting null as output.I am not sure about the structure of my below code for calling a async lamda function.

<?php

/**
 * [getMOOCCouponListDetails description].
 *
 * @param [type] $data          [description]
 * @param [type] $vendorDetails [description]
 *
 * @return [type] [description]
 */

require_once 'vendor/autoload.php';
use Aws\Lambda\LambdaClient;
function addRewardsPoints($vendorid, $data)
{

    if(empty($data) || empty($vendorid)){
        HTTPFailWithCode(401,VBOXLITE_HTTP_MISSING_PARAMS);
    }
    $Payload = [
        "subscriberid" => isset($data['subscriberid']) ? $data['subscriberid']:" ",
        "videocompletion" =>  isset($data['videocompletion']) ? $data['videocompletion']:" ",
        "profileid" =>  isset($data['profileid']) ? $data['profileid']:" ",
        "contentid" =>  isset($data['contentid']) ? $data['contentid']:" ",
        "courseid" => isset($data['courseid']) ? $data['courseid']:" ",
        "vendorid" =>  $vendorid,
        "paymentId" =>  isset($data['paymentId']) ? $data['paymentId']:" " ,
        "planId" => isset($data['planId']) ? $data['planId']:" " ,
    ];

$client = LambdaClient::factory(
    array(
        'version' => 'latest',
        'region'  => 'us-east-1'
    )
);
$result = $client->invokeAsync([
  'FunctionName' => 'actuator-jsonruleengine-dev',
  'InvokeArgs' => $Payload
]);
var_dump($result->get('Payload'));

$finalResult = json_decode($result);
errorlog_withlevel('addRewardsPoints POST  output=======>' . json_encode($finalResult), 3);
return $finalResult;


问:
Send POST request with JSON data Spring boot
I trying to send a post request with json data in a particular format using Spring boot. I am not getting data in expected format. Please help e resolve it. Thanks in advance.

```<code>class UserService{
public void sendRequest(User data){
  HttpHeaders header = new HttpHeaders();
  mapHeaders.set("Content-Type","application/json");
  Map<String,User> m= new HashMap<String,User>();
  m.put("request",data);
  //print m i.e. payload being sent
  HttpEntity entity = new HttpEntity<Object>(m, header);
  String url = some url here
  ResponseEntity<Object> response = restTemplate.exchange(url, httpMethod, entity,
   Object.class);
   }
}

class User{
private String firstName;
private String lastName;

}

</code>```

While printing payload it displays payload as:

```<code>{request=User(firstName=Raj,lastName=Kumar)}
</code>```

I want the data as

```<code>{request={firstName=Raj,lastName=Kumar}}
</code>```

答:
Do as below using Jackson library in case you need to print an object in JSON format:</p>
```<code>import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

    ...
    m.put("request", data);
            ObjectMapper objectMapper =  new ObjectMapper();
            try {
                String jsonString = objectMapper.writeValueAsString(m);
                System.out.println(jsonString);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
    ...
</code>```

Body:
I trying to send a post request with json data in a particular format using Spring boot. I am not getting data in expected format. Please help e resolve it. Thanks in advance.

class UserService{
public void sendRequest(User data){
  HttpHeaders header = new HttpHeaders();
  mapHeaders.set("Content-Type","application/json");
  Map<String,User> m= new HashMap<String,User>();
  m.put("request",data);
  //print m i.e. payload being sent
  HttpEntity entity = new HttpEntity<Object>(m, header);
  String url = some url here
  ResponseEntity<Object> response = restTemplate.exchange(url, httpMethod, entity,
   Object.class);
   }
}

class User{
private String firstName;
private String lastName;

}

While printing payload it displays payload as:

{request=User(firstName=Raj,lastName=Kumar)}

I want the data as

{request={firstName=Raj,lastName=Kumar}}

Body:
Do as below using Jackson library in case you need to print an object in JSON format:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

    ...
    m.put("request", data);
            ObjectMapper objectMapper =  new ObjectMapper();
            try {
                String jsonString = objectMapper.writeValueAsString(m);
                System.out.println(jsonString);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
    ...


问:
Asking the user to re-enter year of birth until birth year < current year
I have a problem that how to keep show a prompt until user enter their birth year is always smaller than the current year. Here is my code I try using loop but now  i struggle. I hope someone can help me, I appreciate it.</p>
```<code><body>
<p id= "age"></p>
<button onclick=" notify()">Try it</button>
<script>
function notify(){
let age = prompt("Your birth year");
        const year = new Date().getFullYear();
        do {
          document.getElementById("age").innerHTML =
            age + " is a good year";
        } while (age < year && age != null);
}
</script>
</body>
</code>```

答:
You could use recursion:

  <button onclick="notify()">Try it</button>

  ```

Body:
I have a problem that how to keep show a prompt until user enter their birth year is always smaller than the current year. Here is my code I try using loop but now  i struggle. I hope someone can help me, I appreciate it.

<button onclick=" notify()">Try it</button>

Body:
You could use recursion:

<body>
  <p id="age"></p>
  <button onclick="notify()">Try it</button>
  <script>
    age_p = document.getElementById("age");
    function notify() {
      let age = prompt("Your birth yeat");
      const year = new Date().getFullYear();
      if (parseInt(age) < year) {
        age_p.innerHTML = age + " is a good year";
      } else {
        notify();
      }
    }
  </script>
  </body>


答:
A tidyverse approach is to use unite, where you can pass the columns vector directly into the function without having to use !!.

```<code>library(tidyverse)

data %>%
  tidyr::unite("combined", columns, sep = "-", remove = FALSE) %>%
  dplyr::relocate(combined, .after = tidyselect::last_col())
</code>```

Output

```<code>   numbers letters combined
     <int> <chr>   <chr>
 1       1 a       1-a
 2       2 b       2-b
 3       3 c       3-c
 4       4 d       4-d
 5       5 e       5-e
 6       6 f       6-f
 7       7 g       7-g
 8       8 h       8-h
 9       9 i       9-i
10      10 j       10-j
</code>```

Title: paste()ing columns whose names are stored in a variable

Body:
A tidyverse approach is to use unite, where you can pass the columns vector directly into the function without having to use !!.

library(tidyverse)

data %>%
  tidyr::unite("combined", columns, sep = "-", remove = FALSE) %>%
  dplyr::relocate(combined, .after = tidyselect::last_col())

Output

   numbers letters combined
     <int> <chr>   <chr>
 1       1 a       1-a
 2       2 b       2-b
 3       3 c       3-c
 4       4 d       4-d
 5       5 e       5-e
 6       6 f       6-f
 7       7 g       7-g
 8       8 h       8-h
 9       9 i       9-i
10      10 j       10-j


问:
Check if two numbers have same digits
I need to write a program which will check if two numbers have same digits.
For example:

```<code>a = 4423, b = 2433;
</code>```

Even though their digits don't appear the same amount if times, they have same digits.

```<code>#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}
</code>```

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

答:
A histogram of 10 digits (or 11 if we want to count the '-' sign) where each frequency is capped between 0 and 1 should be implemented as a vector of bits (a bitmask) stored in an integer. Then of course the solution can handle all the number bases only up to 32, but the overall code should be vastly clearer and smaller, without the need to compare arrays by looping.</p>
```<code>int hash_int(int b) {
    int hash = 0;
    // take abs as unsigned -- now 0 <= a <= 0x80000000u
    // unsigned mod 10 is btw more performant than signed mod
    unsigned int a = b >= 0 ? b : 0u - b;
    // construct the hash, removing duplicate digits as we go
    // performance wise `do {} while` is better than `while`
    // due to less jumping around - here the side effect is
    // that a==0 hashes to 1.
    // For comparison a==0 -> hash = 0 would work equally well
    do {
        hash |= 1 << (a % 10);
        a /= 10;
    } while (a);
    return hash;
}

bool is_same(int a, int b) { return hash_int(a) == hash_int(b); }
</code>```

Title: Check if two numbers have same digits

Body:
I need to write a program which will check if two numbers have same digits.
For example:

a = 4423, b = 2433;

Even though their digits don't appear the same amount if times, they have same digits.

#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

Body:
A histogram of 10 digits (or 11 if we want to count the '-' sign) where each frequency is capped between 0 and 1 should be implemented as a vector of bits (a bitmask) stored in an integer. Then of course the solution can handle all the number bases only up to 32, but the overall code should be vastly clearer and smaller, without the need to compare arrays by looping.

int hash_int(int b) {
    int hash = 0;
    // take abs as unsigned -- now 0 <= a <= 0x80000000u
    // unsigned mod 10 is btw more performant than signed mod
    unsigned int a = b >= 0 ? b : 0u - b;
    // construct the hash, removing duplicate digits as we go
    // performance wise `do {} while` is better than `while`
    // due to less jumping around - here the side effect is
    // that a==0 hashes to 1.
    // For comparison a==0 -> hash = 0 would work equally well
    do {
        hash |= 1 << (a % 10);
        a /= 10;
    } while (a);
    return hash;
}

bool is_same(int a, int b) { return hash_int(a) == hash_int(b); }


问:
What does the keyword ref mean in C#?
Below is my code please explain what is ref cboListType.</p>

```<code>Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}
</code>```

答:
ref keyword means "pass by reference". When you pass some DropDownList reference to LoadListTypes() this reference may be changed. So after this call, the reference you've passed could refer to absolutely another object.

```<code>void func(ref MyClass mc)
{
  mc = new MyClass(2);
}

MyClass mc = new MyClass(1);
MyClass mc2 = mc;
// mc and mc2 are the same
func(ref mc);
// mc and mc2 may differ
</code>```

Title: What does the keyword ref mean in C#?

Body:
Below is my code please explain what is ref cboListType.

Lists.LoadListTypes(ref cboListType);

public static void LoadListTypes(ref DropDownList dropDown)
{
    if (!Util.IsCached(LIST_TYPES))
    {
        Util.InsertIntoCache(LIST_TYPES, DataAccess.ListListTypes());
    }

    dropDown.DataSource = (DataTable)Util.GetFromCache(LIST_TYPES);
    dropDown.DataBind();
    dropDown.Items.Insert(0, new ListItem("", ""));
}

Body:
ref keyword means "pass by reference". When you pass some DropDownList reference to LoadListTypes() this reference may be changed. So after this call, the reference you've passed could refer to absolutely another object.

void func(ref MyClass mc)
{
  mc = new MyClass(2);
}

MyClass mc = new MyClass(1);
MyClass mc2 = mc;
// mc and mc2 are the same
func(ref mc);
// mc and mc2 may differ


问:
Laravel composer update error: Nothing to install or update
When I run composer update, I get the following error:

Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Nothing to install or update
  Generating autoload files
  Illuminate\Foundation\ComposerScripts::postUpdate
  php artisan optimize
    [Symfony\Component\Debug\Exception\FatalErrorException]
    Class 'Laravel\Cashier\CashierServiceProvider' not found
  Script php artisan optimize handling the post-update-cmd event returned with err
  or code 255

I put this code on the app.php file

Laravel\Cashier\CashierServiceProvider::class,

and in the composer.json I also put this

"laravel/cashier": "~6.0"

like in the laravel doc

stack errot

答:
Check the php version in cmd useing php -v

if php version is < 7.0 then install latest version of php.

Uninstall the old verion Xampp

Install latest version of Xampp to upgrade php.


问:
How do you add spaces for aws cloudformation deploy --parameter-overrides and/or --tags?
I am trying to get spaces into the tags parameter for the aws cli and it works if I hardcode it but not if I use bash variables. What is going on and how do I fix it?

This works with out spaces:

```<code>aws cloudformation deploy  \
      --template-file /path_to_template/template.json \
      --stack-name my-new-stack \
      --tags Key1=Value1 Key2=Value2
</code>```

This works with out spaces but with variables:

```<code>tags="Key1=Value1 Key2=Value2"
aws cloudformation deploy \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags $tags
</code>```

This works with spaces:

```<code>aws cloudformation deploy  \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags 'Key1=Value1' 'Key Two=Value2'
</code>```

This does not work, spaces and variables:

```<code>tags="'Key1=Value1' 'Key Two=Value2'"

aws cloudformation deploy  \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags $tags
</code>```

Attempting to fix bash expansion, also does not work, spaces and variables:

```<code>tags="'Key1=Value1' 'Key Two=Value2'"

aws cloudformation deploy  \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags "$tags"
</code>```

Attempting to fix bash expansion, also does not work, spaces and variables:

```<code>tags="'Key1=Value1' 'Key Two=Value2'"

aws cloudformation deploy  \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags "$(printf '%q' $tags)"
</code>```

Error:

Invalid parameter: Tags Reason: The given tag(s) contain invalid
  characters (Service: AmazonSNS; Status Code: 400; Error Code:
  InvalidParameter; Request ID

答:
As of 2022-02 this was still an issue described

here

here also

and a little here

@esolomon is correct you have to array expansion. His answer which works just fine:

deploy=(aws cloudformation deploy
            ...
            --tags $(cat tags.json | jq '.[] | (.Key + "=" + .Value)'))

eval $(echo ${deploy[@]})
```
<p>The actual problem is a result of the shell environment (<code>bin/bash</code> here) that is used in combination with how python cli executable's handling of values. Since the <code>aws cloudformation deploy</code> does not standardize the input but expects the shell program to standardize array input this was causing my problem.</p>
<p>So my errors with the <code>--debug</code> flag turned on produced the first response which is the error and the second response is the expected input into <code>aws cloudformation deploy</code></p>
<p>Error input:</p>
<blockquote>
<p>2022-02-10 17:32:28,137 - MainThread - awscli.clidriver - DEBUG - Arguments entered to CLI: ['cloudformation', 'deploy', '--region', 'us-east-1', ..., '--parameter-overrides', <strong>'PARAM1=dev PARAM2=blah', '--tags', "TAG1='Test Project' TAG2='blah'...",</strong> '--debug']</p>
</blockquote>
<p>Expected input:</p>
<blockquote>
<p>2022-02-10 17:39:40,390 - MainThread - awscli.clidriver - DEBUG - Arguments entered to CLI: ['cloudformation', 'deploy', '--region', 'us-east-1', ..., '--parameter-overrides', <strong>'PARAM1=dev', 'PARAM2=blah', '--tags', "TAG2='Test Project'", 'TAG2=blah',</strong>..., '--debug']</p>
</blockquote>
<p>I was unexpectedly sending in a string instead of array of strings this error resulted in several errors depending on how I sent it:
example TAG: <code>TAG1=Test Project</code></p>
<blockquote>
<p>['Project'] value passed to --tags must be of format Key=Value</p>
</blockquote>
<ul>
<li>the means IFS needs to be set to something other than the default <code>' \t\n'</code>, solution below</li>
</ul>
<blockquote>
<p>An error occurred (ValidationError) when calling the CreateChangeSet operation: 1 validation error detected: Value 'Test Project Tag2=Value2 ...' at 'tags.1.member.value' failed to satisfy constraint: Member must have length less than or equal to 256</p>
</blockquote>
<ul>
<li><strong>the error starts after the first <code>=</code></strong> this error means that I am sending in one long string instead of array items, as seen here when doing <code>[*]</code> instead of <code>[@]</code> <code>aws cloudformation deploy ... --tags "${TAGS[*]}"</code> diff between <code>[*]</code> and <code>[@]</code></li>
</ul>
<p>To fix this the most important thing was that IFS needed to be set to anything other than <code>' \t\n'</code> and secondly I still need to do array expansion with <code>[@]</code> and could not input a string. The <code>--parameter-overrides</code> for me did not have this problem even though similar variable loading BECAUSE it did not have a string.</p>
<p>This was my solution, my params and tags input is all over the place, spaces + sometimes arrays + bad indenting thus the <code>sed</code>:</p>
<pre class="lang-sh prettyprint-override"><code>
export IFS=$'\n'
# Build up the parameters and Tags
PARAMS=($(jq '.[] | .ParameterKey + "=" + if .ParameterValue|type=="array" then .ParameterValue | join(",") else .ParameterValue end ' parameters-${environment}.json \
    | sed -e 's/"//g' \
    | sed -e $'s/\r//g' | tr '\n' ' '))
TAGS=("$(jq -r '.[] | [.Key, .Value] | "\(.[0])=\(.[1])"'  tags-common.json)")
TAGS=($TAGS "$(jq -r '.[] | [.Key, .Value] | "\(.[0])=\(.[1])"' tags-${environment}.json)")

aws cloudformation deploy \
    --region "${REGION}" \
    --no-fail-on-empty-changeset \
    --template-file "stack-name-cfn-transform.yaml" \
    --stack-name "stack-name-${environment}" \
    --capabilities CAPABILITY_NAMED_IAM \
    --parameter-overrides "${params[@]}" \
    --tags "${TAGS[@]}" \
    --profile "${PROFILE}"
</code>```

parameters file

[
    {
        "ParameterKey": "Environment",
        "ParameterValue": "dev"
    }
]
```
<p>tags file - both common and environment specific tag files have same format</p>
<pre class="lang-json prettyprint-override"><code>[
    {
        "Key": "TAG1",
        "Value": "Test Project"
    },
    {
        "Key": "Name With Spaces",
        "Value": "Value With Spaces"
    },
    {
        "Key": "Foo",
        "Value": "Bar"
    }
]
</code>```

Body:
I am trying to get spaces into the tags parameter for the aws cli and it works if I hardcode it but not if I use bash variables. What is going on and how do I fix it?

This works with out spaces:

aws cloudformation deploy  \
      --template-file /path_to_template/template.json \
      --stack-name my-new-stack \
      --tags Key1=Value1 Key2=Value2

This works with out spaces but with variables:

tags="Key1=Value1 Key2=Value2"
aws cloudformation deploy \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags $tags

This works with spaces:

aws cloudformation deploy  \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags 'Key1=Value1' 'Key Two=Value2'

This does not work, spaces and variables:

tags="'Key1=Value1' 'Key Two=Value2'"

aws cloudformation deploy  \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags $tags

Attempting to fix bash expansion, also does not work, spaces and variables:

tags="'Key1=Value1' 'Key Two=Value2'"

aws cloudformation deploy  \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags "$tags"

Attempting to fix bash expansion, also does not work, spaces and variables:

tags="'Key1=Value1' 'Key Two=Value2'"

aws cloudformation deploy  \
  --template-file /path_to_template/template.json \
  --stack-name my-new-stack \
  --tags "$(printf '%q' $tags)"

Error:

Invalid parameter: Tags Reason: The given tag(s) contain invalid
  characters (Service: AmazonSNS; Status Code: 400; Error Code:
  InvalidParameter; Request ID

Body:
As of 2022-02 this was still an issue described

here

here also

and a little here

@esolomon is correct you have to array expansion. His answer which works just fine:

deploy=(aws cloudformation deploy
            ...
            --tags $(cat tags.json | jq '.[] | (.Key + "=" + .Value)'))

eval $(echo ${deploy[@]})

The actual problem is a result of the shell environment (bin/bash here) that is used in combination with how python cli executable's handling of values. Since the aws cloudformation deploy does not standardize the input but expects the shell program to standardize array input this was causing my problem.

So my errors with the --debug flag turned on produced the first response which is the error and the second response is the expected input into aws cloudformation deploy

Error input:

2022-02-10 17:32:28,137 - MainThread - awscli.clidriver - DEBUG - Arguments entered to CLI: ['cloudformation', 'deploy', '--region', 'us-east-1', ..., '--parameter-overrides', 'PARAM1=dev PARAM2=blah', '--tags', "TAG1='Test Project' TAG2='blah'...", '--debug']

Expected input:

2022-02-10 17:39:40,390 - MainThread - awscli.clidriver - DEBUG - Arguments entered to CLI: ['cloudformation', 'deploy', '--region', 'us-east-1', ..., '--parameter-overrides', 'PARAM1=dev', 'PARAM2=blah', '--tags', "TAG2='Test Project'", 'TAG2=blah',..., '--debug']

I was unexpectedly sending in a string instead of array of strings this error resulted in several errors depending on how I sent it:
example TAG: TAG1=Test Project

['Project'] value passed to --tags must be of format Key=Value

the means IFS needs to be set to something other than the default ' \t\n', solution below

An error occurred (ValidationError) when calling the CreateChangeSet operation: 1 validation error detected: Value 'Test Project Tag2=Value2 ...' at 'tags.1.member.value' failed to satisfy constraint: Member must have length less than or equal to 256

the error starts after the first = this error means that I am sending in one long string instead of array items, as seen here when doing [*] instead of [@] aws cloudformation deploy ... --tags "${TAGS[*]}" diff between [*] and [@]

To fix this the most important thing was that IFS needed to be set to anything other than ' \t\n' and secondly I still need to do array expansion with [@] and could not input a string. The --parameter-overrides for me did not have this problem even though similar variable loading BECAUSE it did not have a string.

This was my solution, my params and tags input is all over the place, spaces + sometimes arrays + bad indenting thus the sed:

export IFS=$'\n'
# Build up the parameters and Tags
PARAMS=($(jq '.[] | .ParameterKey + "=" + if .ParameterValue|type=="array" then .ParameterValue | join(",") else .ParameterValue end ' parameters-${environment}.json \
    | sed -e 's/"//g' \
    | sed -e $'s/\r//g' | tr '\n' ' '))
TAGS=("$(jq -r '.[] | [.Key, .Value] | "\(.[0])=\(.[1])"'  tags-common.json)")
TAGS=($TAGS "$(jq -r '.[] | [.Key, .Value] | "\(.[0])=\(.[1])"' tags-${environment}.json)")

aws cloudformation deploy \
    --region "${REGION}" \
    --no-fail-on-empty-changeset \
    --template-file "stack-name-cfn-transform.yaml" \
    --stack-name "stack-name-${environment}" \
    --capabilities CAPABILITY_NAMED_IAM \
    --parameter-overrides "${params[@]}" \
    --tags "${TAGS[@]}" \
    --profile "${PROFILE}"

parameters file

[
    {
        "ParameterKey": "Environment",
        "ParameterValue": "dev"
    }
]

tags file - both common and environment specific tag files have same format

[
    {
        "Key": "TAG1",
        "Value": "Test Project"
    },
    {
        "Key": "Name With Spaces",
        "Value": "Value With Spaces"
    },
    {
        "Key": "Foo",
        "Value": "Bar"
    }
]


问:
CryptoServicesRegistrar.isInApprovedOnlyMode() and CryptoServicesRegistrar.setApprovedOnlyMode(true) has been removed in bouncy castle
As the Title described, these two functions has been removed from bouncy castle v1.50, is there any alternative? I have to use v1.64 or above.

this is my code

```<code>Security.addProvider(new BouncyCastleFipsProvider());
</code>```

and I get the error

```<code>java.lang.NoSuchMethodError: org.bouncycastle.crypto.CryptoServicesRegistrar.isInApprovedOnlyMode()Z
</code>```

It seems like the BouncyCastleFipsProvider() call CryptoServicesRegistrar.isInApprovedOnlyMode() in its constructor, but there is no such function in this version, I don't know why it will call this method.
In order to fit the FedRamp, I have to use FIPSpovider.
Does anyone know how to do?

答:
There are two completely separate providers:

"BC", i.e. BouncyCastleProvider, the very widely used cryptography API, currently at version 1.70 (website).

"BCFIPS", i.e. BouncyCastleFipsProvider, a FIPS-compliant implementation of a more limited set of algorithms, currently at version 1.0.2.3 (website).

These can't be used together. Also BCFIPS is not just a drop-in replacement for BC that suddenly makes your project FIPS-compliant. The great majority of users should be using BC.

The methods you mention are only relevant to BCFIPS, yet you are talking about version numbers that are only relevant to BC, which implies either that you are confused about which jars/provider you are trying to use, or that perhaps you are trying to use both in the same process, which doesn't work.

Body:
As the Title described, these two functions has been removed from bouncy castle v1.50, is there any alternative? I have to use v1.64 or above.

this is my code

Security.addProvider(new BouncyCastleFipsProvider());

and I get the error

java.lang.NoSuchMethodError: org.bouncycastle.crypto.CryptoServicesRegistrar.isInApprovedOnlyMode()Z

It seems like the BouncyCastleFipsProvider() call CryptoServicesRegistrar.isInApprovedOnlyMode() in its constructor, but there is no such function in this version, I don't know why it will call this method.
In order to fit the FedRamp, I have to use FIPSpovider.
Does anyone know how to do?


问:
Showing all odd numbers instead of prime numbers
```<code>def prime_num_gen():

    try:
        r = int(input('Type in the number till which you want to generate your prime numbers : '))

        if r <= 2:
             print('There is no prime number smaller than 2, 2 is the smallest prime number')

        #A list to store primes
        #Storing 2 already, because I need a number to start with
        prime_num = [2]

        #Counter
        #Counter will be divided and if it's a prime; will append it
        x = 3

        #Starting with 3 cus 2 is already considered
        #Having a jump of 2, cus no even num is prime, so considering only odd nums
        while x <= r:
            for num in range(3,x,2):

                if num % x == 0:
                    x += 2
                    break

            else:
                prime_num.append(x)
                x += 2

        print(prime_num)

    except:
        print('Please only give input as a number!\nTry again')
</code>```

For some reason, this code is including all odd numbers as prime numbers. I am complete a novice in coding and even if this seems like a pretty obvious mistake, please tell me so .

Any help will be appreciated!!

答:
There is a small bug in your code. Instead of the condition

```<code>if num % x == 0:
</code>```

You should do

```<code>if x % num == 0:
</code>```

Since num will always be smaller than or equal to x, so its modulus with x will always give the number once again.

Body:
def prime_num_gen():

    try:
        r = int(input('Type in the number till which you want to generate your prime numbers : '))

        if r <= 2:
             print('There is no prime number smaller than 2, 2 is the smallest prime number')

        #A list to store primes
        #Storing 2 already, because I need a number to start with
        prime_num = [2]

        #Counter
        #Counter will be divided and if it's a prime; will append it
        x = 3

        #Starting with 3 cus 2 is already considered
        #Having a jump of 2, cus no even num is prime, so considering only odd nums
        while x <= r:
            for num in range(3,x,2):

                if num % x == 0:
                    x += 2
                    break

            else:
                prime_num.append(x)
                x += 2

        print(prime_num)

    except:
        print('Please only give input as a number!\nTry again')

For some reason, this code is including all odd numbers as prime numbers. I am complete a novice in coding and even if this seems like a pretty obvious mistake, please tell me so .

Any help will be appreciated!!

Body:
There is a small bug in your code. Instead of the condition

if num % x == 0:

You should do

if x % num == 0:

Since num will always be smaller than or equal to x, so its modulus with x will always give the number once again.