问:
Why isn't this perl prog printing about the translated text?
I am new to perl and programming in general, and I just found out about regular expressions and the substitution operator.

```<code>#!/usr/bin/perl

open(LEET, "leet.txt") or die "Can't open leet.txt: $!\n";
while($line = <LEET>) {
    $line =~ s/4/a/gi, s/3/e/gi;
}
print $line;
</code>```

Why doesn't his print anything? I want to make a leet speak translator that opens up a text file and prints out the translated text.

答:
You are only printing the last line. Try moving the print inside your loop:

```<code>while($line = <LEET>) {
    $line =~ s/4/a/gi;
    $line =~ s/3/e/gi;
    print $line;
}
</code>```

I've also used two separate regex substitutions, you can't combine them in the way you've shown in your question.

Note that Perl also has the tr operator, which is another way of doing both (single-character) substitutions in one step:

```<code>$line =~ tr/43/ae/;
</code>```

Body:
I am new to perl and programming in general, and I just found out about regular expressions and the substitution operator.

#!/usr/bin/perl

open(LEET, "leet.txt") or die "Can't open leet.txt: $!\n";
while($line = <LEET>) {
    $line =~ s/4/a/gi, s/3/e/gi;
}
print $line;

Why doesn't his print anything? I want to make a leet speak translator that opens up a text file and prints out the translated text.

Body:
You are only printing the last line. Try moving the print inside your loop:

while($line = <LEET>) {
    $line =~ s/4/a/gi;
    $line =~ s/3/e/gi;
    print $line;
}

I've also used two separate regex substitutions, you can't combine them in the way you've shown in your question.

Note that Perl also has the tr operator, which is another way of doing both (single-character) substitutions in one step:

$line =~ tr/43/ae/;


来源: stackexchange

问:
Convert columns to rows with awk
I have an output file in the following format. How can I convert this into csv with first column as header row and second column as data row?

Input:

```"Node name","SLAVE_DB"
"Node ID","2"
"PostgreSQL version","10.17"
"Total data size","1 GB"
"Conninfo","host=192.168.0.1 port=5432 user=user dbname=postgres"
"Role","standby"
"WAL archiving","disabled (on standbys "archive_mode" must be set to "always" to be effective)"
```

Desired Output:

```
"Node name","Node ID","PostgreSQL version","Total data size","Conninfo","Role","WAL archiving"
"SLAVE_DB","2","10.17","1 GB","host=192.168.0.1 port=5432 user=user dbname=postgres","standby","disabled (on standbys ""archive_mode"" must be set to ""always"" to be effective)"```

[Edit]
I read through similar questions and I tried awk -F "," '{ for (i=1;i<=NF;i++ ) printf $i ", " }'

but it does not produce the desired output. I also want to preserve the quoted fields with in the data.

答:
If we assume that there's never quotes in your first field (the tag/name/header), then using any awk in any shell on every Unix box:

```<code>$ cat tst.awk
BEGIN { FS=OFS="," }
{
    tags[NR] = $1
    vals[NR] = $2
}
END {
    for ( colNr=1; colNr<=NR; colNr++ ) {
        tag = tags[colNr]
        printf "%s%s", tag, (colNr<NR ? OFS : ORS)
    }
    for ( colNr=1; colNr<=NR; colNr++ ) {
        val = vals[colNr]
        gsub(/^"|"$/,"",val)
        gsub(/"/,"\"\"",val)
        printf "\"%s\"%s", val, (colNr<NR ? OFS : ORS)
    }
}
</code>```

```<code>$ awk -f tst.awk file
"Node name","Node ID","PostgreSQL version","Total data size","Conninfo","Role","WAL archiving"
"SLAVE_DB","2","10.17","1 GB","host=192.168.0.1 port=5432 user=user dbname=postgres","standby","disabled (on standbys ""archive_mode"" must be set to ""always"" to be effective)"
</code>```

If you need more than that then see What's the most robust way to efficiently parse CSV using awk?.

ContentLicense: CC BY-SA 4.0

Title: Convert columns to rows with awk

Body:
I have an output file in the following format. How can I convert this into csv with first column as header row and second column as data row?

Input:

"Node name","SLAVE_DB"
"Node ID","2"
"PostgreSQL version","10.17"
"Total data size","1 GB"
"Conninfo","host=192.168.0.1 port=5432 user=user dbname=postgres"
"Role","standby"
"WAL archiving","disabled (on standbys "archive_mode" must be set to "always" to be effective)"

Desired Output:

"Node name","Node ID","PostgreSQL version","Total data size","Conninfo","Role","WAL archiving"
"SLAVE_DB","2","10.17","1 GB","host=192.168.0.1 port=5432 user=user dbname=postgres","standby","disabled (on standbys ""archive_mode"" must be set to ""always"" to be effective)"

[Edit]
I read through similar questions and I tried awk -F "," '{ for (i=1;i<=NF;i++ ) printf $i ", " }'

but it does not produce the desired output. I also want to preserve the quoted fields with in the data.

Body:
If we assume that there's never quotes in your first field (the tag/name/header), then using any awk in any shell on every Unix box:

$ cat tst.awk
BEGIN { FS=OFS="," }
{
    tags[NR] = $1
    vals[NR] = $2
}
END {
    for ( colNr=1; colNr<=NR; colNr++ ) {
        tag = tags[colNr]
        printf "%s%s", tag, (colNr<NR ? OFS : ORS)
    }
    for ( colNr=1; colNr<=NR; colNr++ ) {
        val = vals[colNr]
        gsub(/^"|"$/,"",val)
        gsub(/"/,"\"\"",val)
        printf "\"%s\"%s", val, (colNr<NR ? OFS : ORS)
    }
}

$ awk -f tst.awk file
"Node name","Node ID","PostgreSQL version","Total data size","Conninfo","Role","WAL archiving"
"SLAVE_DB","2","10.17","1 GB","host=192.168.0.1 port=5432 user=user dbname=postgres","standby","disabled (on standbys ""archive_mode"" must be set to ""always"" to be effective)"

If you need more than that then see What's the most robust way to efficiently parse CSV using awk?.


问:
Flutter new project Fatal exit with error code 1
I have created and run successfully flutter project on my laptop, but every time when I have created a new project and run it that requires an internet connection,otherwise gives error "Exception: Gradle task assembleDebug failed with exit code 1"

And when I connected the laptop to the internet then it will download all sdk and dependencies again

答:
Just change gradle and gradle wrapper in these 2 files in your project :

```<code>android/build.gradle:
classpath 'com.android.tools.build:gradle:4.1.0' to 4.0.2

android/gradle/wrapper/gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip to 6.4.1-all
</code>```

This is just a workaround, still looking for a real solution

Body:
Just change gradle and gradle wrapper in these 2 files in your project :

android/build.gradle:
classpath 'com.android.tools.build:gradle:4.1.0' to 4.0.2

android/gradle/wrapper/gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip to 6.4.1-all

This is just a workaround, still looking for a real solution


问:
Error npm install - unable to resolve dependency tree
After npm install,
Error report:

While resolving: reactjs-simple-boilerplate@1.0.0

Found: webpack@4.46.0

node_modules/webpack

dev webpack@"^4.41.2" from the root project

Could not resolve dependency:

peer webpack@"^3.1.0" from extract-text-webpack-plugin@3.0.2

node_modules/extract-text-webpack-plugin

peer extract-text-webpack-plugin@">=0.3.8" from bootstrap-webpack@0.0.5

node_modules/bootstrap-webpack

bootstrap-webpack@"0.0.5" from the root project

enter image description here

Fix the upstream dependency conflict, or retry
this command with --force, or --legacy-peer-deps
to accept an incorrect (and potentially broken) dependency resolution.

Raw JSON explanation object:

```<code>{
  "code": "ERESOLVE",
  "current": {
    "name": "webpack",
    "version": "4.46.0",
    "whileInstalling": {
      "name": "reactjs-simple-boilerplate",
      "version": "1.0.0",
      "path": "/Users/mk/Kr/kr-application-bd786050/kr-site"
    },
    "location": "node_modules/webpack",
    "isWorkspace": false,
    "dependents": [
      {
        "type": "dev",
        "name": "webpack",
        "spec": "^4.41.2",
        "from": {
          "location": "/Users/MK/Kr/kr-application-bd786050/kr-site"
        }
      }
    ]
  },
  "currentEdge": {
    "type": "dev",
    "name": "webpack",
    "spec": "^4.41.2",
    "from": {
      "location": "/Users/MK/Kr/kr-application-bd786050/kr-site"
    }
  },
  "edge": {
    "type": "peer",
    "name": "webpack",
    "spec": "^3.1.0",
    "error": "INVALID",
    "from": {
      "name": "extract-text-webpack-plugin",
      "version": "3.0.2",
      "whileInstalling": {
        "name": "reactjs-simple-boilerplate",
        "version": "1.0.0",
        "path": "/Users/MK/Kr/kr-application-bd786050/kr-site"
      },
      "location": "node_modules/extract-text-webpack-plugin",
      "isWorkspace": false,
      "dependents": [
        {
          "type": "peer",
          "name": "extract-text-webpack-plugin",
          "spec": ">=0.3.8",
          "from": {
            "name": "bootstrap-webpack",
            "version": "0.0.5",
            "whileInstalling": {
              "name": "reactjs-simple-boilerplate",
              "version": "1.0.0",
              "path": "/Users/MK/Kr/kr-application-bd786050/kr-site"
            },
            "location": "node_modules/bootstrap-webpack",
            "isWorkspace": false,
            "dependents": [
              {
                "type": "prod",
                "name": "bootstrap-webpack",
                "spec": "0.0.5",
                "from": {
                  "location": "/Users/MK/Kr/kr-application-bd786050/kr-site"
                }
              }
            ]
          }
        }
      ]
    }
  },
  "strictPeerDeps": false,
  "force": false
}
</code>```

答:
Firstly try running webpack-cli init/webpack init and see if that fixes it.

Next try:

yarn remove extract-text-webpack-plugin

yarn add --dev extract-text-webpack-plugin@next

If neither work, then sometimes this can be a problem if the required package only works with a specific version of node/npm. If you don't already you should try using nvm for managing different versions of node which you can do by writing nvm use <version number> in your terminal.

Research your specific package that's causing dependency issues and see if it requires using a specific node.js version.

Body:
After npm install,
Error report:

While resolving: reactjs-simple-boilerplate@1.0.0

Found: webpack@4.46.0

node_modules/webpack

dev webpack@"^4.41.2" from the root project

Could not resolve dependency:

peer webpack@"^3.1.0" from extract-text-webpack-plugin@3.0.2

node_modules/extract-text-webpack-plugin

peer extract-text-webpack-plugin@">=0.3.8" from bootstrap-webpack@0.0.5

node_modules/bootstrap-webpack

bootstrap-webpack@"0.0.5" from the root project

enter image description here

Fix the upstream dependency conflict, or retry
this command with --force, or --legacy-peer-deps
to accept an incorrect (and potentially broken) dependency resolution.

Raw JSON explanation object:

{
  "code": "ERESOLVE",
  "current": {
    "name": "webpack",
    "version": "4.46.0",
    "whileInstalling": {
      "name": "reactjs-simple-boilerplate",
      "version": "1.0.0",
      "path": "/Users/mk/Kr/kr-application-bd786050/kr-site"
    },
    "location": "node_modules/webpack",
    "isWorkspace": false,
    "dependents": [
      {
        "type": "dev",
        "name": "webpack",
        "spec": "^4.41.2",
        "from": {
          "location": "/Users/MK/Kr/kr-application-bd786050/kr-site"
        }
      }
    ]
  },
  "currentEdge": {
    "type": "dev",
    "name": "webpack",
    "spec": "^4.41.2",
    "from": {
      "location": "/Users/MK/Kr/kr-application-bd786050/kr-site"
    }
  },
  "edge": {
    "type": "peer",
    "name": "webpack",
    "spec": "^3.1.0",
    "error": "INVALID",
    "from": {
      "name": "extract-text-webpack-plugin",
      "version": "3.0.2",
      "whileInstalling": {
        "name": "reactjs-simple-boilerplate",
        "version": "1.0.0",
        "path": "/Users/MK/Kr/kr-application-bd786050/kr-site"
      },
      "location": "node_modules/extract-text-webpack-plugin",
      "isWorkspace": false,
      "dependents": [
        {
          "type": "peer",
          "name": "extract-text-webpack-plugin",
          "spec": ">=0.3.8",
          "from": {
            "name": "bootstrap-webpack",
            "version": "0.0.5",
            "whileInstalling": {
              "name": "reactjs-simple-boilerplate",
              "version": "1.0.0",
              "path": "/Users/MK/Kr/kr-application-bd786050/kr-site"
            },
            "location": "node_modules/bootstrap-webpack",
            "isWorkspace": false,
            "dependents": [
              {
                "type": "prod",
                "name": "bootstrap-webpack",
                "spec": "0.0.5",
                "from": {
                  "location": "/Users/MK/Kr/kr-application-bd786050/kr-site"
                }
              }
            ]
          }
        }
      ]
    }
  },
  "strictPeerDeps": false,
  "force": false
}


问:
Priority Queue - Order Messed Up
I'm having a weird issue where my priority queue prints the last created item first, and then prints everything else in order.

I am working on a version of this assignment for my computer science class. We are using the in-built PriorityQueue in Java. A Disk object can hold 1,000,000 KB of data and a disk has priority if it has the most free space.

In my solution, Disk 7 was created latest, and it is printed on top despite the lower priority. Does anyone know what might be causing this?

Here is my solution:

```<code>public static void findWorstFit(String fileName) throws FileNotFoundException {
    PriorityQueue<Disk> disks = new PriorityQueue<>();
    double totalSize = 0;

    // Process each file and add it to a disk
    Scanner fileScanner = new Scanner(new File(fileName));
    while(fileScanner.hasNextInt()) {
        int file = fileScanner.nextInt();
        if(disks.size() > 0 && disks.peek().freeSpace >= file)
            disks.peek().add(file);
        else
            disks.offer(new Disk(disks.size(), file));
        totalSize += file;
    }

    // Print all the disks
    System.out.println("Total size = " + totalSize/1000000 + " GB");
    System.out.println("Disks req'd = " + disks.size());
    while(!disks.isEmpty())
        System.out.println(disks.poll());
}
</code>```

Here is the expected output:

```<code>Total size  = 6.580996 GB
Disks req'd = 8
5 325754: 347661 326585
0 227744: 420713 351543
7 224009: 383972 392019
4 190811: 324387 484802
6 142051: 340190 263485 254274
3 116563: 347560 204065 331812
2 109806: 396295 230973 262926
1  82266: 311011 286309 320414
</code>```

And here is the actual output:

```<code>Total size  = 6.580996 GB
Disks req'd = 8
7 224009: 383972 392019
5 325754: 347661 326585
0 227744: 420713 351543
4 190811: 324387 484802
6 142051: 340190 263485 254274
3 116563: 347560 204065 331812
2 109806: 396295 230973 262926
1  82266: 311011 286309 320414
</code>```

答:
You don't provide the implementation of the Disk class. I presume this has a comparator so the natural ordering sorts the Disks in order of most free space to least free space.

The issue is really that you are modifying an element within the PriorityQueue - and expecting the queue to reorder the elements for you - but it has no concept that the elements have been changed.

A quick fix would be to remove the head of the queue each time you want to modify it and re-insert it into the queue.

i.e.

replace

```<code>        if(disks.size() > 0 && disks.peek().freeSpace >= file)
            disks.peek().add(file);
        else
            disks.offer(new Disk(disks.size(), file));
</code>```

with

```<code>        if(disks.size() > 0 && disks.peek().freeSpace >= file) {
            Disk toChange = disks.poll();
            toChange.add(file);
            disks.offer(toChange);
        }
        else
            disks.offer(new Disk(disks.size(), file));
</code>```

That would maintain the ordering of the elements within the disks queue.

Title: Priority Queue - Order Messed Up

Body:
I'm having a weird issue where my priority queue prints the last created item first, and then prints everything else in order.

I am working on a version of this assignment for my computer science class. We are using the in-built PriorityQueue in Java. A Disk object can hold 1,000,000 KB of data and a disk has priority if it has the most free space.

In my solution, Disk 7 was created latest, and it is printed on top despite the lower priority. Does anyone know what might be causing this?

Here is my solution:

public static void findWorstFit(String fileName) throws FileNotFoundException {
    PriorityQueue<Disk> disks = new PriorityQueue<>();
    double totalSize = 0;

    // Process each file and add it to a disk
    Scanner fileScanner = new Scanner(new File(fileName));
    while(fileScanner.hasNextInt()) {
        int file = fileScanner.nextInt();
        if(disks.size() > 0 && disks.peek().freeSpace >= file)
            disks.peek().add(file);
        else
            disks.offer(new Disk(disks.size(), file));
        totalSize += file;
    }

    // Print all the disks
    System.out.println("Total size = " + totalSize/1000000 + " GB");
    System.out.println("Disks req'd = " + disks.size());
    while(!disks.isEmpty())
        System.out.println(disks.poll());
}

Here is the expected output:

Total size  = 6.580996 GB
Disks req'd = 8
5 325754: 347661 326585
0 227744: 420713 351543
7 224009: 383972 392019
4 190811: 324387 484802
6 142051: 340190 263485 254274
3 116563: 347560 204065 331812
2 109806: 396295 230973 262926
1  82266: 311011 286309 320414

And here is the actual output:

Total size  = 6.580996 GB
Disks req'd = 8
7 224009: 383972 392019
5 325754: 347661 326585
0 227744: 420713 351543
4 190811: 324387 484802
6 142051: 340190 263485 254274
3 116563: 347560 204065 331812
2 109806: 396295 230973 262926
1  82266: 311011 286309 320414

Body:
You don't provide the implementation of the Disk class. I presume this has a comparator so the natural ordering sorts the Disks in order of most free space to least free space.

The issue is really that you are modifying an element within the PriorityQueue - and expecting the queue to reorder the elements for you - but it has no concept that the elements have been changed.

A quick fix would be to remove the head of the queue each time you want to modify it and re-insert it into the queue.

i.e.

replace

        if(disks.size() > 0 && disks.peek().freeSpace >= file)
            disks.peek().add(file);
        else
            disks.offer(new Disk(disks.size(), file));

with

        if(disks.size() > 0 && disks.peek().freeSpace >= file) {
            Disk toChange = disks.poll();
            toChange.add(file);
            disks.offer(toChange);
        }
        else
            disks.offer(new Disk(disks.size(), file));

That would maintain the ordering of the elements within the disks queue.


问:
Deploy Scrapy Project with Streamlit
I have a scrapy spider that scrapes products information from amazon based on the product link.

I want to deploy this project with streamlit and take the product link as web input, and product information as output data on the web.

I don't know alot about deployment, so anyone can help me with that.

答: You can create a public repository on GitHub with streamlit and connect your account with 0auth. Then you can deploy it on the streamlit servers after signing in the streamlit website.</p>

Title: Deploy Scrapy Project with Streamlit


问:
ASP.NET / MVC 1.0 Components and Ajax controls - Grid - Calendar - Search?
Hello I'm rather new to developing with MVC and I'm looking to find as many Ajax controls that integrate seamlessly into my new MVC 1.0 ASP.Net application. Specifically, tree controls, searching, outlook calendaresque, and inline updating.</p>

答: I believe all the controls should work fine under MVC, it's still ASP.NET at the end of the day.</p>

OwnerDisplayName: Jukeman

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Lazarus


问:
What is the impact of not calling the arguments while calling a function
My question is about the difference between two ways to pass the the arguments of a function

for instance

```<code>function1(obj1, obj2, obj3, obj4, obj5)
</code>```

or

```<code>function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)
</code>```

Is there a rule/convention/document for that?

I can see at least 2 situations where the first way is not great

If we want to add a new argument, we are forced to add it at the end of the list, which may not great for the common sense (as I like to group arguments that goes together)

The arguments with default have to be put at the end of the list, otherwise you have to input it even if you use the default value.

Any ideas on that?

答:
Function arguments in R can be matched via position or by name and you as the person punching things into the keyboard are afforded some flexibility in how you decide to use or abuse that. One of the immediate benefits to using the named arguments is that you can change the order of the arguments within the function as you see fit. i.e.

```<code>function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)
</code>```

and

```<code>function1(arg5=obj5, arg4=obj4, arg3=obj3, arg2=obj2, arg1=obj1)
</code>```

will evaluate in the same fashion, while

```<code>function1(obj1, aobj2, obj3, obj4, obj5)
</code>```

and

```<code>function1(obj5, aobj4, obj3, obj2, obj1)
</code>```

will not. Function arguments can also be partially matched and are matched using the following criteria:

exact match for named argument

partial match for named argument

positional match

This can obviously lead to some unintended consequences if you aren't careful with the partial matching. I believe that if an argument is matched by name, it is "removed" from the positional search, though I can't find a specific reference for that at the moment. As a note of common use, I tend to see people use the positional matching for the first argument in a function, and then specify others that may be optional afterwords by name. Again, this is mostly personal convention and habit as far as I'm concerned.

ContentLicense: CC BY-SA 3.0

Body:
My question is about the difference between two ways to pass the the arguments of a function

for instance

function1(obj1, obj2, obj3, obj4, obj5)

or

function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)

Is there a rule/convention/document for that?

I can see at least 2 situations where the first way is not great

If we want to add a new argument, we are forced to add it at the end of the list, which may not great for the common sense (as I like to group arguments that goes together)

The arguments with default have to be put at the end of the list, otherwise you have to input it even if you use the default value.

Any ideas on that?

Body:
Function arguments in R can be matched via position or by name and you as the person punching things into the keyboard are afforded some flexibility in how you decide to use or abuse that. One of the immediate benefits to using the named arguments is that you can change the order of the arguments within the function as you see fit. i.e.

function1(arg1=obj1, arg2=obj2, arg3=obj3, arg4=obj4, arg5=obj5)

and

function1(arg5=obj5, arg4=obj4, arg3=obj3, arg2=obj2, arg1=obj1)

will evaluate in the same fashion, while

function1(obj1, aobj2, obj3, obj4, obj5)

and

function1(obj5, aobj4, obj3, obj2, obj1)

will not. Function arguments can also be partially matched and are matched using the following criteria:

exact match for named argument

partial match for named argument

positional match

This can obviously lead to some unintended consequences if you aren't careful with the partial matching. I believe that if an argument is matched by name, it is "removed" from the positional search, though I can't find a specific reference for that at the moment. As a note of common use, I tend to see people use the positional matching for the first argument in a function, and then specify others that may be optional afterwords by name. Again, this is mostly personal convention and habit as far as I'm concerned.


问:
How to update a single key value pair in an array of objects in react?
I am trying to update a single key value pair in an array of objets using React.

Here is the setup

An array of objects

const array = [
  {id:1,name:'Tyler',age:23},
  {id:2,name:'Lauren',age:28},
  {id:3,name:'Nico',age:14},
]
```
<p>Given an id and age, I want to be able to update the single object that matches the id. For example, given an id of 2 and age of 56, <code>{id:2,name:'Lauren',age:28}</code> should change to <code>{id:2,name:'Lauren',age:56}</code></p>
<h3>My approach</h3>
<p>I've set up useState to copy the array of object. However, I am struggling to filter out for the selected id, change the age, and return the updated array.</p>
<p>This is what I currently have:</p>
<pre class="lang-js prettyprint-override"><code>import { useState } from "react";

const array = [
  { id: 1, name: "Tyler", age: 23 },
  { id: 2, name: "Lauren", age: 28 },
  { id: 3, name: "Nico", age: 14 }
];

export default function App() {
  const [list, setList] = useState(array);

  const updateAge = (id = 2, age = 56) => {
    setList([...list, list.filter((item) => item.id === id)]);
  };

  return (
    <>
      <ul>
        {list.map((item) => {
          return (
            <li>
              {item.name} | {item.age}
            </li>
          );
        })}
      </ul>
      <button onClick={updateAge}>Update age</button>
    </>
  );
}

</code>```

Here is my codesandbox link

答:
You can update you array like this</p>
```<code>import { useState } from "react";
const array = [
  { id: 1, name: "Tyler", age: 23 },
  { id: 2, name: "Lauren", age: 28 },
  { id: 3, name: "Nico", age: 14 }
];

export default function App() {
  const [list, setList] = useState(array);

  const updateAge = (id = 2, age = 56) => {
    setList(list.map(l=>l.id==id?{...l,age:age}:l));
  };

  return (
    <>
      <ul>
        {list.map((item) => {
          return (
            <li>
              {item.name} | {item.age}
            </li>
          );
        })}
      </ul>
      <button onClick={updateAge}>Update age</button>
    </>
  );
}
</code>```

Body:
I am trying to update a single key value pair in an array of objets using React.

Here is the setup

An array of objects

const array = [
  {id:1,name:'Tyler',age:23},
  {id:2,name:'Lauren',age:28},
  {id:3,name:'Nico',age:14},
]

Given an id and age, I want to be able to update the single object that matches the id. For example, given an id of 2 and age of 56, {id:2,name:'Lauren',age:28} should change to {id:2,name:'Lauren',age:56}

My approach

I've set up useState to copy the array of object. However, I am struggling to filter out for the selected id, change the age, and return the updated array.

This is what I currently have:

import { useState } from "react";

const array = [
  { id: 1, name: "Tyler", age: 23 },
  { id: 2, name: "Lauren", age: 28 },
  { id: 3, name: "Nico", age: 14 }
];

export default function App() {
  const [list, setList] = useState(array);

  const updateAge = (id = 2, age = 56) => {
    setList([...list, list.filter((item) => item.id === id)]);
  };

  return (
    <>

        {list.map((item) => {
          return (

              {item.name} | {item.age}

          );
        })}

      <button onClick={updateAge}>Update age</button>
    </>
  );
}

Here is my codesandbox link

Body:
You can update you array like this

import { useState } from "react";
const array = [
  { id: 1, name: "Tyler", age: 23 },
  { id: 2, name: "Lauren", age: 28 },
  { id: 3, name: "Nico", age: 14 }
];

export default function App() {
  const [list, setList] = useState(array);

  const updateAge = (id = 2, age = 56) => {
    setList(list.map(l=>l.id==id?{...l,age:age}:l));
  };

  return (
    <>
      <ul>
        {list.map((item) => {
          return (
            <li>
              {item.name} | {item.age}
            </li>
          );
        })}
      </ul>
      <button onClick={updateAge}>Update age</button>
    </>
  );
}


问:
Combining two ffmpeg commands
At the moment, I managed to achieve my goal by issuing these two commands:

```<code>ffmpeg -y -f ogg -i pipe:0 -c:a libfdk_aac tmp.m4a
ffmpeg -y -i tmp.m4a -i ${PATH_DIR}cover.jpg -map 0 -map 1 -c copy -c:v:1 mpeg -disposition:v:0 attached_pic -metadata title="${title}" -metadata album="${album}" -metadata artist="${artist}" "${fname}"
</code>```

How to combine them into one command?

答:
As your first command is about the audio then this modified second command should work for you:</p>
```<code>ffmpeg -y -f ogg -i pipe:0 -i ${PATH_DIR}cover.jpg -map 0 -map 1 -c copy -c:a libfdk_aac -c:v:1 mpeg -disposition:v:0 attached_pic -metadata title="${title}" -metadata album="${album}" -metadata artist="${artist}" "${fname}"
</code>```

Title: Combining two ffmpeg commands

Body:
At the moment, I managed to achieve my goal by issuing these two commands:

ffmpeg -y -f ogg -i pipe:0 -c:a libfdk_aac tmp.m4a
ffmpeg -y -i tmp.m4a -i ${PATH_DIR}cover.jpg -map 0 -map 1 -c copy -c:v:1 mpeg -disposition:v:0 attached_pic -metadata title="${title}" -metadata album="${album}" -metadata artist="${artist}" "${fname}"

How to combine them into one command?

Body:
As your first command is about the audio then this modified second command should work for you:

ffmpeg -y -f ogg -i pipe:0 -i ${PATH_DIR}cover.jpg -map 0 -map 1 -c copy -c:a libfdk_aac -c:v:1 mpeg -disposition:v:0 attached_pic -metadata title="${title}" -metadata album="${album}" -metadata artist="${artist}" "${fname}"


问:
Using ShouldBeEquivalentTo and handling different names
I want to make a mapper test that maps a database model to a dto

In the database model there is

```<code>class Order
{
    long Id
}
</code>```

But on the Dto the same field is named

```<code>class OrderDto
{
    long OrderId
}
</code>```

Using ShouldBeEquivalentTo how do I tell FluentAssertions that these fields are the same, but the name is different?

答:
This should finally be possible in 6.5 release: </p>
```<code>orderDto.Should().BeEquivalentTo(order, options => options
    .WithMapping<OrderDto>(e => e.Id, s => s.OrderId));
</code>```

Body:
I want to make a mapper test that maps a database model to a dto

In the database model there is

class Order
{
    long Id
}

But on the Dto the same field is named

class OrderDto
{
    long OrderId
}

Using ShouldBeEquivalentTo how do I tell FluentAssertions that these fields are the same, but the name is different?

Body:
This should finally be possible in 6.5 release:

orderDto.Should().BeEquivalentTo(order, options => options
    .WithMapping<OrderDto>(e => e.Id, s => s.OrderId));


问:
Why can't I create an association with several fields?
I'm trying to create this association but VS tells me that cannot be possible.

答: Well, in your example, this would mean that: Range1ID, Range2ID, Range3ID and Range4ID all need to be equal (among themselves and to RangeID). If they are always equal, you don't need separate fields.


问:
How to Cut Incomplete Rows and Paste In Another Workbook with VBA?
I am cycling through all the Green Tabs in a workbook.  When I come to a row of data where there is no value in Column G, I select that row, cut it, and open another workbook entitled "Unpaid AR." In that workbook, I find the first unused row, and Paste.  Everything functions properly except for the Paste - nothing pastes, and I have tried several different techniques.  Any ideas what could be going wrong?</p>
```<code>Public Sub CutNPaste()
  Dim ws As Worksheet
  Dim ARRange As String
  Dim ARFilePath As String
  Dim ARcell As Range
  Dim CopyRange As String
  Dim i As Integer
  Dim varRange As String

  ARFilePath = "Unpaid AR.xlsx"

  For Each ws In ThisWorkbook.Worksheets
    ws.Activate
    If ws.Tab.ColorIndex = 10 Then  'If Tab is Green, Then...
      ReportRows = ActiveSheet.UsedRange.Rows.Count  'Get how many rows in the report
      Let ARRange = "G" & "2" & ":" & "G" & ReportRows 'Range to Inspect for Blanks
      i = 2

      For Each ARcell In Range(ARRange)
        Let CopyRange = "A" & i & ":" & "I" & i 'Set the copy range when blank is encountered
        If ARcell.Value = "" Then
          Range(CopyRange).Select
          Selection.Cut
          Workbooks.Open ARFilePath 'Open the Unpaid AR workbook
          Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select 'Find the first open row
          ActiveSheet.Paste 'This is where NOTHING happens
          Workbooks("Unpaid AR.xlsx").Close SaveChanges:=True 'Save and close destination wkbk
          Application.CutCopyMode = False
        End If
        i = i + 1
      Next ARcell
    End If
 Next ws

End Sub
</code>```

答:
i change a little bit...

```<code>Public Sub CutNPaste()
  Dim ws As Worksheet
  Dim ARRange As String
  Dim ARFilePath As String
  Dim ARcell As Range
  Dim CopyRange As Range
  Dim i As Integer
  Dim varRange As String
  Dim wkbTarget As Workbook
  Dim ReportRows As Long

  ARFilePath = ThisWorkbook.Path & "\Unpaid AR.xlsx"

  Set wkbTarget = Workbooks.Open(ARFilePath) 'Open the Unpaid AR workbook

  For Each ws In ThisWorkbook.Worksheets

    If ws.Tab.ColorIndex = 10 Then

      ReportRows = ws.UsedRange.Rows.Count

      For i = ReportRows To 2 Step -1

        Set CopyRange = ws.Range("A" & i & ":" & "I" & i)

        If ws.Cells(i, 7).Value = "" Then

          CopyRange.Cut Destination:=wkbTarget.Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)

          Application.CutCopyMode = False
        End If

      Next i
    End If
 Next ws

     wkbTarget.Close SaveChanges:=True 'Save and close destination wkbk

End Sub
</code>```

BR
Bernd

Body:
I am cycling through all the Green Tabs in a workbook.  When I come to a row of data where there is no value in Column G, I select that row, cut it, and open another workbook entitled "Unpaid AR." In that workbook, I find the first unused row, and Paste.  Everything functions properly except for the Paste - nothing pastes, and I have tried several different techniques.  Any ideas what could be going wrong?

Public Sub CutNPaste()
  Dim ws As Worksheet
  Dim ARRange As String
  Dim ARFilePath As String
  Dim ARcell As Range
  Dim CopyRange As String
  Dim i As Integer
  Dim varRange As String

  ARFilePath = "Unpaid AR.xlsx"

  For Each ws In ThisWorkbook.Worksheets
    ws.Activate
    If ws.Tab.ColorIndex = 10 Then  'If Tab is Green, Then...
      ReportRows = ActiveSheet.UsedRange.Rows.Count  'Get how many rows in the report
      Let ARRange = "G" & "2" & ":" & "G" & ReportRows 'Range to Inspect for Blanks
      i = 2

      For Each ARcell In Range(ARRange)
        Let CopyRange = "A" & i & ":" & "I" & i 'Set the copy range when blank is encountered
        If ARcell.Value = "" Then
          Range(CopyRange).Select
          Selection.Cut
          Workbooks.Open ARFilePath 'Open the Unpaid AR workbook
          Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select 'Find the first open row
          ActiveSheet.Paste 'This is where NOTHING happens
          Workbooks("Unpaid AR.xlsx").Close SaveChanges:=True 'Save and close destination wkbk
          Application.CutCopyMode = False
        End If
        i = i + 1
      Next ARcell
    End If
 Next ws

End Sub

Body:
i change a little bit...

Public Sub CutNPaste()
  Dim ws As Worksheet
  Dim ARRange As String
  Dim ARFilePath As String
  Dim ARcell As Range
  Dim CopyRange As Range
  Dim i As Integer
  Dim varRange As String
  Dim wkbTarget As Workbook
  Dim ReportRows As Long

  ARFilePath = ThisWorkbook.Path & "\Unpaid AR.xlsx"

  Set wkbTarget = Workbooks.Open(ARFilePath) 'Open the Unpaid AR workbook

  For Each ws In ThisWorkbook.Worksheets

    If ws.Tab.ColorIndex = 10 Then

      ReportRows = ws.UsedRange.Rows.Count

      For i = ReportRows To 2 Step -1

        Set CopyRange = ws.Range("A" & i & ":" & "I" & i)

        If ws.Cells(i, 7).Value = "" Then

          CopyRange.Cut Destination:=wkbTarget.Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)

          Application.CutCopyMode = False
        End If

      Next i
    End If
 Next ws

     wkbTarget.Close SaveChanges:=True 'Save and close destination wkbk

End Sub

BR
Bernd


问:
How to use dependentRequired with relative reference in JSON schema
I have below JSON schema in my app, and i am using NewtonSoft JSON schema validation library to validate user JSON against my schema.

The rules that i need to set are -

if user sets property2 in the JSON then property3 should also exist and subProperty2 should also exist underneath property3.

if user does not set property2 then property3 is not required.

I used dependentRequired for this with relative reference using period(.) but that did not work with NewtonSoft package. I tried in 2 different ways, both without expected result.

{
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "property1": {
      ...
    },
    "property2": {
      ...
    },
    "property3": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "subProperty1": {
          ...
        },
        "subProperty2": {
          ...
        },
      }
    }
  },
   "required": [
    "property1"
  ]
}
```
<p>//try 1</p>
<pre class="lang-json prettyprint-override"><code>  "dependentRequired": {
    "property2": [ "property3.subProperty2" ]
  },
</code>```

//try 2

  "dependentRequired": {
    "property2": {
      "required": [ "property3" ],
      "property3": {
        "required": [ "subProperty2" ]
      }
    }
  }
```

Can someone help me with this?

答:
The dot notation used in the first try is not supported in JSON Schema.

The second try is the right idea, but since you are using a schema, you need to use dependentSchemas instead of dependentRequired. Also, you are missing the properties keyword to make that a valid schema.

  "dependentSchemas": {
    "property2": {
      "required": [ "property3" ],
      "properties": {
        "property3": {
          "required": [ "subProperty2" ]
        }
      }
    }
  },
```

Body:
I have below JSON schema in my app, and i am using NewtonSoft JSON schema validation library to validate user JSON against my schema.

The rules that i need to set are -

if user sets property2 in the JSON then property3 should also exist and subProperty2 should also exist underneath property3.

if user does not set property2 then property3 is not required.

I used dependentRequired for this with relative reference using period(.) but that did not work with NewtonSoft package. I tried in 2 different ways, both without expected result.

{
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "property1": {
      ...
    },
    "property2": {
      ...
    },
    "property3": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "subProperty1": {
          ...
        },
        "subProperty2": {
          ...
        },
      }
    }
  },
   "required": [
    "property1"
  ]
}

//try 1

  "dependentRequired": {
    "property2": [ "property3.subProperty2" ]
  },

//try 2

  "dependentRequired": {
    "property2": {
      "required": [ "property3" ],
      "property3": {
        "required": [ "subProperty2" ]
      }
    }
  }

Can someone help me with this?


问:
PHP check if point is inside a circle
I have codes below

circle.php

```<code>class point{
    private $x;
    private $y;

    function __construct($x, $y){
        $this->x = $x;
        $this->y = $y;
    }

    public function getX(){
        return $this->x;
    }

    public function getY(){
        return $this->y;
    }

}

class circle{
    private $x_circle;
    private $y_circle;
    private $radius;

    function __construct($x_circle, $y_circle, $radius){
        $this->x_circle = $x_circle;
        $this->y_circle = $y_circle;
        $this->radius = $radius;
    }

    public function getCircleX(){
        return $this->x_circle;
    }

    public function getCircleY(){
        return $this->y_circle;
    }

    public function getRadius(){
        return $this->radius;
    }

    public function checkIfInside(){
        if(pow(getX() - getCircleX(), 2) + pow(getY() - getCircleY(), 2) < pow(getRadius(),2)){
            return true;
        } else {
            return false;
        }

    }
}
</code>```

index.php

```<code>include 'circle.php';

$point= new point(3, 4);
$circle= new circle(10, 10, 100);
$circle->checkIfInside();
</code>```

I try to check if point is inside a circle. With point class we declare point coordinates(x,y). With circle class we declare the coordinates of circle(x,y) and radius. But I get this error: Uncaught Error: Call to undefined function getX()

答:
getX() is not a global function, but a method of the point class. Methods must be called as $object->method(). (While inside a method such as checkIfInside(), the reference to the current object is $this.)

The same applies to the other methods you are calling in the statement below:

```<code>if(pow(getX() - getCircleX(), 2) + pow(getY() - getCircleY(), 2) < pow(getRadius(),2)){
</code>```

Title: PHP check if point is inside a circle

Body:
I have codes below

circle.php

class point{
    private $x;
    private $y;

    function __construct($x, $y){
        $this->x = $x;
        $this->y = $y;
    }

    public function getX(){
        return $this->x;
    }

    public function getY(){
        return $this->y;
    }

}

class circle{
    private $x_circle;
    private $y_circle;
    private $radius;

    function __construct($x_circle, $y_circle, $radius){
        $this->x_circle = $x_circle;
        $this->y_circle = $y_circle;
        $this->radius = $radius;
    }

    public function getCircleX(){
        return $this->x_circle;
    }

    public function getCircleY(){
        return $this->y_circle;
    }

    public function getRadius(){
        return $this->radius;
    }

    public function checkIfInside(){
        if(pow(getX() - getCircleX(), 2) + pow(getY() - getCircleY(), 2) < pow(getRadius(),2)){
            return true;
        } else {
            return false;
        }

    }
}

index.php

include 'circle.php';

$point= new point(3, 4);
$circle= new circle(10, 10, 100);
$circle->checkIfInside();

I try to check if point is inside a circle. With point class we declare point coordinates(x,y). With circle class we declare the coordinates of circle(x,y) and radius. But I get this error: Uncaught Error: Call to undefined function getX()

Body:
getX() is not a global function, but a method of the point class. Methods must be called as $object->method(). (While inside a method such as checkIfInside(), the reference to the current object is $this.)

The same applies to the other methods you are calling in the statement below:

if(pow(getX() - getCircleX(), 2) + pow(getY() - getCircleY(), 2) < pow(getRadius(),2)){


答:
You can use the map function to produce a new array to set the state with.

```<code>const updateAge = (id, age) => {
    console.log(id, age);
    setList(
      list.map((item) => {
        if (item.id === id) {
          return { ...item, age };
        } else {
          return item;
        }
      })
    );
  };
</code>```

If the id matches, it will merge the new age, otherwise it will return the item unchanged.

Note that it will only produce new objects for updated age, the rest will be the same references. That is to say it will be a new array, but most objects (except the changed one) will be the same. If you want new objects you can return { ...item } in the else clause as well.

In this particular case React will only be concerned that you set the state with new array.

Here's the sandbox

Title: How to update a single key value pair in an array of objects in react?

Body:
You can use the map function to produce a new array to set the state with.

const updateAge = (id, age) => {
    console.log(id, age);
    setList(
      list.map((item) => {
        if (item.id === id) {
          return { ...item, age };
        } else {
          return item;
        }
      })
    );
  };

If the id matches, it will merge the new age, otherwise it will return the item unchanged.

Note that it will only produce new objects for updated age, the rest will be the same references. That is to say it will be a new array, but most objects (except the changed one) will be the same. If you want new objects you can return { ...item } in the else clause as well.

In this particular case React will only be concerned that you set the state with new array.

Here's the sandbox


问:
T-SQL - batch delimiter required
I am trying to build Visual Studio solution for Azure SQL Database.

I have SQL script with CREATE TABLE and its extended attributes:

create table schema.table_name (
   table_name_Key integer not null,
   constraint PK_table_Name primary key (table_Name_Key, Some_Column)
)
go

if exists (select 1 from  sys.extended_properties
           where major_id = object_id('table_name') and minor_id = 0)
begin
   execute sp_dropextendedproperty 'MS_Description',
   'user', 'schema', 'table', 'table_name' ;
end

execute sp_addextendedproperty 'MS_Description',
   'This table will be used for ....',
   'user', 'schema', 'table', 'table_name';
go

if exists (select 1 from sys.extended_properties p
           where p.major_id = object_id('table_name')
             and p.minor_id = (select c.column_id from sys.columns c
                               where c.object_id = p.major_id
                                 and c.name = 'table_name_Key'))
begin
   execute sp_dropextendedproperty 'MS_Description',
   'user', 'schema', 'table', 'table_name', 'column', 'table_name_Key';
end

execute sp_addextendedproperty 'MS_Description',
   'Primary Key of table_name table',
   'user', 'schema', 'table', 'table_name', 'column', 'table_name_Key';
go
```

I am still getting errors when building that I am missing batch delimiter:

Error SQL71006: Only one statement is allowed per batch. A batch separator, such as 'GO', might be required between statements.

What am I missing and where? I already tried to add go after end but still error.

答:
If you are using SQL Server Data Tools (SSDT) database projects in Visual Studio then you need to think about things differently (and work through some of the tutorials, or this one).

Basically each object is held in a single script and you do not have to write conditional statements (like IF EXISTS ...).  You simply define the object as you want it and SqlPackage.exe works out at deploy-time what the definition should be.

A simple table with one extended property:

```<code>CREATE TABLE [testSchema].[table_name] (
    [table_name_Key] INT          NOT NULL,
    [Some_Column]    VARCHAR (10) NOT NULL,
    CONSTRAINT [PK_table_Name] PRIMARY KEY CLUSTERED ([table_name_Key] ASC, [Some_Column] ASC)
);

GO
EXECUTE sp_addextendedproperty @name = N'Caption', @value = 'Some_column is a required column.', @level0type = N'SCHEMA', @level0name = N'testSchema', @level1type = N'TABLE', @level1name = N'table_name', @level2type = N'COLUMN', @level2name = N'Some_Column';
</code>```

Define your table in a similar manner to above, press Build and work through the errors.

Title: T-SQL - batch delimiter required

Body:
I am trying to build Visual Studio solution for Azure SQL Database.

I have SQL script with CREATE TABLE and its extended attributes:

create table schema.table_name (
   table_name_Key integer not null,
   constraint PK_table_Name primary key (table_Name_Key, Some_Column)
)
go

if exists (select 1 from  sys.extended_properties
           where major_id = object_id('table_name') and minor_id = 0)
begin
   execute sp_dropextendedproperty 'MS_Description',
   'user', 'schema', 'table', 'table_name' ;
end

execute sp_addextendedproperty 'MS_Description',
   'This table will be used for ....',
   'user', 'schema', 'table', 'table_name';
go

if exists (select 1 from sys.extended_properties p
           where p.major_id = object_id('table_name')
             and p.minor_id = (select c.column_id from sys.columns c
                               where c.object_id = p.major_id
                                 and c.name = 'table_name_Key'))
begin
   execute sp_dropextendedproperty 'MS_Description',
   'user', 'schema', 'table', 'table_name', 'column', 'table_name_Key';
end

execute sp_addextendedproperty 'MS_Description',
   'Primary Key of table_name table',
   'user', 'schema', 'table', 'table_name', 'column', 'table_name_Key';
go

I am still getting errors when building that I am missing batch delimiter:

Error SQL71006: Only one statement is allowed per batch. A batch separator, such as 'GO', might be required between statements.

What am I missing and where? I already tried to add go after end but still error.

Body:
If you are using SQL Server Data Tools (SSDT) database projects in Visual Studio then you need to think about things differently (and work through some of the tutorials, or this one).

Basically each object is held in a single script and you do not have to write conditional statements (like IF EXISTS ...).  You simply define the object as you want it and SqlPackage.exe works out at deploy-time what the definition should be.

A simple table with one extended property:

CREATE TABLE [testSchema].[table_name] (
    [table_name_Key] INT          NOT NULL,
    [Some_Column]    VARCHAR (10) NOT NULL,
    CONSTRAINT [PK_table_Name] PRIMARY KEY CLUSTERED ([table_name_Key] ASC, [Some_Column] ASC)
);

GO
EXECUTE sp_addextendedproperty @name = N'Caption', @value = 'Some_column is a required column.', @level0type = N'SCHEMA', @level0name = N'testSchema', @level1type = N'TABLE', @level1name = N'table_name', @level2type = N'COLUMN', @level2name = N'Some_Column';

Define your table in a similar manner to above, press Build and work through the errors.


问:
String Output in Real-Mode by using LODS instruction
I'm need to write function, which output a string in real-mode.
There is that code:

```<code>;; ds:si - string address, cx - length of string
   cld
putc:
   lods
   mov ah, 0x0E
   xor bh, bh
   int 0x10          ;; display character, advancing cursor and scrolling screen
                     ;; as necessary
   loop putc
</code>```

But it output only first character few (defined by the CX register) times, a.e. the SI register don't increase.
Is where a error?

答:
lods isn't a valid instruction mnemonic; you probably mean lodsb.

On my assembler (nasm), a token that isn't a valid mnemonic gets parsed as a label instead, and so no code is emitted.  Thus your lods is effectively a no-op, so no wonder SI doesn't increment.  (The assembler does give a warning though, does yours?)

Body:
I'm need to write function, which output a string in real-mode.
There is that code:

;; ds:si - string address, cx - length of string
   cld
putc:
   lods
   mov ah, 0x0E
   xor bh, bh
   int 0x10          ;; display character, advancing cursor and scrolling screen
                     ;; as necessary
   loop putc

But it output only first character few (defined by the CX register) times, a.e. the SI register don't increase.
Is where a error?


问:
Check if List contains object without fields
I have an API response that can respond with an array like this:

```<code>[
    {
        "id": 1,
        "title": "Warning"
    },
    {
        "id": 2,
        "title": "Warning"
    }
]
</code>```

sometimes it can respond just empty array

```<code>[]
</code>```

in my case i created a class for this object.
Something like this:

```<code>class Warning:
    def __init__(self, data: Dict):
        if bool(data):
            self.id: int = data["id"]
            self.title: str = data["title"]
        else:
            pass

if __name__ == '__main__':
    data = {
        "id": 123455,
        "title": "Warning"
    }
    empty_data = {}
    object1: List[Warning] = [Warning(data)]
    object2: List[Warning] = [Warning(empty_data)]
    if object1:
        print("we have a warnings")
    if object2:
        print("we don't have warnings")
</code>```

I can't understand, how can I check if i get List of Object with empty fields like object2?

答:
I would suggest looking at the __bool__  class method which enables you to determine the boolean value of a python class.

However, you will also need to decide what the boolean value of the list should be e.g. should bool([Warning(empty_data), Warning(data)]) return False or True?

Body:
I have an API response that can respond with an array like this:

[
    {
        "id": 1,
        "title": "Warning"
    },
    {
        "id": 2,
        "title": "Warning"
    }
]

sometimes it can respond just empty array

[]

in my case i created a class for this object.
Something like this:

class Warning:
    def __init__(self, data: Dict):
        if bool(data):
            self.id: int = data["id"]
            self.title: str = data["title"]
        else:
            pass

if __name__ == '__main__':
    data = {
        "id": 123455,
        "title": "Warning"
    }
    empty_data = {}
    object1: List[Warning] = [Warning(data)]
    object2: List[Warning] = [Warning(empty_data)]
    if object1:
        print("we have a warnings")
    if object2:
        print("we don't have warnings")

I can't understand, how can I check if i get List of Object with empty fields like object2?


问:
PHP Regex Match those which start with Capital letter
It sounds pretty simple but I cant figure this out, please help me out.

So... I have file with following data:

```<code>Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..
</code>```

I need to match only the whole part that starts with "Name:" ... NOT "Surname:" ...

Here is what I am using right now to match it:

```<code>/Name(:)(.*)/i
</code>```

It will match both but I need just Name: ...

Please dont suggest any other way of finding, just please help me out with regex to work the way I described.

答:
The ^ character will match the start of the line:

```<code>/^Name(:)(.*)/
</code>```

Note, I've removed the i modifier, which makes your search case-insensitive.

Sample:

```<code>% cat ./test.php
#!/usr/bin/env php
<?php

$regex = '/^Name(:)(.*)/';

$data = <<<EOD
Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..
EOD;

foreach (explode("\n", $data, -1) as $line)
{
    if (preg_match($regex, $line, $matches))
    {
        printf("Found %s\n", $matches[2]);
    }
}

?>

% ./test.php
Found  Santi
Found  Rob
</code>```

Body:
It sounds pretty simple but I cant figure this out, please help me out.

So... I have file with following data:

Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..

I need to match only the whole part that starts with "Name:" ... NOT "Surname:" ...

Here is what I am using right now to match it:

/Name(:)(.*)/i

It will match both but I need just Name: ...

Please dont suggest any other way of finding, just please help me out with regex to work the way I described.

Body:
The ^ character will match the start of the line:

/^Name(:)(.*)/

Note, I've removed the i modifier, which makes your search case-insensitive.

Sample:

% cat ./test.php
#!/usr/bin/env php
<?php

$regex = '/^Name(:)(.*)/';

$data = <<<EOD
Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..
EOD;

foreach (explode("\n", $data, -1) as $line)
{
    if (preg_match($regex, $line, $matches))
    {
        printf("Found %s\n", $matches[2]);
    }
}

?>

% ./test.php
Found  Santi
Found  Rob


问:
Disabling search functionality for drop-down menu default selection
I am trying to use the code below so website users have the option to select which database they'd like to search from a list of drop-down menu options. The code works just fine, but users are able to submit a search when the drop-down menu is set to the default selection which results in an error. I only want users to be able to submit a search if they select Option 1, Option 2, etc. from the drop-down menu.

Is there a way to accomplish this?  Thanks in advance!

<form name="searchform" onSubmit="return dosearch();">
Search:
<select name="sengines">
<option value="" disabled selected>Select an option by category</option>
<option value="">Option 1</option>
<option value="">Option 2</option>
<option value="">Option 3</option>
<option value="">Option 4</option>
</select>
For:
<input type="text" name="searchterms">
<input type="submit" name="SearchSubmit" value="Search">
</form>
```

答:
Step 1

First, you should assign different values to each dropdown options. Right now, all options have the same value "", so you can not differentiate among selected options.

<option value="option_0" disabled selected>Select an option by category</option>
<option value="option_1">Option 1</option>
<option value="option_2">Option 2</option>
<option value="option_3">Option 3</option>
<option value="option_4">Option 4</option>
```
<h2>Step 2</h2>
<p>In <code>dosearch()</code> function, check if the selected option is different than <code>option_0</code>. If it is, then perform the search. If it is not, alert the user that he should select the option from dropdown first.</p>
<pre class="lang-js prettyprint-override"><code>function dosearch() {
  const sf = document.searchform;
  const selected_option = sf.sengines.options[sf.sengines.selectedIndex].value;
  if (selected_option === "option_0") {
    alert('Choose an option from dropdown first.')
  } else {
    const submitto = sf.sengines.options[sf.sengines.selectedIndex].value + escape(sf.searchterms.value);
    window.location.href = submitto;
    return false;
  }
}
</code>```

Working example

Body:
Step 1

First, you should assign different values to each dropdown options. Right now, all options have the same value "", so you can not differentiate among selected options.

<option value="option_0" disabled selected>Select an option by category</option>
<option value="option_1">Option 1</option>
<option value="option_2">Option 2</option>
<option value="option_3">Option 3</option>
<option value="option_4">Option 4</option>

Step 2

In dosearch() function, check if the selected option is different than option_0. If it is, then perform the search. If it is not, alert the user that he should select the option from dropdown first.

function dosearch() {
  const sf = document.searchform;
  const selected_option = sf.sengines.options[sf.sengines.selectedIndex].value;
  if (selected_option === "option_0") {
    alert('Choose an option from dropdown first.')
  } else {
    const submitto = sf.sengines.options[sf.sengines.selectedIndex].value + escape(sf.searchterms.value);
    window.location.href = submitto;
    return false;
  }
}

Working example


问:
How to consume the latest records from the topic using Spring Cloud Stream?
I have a Kafka Streams processor that consumes three topics and tries to merge (Joining operation) them on the key. After joining successfully, it does some aggregation and then pushes results to the target topic.
After the application runs for the first time, it tries to consume all data from those topics. Two of those topics use like lookup table, which means that I need to consume all data from the beginning. But one of those topics is my main topic. So I need to consume from the latest. But my application consumes all Kafka topics from the beginning. So I want to consume two topics from the start and one from the latest.
I'm using Spring Cloud Stream, Kafka Streams Binder. Here are my configs and some code snippets;

Application.yaml :

```<code>spring.cloud.stream.function.definition: processName;
spring.cloud.stream.kafka.streams.binder.functions.processName.applicationId: myappId
spring.cloud.stream.bindings.processName-in-0.destination: mainTopic
spring.cloud.stream.bindings.processName-in-0.consumer.group: mainTopic-cg
spring.cloud.stream.bindings.processName-in-0.consumer.startOffset: latest
spring.cloud.stream.bindings.processName-in-1.destination: secondTopic
spring.cloud.stream.bindings.processName-in-1.consumer.group: secondTopic-cg
spring.cloud.stream.bindings.processName-in-1.consumer.startOffset: earliest
spring.cloud.stream.bindings.processName-in-2.destination: thirdTopic
spring.cloud.stream.bindings.processName-in-2.consumer.group: thirdTopic-cg
spring.cloud.stream.bindings.processName-in-2.consumer.startOffset: earliest
spring.cloud.stream.bindings.processName-out-0.destination: otputTopics

spring.cloud.stream.kafka.streams.binder.replication-factor: 1
spring.cloud.stream.kafka.streams.binder.configuration.commit.interval.ms: 10000
spring.cloud.stream.kafka.streams.binder.configuration.state.dir: state-store
</code>```

Streams processor:

```<code>public Function<KStream<String, MainTopic>,
        Function<KTable<String, SecondTopic>,
                Function<KTable<String, ThirdTopic>,
                        KStream<String, OutputTopic>>>> processName(){
    return mainTopicKStream -> (
            secondTopicTable -> (
                    thirdTopicKTable -> (
                            aggregateOperations.AggregateByAmount(
                                    joinOperations.JoinSecondThirdTopic(mainTopicKStream ,secondTopicTable ,thirdTopicKTable )
                                            .filter((k,v) -> v.IsOk() != 4)
                                            .groupByKey(Grouped.with(AppSerdes.String(), AppSerdes.OutputTopic()))
                                    , TimeWindows.of(Duration.ofMinutes(1)).advanceBy(Duration.ofMinutes(1))
                            ).toStream()
                    )
            ));
}
</code>```

答: A couple of points. When you have a Kafka Streams application using Spring Cloud Stream binder, you do not need to set group information on the bindings, just your applicationId setup is sufficient. Therefore, I suggest removing those 3 group properties from your configuration. Another thing is that any consumer specific binding properties when using Kafka streams binder needs to be set under spring.cloud.stream.kafka.streams.bindings.<binding-name>.consumer.... This is mentioned in this section of the docs. Please change your startOffset configuration accordingly. Also, look at the same section of the docs for an explanation of the semantics for using startOffset in Kafka Streams binder. Basically, the start offset property is honored only when you start the application for the first time. By default it is earliest when there are no committed offsets, but you can override to latest using the property. You can materialize the incoming KTables as state stores and thus have access to all the lookup data.

Body:
I have a Kafka Streams processor that consumes three topics and tries to merge (Joining operation) them on the key. After joining successfully, it does some aggregation and then pushes results to the target topic.
After the application runs for the first time, it tries to consume all data from those topics. Two of those topics use like lookup table, which means that I need to consume all data from the beginning. But one of those topics is my main topic. So I need to consume from the latest. But my application consumes all Kafka topics from the beginning. So I want to consume two topics from the start and one from the latest.
I'm using Spring Cloud Stream, Kafka Streams Binder. Here are my configs and some code snippets;

Application.yaml :

spring.cloud.stream.function.definition: processName;
spring.cloud.stream.kafka.streams.binder.functions.processName.applicationId: myappId
spring.cloud.stream.bindings.processName-in-0.destination: mainTopic
spring.cloud.stream.bindings.processName-in-0.consumer.group: mainTopic-cg
spring.cloud.stream.bindings.processName-in-0.consumer.startOffset: latest
spring.cloud.stream.bindings.processName-in-1.destination: secondTopic
spring.cloud.stream.bindings.processName-in-1.consumer.group: secondTopic-cg
spring.cloud.stream.bindings.processName-in-1.consumer.startOffset: earliest
spring.cloud.stream.bindings.processName-in-2.destination: thirdTopic
spring.cloud.stream.bindings.processName-in-2.consumer.group: thirdTopic-cg
spring.cloud.stream.bindings.processName-in-2.consumer.startOffset: earliest
spring.cloud.stream.bindings.processName-out-0.destination: otputTopics

spring.cloud.stream.kafka.streams.binder.replication-factor: 1
spring.cloud.stream.kafka.streams.binder.configuration.commit.interval.ms: 10000
spring.cloud.stream.kafka.streams.binder.configuration.state.dir: state-store

Streams processor:

public Function<KStream<String, MainTopic>,
        Function<KTable<String, SecondTopic>,
                Function<KTable<String, ThirdTopic>,
                        KStream<String, OutputTopic>>>> processName(){
    return mainTopicKStream -> (
            secondTopicTable -> (
                    thirdTopicKTable -> (
                            aggregateOperations.AggregateByAmount(
                                    joinOperations.JoinSecondThirdTopic(mainTopicKStream ,secondTopicTable ,thirdTopicKTable )
                                            .filter((k,v) -> v.IsOk() != 4)
                                            .groupByKey(Grouped.with(AppSerdes.String(), AppSerdes.OutputTopic()))
                                    , TimeWindows.of(Duration.ofMinutes(1)).advanceBy(Duration.ofMinutes(1))
                            ).toStream()
                    )
            ));
}


问:
PostgreSQL use NULL column or empty - effect on index
I want to create a table for my users. username is NULL by default ... also user first name and last name but i have 2 implementions of my users table and i want to know which one is better... i must use NULL for these columns (username, first_name, last_name, ...) or all columns be NOT NULL
and just use '' for those empty columns ? I want to know that using NULL is better or keep the tables NOT NULL and just use empty string '' ?

Also for indexing, which one is better ?

Way 1 (All NOT NULL with empty string)

```<code>CREATE TABLE "user"(
  "id" serial NOT NULL,
  "username" character varying(16) NOT NULL DEFAULT '',
  "first_name" character varying(32) NOT NULL DEFAULT '',
  "last_name" character varying(32) NOT NULL DEFAULT '',
);

CREATE INDEX "user_username_idx"
    ON "username" USING hash ("username")
    WHERE "username" <> '';

CREATE INDEX "user_first_name_idx"
    ON "first_name" USING gin ("first_name" gin_trgm_ops)
    WHERE "first_name" <> '';

CREATE INDEX "user_last_name_idx"
    ON "last_name" USING gin ("last_name" gin_trgm_ops)
    WHERE "last_name" <> '';
</code>```

Way 2 (Using NULL)

```<code>CREATE TABLE "user"(
  "id" serial NOT NULL,
  "username" character varying(16) DEFAULT NULL,
  "first_name" character varying(32) DEFAULT NULL,
  "last_name" character varying(32) DEFAULT NULL,
);

CREATE INDEX "user_username_idx"
    ON "username" USING hash ("username");

CREATE INDEX "user_first_name_idx"
    ON "first_name" USING gin ("first_name" gin_trgm_ops);

CREATE INDEX "user_last_name_idx"
    ON "last_name" USING gin ("last_name" gin_trgm_ops);
</code>```

Which way is better for both storage usage or index performance and ... ??

答:
Performance and storage wise it won't matter much.

Usually null is used when there is no data available and an empty string is used when there is data, but it is just empty.

If you want to be efficient on storage and performance it would be worthwhile to have a look at your indexes, because those also come with drawbacks:

An index costs disk space.

An index needs to be updated each time you write something to this table.

An index is basically a copy of your data.

I would advise to only add an index on a column if you really need it.

Body:
I want to create a table for my users. username is NULL by default ... also user first name and last name but i have 2 implementions of my users table and i want to know which one is better... i must use NULL for these columns (username, first_name, last_name, ...) or all columns be NOT NULL
and just use '' for those empty columns ? I want to know that using NULL is better or keep the tables NOT NULL and just use empty string '' ?

Also for indexing, which one is better ?

Way 1 (All NOT NULL with empty string)

CREATE TABLE "user"(
  "id" serial NOT NULL,
  "username" character varying(16) NOT NULL DEFAULT '',
  "first_name" character varying(32) NOT NULL DEFAULT '',
  "last_name" character varying(32) NOT NULL DEFAULT '',
);

CREATE INDEX "user_username_idx"
    ON "username" USING hash ("username")
    WHERE "username" <> '';

CREATE INDEX "user_first_name_idx"
    ON "first_name" USING gin ("first_name" gin_trgm_ops)
    WHERE "first_name" <> '';

CREATE INDEX "user_last_name_idx"
    ON "last_name" USING gin ("last_name" gin_trgm_ops)
    WHERE "last_name" <> '';

Way 2 (Using NULL)

CREATE TABLE "user"(
  "id" serial NOT NULL,
  "username" character varying(16) DEFAULT NULL,
  "first_name" character varying(32) DEFAULT NULL,
  "last_name" character varying(32) DEFAULT NULL,
);

CREATE INDEX "user_username_idx"
    ON "username" USING hash ("username");

CREATE INDEX "user_first_name_idx"
    ON "first_name" USING gin ("first_name" gin_trgm_ops);

CREATE INDEX "user_last_name_idx"
    ON "last_name" USING gin ("last_name" gin_trgm_ops);

Which way is better for both storage usage or index performance and ... ??


问:
Azure Data Factory V2: Optional parameters
I'm using ADFv2 and I would like to use some optional parameters defined at the dataset level. I didn't found if that can be achieved.

If I define a parameter in the dataset (after defining a parameter at the pipeline level and connecting the two so the pipeline passes the value to the parameter at the dataset level) when I run the pipeline manually and don't specify a value I get the error

```<code>No value provided for Parameter 'parameter'
</code>```

答:
Instead of @coalesce you can use ? like @dataset()?.fileName if empty return null.
"defaultValue": you can fill @null or [] or better @''. Data Factory and Synapse Analytics cross pass parameters need some input to validate pipeline.

Null Values Sample

If Null return null

Body:
I'm using ADFv2 and I would like to use some optional parameters defined at the dataset level. I didn't found if that can be achieved.

If I define a parameter in the dataset (after defining a parameter at the pipeline level and connecting the two so the pipeline passes the value to the parameter at the dataset level) when I run the pipeline manually and don't specify a value I get the error

No value provided for Parameter 'parameter'


答:
Use data[np.where(data.OType.str.contains("YSOc"))]

This filters the original array by the indices given by the where function.

Title: Numpy where but keep original data that holds true

Body:
I have an array that I'm using np.where on. However, the output of the conditional statement just return the index of the true values.

Here's the statement I'm using:

data = np.where(data.OType.str.contains("YSOc"))

Input data

        Region     RAJ2000    DEJ2000                OType
0       LUP_III  242.588882 -38.644272                 Zero
1       LUP_III  242.588882 -39.302551                  two
2       LUP_III  242.588882 -39.377029                 star
3       LUP_III  242.595749 -38.762226                  one
4       LUP_III  242.602203 -39.317276                  two
        ...         ...        ...                  ...
582347  LUP_III  242.174133 -39.026955  YSOc_star+dust(MP1)
582348  LUP_III  242.178635 -39.104069  YSOc_star+dust(IR4)
582349  LUP_III  242.199524 -38.833614  YSOc_star+dust(IR4)
582350  LUP_III  242.205811 -39.094246  YSOc_star+dust(IR2)
582351  LUP_III  242.214279 -39.091789  YSOc_star+dust(IR2)

Output

(array([  4350,   5726,   6432,   9324,  13815,  14139,  18445,  29680,
        32350,  37842,  37956,  39458,  40384,  42086,  42241,  70026,
        87998,  95434,  95680, 100641, 140513, 144178, 158947, 161837,
       184541, 187837, 198310, 215526, 218879, 222999, 230776, 232013,
       233383, 235072, 251165, 259407, 267365, 268906, 269205, 286646,
       290633, 291358, 313746, 313779, 315215, 329447, 330986, 336783,
       336831, 339249, 341296, 348079, 351279, 351764, 353540, 356300,
       357192, 363877, 379226, 385232, 385635, 386531, 388968, 389570,
       397586, 400390, 402026, 436435, 438384, 439781, 443509, 447030,
       447881, 459637, 459906, 460051, 460722, 461185, 461459, 461556,
       461655, 461993, 465299, 465743, 466993, 467071, 468263, 469951,
       470610, 471196, 472743, 475490, 475665, 476385, 478243, 478549,
       478599, 478998, 484449, 485657, 486718, 486820, 486851, 487030,
       487446, 489547, 501403, 502071, 506799, 507159, 510826, 511213,
       512757, 513549, 514043, 514117, 514189, 514353, 514611, 514672,
       518171, 518276, 519617, 522213, 532190, 538127, 542022, 542202,
       542283, 542368, 547522, 547810, 548793, 552908, 554167, 557280,
       559775, 561043, 561541, 562073, 562375, 562401, 562634, 562699,
       562928, 562958, 564007, 564567, 567201, 568651, 570026, 573017,
       579175, 580137, 580332, 580402, 580473, 581081, 582273, 582274,
       582275, 582276, 582277, 582278, 582279, 582280, 582281, 582282,
       582283, 582284, 582285, 582286, 582287, 582288, 582289, 582290,
       582291, 582292, 582293, 582294, 582295, 582296, 582297, 582298,
       582299, 582300, 582301, 582302, 582303, 582304, 582305, 582306,
       582307, 582308, 582309, 582310, 582311, 582312, 582313, 582314,
       582315, 582316, 582317, 582318, 582319, 582320, 582321, 582322,
       582323, 582324, 582325, 582326, 582327, 582328, 582329, 582330,
       582331, 582332, 582333, 582334, 582335, 582336, 582337, 582338,
       582339, 582340, 582341, 582342, 582343, 582344, 582345, 582346,
       582347, 582348, 582349, 582350, 582351]),)

How do I make the output return the values from the original array that is returned from the statement rather than their indexes.


问:
React route to a specific product details page from a product page
I have a product page, where if the user clicks on a specific product card, it will redirect the user to a new page where that specific product details will be displayed only. However, in my code, even after redirecting it to the details page, it still shows the entire product list on that page. I need a bit of help to solve this issue. I have tried passing props to differentiate. But it doesn't seem to work.
My FeaturedProduct.js:

```<code>import React from "react";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import ProductDetails from "./ProductDetails";
import axios from "axios";

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (
    <div>
      <h1> Your Products List is shown below:</h1>
      <div className="item-container">

        {products.map((product) => (
          <div className="card" key={product.id}>
            {" "}

            <h3>{product.item}</h3>
            <p>
              {product.city}, {product.state}
            </p>
            <Router>
              <Link to="/productdetails">More Details</Link>

              <Switch>
                <Route path="/productdetails">
                <ProductDetails product={product}/>
                </Route>
              </Switch>
            </Router>
          </div>
        ))}
      </div>
    </div>
  );
}

export default FeaturedProduct;
</code>```

My ProductDetails.js:

```<code>function ProductDetails(props) {
const {name, color} = props.product;

  return (
    <div>
      <div>
        <h1>{name}</h1>
        <h1>{color}</h1>
      </div>
    </div>
  );
}
export default  ProductDetails;
</code>```

My App.js:

```<code>import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import FeaturedProduct from "./FeaturedProduct";

import "./App.css";

function App() {
  return (
    <div className="App">
      <FeaturedProduct />
    </div>
  );
}

export default App;
</code>```

答:
Issue

You are rendering that same router/link/route for each mapped product element.

```<code><Router>
  <Link to="/productdetails">More Details</Link>

  <Switch>
    <Route path="/productdetails">
      <ProductDetails product={product}/>
    </Route>
  </Switch>
</Router>
</code>```

This means when the path is "/productdetails" you render a Route and ProductDetails component for each and every one of them.

A Solution

It is more common to render one single Router and Route for a product details page with either a specific product id as a route param or to pass entire product object in route state (though less common).

Move the Router into App to provide a single routing context to the app:

```<code>function App() {
  return (
    <Router>
      <div className="App">
        <FeaturedProduct />
      </div>
    </Router>
  );
}
</code>```

Move the Switch and Route below the products mapping, leaving only the Link in the map callback. Link to a specific product id and use the Route's render prop to search for the matching product by id to pass in as a prop:

```<code>function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (
    <div>
      <h1> Your Products List is shown below:</h1>
      <div className="item-container">
        {products.map((product) => (
          <div className="card" key={product.id}>
            <h3>{product.item}</h3>
            <p>
              {product.city}, {product.state}
            </p>
            <Link to={`/product/${product.id}`}>More Details</Link>
          </div>
        ))}
      </div>
      <Switch>
        <Route
          path="/product/:id"
          render={({ match }) => (
            <ProductDetails
              product={products.find(
                (product) => String(product.id) === match.params.id
              )}
            />
          )}
        />
      </Switch>
    </div>
  );
}
</code>```

Body:
I have a product page, where if the user clicks on a specific product card, it will redirect the user to a new page where that specific product details will be displayed only. However, in my code, even after redirecting it to the details page, it still shows the entire product list on that page. I need a bit of help to solve this issue. I have tried passing props to differentiate. But it doesn't seem to work.
My FeaturedProduct.js:

import React from "react";
import { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import ProductDetails from "./ProductDetails";
import axios from "axios";

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (

 Your Products List is shown below:

        {products.map((product) => (

            {" "}

{product.item}

              {product.city}, {product.state}

            <Router>
              <Link to="/productdetails">More Details</Link>

              <Switch>
                <Route path="/productdetails">
                <ProductDetails product={product}/>
                </Route>
              </Switch>
            </Router>

        ))}

  );
}

export default FeaturedProduct;

My ProductDetails.js:

function ProductDetails(props) {
const {name, color} = props.product;

  return (

{name}

{color}

  );
}
export default  ProductDetails;

My App.js:

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import FeaturedProduct from "./FeaturedProduct";

import "./App.css";

function App() {
  return (

      <FeaturedProduct />

  );
}

export default App;

Body:
Issue

You are rendering that same router/link/route for each mapped product element.

<Router>
  <Link to="/productdetails">More Details</Link>

  <Switch>
    <Route path="/productdetails">
      <ProductDetails product={product}/>
    </Route>
  </Switch>
</Router>

This means when the path is "/productdetails" you render a Route and ProductDetails component for each and every one of them.

A Solution

It is more common to render one single Router and Route for a product details page with either a specific product id as a route param or to pass entire product object in route state (though less common).

Move the Router into App to provide a single routing context to the app:

function App() {
  return (
    <Router>
      <div className="App">
        <FeaturedProduct />
      </div>
    </Router>
  );
}

Move the Switch and Route below the products mapping, leaving only the Link in the map callback. Link to a specific product id and use the Route's render prop to search for the matching product by id to pass in as a prop:

function FeaturedProduct(props) {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetchProducts();
  }, []);

  function fetchProducts() {
    axios
      .get("https://shoppingapiacme.herokuapp.com/shopping")
      .then((res) => {
        console.log(res);
        setProducts(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }
  return (
    <div>
      <h1> Your Products List is shown below:</h1>
      <div className="item-container">
        {products.map((product) => (
          <div className="card" key={product.id}>
            <h3>{product.item}</h3>
            <p>
              {product.city}, {product.state}
            </p>
            <Link to={`/product/${product.id}`}>More Details</Link>
          </div>
        ))}
      </div>
      <Switch>
        <Route
          path="/product/:id"
          render={({ match }) => (
            <ProductDetails
              product={products.find(
                (product) => String(product.id) === match.params.id
              )}
            />
          )}
        />
      </Switch>
    </div>
  );
}


问:
Is it possible to test static private methods used from public static methods with Mockito (not PowerMockito!)?
I have a public static method which internally uses another static but private method. SonarQube bothers me to test this private method. How can I do this using Mockito (inline)?

```<code>public class MyClass {
    public static boolean isXxxValid(String value1, String value2) {
        try {
            var s = myPrivateMethod(anyString);
            ...
        } catch (Exception ex) {
            ...
        }
    }

    private static String myPrivateMethod(final String input) {
        ...
    }
}
</code>```

How can I test or mock myPrivateMethod()?

答:
In general the testing of private methods should be done via the business interface (the public methods of your class).

But since you are mentioning powermock I guess your idea is to mock that privat method to test your public method. That would be another anti pattern. You should never mock parts of the class under test.

In your case it seem that you need to mock the external dependencies that are used in your private method.

Body:
I have a public static method which internally uses another static but private method. SonarQube bothers me to test this private method. How can I do this using Mockito (inline)?

public class MyClass {
    public static boolean isXxxValid(String value1, String value2) {
        try {
            var s = myPrivateMethod(anyString);
            ...
        } catch (Exception ex) {
            ...
        }
    }

    private static String myPrivateMethod(final String input) {
        ...
    }
}

How can I test or mock myPrivateMethod()?


问:
TypeError: messages.map is not a function
I am making facebook messenger clone using reactjs but this error stops my working as application was running smoothly but unfortunately this error stuck me.</p>
```<code>{

    messages.map(messages => (
      <Message username={userName} message={messages} />

    ))
  }
</code>```

答:
First of all map() function use for JS array, that's why be sure messages is array, after that if messages is array but it is null in this case you get this error.
in addition you can check this question
React Uncaught TypeError: this.state.messages.map is not a function</p>

Body:
I am making facebook messenger clone using reactjs but this error stops my working as application was running smoothly but unfortunately this error stuck me.

{

    messages.map(messages => (
      <Message username={userName} message={messages} />

    ))
  }


问:
Sorting a vector of objects in C++
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

```<code>class Information {

private:
int age;
string name;

//etc, etc...
};
</code>```

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

```<code>sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());
</code>```

listOfPeople would be the vector.

Any help would be greatly appreciated.

答:
You need to create a comparator function or functor class that takes two Information references and returns true if the first should be ordered before the second.

The following will sort from oldest to youngest:

```<code>bool CompareAges(const Information & left, const Information & right)
{
    return left.age > right.age;
}

std::sort(listOfPeople.begin(), listOfPeople.end(), CompareAges);
</code>```

To select whether to sort ascending or descending, you can have two different calls to sort with different comparison functions, or you can create a functor class that has a flag determining how the items should be sorted.

```<code>struct CompareAgesUpOrDown
{
    CompareAgesUpOrDown(bool bDown) : m_bDown(bDown) {}
    bool operator() (const Information & left, const Information & right)
    {
        if (m_bDown)
            return left.age < right.age;
        else
            return left.age > right.age;
    }
    bool m_bDown;
};

bool bDown = ...;
std::sort(std::sort(listOfPeople.begin(), listOfPeople.end(), CompareAgesUpOrDown(bDown));
</code>```

Title: Sorting a vector of objects in C++

Body:
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

class Information {

private:
int age;
string name;

//etc, etc...
};

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());

listOfPeople would be the vector.

Any help would be greatly appreciated.

Body:
You need to create a comparator function or functor class that takes two Information references and returns true if the first should be ordered before the second.

The following will sort from oldest to youngest:

bool CompareAges(const Information & left, const Information & right)
{
    return left.age > right.age;
}

std::sort(listOfPeople.begin(), listOfPeople.end(), CompareAges);

To select whether to sort ascending or descending, you can have two different calls to sort with different comparison functions, or you can create a functor class that has a flag determining how the items should be sorted.

struct CompareAgesUpOrDown
{
    CompareAgesUpOrDown(bool bDown) : m_bDown(bDown) {}
    bool operator() (const Information & left, const Information & right)
    {
        if (m_bDown)
            return left.age < right.age;
        else
            return left.age > right.age;
    }
    bool m_bDown;
};

bool bDown = ...;
std::sort(std::sort(listOfPeople.begin(), listOfPeople.end(), CompareAgesUpOrDown(bDown));