问:
shuffle only 5 of 20 random items of an html list (see the code)
good morning and thanks in advance to the whole community for this magnificent support. Who can help me to improveI a function to this code to return only 5 elements randomly from the entire list of 20 elements. I enter the code that now shows randomly the entire list.  Thanks to the whole community...

var list = document.getElementById("items"),
newlist = document.getElementById("shuffle");
function shuffle(items)
{
    var cached = items.slice(0), temp, i = cached.length, rand;
    while(--i)
    {
        rand = Math.floor(i * Math.random());
        temp = cached[rand];
        cached[rand] = cached[i];
        cached[i] = temp;
    }
    return cached;
}
function shuffleNodes()
{
    var nodes = list.children, i = 0;
    nodes = Array.prototype.slice.call(nodes);
    nodes = shuffle(nodes);
    while(i < nodes.length)
    {
        list.appendChild(nodes[i]);
        ++i;
    }
}
window.onload = shuffleNodes;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="something">
<div class="classname">

<dl id="items">
    <dd>1. item.<br></dd>
    <dd>2. item.<br></dd>
    <dd>3. item.<br></dd>
    <dd>4. item.<br></dd>
    <dd>5. item.<br></dd>
    <dd>6. item.<br></dd>
    <dd>7. item.<br></dd>
    <dd>8. item.<br></dd>
    <dd>9. item.<br></dd>
    <dd>10. item.<br></dd>
    <dd>11. item.<br></dd>
    <dd>12. item.<br></dd>
    <dd>13. item.<br></dd>
    <dd>14. item.<br></dd>
    <dd>15. item.<br></dd>
    <dd>16. item.<br></dd>
    <dd>17. item.<br></dd>
    <dd>18. item.<br></dd>
    <dd>19. item.<br></dd>
    <dd>20. item.<br></dd>
</dl>

</div>
</form></code>```

答:
Good Morning, and thanks for the code! could you give me one last help? I'm trying but I can not divide this list (total 20 items); select random elements; Mix:
2 elements (between 0.10) and 2 elements (between 10.20) and show everything randomly when the page loads...  in the snipped the list is divided (between 0 and 10) and the first 2 elements are selected....

var list = document.getElementById("items"),
newlist = document.getElementById("shuffle");
function shuffle(items)
{
    var cached = items.slice(0,10), temp, i = cached.length, rand;
    while(--i)
    {
        rand = Math.floor(i * Math.random());
        temp = cached[rand];
        cached[rand] = cached[i];
        cached[i] = temp;
    }
    return cached;
}
function shuffleNodes()
{
    var nodes = list.children, i = 0;
    nodes = Array.prototype.slice.call(nodes);
    nodes = shuffle(nodes);

    list.innerHTML = "";

    while(i < 2)
    {
        list.appendChild(nodes[i]);
        ++i;
    }
}
window.onload = shuffleNodes;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="something">
<div class="classname">

<dl id="items">
    <dd>1. item.<br></dd>
    <dd>2. item.<br></dd>
    <dd>3. item.<br></dd>
    <dd>4. item.<br></dd>
    <dd>5. item.<br></dd>
    <dd>6. item.<br></dd>
    <dd>7. item.<br></dd>
    <dd>8. item.<br></dd>
    <dd>9. item.<br></dd>
    <dd>10. item.<br></dd>
    <dd>11. item.<br></dd>
    <dd>12. item.<br></dd>
    <dd>13. item.<br></dd>
    <dd>14. item.<br></dd>
    <dd>15. item.<br></dd>
    <dd>16. item.<br></dd>
    <dd>17. item.<br></dd>
    <dd>18. item.<br></dd>
    <dd>19. item.<br></dd>
    <dd>20. item.<br></dd>
</dl>

</div>
</form></code>```

Body:
good morning and thanks in advance to the whole community for this magnificent support. Who can help me to improveI a function to this code to return only 5 elements randomly from the entire list of 20 elements. I enter the code that now shows randomly the entire list.  Thanks to the whole community...

var list = document.getElementById("items"),
newlist = document.getElementById("shuffle");
function shuffle(items)
{
    var cached = items.slice(0), temp, i = cached.length, rand;
    while(--i)
    {
        rand = Math.floor(i * Math.random());
        temp = cached[rand];
        cached[rand] = cached[i];
        cached[i] = temp;
    }
    return cached;
}
function shuffleNodes()
{
    var nodes = list.children, i = 0;
    nodes = Array.prototype.slice.call(nodes);
    nodes = shuffle(nodes);
    while(i < nodes.length)
    {
        list.appendChild(nodes[i]);
        ++i;
    }
}
window.onload = shuffleNodes;

<form id="something">

1. item.

2. item.

3. item.

4. item.

5. item.

6. item.

7. item.

8. item.

9. item.

10. item.

11. item.

12. item.

13. item.

14. item.

15. item.

16. item.

17. item.

18. item.

19. item.

20. item.

</form>

Body:
Good Morning, and thanks for the code! could you give me one last help? I'm trying but I can not divide this list (total 20 items); select random elements; Mix:
2 elements (between 0.10) and 2 elements (between 10.20) and show everything randomly when the page loads...  in the snipped the list is divided (between 0 and 10) and the first 2 elements are selected....

var list = document.getElementById("items"),
newlist = document.getElementById("shuffle");
function shuffle(items)
{
    var cached = items.slice(0,10), temp, i = cached.length, rand;
    while(--i)
    {
        rand = Math.floor(i * Math.random());
        temp = cached[rand];
        cached[rand] = cached[i];
        cached[i] = temp;
    }
    return cached;
}
function shuffleNodes()
{
    var nodes = list.children, i = 0;
    nodes = Array.prototype.slice.call(nodes);
    nodes = shuffle(nodes);

    list.innerHTML = "";

    while(i < 2)
    {
        list.appendChild(nodes[i]);
        ++i;
    }
}
window.onload = shuffleNodes;

<form id="something">
<div class="classname">

<dl id="items">
    <dd>1. item.<br></dd>
    <dd>2. item.<br></dd>
    <dd>3. item.<br></dd>
    <dd>4. item.<br></dd>
    <dd>5. item.<br></dd>
    <dd>6. item.<br></dd>
    <dd>7. item.<br></dd>
    <dd>8. item.<br></dd>
    <dd>9. item.<br></dd>
    <dd>10. item.<br></dd>
    <dd>11. item.<br></dd>
    <dd>12. item.<br></dd>
    <dd>13. item.<br></dd>
    <dd>14. item.<br></dd>
    <dd>15. item.<br></dd>
    <dd>16. item.<br></dd>
    <dd>17. item.<br></dd>
    <dd>18. item.<br></dd>
    <dd>19. item.<br></dd>
    <dd>20. item.<br></dd>
</dl>

</div>
</form>


来源: stackexchange

问:
module has no exports in typescript lib
I define a simple function in typescript public lib index.ts like this:

```<code>export function demo(){
    return 1;
}
</code>```

when I added the public lib in package.json and use the function in my project like this:

```<code>import{demo} from "wheel/dist/index";
demo();
</code>```

show compile error:

```<code>export 'demo' (imported as 'demo') was not found in 'wheel/dist/index' (module has no exports)
 @ ./src/background/index.ts 2:0-111 9:8-23 12:8-32 15:8-19
</code>```

why did this happen? what should I do to fix it? this is the public lib tsconfig.json:

```<code>{
  "compilerOptions": {
    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */

    /* Emit */
    "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "outDir": "./dist",
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  },
  "exclude": [
    "dist"
  ]
}
</code>```

and this is my package.json of the public lib:

```<code>{
  "name": "js-wheel",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "test": "jest",
    "build": "tsc",
    "watch:build": "tsc --watch",
    "watch:server": "nodemon './dist/index.js' --watch './dist'",
    "start": "npm-run-all clean build --parallel watch:build watch:server --print-label",
    "release": "tsc && npm publish"
  },
  "dependencies": {
    "@types/chrome": "^0.0.178",
    "dayjs": "^1.10.7",
    "npm": "^8.4.1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/jiangxiaoqiang/js-wheel.git"
  },
  "author": "jiangtingqiang@gmail.com",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/jiangxiaoqiang/js-wheel/issues"
  },
  "homepage": "https://github.com/jiangxiaoqiang/js-wheel#readme",
  "devDependencies": {
    "jest": "^27.4.7",
    "typescript": "^4.5.5"
  }
}
</code>```

I have searching from internet and found many demo code just like what I write. I searching for hours still did not find any clue where is going wrong with my code. I import the public lib in current project like this:

```<code>"js-wheel":"jiangxiaoqiang/js-wheel"
</code>```

答:
I am facing a similiar problem recently, try to tweak the typescript compilerOptions config like this:

```<code>{
  "compilerOptions": {
    /* Language and Environment */
    "target": "es5",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

    /* Modules */
    "module": "esnext",
}
</code>```

this is the final code:

```<code>// public lib index.ts
export function demo(){
    return 1;
}

// current project import and invoke
import { demo } from "js-wheel/dist/index";

demo();
</code>```

ContentLicense: CC BY-SA 4.0

Title: module has no exports in typescript lib

Body:
I define a simple function in typescript public lib index.ts like this:

export function demo(){
    return 1;
}

when I added the public lib in package.json and use the function in my project like this:

import{demo} from "wheel/dist/index";
demo();

show compile error:

export 'demo' (imported as 'demo') was not found in 'wheel/dist/index' (module has no exports)
 @ ./src/background/index.ts 2:0-111 9:8-23 12:8-32 15:8-19

why did this happen? what should I do to fix it? this is the public lib tsconfig.json:

{
  "compilerOptions": {
    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */

    /* Emit */
    "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "outDir": "./dist",
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  },
  "exclude": [
    "dist"
  ]
}

and this is my package.json of the public lib:

{
  "name": "js-wheel",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "test": "jest",
    "build": "tsc",
    "watch:build": "tsc --watch",
    "watch:server": "nodemon './dist/index.js' --watch './dist'",
    "start": "npm-run-all clean build --parallel watch:build watch:server --print-label",
    "release": "tsc && npm publish"
  },
  "dependencies": {
    "@types/chrome": "^0.0.178",
    "dayjs": "^1.10.7",
    "npm": "^8.4.1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/jiangxiaoqiang/js-wheel.git"
  },
  "author": "jiangtingqiang@gmail.com",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/jiangxiaoqiang/js-wheel/issues"
  },
  "homepage": "https://github.com/jiangxiaoqiang/js-wheel#readme",
  "devDependencies": {
    "jest": "^27.4.7",
    "typescript": "^4.5.5"
  }
}

I have searching from internet and found many demo code just like what I write. I searching for hours still did not find any clue where is going wrong with my code. I import the public lib in current project like this:

"js-wheel":"jiangxiaoqiang/js-wheel"

Body:
I am facing a similiar problem recently, try to tweak the typescript compilerOptions config like this:

{
  "compilerOptions": {
    /* Language and Environment */
    "target": "es5",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */

    /* Modules */
    "module": "esnext",
}

this is the final code:

// public lib index.ts
export function demo(){
    return 1;
}

// current project import and invoke
import { demo } from "js-wheel/dist/index";

demo();


问:
C program prints 1 twice in a while loop, why?
Code snippet

```<code>```c
#include <stdio.h>

int main(void) {
  short int a;
  scanf("%hd", &a);
  while (a != 5) {
    printf("%hd\n", a);
    a++;
  }
  return 0;
}
```
<p>The output of this code is:</p>
<p>Code snippet</p>
```1
1
2
3
4
```
<p>I am expecting the output to be:</p>
<p>Code snippet</p>
```1
2
3
4
5
```

But why is the output different from what I am expecting?

I have tried the following:

I have checked the syntax of the code. It is correct.

I have run the code on different compilers. The output is the same on all compilers.

I have tried different values for a. The output is the same for all values of a.

答: @Red Sky is right, the first one is your input,

Body:
Code snippet

```c
#include <stdio.h>

int main(void) {
  short int a;
  scanf("%hd", &a);
  while (a != 5) {
    printf("%hd\n", a);
    a++;
  }
  return 0;
}

The output of this code is:

Code snippet

1
1
2
3
4

I am expecting the output to be:

Code snippet

1
2
3
4
5

But why is the output different from what I am expecting?

I have tried the following:

I have checked the syntax of the code. It is correct.

I have run the code on different compilers. The output is the same on all compilers.

I have tried different values for a. The output is the same for all values of a.


问:
Is there an API call for changing user password on keycloak?
I am trying to implement my own form for changing a user's password. I tried to find an API for changing a user's password in Keycloak but I couldn't find anything in the documentation.
Is there an API for doing it?</p>

答:
:-)</p>
```<code>#!/bin/bash
#CHANGE ADMIN PASSWORD

apt update
apt install -y curl jq

KEYCLOAK_HOST=http://127.0.0.1:8080
ADMIN_USER_OLD_PASSWORD=
ADMIN_USER_NEW_PASSWORD=
TOKEN=$(curl -s -X POST -H 'Content-Type: application/x-www-form-urlencoded' -d "username=admin&password=$ADMIN_USER_OLD_PASSWORD&client_id=admin-cli&grant_type=password" "$KEYCLOAK_HOST/auth/realms/master/protocol/openid-connect/token" | jq -r ".access_token" ;)
ADMIN_USER_ID=$(curl -s -X GET -H "Authorization: Bearer $TOKEN" -H "Content-type: application/json;charset=UTF-8" -H 'Accept: application/json' "$KEYCLOAK_HOST/auth/admin/realms/master/users" | jq -r '.[] | select(.username=="admin") | .id' )
curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-type: application/json;charset=UTF-8" -H 'Accept: application/json' "$KEYCLOAK_HOST/auth/admin/realms/master/users/$ADMIN_USER_ID/reset-password" -d "{\"type\":\"password\",\"value\":\"$ADMIN_USER_NEW_PASSWORD\",\"temporary\":false}"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
:-)

#!/bin/bash
#CHANGE ADMIN PASSWORD

apt update
apt install -y curl jq

KEYCLOAK_HOST=http://127.0.0.1:8080
ADMIN_USER_OLD_PASSWORD=
ADMIN_USER_NEW_PASSWORD=
TOKEN=$(curl -s -X POST -H 'Content-Type: application/x-www-form-urlencoded' -d "username=admin&password=$ADMIN_USER_OLD_PASSWORD&client_id=admin-cli&grant_type=password" "$KEYCLOAK_HOST/auth/realms/master/protocol/openid-connect/token" | jq -r ".access_token" ;)
ADMIN_USER_ID=$(curl -s -X GET -H "Authorization: Bearer $TOKEN" -H "Content-type: application/json;charset=UTF-8" -H 'Accept: application/json' "$KEYCLOAK_HOST/auth/admin/realms/master/users" | jq -r '.[] | select(.username=="admin") | .id' )
curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-type: application/json;charset=UTF-8" -H 'Accept: application/json' "$KEYCLOAK_HOST/auth/admin/realms/master/users/$ADMIN_USER_ID/reset-password" -d "{\"type\":\"password\",\"value\":\"$ADMIN_USER_NEW_PASSWORD\",\"temporary\":false}"


问:
Controlling an input/output box via php/javascript
i have a php/javascript webbased application running on a hosted server (dreamhost), and im looking to setup an input output box in-house that can take an identifier from the php application and trigger a specific output based on the trigger.

For example. Lets say i have an input/output device with 10 outputs. And i have 10 records in my php application. I want to say, "when record #1 is being viewed, activate output #1 on the input/output box"

Are there any input/output boxes that can be triggered via php or javascript?

答:
You can save input and output values in some sort of database on server. Your "input/output box" should contact with hosted server for getting output values and sending input values.

When users access server with web browser, you can serve input values which sent from "i/o box" and users can change output values too. When an output changes, next time "i/o box's" request to server receives new output values and changes it's output states according these values.

Here's the summary:

Your i/o box should have web request capability (Ethernet controller and tcp/ip stack or equivalents of these).

Your PHP script should handle i/o box's request and writes i/o box's input values to database. Also PHP script should respond with output values which are stored in database too.

Your PHP script should handle user requests. User can view input values and send requests for changing output values. Your PHP script should handle output change requests and write them to database.

Your i/o box need to do request to your server. This way it can send new input values and receive new output values.


问:
Running Firecracker inside Docker
Is there any way to run Firecracker inside Docker container.

I tried the basic networking in firecracker although having containerized firecracker can have many benefits

No hurdle to create and manage overlay network and attach

Deploy in Docker swarm and in Kubernetes

No need to clean IPTables/Network rules
etc.

答:
Setup Tutorial

You find a good tutorial with all the basics at the Weaveworks

fire-up-your-vms-with-weave-ignite

it introduces

weaveworks ignite (Github)

Ignite works like a One-to-One replacement for "docker", and it does work on my Raspberry PI 4, with Debian11 too.

How to use

Create and start a VM

```<code> $ sudo ignite run weaveworks/ignite-ubuntu \
                --cpus 1 \
                --memory 1GB \
                --ssh \
                --name my-vm1
</code>```

Show your VM Processes

```<code> $ ignite ps
</code>```

Login into your running VM

```<code> $ sudo ignite ssh my-vm1
</code>```

It takes a couple of sec to start (manualy) a new VM on my Raspberry PI 4 (8Gb, 64bit Debian11):

Login into any of these

```<code>$ sudo ignite ssh my-vm3
</code>```

Footloose

If you add footloose you can start up a cluster of MicroVMs, which allows additional scenarios. It works  more less like docker-swarm with VMs. Footloose reads a description of the Cluster of Machines to create from a file, by default named footloose.yaml. Please check

footloose vm cluster (Github)

Note: be aware of a Apache ignite, which is a solution for something else, and don't get confused by it.

The initial idea for this answer is from my gist here

Title: Running Firecracker inside Docker

Body:
Setup Tutorial

You find a good tutorial with all the basics at the Weaveworks

fire-up-your-vms-with-weave-ignite

it introduces

weaveworks ignite (Github)

Ignite works like a One-to-One replacement for "docker", and it does work on my Raspberry PI 4, with Debian11 too.

How to use

Create and start a VM

 $ sudo ignite run weaveworks/ignite-ubuntu \
                --cpus 1 \
                --memory 1GB \
                --ssh \
                --name my-vm1

Show your VM Processes

 $ ignite ps

Login into your running VM

 $ sudo ignite ssh my-vm1

It takes a couple of sec to start (manualy) a new VM on my Raspberry PI 4 (8Gb, 64bit Debian11):

Login into any of these

$ sudo ignite ssh my-vm3

Footloose

If you add footloose you can start up a cluster of MicroVMs, which allows additional scenarios. It works  more less like docker-swarm with VMs. Footloose reads a description of the Cluster of Machines to create from a file, by default named footloose.yaml. Please check

footloose vm cluster (Github)

Note: be aware of a Apache ignite, which is a solution for something else, and don't get confused by it.

The initial idea for this answer is from my gist here


问:
Match fieldset width with button width

I have a `fieldset` and a `button` below it and i want these elements width to match.

How could I do that ?

I am new to programming and i don't really know much about CSS, so my field of knowledge is not yet very large.

Thank you.

fieldset {
  position:relative;
  width: 15%;
  margin: 0%;
}
button {
  background-color: black;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  transition: 0.3s;
}
button:hover {
  background-color: white;
  color: black;
}```

答:
You can add width 100% to the button. Is it that what you looking for?

fieldset {
  position:relative;
  width: 15%;
  margin: 0%;
}
button {
  width: 100%;
  background-color: black;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  transition: 0.3s;
}
button:hover {
  background-color: white;
  color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset>
  <button>btn</button>
</fieldset></code>```

Title: Match fieldset width with button width

Body:
You can add width 100% to the button. Is it that what you looking for?

fieldset {
  position:relative;
  width: 15%;
  margin: 0%;
}
button {
  width: 100%;
  background-color: black;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  cursor: pointer;
  transition: 0.3s;
}
button:hover {
  background-color: white;
  color: black;
}

<fieldset>
  <button>btn</button>
</fieldset>


问:
How can I store divs content into an array?
Hello this is my first post, i have been learning javascript for a week.
I want to make a little app that calculate how much do you spend on subscription per month.

You can add a new subscription with the name and the subscription price with two inputs --> and it creates 2 new div(one is subscriptionName the other is subscriptionPrice) they are store into a new div (newSubscription).

Now i would like to store all the subscriptionPrice var into an array and addition all of them.
(is it the right logic to apply ? maybe im wrong).

I also thought about doing the addition of the :

.abo-list > .abo:nth-child(1) > .abo-price

.abo-list > .abo:nth-child(1+1) > .abo-price

...

I have tried with this technic but the consol do not show even the first oneAboPrice.

```<code> var pricesValues = [];
for (var i = 0; i < oneAboPrice.length; i++) {
    pricesValues.push(oneAboPrice[i].textContent);
}
console.log(pricesValues); /*dont show the values of every oneAboPrice*/
</code>```

//Selectors
const nameInput = document.querySelector('.name');
const price = document.querySelector('.price');
const validate = document.querySelector('.validate');
const abosList = document.querySelector('.abo-list');
const montantTotal = document.querySelector('.montant-total');

//event listeners

validate.addEventListener('click', addAbo);
abosList.addEventListener('click', clickModify);

//functions
function addAbo(event){
    event.preventDefault();
    //creating the NewAbo DIV
    const Abodiv = document.createElement('div');
    Abodiv.classList.add('abo');
    //creating a LI
    const newAbo = document.createElement('li');
    newAbo.innerText = nameInput.value + ' ' ;
    newAbo.classList.add('abo-item');
    Abodiv.appendChild(newAbo);
    //creating a div Price of one Sub
    const oneAboPrice = document.createElement('div');
    oneAboPrice.classList.add('abo-price');
    oneAboPrice.innerText = price.value;
    Abodiv.appendChild(oneAboPrice);
    //modify button
    const modifyAbo = document.createElement('button');
    modifyAbo.innerHTML = '';
    modifyAbo.classList.add('modifyAbo');
    Abodiv.appendChild(modifyAbo);
    //trash button
    const trashAbo = document.createElement('button');
    trashAbo.innerHTML = '';
    trashAbo.classList.add("trashAbo");
    Abodiv.appendChild(trashAbo);
    //append to Abo-list
    abosList.appendChild(Abodiv);

    //total Amount of every newAboPrice

    //reset input value
    nameInput.value ="";
    price.value="";

    //store every .abo price (oneAboPrice)value into an array (this is where i need help)
    var pricesValues = [];
    for (var i = 0; i < oneAboPrice.length; i++) {
        pricesValues.push(oneAboPrice[i].textContent);
    }
    console.log(pricesValues); /*dont show the values of every oneAboPrice*/

    montantTotal.innerHTML = parseFloat(oneAboPrice.textContent); /* + oneAboPrice nth:child(2) + ....*/
}

function clickModify(e) {
    const item = e.target;
    //Delete newAbo
    if(item.classList[0] === "trashAbo"){
        const abo = item.parentElement;
    abo.remove();
    }
    //modify newAbo (To do)

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins&family=Saira+Extra+Condensed:wght@500&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.content-container{
    display: flex;
    justify-content: space-around;
}

.abo{
    display: flex;
    justify-content: space-between;
    list-style-type: none;
}

.abo li{
    flex: 1;
}
.fa-trash{
    pointer-events: none;
}

.abo-price{
    background: red;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="style.css">
    <title>Gestionnaire d'abonnements</title>

Nom de l'abonnement
<input type="text"  class="name" placeholder="netflix">

Prix mensuel
<input type="number" class="price" placeholder="13,49">
            <input type="button" value="Valide" class="validate">

MES ABOS

```

答:
I understand that you want to show the array of all items using this loop:

for (var i = 0; i < oneAboPrice.length; i++) {
    pricesValues.push(oneAboPrice[i].textContent);
}
```
<p>The problem is, <code>oneAboPrice</code> is not the <strong>all items</strong> that you want, it's a new element that you just created with this code:</p>
<pre class="lang-js prettyprint-override"><code>//creating a div Price of one Sub
const oneAboPrice = document.createElement('div');
oneAboPrice.classList.add('abo-price');
oneAboPrice.innerText = price.value;
Abodiv.appendChild(oneAboPrice);
</code>```

Solution

So, to correctly loop through all items, this is what the loop should be:

document.querySelectorAll('.abo-price').forEach(item => {
    pricesValues.push(parseFloat(item.innerHTML));
});
```
<p>Let's me explain. <code>document.querySelectorAll('.abo-price')</code> will select all of your <code>oneAboPrice</code> at the time being. Then you can use <code>item.innerHTML</code> to get the text inside of each item, not <code>item.textContent</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//Selectors
const nameInput = document.querySelector('.name');
const price = document.querySelector('.price');
const validate = document.querySelector('.validate');
const abosList = document.querySelector('.abo-list');
const montantTotal = document.querySelector('.montant-total');

//event listeners

validate.addEventListener('click', addAbo);
abosList.addEventListener('click', clickModify);

//functions
function addAbo(event) {
  event.preventDefault();
  //creating the NewAbo DIV
  const Abodiv = document.createElement('div');
  Abodiv.classList.add('abo');
  //creating a LI
  const newAbo = document.createElement('li');
  newAbo.innerText = nameInput.value + ' ';
  newAbo.classList.add('abo-item');
  Abodiv.appendChild(newAbo);
  //creating a div Price of one Sub
  const oneAboPrice = document.createElement('div');
  oneAboPrice.classList.add('abo-price');
  oneAboPrice.innerText = price.value;
  Abodiv.appendChild(oneAboPrice);
  //modify button
  const modifyAbo = document.createElement('button');
  modifyAbo.innerHTML = '<i class="fa-solid fa-pen"></i>';
  modifyAbo.classList.add('modifyAbo');
  Abodiv.appendChild(modifyAbo);
  //trash button
  const trashAbo = document.createElement('button');
  trashAbo.innerHTML = '<i class="fa fa-trash"></i>';
  trashAbo.classList.add("trashAbo");
  Abodiv.appendChild(trashAbo);
  //append to Abo-list
  abosList.appendChild(Abodiv);

  //total Amount of every newAboPrice

  //reset input value
  nameInput.value = "";
  price.value = "";

  //store every .abo price (oneAboPrice)value into an array (this is where i need help)
  var pricesValues = [];
  document.querySelectorAll('.abo-price').forEach(item => {
    pricesValues.push(parseFloat(item.innerHTML));
  });

  console.log(pricesValues); /*dont show the values of every oneAboPrice*/

  montantTotal.innerHTML = parseFloat(oneAboPrice.textContent); /* + oneAboPrice nth:child(2) + ....*/
}

function clickModify(e) {
  const item = e.target;
  //Delete newAbo
  if (item.classList[0] === "trashAbo") {
    const abo = item.parentElement;
    abo.remove();
  }
  //modify newAbo (To do)

}</code>```

@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins&family=Saira+Extra+Condensed:wght@500&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.content-container {
  display: flex;
  justify-content: space-around;
}

.abo {
  display: flex;
  justify-content: space-between;
  list-style-type: none;
}

.abo li {
  flex: 1;
}

.fa-trash {
  pointer-events: none;
}

.abo-price {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer"
  />
  <link rel="stylesheet" href="style.css">
  <title>Gestionnaire d'abonnements</title>
</head>

<body>
  <div class="content-container">
    <div class="left">
      <p>Nom de l'abonnement</p><input type="text" class="name" placeholder="netflix">
      <p>Prix mensuel</p><input type="number" class="price" placeholder="13,49">
      <input type="button" value="Valide" class="validate">
    </div>
    <div class="right">
      <h1>MES ABOS</h1>
      <ul class="abo-list">

      </ul>
      <p class="montant-total"></p>
    </div>
  </div>
  <script src="app.js"></script>
</body>

</html></code>```

Body:
Hello this is my first post, i have been learning javascript for a week.
I want to make a little app that calculate how much do you spend on subscription per month.

You can add a new subscription with the name and the subscription price with two inputs --> and it creates 2 new div(one is subscriptionName the other is subscriptionPrice) they are store into a new div (newSubscription).

Now i would like to store all the subscriptionPrice var into an array and addition all of them.
(is it the right logic to apply ? maybe im wrong).

I also thought about doing the addition of the :

.abo-list > .abo:nth-child(1) > .abo-price

.abo-list > .abo:nth-child(1+1) > .abo-price

...

I have tried with this technic but the consol do not show even the first oneAboPrice.

 var pricesValues = [];
for (var i = 0; i < oneAboPrice.length; i++) {
    pricesValues.push(oneAboPrice[i].textContent);
}
console.log(pricesValues); /*dont show the values of every oneAboPrice*/

//Selectors
const nameInput = document.querySelector('.name');
const price = document.querySelector('.price');
const validate = document.querySelector('.validate');
const abosList = document.querySelector('.abo-list');
const montantTotal = document.querySelector('.montant-total');

//event listeners

validate.addEventListener('click', addAbo);
abosList.addEventListener('click', clickModify);

//functions
function addAbo(event){
    event.preventDefault();
    //creating the NewAbo DIV
    const Abodiv = document.createElement('div');
    Abodiv.classList.add('abo');
    //creating a LI
    const newAbo = document.createElement('li');
    newAbo.innerText = nameInput.value + ' ' ;
    newAbo.classList.add('abo-item');
    Abodiv.appendChild(newAbo);
    //creating a div Price of one Sub
    const oneAboPrice = document.createElement('div');
    oneAboPrice.classList.add('abo-price');
    oneAboPrice.innerText = price.value;
    Abodiv.appendChild(oneAboPrice);
    //modify button
    const modifyAbo = document.createElement('button');
    modifyAbo.innerHTML = '';
    modifyAbo.classList.add('modifyAbo');
    Abodiv.appendChild(modifyAbo);
    //trash button
    const trashAbo = document.createElement('button');
    trashAbo.innerHTML = '';
    trashAbo.classList.add("trashAbo");
    Abodiv.appendChild(trashAbo);
    //append to Abo-list
    abosList.appendChild(Abodiv);

    //total Amount of every newAboPrice

    //reset input value
    nameInput.value ="";
    price.value="";

    //store every .abo price (oneAboPrice)value into an array (this is where i need help)
    var pricesValues = [];
    for (var i = 0; i < oneAboPrice.length; i++) {
        pricesValues.push(oneAboPrice[i].textContent);
    }
    console.log(pricesValues); /*dont show the values of every oneAboPrice*/

    montantTotal.innerHTML = parseFloat(oneAboPrice.textContent); /* + oneAboPrice nth:child(2) + ....*/
}

function clickModify(e) {
    const item = e.target;
    //Delete newAbo
    if(item.classList[0] === "trashAbo"){
        const abo = item.parentElement;
    abo.remove();
    }
    //modify newAbo (To do)

}

@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins&family=Saira+Extra+Condensed:wght@500&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.content-container{
    display: flex;
    justify-content: space-around;
}

.abo{
    display: flex;
    justify-content: space-between;
    list-style-type: none;
}

.abo li{
    flex: 1;
}
.fa-trash{
    pointer-events: none;
}

.abo-price{
    background: red;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="style.css">
    <title>Gestionnaire d'abonnements</title>

Nom de l'abonnement
<input type="text"  class="name" placeholder="netflix">

Prix mensuel
<input type="number" class="price" placeholder="13,49">
            <input type="button" value="Valide" class="validate">

MES ABOS

Body:
I understand that you want to show the array of all items using this loop:

for (var i = 0; i < oneAboPrice.length; i++) {
    pricesValues.push(oneAboPrice[i].textContent);
}

The problem is, oneAboPrice is not the all items that you want, it's a new element that you just created with this code:

//creating a div Price of one Sub
const oneAboPrice = document.createElement('div');
oneAboPrice.classList.add('abo-price');
oneAboPrice.innerText = price.value;
Abodiv.appendChild(oneAboPrice);

Solution

So, to correctly loop through all items, this is what the loop should be:

document.querySelectorAll('.abo-price').forEach(item => {
    pricesValues.push(parseFloat(item.innerHTML));
});

Let's me explain. document.querySelectorAll('.abo-price') will select all of your oneAboPrice at the time being. Then you can use item.innerHTML to get the text inside of each item, not item.textContent.

//Selectors
const nameInput = document.querySelector('.name');
const price = document.querySelector('.price');
const validate = document.querySelector('.validate');
const abosList = document.querySelector('.abo-list');
const montantTotal = document.querySelector('.montant-total');

//event listeners

validate.addEventListener('click', addAbo);
abosList.addEventListener('click', clickModify);

//functions
function addAbo(event) {
  event.preventDefault();
  //creating the NewAbo DIV
  const Abodiv = document.createElement('div');
  Abodiv.classList.add('abo');
  //creating a LI
  const newAbo = document.createElement('li');
  newAbo.innerText = nameInput.value + ' ';
  newAbo.classList.add('abo-item');
  Abodiv.appendChild(newAbo);
  //creating a div Price of one Sub
  const oneAboPrice = document.createElement('div');
  oneAboPrice.classList.add('abo-price');
  oneAboPrice.innerText = price.value;
  Abodiv.appendChild(oneAboPrice);
  //modify button
  const modifyAbo = document.createElement('button');
  modifyAbo.innerHTML = '<i class="fa-solid fa-pen"></i>';
  modifyAbo.classList.add('modifyAbo');
  Abodiv.appendChild(modifyAbo);
  //trash button
  const trashAbo = document.createElement('button');
  trashAbo.innerHTML = '<i class="fa fa-trash"></i>';
  trashAbo.classList.add("trashAbo");
  Abodiv.appendChild(trashAbo);
  //append to Abo-list
  abosList.appendChild(Abodiv);

  //total Amount of every newAboPrice

  //reset input value
  nameInput.value = "";
  price.value = "";

  //store every .abo price (oneAboPrice)value into an array (this is where i need help)
  var pricesValues = [];
  document.querySelectorAll('.abo-price').forEach(item => {
    pricesValues.push(parseFloat(item.innerHTML));
  });

  console.log(pricesValues); /*dont show the values of every oneAboPrice*/

  montantTotal.innerHTML = parseFloat(oneAboPrice.textContent); /* + oneAboPrice nth:child(2) + ....*/
}

function clickModify(e) {
  const item = e.target;
  //Delete newAbo
  if (item.classList[0] === "trashAbo") {
    const abo = item.parentElement;
    abo.remove();
  }
  //modify newAbo (To do)

}

@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Poppins&family=Saira+Extra+Condensed:wght@500&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.content-container {
  display: flex;
  justify-content: space-around;
}

.abo {
  display: flex;
  justify-content: space-between;
  list-style-type: none;
}

.abo li {
  flex: 1;
}

.fa-trash {
  pointer-events: none;
}

.abo-price {
  background: red;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer"
  />
  <link rel="stylesheet" href="style.css">
  <title>Gestionnaire d'abonnements</title>
</head>

<body>
  <div class="content-container">
    <div class="left">
      <p>Nom de l'abonnement</p><input type="text" class="name" placeholder="netflix">
      <p>Prix mensuel</p><input type="number" class="price" placeholder="13,49">
      <input type="button" value="Valide" class="validate">
    </div>
    <div class="right">
      <h1>MES ABOS</h1>
      <ul class="abo-list">

      </ul>
      <p class="montant-total"></p>
    </div>
  </div>
  <script src="app.js"></script>
</body>

</html>


问:
What should happen to template class static member variables with definition in the .h file
If a template class definition contains a static member variable that depends on the template type, I'm unsure of what the reliable behavior should be?

In my case it is desirable to place the definition of that static member in the same .h file as the class definition, since

I want the class to be general for many template data types that I don't currently
know.

I want only one instance of the static member to be shared
throughout my program for each given template type. ( one for all MyClass<int> and one for all MyClass<double>, etc.

I can be most brief by saying that the code listed at this link behaves exactly as I want when compiled with gcc 4.3.  Is this behavior according to the C++ Standard so that I can rely on it when using other compilers?

That link is not my code, but a counter example posted by CodeMedic to the discussion here.  I've found several other debates like this one but nothing I consider conclusive.

I think the linker is consolidating the multiple definitions found ( in the example a.o and b.o  ).
Is this the required/reliable linker behavior?

答:
From N3290, 14.6:

A [...] static data member of a class template shall be defined in
  every translation unit in which it is implicitly instantiated [...], unless the corresponding specialization is explicitly instantiated [...] .

Typically, you put the static member definition in the header file, along with the template class definition:

```<code>template <typename T>
class Foo
{
  static int n;                       // declaration
};

template <typename T> int Foo<T>::n;  // definition
</code>```

To expand on the concession: If you plan on using explicit instantiations in your code, like:

```<code>template <> int Foo<int>::n = 12;
</code>```

then you must not put the templated definition in the header if Foo<int> is also used in other TUs other than the one containing the explicit instantiation, since you'd then get multiple definitions.

However, if you do need to set an initial value for all possible parameters without using explicit instantiation, you have to put that in the header, e.g. with TMP:

```<code>// in the header
template <typename T> int Foo<T>::n = GetInitialValue<T>::value;  // definition + initialization
</code>```

Body:
From N3290, 14.6:

A [...] static data member of a class template shall be defined in
  every translation unit in which it is implicitly instantiated [...], unless the corresponding specialization is explicitly instantiated [...] .

Typically, you put the static member definition in the header file, along with the template class definition:

template <typename T>
class Foo
{
  static int n;                       // declaration
};

template <typename T> int Foo<T>::n;  // definition

To expand on the concession: If you plan on using explicit instantiations in your code, like:

template <> int Foo<int>::n = 12;

then you must not put the templated definition in the header if Foo<int> is also used in other TUs other than the one containing the explicit instantiation, since you'd then get multiple definitions.

However, if you do need to set an initial value for all possible parameters without using explicit instantiation, you have to put that in the header, e.g. with TMP:

// in the header
template <typename T> int Foo<T>::n = GetInitialValue<T>::value;  // definition + initialization


问:
Carbon DateTime package
Trying to format a timestamp with Carbon diffForHumans(), passing in the following params, so it reads as:

```<code>$new_format = $old_format->diffForHumans(['parts' => 1, 'options' => Carbon::CEIL]);
</code>```

When it attempts to format a date ~1 month ago, it leads to an "undefined offset -1" error.

```<code>echo Carbon::parse('2022-01-11 15:36:29')->diffForHumans(['parts' => 1, 'options' => Carbon::CEIL]);
echo Carbon::parse('2022-01-10 16:57:38')->diffForHumans(['parts' => 1, 'options' => Carbon::CEIL]);
</code>```

The  examples above, the top run works, where as the bottom one errors. Is there an explanation, why it breaks with these params, or better yet a solution that would give me the same result? Changing to Carbon::FLOOR or ROUND works fine, but aren't viable for what I need.

Thanks.

答:
This bug is fixed in version 2.57.0. Thanks for the report.

https://github.com/briannesbitt/Carbon/pull/2547

You can test it using composer update nesbot/carbon

Title: Carbon DateTime package

Body:
Trying to format a timestamp with Carbon diffForHumans(), passing in the following params, so it reads as:

$new_format = $old_format->diffForHumans(['parts' => 1, 'options' => Carbon::CEIL]);

When it attempts to format a date ~1 month ago, it leads to an "undefined offset -1" error.

echo Carbon::parse('2022-01-11 15:36:29')->diffForHumans(['parts' => 1, 'options' => Carbon::CEIL]);
echo Carbon::parse('2022-01-10 16:57:38')->diffForHumans(['parts' => 1, 'options' => Carbon::CEIL]);

The  examples above, the top run works, where as the bottom one errors. Is there an explanation, why it breaks with these params, or better yet a solution that would give me the same result? Changing to Carbon::FLOOR or ROUND works fine, but aren't viable for what I need.

Thanks.


问:
Should I deep copy when modifying nested object?
I recently started learning functional programming in Javascript, and one thing that's valued is Immutability. One way to preserve immutability is to when we want to modify some object that we first create a copy and then modify that copy and return it, for example:

const person = {
    firstName: 'John',
    lastName: 'Smith',
}

const modifyFName = obj => {
    const objCopy = {...obj};
    objCopy.firstName = 'James';
    return objCopy;
}

console.log(modifyFName(person)) // {firstName: 'James', lastName: 'Smith'}
console.log(person) // {firstName: 'John', lastName: 'Smith'}
```
<p>But if I want to modify some deeply nested object creating shallow copy like one above wouldn't make much of a difference, for example:</p>
<pre class="lang-js prettyprint-override"><code>const person = {
    firstName: 'John',
    lastName: 'Smith',
    parents: {
        mom: {
            firstName: 'Jennifer',
            lastName: "Swift"
        },
        dad: {
            firstName: 'Tom',
            lastName: 'Cartman'
        }
    }
}

const modifyDadName = obj => {
    const objCopy = {...obj};
    objCopy.parents.dad.firstName = 'Aurelion';
    return objCopy;
}

console.log(modifyDadName(person)) // {... dad: "Aurelion"}
console.log(person) // {... dad: "Aurelion"}
</code>```

Both objects have changed. So I am wondering in this situation should I perhaps use deep copy, or maybe use some third-party Immutable data structures, or is there some other solution for this?

答:
You're right that a shallow copy doesn't help, but you don't need a full deep copy, you only have to make copies of the things you want to change. In your case, that's person, parents, and dad, but not mom:

```<code>const modifyDadName = obj => {
    return {                            // Replacement `obj` (`person`)
        ...obj,
        parents: {                      // Replacement `obj.parents`
            ...obj.parents,
            dad: {                      // Replacement `obj.parents.dad`
                ...obj.parents.dad,
                firstName: "Aurelion",  // New name
            }
        }
    };
};
</code>```

dad changes because, well, that's the operation we're doing (changing firstName). :-) parents changes because changing dad means there's a new object on its dad property. person (obj) changes because there's a new parents object. But mom doesn't change, so we can reuse the same object.

Body:
I recently started learning functional programming in Javascript, and one thing that's valued is Immutability. One way to preserve immutability is to when we want to modify some object that we first create a copy and then modify that copy and return it, for example:

const person = {
    firstName: 'John',
    lastName: 'Smith',
}

const modifyFName = obj => {
    const objCopy = {...obj};
    objCopy.firstName = 'James';
    return objCopy;
}

console.log(modifyFName(person)) // {firstName: 'James', lastName: 'Smith'}
console.log(person) // {firstName: 'John', lastName: 'Smith'}

But if I want to modify some deeply nested object creating shallow copy like one above wouldn't make much of a difference, for example:

const person = {
    firstName: 'John',
    lastName: 'Smith',
    parents: {
        mom: {
            firstName: 'Jennifer',
            lastName: "Swift"
        },
        dad: {
            firstName: 'Tom',
            lastName: 'Cartman'
        }
    }
}

const modifyDadName = obj => {
    const objCopy = {...obj};
    objCopy.parents.dad.firstName = 'Aurelion';
    return objCopy;
}

console.log(modifyDadName(person)) // {... dad: "Aurelion"}
console.log(person) // {... dad: "Aurelion"}

Both objects have changed. So I am wondering in this situation should I perhaps use deep copy, or maybe use some third-party Immutable data structures, or is there some other solution for this?

Body:
You're right that a shallow copy doesn't help, but you don't need a full deep copy, you only have to make copies of the things you want to change. In your case, that's person, parents, and dad, but not mom:

const modifyDadName = obj => {
    return {                            // Replacement `obj` (`person`)
        ...obj,
        parents: {                      // Replacement `obj.parents`
            ...obj.parents,
            dad: {                      // Replacement `obj.parents.dad`
                ...obj.parents.dad,
                firstName: "Aurelion",  // New name
            }
        }
    };
};

dad changes because, well, that's the operation we're doing (changing firstName). :-) parents changes because changing dad means there's a new object on its dad property. person (obj) changes because there's a new parents object. But mom doesn't change, so we can reuse the same object.


问:
c++ const convert

Possible Duplicate:

  why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

I have a function:

```<code>bool isCirclePolygonIntersection(const Point*, const int*, const Point*,
                                 const Point**, const int*);
</code>```

and I'm trying to call it like this:

```<code>isCirclePolygonIntersection(p, &r, poly_coord, poly, &poly_size)
</code>```

where poly defined like this:

```<code>Point** poly = new Point*[poly_size];
</code>```

and there is a compiler error when I'm trying to compile it:

```<code>error C2664: 'isCirclePolygonIntersection' : cannot convert parameter 4 from 'Point **' to 'const Point **'
1>          Conversion loses qualifiers
</code>```

from what I've learned is that you cannot give const argument to function when a function expects a non const argument, but it's fine otherwise.
Does anyone knows what is the problem??
Thanks.

答:
Parashift has a great explanation on why this is prohibited:

http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17

Title: c++ const convert

Body:
Possible Duplicate:

  why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

I have a function:

bool isCirclePolygonIntersection(const Point*, const int*, const Point*,
                                 const Point**, const int*);

and I'm trying to call it like this:

isCirclePolygonIntersection(p, &r, poly_coord, poly, &poly_size)

where poly defined like this:

Point** poly = new Point*[poly_size];

and there is a compiler error when I'm trying to compile it:

error C2664: 'isCirclePolygonIntersection' : cannot convert parameter 4 from 'Point **' to 'const Point **'
1>          Conversion loses qualifiers

from what I've learned is that you cannot give const argument to function when a function expects a non const argument, but it's fine otherwise.
Does anyone knows what is the problem??
Thanks.


问:
How to use eles.components() to filter direct neighbours of one node?
I want to filter all nodes not further away then one edge of a given node. I dont have a compound graph. I tried

```<code>var children = cy.$('#1').components()
</code>```

But this only returns the node #1. I also tried

```<code>var allEles = cy.elements()
var myChildren = allEles.componentsOf(cy.$('#1'))
</code>```

But this seems to return all nodes again. The docs also state a selector syntax "> (child selector) Matches direct children of the parent node (e.g. node > node)." But I cant figure that one out either. I tried

```<code>var myChildren = cy.elements('node#1 > node')
</code>```

getting an empty array.

So, how can filter for direct children (depth=1) of a given node?

答:
Did you try use:

```<code>// outgoers return all elements (edges as well) comming out from $('#1')
// nodes() > select only nodes
var children = cy.$('#1').outgoers().nodes();
</code>```

doc: https://js.cytoscape.org/#nodes.outgoers

Body:
I want to filter all nodes not further away then one edge of a given node. I dont have a compound graph. I tried

var children = cy.$('#1').components()

But this only returns the node #1. I also tried

var allEles = cy.elements()
var myChildren = allEles.componentsOf(cy.$('#1'))

But this seems to return all nodes again. The docs also state a selector syntax "> (child selector) Matches direct children of the parent node (e.g. node > node)." But I cant figure that one out either. I tried

var myChildren = cy.elements('node#1 > node')

getting an empty array.

So, how can filter for direct children (depth=1) of a given node?

Body:
Did you try use:

// outgoers return all elements (edges as well) comming out from $('#1')
// nodes() > select only nodes
var children = cy.$('#1').outgoers().nodes();

doc: https://js.cytoscape.org/#nodes.outgoers


问:
jQuery loop through all h3 and selects on page and format output in textarea
So I have a basic structure of a page and my corresponding script:

jQuery('select').change(function() {
  var abc = jQuery("select option:selected").text();
  var def = jQuery("h3").text();
  jQuery('textarea[name="ghi"]', $form).val(def + "\n\n" + abc).change();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h3>Title</h3>
<select>
  <option value="A">This is Option a</option>
</select>

<h3>Title</h3>
<select>
  <option value="B">This is Option b</option>
</select></code>```

This outputs each as

```<code>Title Title This is Option a This is Option b
</code>```

Which I understand - but how do I get the textarea to output as

```<code>Title This is Option a
Title This is Option b
</code>```

Is that even possible?

答:
vi,
Here is how I solved your question,
First, I have gotten all H3 and Selected options then I added each H3(s) as a title

Title
This is option A
Title
This is option B

here is my sample code

```<code>    $( document ).ready(function() {
    console.log( "ready!" );

    var h3s = $('h3').each(function(value) {
        value + "\n";
    });

    var options = $('select option:selected').each(function(value) {
        value + "\n";
    });

    var output = "";
    $(h3s).each(function(i, value) {
        console.log("Index: " + i + " value: " + value.innerText + "\n" + options[i].innerText);
        output += value.innerText + "\n" + options[i].innerText + "\n";
    });

    $('body').append($('<textarea>', {
        name: 'ghi'
    }).val(output));

});
</code>```

Please let me know if I have solved your question.

Body:
So I have a basic structure of a page and my corresponding script:

jQuery('select').change(function() {
  var abc = jQuery("select option:selected").text();
  var def = jQuery("h3").text();
  jQuery('textarea[name="ghi"]', $form).val(def + "\n\n" + abc).change();
});

Title

<select>
  <option value="A">This is Option a</option>
</select>

Title

<select>
  <option value="B">This is Option b</option>
</select>

This outputs each as

Title Title This is Option a This is Option b

Which I understand - but how do I get the textarea to output as

Title This is Option a
Title This is Option b

Is that even possible?

Body:
vi,
Here is how I solved your question,
First, I have gotten all H3 and Selected options then I added each H3(s) as a title

Title
This is option A
Title
This is option B

here is my sample code

    $( document ).ready(function() {
    console.log( "ready!" );

    var h3s = $('h3').each(function(value) {
        value + "\n";
    });

    var options = $('select option:selected').each(function(value) {
        value + "\n";
    });

    var output = "";
    $(h3s).each(function(i, value) {
        console.log("Index: " + i + " value: " + value.innerText + "\n" + options[i].innerText);
        output += value.innerText + "\n" + options[i].innerText + "\n";
    });

    $('body').append($('<textarea>', {
        name: 'ghi'
    }).val(output));

});

Please let me know if I have solved your question.


问:
I have a code that opens excel application with win32com and similar code with xlwings
The code looks like this:

```<code>wbtest = xw.Book('test1.xlsx')

ws1 = wbtest.sheets['Sheet1']
ws1.range("A1").value ="100"
wbtest.save()
wbtest.save(r'C:\Users\afoto001.000\Desktop\All projects\DC projects\codes\test1.xlsx')
wb.kill()
</code>```

The code basically starts an excel document and writes 100 to Sheet1. After that, I'd like Excel to close on its own, without the need for user intervention. Any suggestions or ideas would be much appreciated.

答:
I used this at the end of my code and now my Excel processes close automatically:

```<code>quit()
sys.exit()
def quit(self):
        self.xlBook.Close(SaveChanges=0)
        self.xlApp.Quit()
        del self.xlApp
</code>```

Body:
The code looks like this:

wbtest = xw.Book('test1.xlsx')

ws1 = wbtest.sheets['Sheet1']
ws1.range("A1").value ="100"
wbtest.save()
wbtest.save(r'C:\Users\afoto001.000\Desktop\All projects\DC projects\codes\test1.xlsx')
wb.kill()

The code basically starts an excel document and writes 100 to Sheet1. After that, I'd like Excel to close on its own, without the need for user intervention. Any suggestions or ideas would be much appreciated.

Body:
I used this at the end of my code and now my Excel processes close automatically:

quit()
sys.exit()
def quit(self):
        self.xlBook.Close(SaveChanges=0)
        self.xlApp.Quit()
        del self.xlApp


问:
searching the longest series of same string in the row
Hi i need to find a longest series of same number in a row

```<code>list = [1,1,1,1,2,2,3,4,5,6]

answer(`number 1 was 4 times in a row`)

</code>```

przyklad.txt

I write my own version of this algorithm, but it returns 6024 instead of 198 (this is a true answer). This is my exam task algorithmic, and I don't understand how this algorithm needs to work. Can someone explain me this or give a link to a solution to my problem ?

orginal

```<code>
with open('przyklad.txt','r') as plik:
    wiersze = plik.read().splitlines()
    dane = []
    pomciag = 1
    ciag = 1
    for w in wiersze:
        dane = w.split()
        for i in range(len(dane)-1):
            a = dane[i]
            b = dane[i+1]
            if a == b:
                pomciag += 1
            elif pomciag > ciag:
                ciag = pomciag
                pomciag = 1
        if pomciag > ciag:
            ciag = pomciag
            pomciag = 1
    print(ciag)
</code>```

translated

```<code>with open('przyklad.txt','r') as file:
    verse = file.read().splitlines()
    date = []
    helpSeries = 1
    series = 1
    for w in verse:
        date = w.split()
        for i in range(len(date) - 1):
            a = date[i]
            b = date[i + 1]
            if a == b:
                helpSeries += 1
            elif helpSeries > series:
                series = helpSeries
                helpSeries = 1
        if helpSeries > series:
            series = helpSeries
            helpSeries = 1
    print(series)
</code>```

答: the pomciag variable should be refreshed inside the for loop if you want the algo to find the longest series of same number in a row. Otherwise, it will continue to plus 1, that is why the result shows 6024</p>

Body:
Hi i need to find a longest series of same number in a row

list = [1,1,1,1,2,2,3,4,5,6]

answer(`number 1 was 4 times in a row`)

przyklad.txt

I write my own version of this algorithm, but it returns 6024 instead of 198 (this is a true answer). This is my exam task algorithmic, and I don't understand how this algorithm needs to work. Can someone explain me this or give a link to a solution to my problem ?

orginal

with open('przyklad.txt','r') as plik:
    wiersze = plik.read().splitlines()
    dane = []
    pomciag = 1
    ciag = 1
    for w in wiersze:
        dane = w.split()
        for i in range(len(dane)-1):
            a = dane[i]
            b = dane[i+1]
            if a == b:
                pomciag += 1
            elif pomciag > ciag:
                ciag = pomciag
                pomciag = 1
        if pomciag > ciag:
            ciag = pomciag
            pomciag = 1
    print(ciag)

translated

with open('przyklad.txt','r') as file:
    verse = file.read().splitlines()
    date = []
    helpSeries = 1
    series = 1
    for w in verse:
        date = w.split()
        for i in range(len(date) - 1):
            a = date[i]
            b = date[i + 1]
            if a == b:
                helpSeries += 1
            elif helpSeries > series:
                series = helpSeries
                helpSeries = 1
        if helpSeries > series:
            series = helpSeries
            helpSeries = 1
    print(series)


问:
Wordwrap Default set to "on" in VS Code
Is there anyway to set WordWrap to "on" by default. in VS-Code Editor. So that even after restarting the editor it stays "on". So that in my whole life I do not have to change it ever again.</p>

答:
Go to Settings (Crtl+,) and search for wordWrap, by default the value is off, turn it on.
Switching to "on" activates word wrap on all documents in Visual Studio Code.

Now, if you open settings.json, with (Crtl+Shift+P), Open Settings (JSON),  you will see that "editor.wordWrap": "on" will be present.

Every time you restart VScode those settings will be applied.

Title: Wordwrap Default set to "on" in VS Code


问:
Gallery pics re-sized when seeing from android
I’m quite a newbie around here so this kinda feel like I’m learning sanscrit. Thrilling and overwhelming at the same time.

Anyway, the thing is I'm using wordpress at my laptop and I'm sttrugling at keeping my pics at the size expected when I switch to android. They look totally fine on the laptop preview for the phone, but on the real world they're basically turning into a thumbnail. I attach a picture of expectation versus reality

I apologize in advance because I suspect this is part of the ABC of programming; I don't even know if I should be uploading my pics with a particular size. I promise I'm training to become a proper padawan, and 'll appreciate any feedback.

Thank you so much for your time, and have a great day!

答:
If you are starting with Wordpress, best thing to do is to work with themes supported by Elementor & one that allows you to modify the design for desktop, tablet, & mobile versions separately.
-Select 'Edit with Elementor'
-select the section with these six pictures. in the '#Edit Section' box at the right, you will see three options- layout/content, style, advanced.
-Select 'Advanced' and scroll down till the bottom section.
-Select the 3rd last option, 'Responsive'. From here you can hide the mentioned section for mobile.
It would look something like the attached picture

DO BEAR IN MIND THAT I HAVE ADDED SAME BUTTON TWICE - the button at the left is visible to site visitors using desktop/tablet. At the right part, you can see same button blurred. That's 'cause I hid it from Desktop & Tab.

Similarly, you too have to add section with pictures again to show in mobile only.
For that, find and click on Responsive icon & select Mobile.
Decorate the section just the way you want and do not forget to hide it from PC & Tab.


问:
Conflict between mix-ins for abstract dataclasses

1. A problem with dataclass mix-ins, solved

To make abstract dataclasses that type-check under mypy, I've been breaking them into two classes, one that contains the abstract methods and one that contains the data members, as explained in this answer. The abstract class inherits from the dataclass. This runs into a problem, though, when another abstract-class-and-dataclass pair inherits from the first one: the "ancestor" dataclass's fields get wiped out by the "descendant". For example:

```<code>from dataclasses import dataclass
from abc import ABC, abstractmethod

@dataclass
class ADataclassMixin:
    a_field: int = 1

class A(ADataclassMixin, ABC):
    @abstractmethod
    def method(self):
        pass

@dataclass
#class BDataclassMixin(A):  # works  but fails mypy 0.931 type-check
class BDataclassMixin:  # fails
    b_field: int = 2
    pass

class B(BDataclassMixin, A):
    def method(self):
        return self

o = B(a_field=5)
</code>```

The last line fails, yielding this error message:

```<code>TypeError: BDataclassMixin.__init__() got an unexpected keyword argument 'a_field'
</code>```

B's method-resolution order (B.__mro__) is (B, BDataclassMixin, A, ADataclassMixin, ABC, object), as expected. But a_field is not found.

A solution, shown in the commented-out line above, is to put the ancestor class explicitly in the descendant dataclass's declaration: class BDataclassMixin(A) instead of class BDataclassMixin. This fails type-checking, though, because a dataclass can only be a concrete class.

2. A problem with that solution, unsolved

The above solution breaks down if we add a third class, inheriting from B:

```<code>@dataclass
#class CDataclassMixin:  # fails
class CDataclassMixin(A):  # fails
#class CDataclassMixin(B, A):  # works  but fails type-check
    c_field: int = 3
    pass

class C(CDataclassMixin, B):
    def method(self):
        return "C's result"
    pass

o = C(b_field=5)
</code>```

Now, C has a_field and c_field but has lost b_field.

I have found that if I declare CDataclassMixin explicitly to inherit from B and A (in that order), b_field will be in the resulting class along with a_field_ and c_field`. However, explicitly stating the inheritance hierarchy in every mix-in defeats the purpose of mix-ins, which is to be able to code them independently of all the other mix-ins and to mix them easily and any way you like.

What is the correct way to make abstract dataclass mix-ins, so that classes that inherit from them include all the dataclass fields?

答:
Putting the mixin as the last base class works without error:</p>
```<code>@dataclass
class ADataclassMixin:
    a_field: int = 1

class A(ABC, ADataclassMixin):

    @abstractmethod
    def method(self):
        pass

@dataclass
class BDataclassMixin:
    b_field: int = 2

class B(A, BDataclassMixin):

    def method(self):
        return self

o = B(a_field=5)
print((o.a_field, o.b_field))  # (5,2)
</code>```

Body:
1. A problem with dataclass mix-ins, solved

To make abstract dataclasses that type-check under mypy, I've been breaking them into two classes, one that contains the abstract methods and one that contains the data members, as explained in this answer. The abstract class inherits from the dataclass. This runs into a problem, though, when another abstract-class-and-dataclass pair inherits from the first one: the "ancestor" dataclass's fields get wiped out by the "descendant". For example:

from dataclasses import dataclass
from abc import ABC, abstractmethod

@dataclass
class ADataclassMixin:
    a_field: int = 1

class A(ADataclassMixin, ABC):
    @abstractmethod
    def method(self):
        pass

@dataclass
#class BDataclassMixin(A):  # works  but fails mypy 0.931 type-check
class BDataclassMixin:  # fails
    b_field: int = 2
    pass

class B(BDataclassMixin, A):
    def method(self):
        return self

o = B(a_field=5)

The last line fails, yielding this error message:

TypeError: BDataclassMixin.__init__() got an unexpected keyword argument 'a_field'

B's method-resolution order (B.__mro__) is (B, BDataclassMixin, A, ADataclassMixin, ABC, object), as expected. But a_field is not found.

A solution, shown in the commented-out line above, is to put the ancestor class explicitly in the descendant dataclass's declaration: class BDataclassMixin(A) instead of class BDataclassMixin. This fails type-checking, though, because a dataclass can only be a concrete class.

2. A problem with that solution, unsolved

The above solution breaks down if we add a third class, inheriting from B:

@dataclass
#class CDataclassMixin:  # fails
class CDataclassMixin(A):  # fails
#class CDataclassMixin(B, A):  # works  but fails type-check
    c_field: int = 3
    pass

class C(CDataclassMixin, B):
    def method(self):
        return "C's result"
    pass

o = C(b_field=5)

Now, C has a_field and c_field but has lost b_field.

I have found that if I declare CDataclassMixin explicitly to inherit from B and A (in that order), b_field will be in the resulting class along with a_field_ and c_field`. However, explicitly stating the inheritance hierarchy in every mix-in defeats the purpose of mix-ins, which is to be able to code them independently of all the other mix-ins and to mix them easily and any way you like.

What is the correct way to make abstract dataclass mix-ins, so that classes that inherit from them include all the dataclass fields?

Body:
Putting the mixin as the last base class works without error:

@dataclass
class ADataclassMixin:
    a_field: int = 1

class A(ABC, ADataclassMixin):

    @abstractmethod
    def method(self):
        pass

@dataclass
class BDataclassMixin:
    b_field: int = 2

class B(A, BDataclassMixin):

    def method(self):
        return self

o = B(a_field=5)
print((o.a_field, o.b_field))  # (5,2)


问:
how can generate a image URL from image?
I am working on a face recognition API that accept only image URL .

I want to generate a image URL from image of my local computer in python .Any solution to generate the image URL in python ? so I can pass the image URL in to API (that only take image URL).

Here is my code :

```<code>import requests

# put your keys in the header
headers = {
    "app_id": "4353454",
    "app_key": "5474565rfedgry564353tgtr"
}

#here I want to convert the image to image URL so I can easily pass it as a
argument into API

payload = '{"image":"image_URL"}'

url = "url_of_API"

r = requests.post(url, data= payload, headers=headers)
print(r.content)
</code>```

Any solution will highly appreciated .

答: There are bots in telegram which can convert image to url you will need to use telegram  api to upload image to bot and it will reply with url</p>

Body:
I am working on a face recognition API that accept only image URL .

I want to generate a image URL from image of my local computer in python .Any solution to generate the image URL in python ? so I can pass the image URL in to API (that only take image URL).

Here is my code :

import requests

# put your keys in the header
headers = {
    "app_id": "4353454",
    "app_key": "5474565rfedgry564353tgtr"
}

#here I want to convert the image to image URL so I can easily pass it as a
argument into API

payload = '{"image":"image_URL"}'

url = "url_of_API"

r = requests.post(url, data= payload, headers=headers)
print(r.content)

Any solution will highly appreciated .


问:
preg_replace problems
I have a string The Incredible Hulk (2008) and use pattern

```<code>/^\([0-9]{1,4}\)$/
</code>```

to remove (2008). PHP code looks like this:

```<code>$x = trim(preg_replace("/^\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));
</code>```

And the result is:

```<code>The Incredible Hulk (2008)
</code>```

What am I doing wrong?

答:
Just remove the ^ sign (beginning of line).

```<code>$x = trim(preg_replace("/\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));
</code>```

(you might want to remove the $ sign as well (end of line))

More info about PHP meta characters in the documentation:
http://www.php.net/manual/en/regexp.reference.meta.php

Title: preg_replace problems

Body:
I have a string The Incredible Hulk (2008) and use pattern

/^\([0-9]{1,4}\)$/

to remove (2008). PHP code looks like this:

$x = trim(preg_replace("/^\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));

And the result is:

The Incredible Hulk (2008)

What am I doing wrong?

Body:
Just remove the ^ sign (beginning of line).

$x = trim(preg_replace("/\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));

(you might want to remove the $ sign as well (end of line))

More info about PHP meta characters in the documentation:
http://www.php.net/manual/en/regexp.reference.meta.php


问:
A way to use useReducer function on other buttons
I'm new in React.js. I would like to pass the same behaviour again but on the other two buttons like i did in the first.

I started with the following function to pass on my useReducer:

```<code>const hoverReducer = (state, action) => {
let newState;
switch (action.type) {
    case 'true':
        newState = {
            transform: `scale(1.08)`,
            backgroundColor: "transparent",
            border: "none",
            transition: `all 0.3s ease-in.out`
        }
        break;
    case 'false':
        newState = {
            transform: `scale(1.0)`,
            backgroundColor: "transparent",
            border: "none",
        }
        break;
    default:
        throw new Error();
    }
    return newState;
}
</code>```

then in my function Primary() i did this:

```<code>const initialState = {
    transform: `scale(1.0)`,
    backgroundColor: "transparent",
    border: "none"
}

const [buttonStyle, setButtonStyle] = useReducer(hoverReducer, initialState)

const addHover = ()=>{
    setButtonStyle({type: 'true'})
}
const removeHover = () =>{
    setButtonStyle({type: 'false'})

}
</code>```

my return:

```<code>    return (
    <div>
        <button style={buttonStyle} onMouseEnter={() => addHover()}
            onMouseLeave={() => removeHover()}
        >
            <img src="https://i.ibb.co/mJ6fzbt/gm-c.png" border="0" style={styleImg} />
        </button>
        <button >
            <img src="https://i.ibb.co/znbBNmX/link-c.png" border="0" style={styleImg} />
        </button>
        <button >
            <img src="https://i.ibb.co/HXXjyPT/twi-c.png"  border="0" style={styleImg} />
        </button>

    </div>
)
</code>```

Thanks in advance.

答:
You should create a new component with the hovering logic in that way each button you create has that logic in it. And accept src URL for the image plus anything you need as props.

MyButton

```<code>const MyButton = ({ styleImg, src }) => {
  const initialState = {
    transform: `scale(1.0)`,
    backgroundColor: "transparent",
    border: "none"
  };

  const [buttonStyle, setButtonStyle] = useReducer(hoverReducer, initialState);

  const addHover = () => {
    setButtonStyle({ type: "true" });
  };
  const removeHover = () => {
    setButtonStyle({ type: "false" });
  };

  return (
    <button
      style={buttonStyle}
      onMouseEnter={() => addHover()}
      onMouseLeave={() => removeHover()}
    >
      <img src={src} border="0" style={styleImg} />
    </button>
  );
};
</code>```

App

```<code>export default function App() {
  return (
    <div>
      <MyButton src="https://i.ibb.co/mJ6fzbt/gm-c.png" styleImg={""} />
      <MyButton src="https://i.ibb.co/znbBNmX/link-c.png" styleImg={""} />
      <MyButton src="https://i.ibb.co/HXXjyPT/twi-c.png" styleImg={""} />
    </div>
  );
}
</code>```

Body:
I'm new in React.js. I would like to pass the same behaviour again but on the other two buttons like i did in the first.

I started with the following function to pass on my useReducer:

const hoverReducer = (state, action) => {
let newState;
switch (action.type) {
    case 'true':
        newState = {
            transform: `scale(1.08)`,
            backgroundColor: "transparent",
            border: "none",
            transition: `all 0.3s ease-in.out`
        }
        break;
    case 'false':
        newState = {
            transform: `scale(1.0)`,
            backgroundColor: "transparent",
            border: "none",
        }
        break;
    default:
        throw new Error();
    }
    return newState;
}

then in my function Primary() i did this:

const initialState = {
    transform: `scale(1.0)`,
    backgroundColor: "transparent",
    border: "none"
}

const [buttonStyle, setButtonStyle] = useReducer(hoverReducer, initialState)

const addHover = ()=>{
    setButtonStyle({type: 'true'})
}
const removeHover = () =>{
    setButtonStyle({type: 'false'})

}

my return:

    return (

        <button style={buttonStyle} onMouseEnter={() => addHover()}
            onMouseLeave={() => removeHover()}
        >

        </button>
        <button >

        </button>
        <button >

        </button>

)

Thanks in advance.

Body:
You should create a new component with the hovering logic in that way each button you create has that logic in it. And accept src URL for the image plus anything you need as props.

MyButton

const MyButton = ({ styleImg, src }) => {
  const initialState = {
    transform: `scale(1.0)`,
    backgroundColor: "transparent",
    border: "none"
  };

  const [buttonStyle, setButtonStyle] = useReducer(hoverReducer, initialState);

  const addHover = () => {
    setButtonStyle({ type: "true" });
  };
  const removeHover = () => {
    setButtonStyle({ type: "false" });
  };

  return (
    <button
      style={buttonStyle}
      onMouseEnter={() => addHover()}
      onMouseLeave={() => removeHover()}
    >
      <img src={src} border="0" style={styleImg} />
    </button>
  );
};

App

export default function App() {
  return (
    <div>
      <MyButton src="https://i.ibb.co/mJ6fzbt/gm-c.png" styleImg={""} />
      <MyButton src="https://i.ibb.co/znbBNmX/link-c.png" styleImg={""} />
      <MyButton src="https://i.ibb.co/HXXjyPT/twi-c.png" styleImg={""} />
    </div>
  );
}


问:
Random nucleotides sequence
i started learning python today and i had this project in mind where the code would generate a random nucleotides sequence. This is the code im using for now its its working perfectly fine

```<code>import random
import string
nuc = '*Chaine aleatoire de nucleotides (Brin transcrit)*     :'
nucBNT = '*Chaine aleatoire de nucleotides (Brin non transcrit)* :'
nucleotides_length = 30
possible_characters = "ATCG"
random_character_list = [random.choice(possible_characters) for i in range(nucleotides_length)]
random_nucleotides = "".join(random_character_list)
print(nuc, random_nucleotides)
</code>```

I was then thinking about it generating the completing nucleotide sequence ( replacing Adenine by Thymine, Guanine by Cytosine, Thymine by Adenine and Cytosine by Guanine) but this is my first time opening Python and i dont know any way on how to do this despite looking on internet. Any help would be highly appreciated

Have a great day

答:
The simplest* way would be to set up a dictionary with an entry for each substitution. The keys (on the left) are the inputs, and the values (on the right) are what you want to replace each one with:

substitute = {
    "A": "T",
    "G": "C",
    "T": "A",
    "C": "G",
}
```
<p>Then you can use this to replace each character in <code>random_nucleotides</code>, character-by-character:</p>
<pre class="lang-py prettyprint-override"><code>completed_nucleotides = "".join([substitute[c] for c in random_nucleotides])
</code>```

* for a certain value of "simplest", anyway

There are a number of general solutions out there for making multiple substitutions to a string using string.replace or re.sub. This answer maybe is the most complete list of them. However in this case the substitutions are cyclic(?): the As and Ts swap, and the Cs and Gs swap. If you replace characters across the whole string at once, you replace all the As with Ts, then all the Ts with As, and you're left with only As and no Ts.

You could remove the cyclic condition by having one string be lowercase. Then you could use one of the more common multiple-substitutions-in-a-string method.

Title: Random nucleotides sequence

Body:
i started learning python today and i had this project in mind where the code would generate a random nucleotides sequence. This is the code im using for now its its working perfectly fine

import random
import string
nuc = '*Chaine aleatoire de nucleotides (Brin transcrit)*     :'
nucBNT = '*Chaine aleatoire de nucleotides (Brin non transcrit)* :'
nucleotides_length = 30
possible_characters = "ATCG"
random_character_list = [random.choice(possible_characters) for i in range(nucleotides_length)]
random_nucleotides = "".join(random_character_list)
print(nuc, random_nucleotides)

I was then thinking about it generating the completing nucleotide sequence ( replacing Adenine by Thymine, Guanine by Cytosine, Thymine by Adenine and Cytosine by Guanine) but this is my first time opening Python and i dont know any way on how to do this despite looking on internet. Any help would be highly appreciated

Have a great day

Body:
The simplest* way would be to set up a dictionary with an entry for each substitution. The keys (on the left) are the inputs, and the values (on the right) are what you want to replace each one with:

substitute = {
    "A": "T",
    "G": "C",
    "T": "A",
    "C": "G",
}

Then you can use this to replace each character in random_nucleotides, character-by-character:

completed_nucleotides = "".join([substitute[c] for c in random_nucleotides])

* for a certain value of "simplest", anyway

There are a number of general solutions out there for making multiple substitutions to a string using string.replace or re.sub. This answer maybe is the most complete list of them. However in this case the substitutions are cyclic(?): the As and Ts swap, and the Cs and Gs swap. If you replace characters across the whole string at once, you replace all the As with Ts, then all the Ts with As, and you're left with only As and no Ts.

You could remove the cyclic condition by having one string be lowercase. Then you could use one of the more common multiple-substitutions-in-a-string method.


问:
What is the practical use of the identity function in R?
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

```<code>identity <- function (x){x}
</code>```

Why would such a trivial function ever be useful?  Why would it be included in base R?

Body:
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

identity <- function (x){x}

Why would such a trivial function ever be useful?  Why would it be included in base R?

Body:
I use it from time to time with the apply function of commands.

For instance, you could write t() as:

dat <- data.frame(x=runif(10),y=runif(10))
apply(dat,1,identity)

       [,1]      [,2]      [,3]      [,4]      [,5]      [,6]       [,7]
x 0.1048485 0.7213284 0.9033974 0.4699182 0.4416660 0.1052732 0.06000952
y 0.7225307 0.2683224 0.7292261 0.5131646 0.4514837 0.3788556 0.46668331
       [,8]      [,9]      [,10]
x 0.2457748 0.3833299 0.86113771
y 0.9643703 0.3890342 0.01700427


问:
php artisan make:controller PostsController --resource: --resource not generating functions
When running
php artisan make:controller PostsController --resource,
the index, create, show etc. functions are not generated.
I also tried -r but no luck,
are --resource/-r depracated?

Is it fine if I'll just manually create it?

Please help

Laravel Version : 8.11.2

答: if you already creat postscontroller and controller not provide index, create, edit funtion then delete your postscontroller &  run this command in your terminal in new file you have index, creat etc.  php artisan make:controller PostsController --resource</p>


问:
Why does my SwiftUI view not get onChange updates from a @Binding member of a @StateObject?
Given the setup I've outlined below, I'm trying to determine why ChildView's .onChange(of: _) is not receiving updates.

import SwiftUI

struct SomeItem: Equatable {
    var doubleValue: Double
}

struct ParentView: View {
    @State
    private var someItem = SomeItem(doubleValue: 45)

    var body: some View {
        Color.black
            .overlay(alignment: .top) {
                Text(someItem.doubleValue.description)
                    .font(.system(size: 50))
                    .foregroundColor(.white)
            }
            .onTapGesture { someItem.doubleValue += 10.0 }
            .overlay { ChildView(someItem: $someItem) }
    }
}

struct ChildView: View {
    @StateObject
    var viewModel: ViewModel

    init(someItem: Binding<SomeItem>) {
        _viewModel = StateObject(wrappedValue: ViewModel(someItem: someItem))
    }

    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 50, height: 70, alignment: .center)
            .rotationEffect(
                Angle(degrees: viewModel.someItem.doubleValue)
            )
            .onTapGesture { viewModel.changeItem() }
            .onChange(of: viewModel.someItem) { _ in
                print("Change Detected", viewModel.someItem.doubleValue)
            }
    }
}

@MainActor
final class ViewModel: ObservableObject {
    @Binding
    var someItem: SomeItem

    public init(someItem: Binding<SomeItem>) {
        self._someItem = someItem
    }

    public func changeItem() {
        self.someItem = SomeItem(doubleValue: .zero)
    }
}
```

Interestingly, if I make the following changes in ChildView, I get the behavior I want.

Change @StateObject to @ObservedObject

Change _viewModel = StateObject(wrappedValue: ViewModel(someItem: someItem)) to viewModel = ViewModel(someItem: someItem)

From what I understand, it is improper for ChildView's viewModel to be @ObservedObject because ChildView owns viewModel but @ObservedObject gives me the behavior I need whereas @StateObject does not.

Here are the differences I'm paying attention to:

When using @ObservedObject, I can tap the black area and see the changes applied to both the white text and red rectangle. I can also tap the red rectangle and see the changes observed in ParentView through the white text.

When using @StateObject, I can tap the black area and see the changes applied to both the white text and red rectangle. The problem lies in that I can tap the red rectangle here and see the changes reflected in ParentView but ChildView doesn't recognize the change (rotation does not change and "Change Detected" is not printed).

Is @ObservedObject actually correct since ViewModel contains a @Binding to a @State created in ParentView?

答: Actually we don't use view model objects at all in SwiftUI, see [Data Essentials in SwiftUI WWDC 2020]. As shown in the video at 4:33 create a custom struct to hold the item, e.g. ChildViewConfig and init it in an @State in the parent. Set the childViewConfig.item in a handler or add any mutating custom funcs. Pass the binding $childViewConfig or $childViewConfig.item to the to the child View if you need write access. It's all very simple if you stick to structs and value semantics.

Body:
Given the setup I've outlined below, I'm trying to determine why ChildView's .onChange(of: _) is not receiving updates.

import SwiftUI

struct SomeItem: Equatable {
    var doubleValue: Double
}

struct ParentView: View {
    @State
    private var someItem = SomeItem(doubleValue: 45)

    var body: some View {
        Color.black
            .overlay(alignment: .top) {
                Text(someItem.doubleValue.description)
                    .font(.system(size: 50))
                    .foregroundColor(.white)
            }
            .onTapGesture { someItem.doubleValue += 10.0 }
            .overlay { ChildView(someItem: $someItem) }
    }
}

struct ChildView: View {
    @StateObject
    var viewModel: ViewModel

    init(someItem: Binding<SomeItem>) {
        _viewModel = StateObject(wrappedValue: ViewModel(someItem: someItem))
    }

    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 50, height: 70, alignment: .center)
            .rotationEffect(
                Angle(degrees: viewModel.someItem.doubleValue)
            )
            .onTapGesture { viewModel.changeItem() }
            .onChange(of: viewModel.someItem) { _ in
                print("Change Detected", viewModel.someItem.doubleValue)
            }
    }
}

@MainActor
final class ViewModel: ObservableObject {
    @Binding
    var someItem: SomeItem

    public init(someItem: Binding<SomeItem>) {
        self._someItem = someItem
    }

    public func changeItem() {
        self.someItem = SomeItem(doubleValue: .zero)
    }
}

Interestingly, if I make the following changes in ChildView, I get the behavior I want.

Change @StateObject to @ObservedObject

Change _viewModel = StateObject(wrappedValue: ViewModel(someItem: someItem)) to viewModel = ViewModel(someItem: someItem)

From what I understand, it is improper for ChildView's viewModel to be @ObservedObject because ChildView owns viewModel but @ObservedObject gives me the behavior I need whereas @StateObject does not.

Here are the differences I'm paying attention to:

When using @ObservedObject, I can tap the black area and see the changes applied to both the white text and red rectangle. I can also tap the red rectangle and see the changes observed in ParentView through the white text.

When using @StateObject, I can tap the black area and see the changes applied to both the white text and red rectangle. The problem lies in that I can tap the red rectangle here and see the changes reflected in ParentView but ChildView doesn't recognize the change (rotation does not change and "Change Detected" is not printed).

Is @ObservedObject actually correct since ViewModel contains a @Binding to a @State created in ParentView?