问:
Difference between ArrayIterator, ArrayObject and Array in PHP
Can somebody explain clearly the fundamental differences between ArrayIterator, ArrayObject and Array in PHP in terms of functionality and operation? Thanks!

答:
Array is array type, ArrayObject and ArrayIterator are built-in classes, with their instances being object type, that partially behave like arrays on syntax and usage level.

For the classes I think the quick idea can be gained from the interfaces they implement:

class ArrayObject implements IteratorAggregate, ArrayAccess, Serializable, Countable {
```
<pre class="lang-php prettyprint-override"><code>class ArrayIterator implements SeekableIterator, ArrayAccess, Serializable, Countable {
</code>```

Both classes implement:

ArrayAccess, so they support array syntax to access values

Countable, so they support count of values, like arrays do

Iterator (though in different ways), so they fit iterable type and can be looped over with foreach and such

One way to look at it, is that classes go through a lot of trouble to work like an array. The point is that being classes, they can be extended and customized.

They would also be inherently interoperable with any code that expects Iterator in general, so the basic use case is just that - wrapping to feed array data into iterator code.

So in a nutshell ArrayObject and ArrayIterator are Do It Yourself arrays (with some implementation differences between the two). Their instances (partially) behave like array type, but as classes they are extensible and as Iterator implementers they are interoperable with code that wants that.

Unless you need a deeply custom behavior and/or Iterator interoperability, sticking with array type is probably the way to go between these.

Notably there are also implementations of collections around, that aim to deliver the class benefits with more friendly abstractions.

Body:
Array is array type, ArrayObject and ArrayIterator are built-in classes, with their instances being object type, that partially behave like arrays on syntax and usage level.

For the classes I think the quick idea can be gained from the interfaces they implement:

class ArrayObject implements IteratorAggregate, ArrayAccess, Serializable, Countable {

class ArrayIterator implements SeekableIterator, ArrayAccess, Serializable, Countable {

Both classes implement:

ArrayAccess, so they support array syntax to access values

Countable, so they support count of values, like arrays do

Iterator (though in different ways), so they fit iterable type and can be looped over with foreach and such

One way to look at it, is that classes go through a lot of trouble to work like an array. The point is that being classes, they can be extended and customized.

They would also be inherently interoperable with any code that expects Iterator in general, so the basic use case is just that - wrapping to feed array data into iterator code.

So in a nutshell ArrayObject and ArrayIterator are Do It Yourself arrays (with some implementation differences between the two). Their instances (partially) behave like array type, but as classes they are extensible and as Iterator implementers they are interoperable with code that wants that.

Unless you need a deeply custom behavior and/or Iterator interoperability, sticking with array type is probably the way to go between these.

Notably there are also implementations of collections around, that aim to deliver the class benefits with more friendly abstractions.


来源: stackexchange

问:
Download File from URL into download folder C#
I would like to know how to download a file from a url into your downloads folder. I already tried doing this:

```<code>private void guna2Button1_Click(object sender, EventArgs e)
{
        using (var client = new WebClient())
        {
            client.DownloadFile("https://test.com/hello.txt", "hello.txt");
        }
    }
</code>```

When I actually put in a valid url and file, it would go where my project would be located. I would like it to be saved in my downloads folder, how would I do this?

答:
There are several solutions:

If you just need to work on your computer and your session, replace your second parameter "hello.txt" by something like that: @"c:\users\yourname\downloads\hello.txt", where 'yourname' is the folder corresponding to your session, and @ indicates \ won't escape chars in the following string so this string would be verbatim. But this will work only on your computer and your session, of course.

Use The NuGet package Syroot.Windows.IO.KnownFolders: right-clic on References on the solutions explorer and add this nugget package. Then, do this:

Add the following at the beginning:

```<code>using Syroot.Windows.IO;
using System.IO;
</code>```

Modify your method:

```<code> private void guna2Button1_Click(object sender, EventArgs e)
 {
     using (var client = new WebClient())
     {
         string downloadFolder = KnownFolders.Downloads.Path;
         string destFile = Path.Combine(downloadFolder, "hello.txt");
         client.DownloadFile("https://test.com/hello.txt", destFile);
     }
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to know how to download a file from a url into your downloads folder. I already tried doing this:

private void guna2Button1_Click(object sender, EventArgs e)
{
        using (var client = new WebClient())
        {
            client.DownloadFile("https://test.com/hello.txt", "hello.txt");
        }
    }

When I actually put in a valid url and file, it would go where my project would be located. I would like it to be saved in my downloads folder, how would I do this?

Body:
There are several solutions:

If you just need to work on your computer and your session, replace your second parameter "hello.txt" by something like that: @"c:\users\yourname\downloads\hello.txt", where 'yourname' is the folder corresponding to your session, and @ indicates \ won't escape chars in the following string so this string would be verbatim. But this will work only on your computer and your session, of course.

Use The NuGet package Syroot.Windows.IO.KnownFolders: right-clic on References on the solutions explorer and add this nugget package. Then, do this:

Add the following at the beginning:

using Syroot.Windows.IO;
using System.IO;

Modify your method:

 private void guna2Button1_Click(object sender, EventArgs e)
 {
     using (var client = new WebClient())
     {
         string downloadFolder = KnownFolders.Downloads.Path;
         string destFile = Path.Combine(downloadFolder, "hello.txt");
         client.DownloadFile("https://test.com/hello.txt", destFile);
     }
 }


问:
Matplotlib don't show all ticks/labels with bar chart. It skips first of y axis and last one of x axis
Matplotlib don't show all ticks/labels with bar chart. It skips first of y axis and last one of x axis.

```<code>figsize = plt.figure(figsize = (8,6))
axes1 = plt.subplot(2,2,1,title = "Scatter plot with Upper Traingle Markers")
axes1.set_xticks([0.0, 0.4, 0.8, 1.2])
axes1.set_yticks([-0.2, 0.2, 0.6, 1.0])
axes1.set_xlim(0,1.2)
axes1.set_ylim(-0.2,1.0)
axes2 = plt.subplot(2,2,2,title = "Scatter plot with Plus Markers")
axes2.set_xticks([0.0, 0.4, 0.8, 1.2])
axes2.set_yticks([-0.2, 0.2, 0.6, 1.0])
axes3 = plt.subplot(2,2,3,title = "Scatter plot with Circle Markers")
axes3.set_xticks([0.0, 0.4, 0.8, 1.2])
axes3.set_yticks([-0.2, 0.2, 0.6, 1.0])
axes4 = plt.subplot(2,2,4,title = "Scatter plot with Diamond Markers")
axes4.set_xticks([0.0, 0.4, 0.8, 1.2])
axes4.set_yticks([-0.2, 0.2, 0.6, 1.0])
np.random.seed(1000)
x = np.random.rand(10)
y = np.random.rand(10)
z = np.sqrt(x**2+y**2)
axes1.scatter(x,y, s = 80,c =z,marker = "^")
axes2.scatter(x,y, s = 80,c =z,marker = "+")
axes3.scatter(x,y, s = 80,c =z,marker = "o")
axes4.scatter(x,y, s = 80,c =z,marker = "d")
plt.tight_layout()
plt.savefig("x.png")
</code>```

Expected plot

My plot

. Starts at zero and zero. If I don't use the lim functions the graph start at the same point as expected plot.

If the graph images won't match, My test cases wont pass. Can you help me with this

答:
Matplotlib will not automatically expand your axis limits to in response to changing the axis ticks. Autoscaling only applies to plotted data points.

If the automatic limits are not suitable for you, then you need to use the ax.set_xlim and/or .set_ylim methods to manually X and/or Y limits.

Body:
Matplotlib don't show all ticks/labels with bar chart. It skips first of y axis and last one of x axis.

figsize = plt.figure(figsize = (8,6))
axes1 = plt.subplot(2,2,1,title = "Scatter plot with Upper Traingle Markers")
axes1.set_xticks([0.0, 0.4, 0.8, 1.2])
axes1.set_yticks([-0.2, 0.2, 0.6, 1.0])
axes1.set_xlim(0,1.2)
axes1.set_ylim(-0.2,1.0)
axes2 = plt.subplot(2,2,2,title = "Scatter plot with Plus Markers")
axes2.set_xticks([0.0, 0.4, 0.8, 1.2])
axes2.set_yticks([-0.2, 0.2, 0.6, 1.0])
axes3 = plt.subplot(2,2,3,title = "Scatter plot with Circle Markers")
axes3.set_xticks([0.0, 0.4, 0.8, 1.2])
axes3.set_yticks([-0.2, 0.2, 0.6, 1.0])
axes4 = plt.subplot(2,2,4,title = "Scatter plot with Diamond Markers")
axes4.set_xticks([0.0, 0.4, 0.8, 1.2])
axes4.set_yticks([-0.2, 0.2, 0.6, 1.0])
np.random.seed(1000)
x = np.random.rand(10)
y = np.random.rand(10)
z = np.sqrt(x**2+y**2)
axes1.scatter(x,y, s = 80,c =z,marker = "^")
axes2.scatter(x,y, s = 80,c =z,marker = "+")
axes3.scatter(x,y, s = 80,c =z,marker = "o")
axes4.scatter(x,y, s = 80,c =z,marker = "d")
plt.tight_layout()
plt.savefig("x.png")

Expected plot

My plot

. Starts at zero and zero. If I don't use the lim functions the graph start at the same point as expected plot.

If the graph images won't match, My test cases wont pass. Can you help me with this


问:
StandardScaler giving error "could not convert string to float:"
I have a column that shows random latitude/longitude as a string in excel.

I successfully split into the training/test set but I get an error when scaling.
I am using Standard scaler to then fit into a regression model but keep getting the error:

答: I have couple of suggestions and some solutions that might fix your issue. Firstly the error "could not convert string to float" is arising due to the fact that the column "Customer_address" and "Store_address" are of type string. Standard scalar will work with float and integers, but not string. Also, the solution to the problem could be to split those "Customer_address", "Store_address"  into "Customer_address_latitude" , "Customer_address_longitude" "Store_address_latitude" , "Store_address_longitude" as float type, and then use standard scaler.</p>


问:
Unique numbers with missing digits
I have this problem that I must solve in time that is polynomial in N, K and D given below:

Let N, K be some natural numbers.
Then a, b, c ... are N numbers of exactly K digits each.

a, b, c ... contain only the digits 1 and 2 in some order given by the input.

Although, there have only D digits that are visible, the rest of them being hidden (the hidden digits will be noted with the character "?").

There may be different numbers such that one or more of a, b, c ... are generalizations of the said number:

e.g.

2?122 is a generalization for  21122 and 22122

2?122 is not a generalization for 11111

12??? and ?21?? are both generalizations for 12112

???22 and ???11 cannot be generalizations of the same number

Basically, some number is a generalization of the other if the latter can be one of the "unhidden" versions of the former.

Question:

How many different numbers there are such that at least one of a, b, c or ... is their generalization?***

Quick Reminder:

N = nº of numbers

K = nº of digits in each number

D = nº of visible digits in each number

Conditions & Limitations:

N, K, D are natural numbers

1 ≤ N

1 ≤ D < K

Input / Output snippets for verification of the algorithm:

Input:

```<code>    N = 3, K = 5, D = 3

    112??
    ?122?
    1?2?1
</code>```

Output:

```<code>    8
</code>```

Explanation:

The numbers are 11211, 11212, 11221, 11222, 12211, 12221, 21221, 21222, which are 8 numbers.

11211, 11212, 11221, 11222 are the generalizations of 112??

11221, 11222, 21221, 21222 are the generalizations of ?122?

11211, 11221, 12211, 12221 are the generalizations of 1?2?1

Input:

```<code>    N = 2, K = 3, D = 1

    1??
    ?2?
</code>```

Output:

```<code>    6
</code>```

Explanation:

The numbers are 111, 112, 121, 122, 221, 222, which are 6 numbers.

From my calculations, I found out that there are 2^(K-D) possible numbers in total that have a as their generalization, 2^(K-D) possible numbers in total that have b as their generalization etc., leaving me with N*2^(K-D) numbers.

My big problem is that I found cases where a number has multiple generalizations and therefore it repeats inside N*2^(K-D), so the real nº of different numbers will be, in this case, something smaller than N*2^(K-D).

I don't know how to find only the different numbers and I need your help.

Thank you very much!

EDIT: Answer to «n. 1.8e9-where's-my-share m.»'s question from the comments:

If you have two generalisations, can you find out how many numbers they both generalise?

For two given general numbers a and b (general meaning that they both contain "?"), it is possible to find nº of numbers generalised by both a and b in polynomial time by using the following logic:

1 - we declare some variable q = 1

2 - we start "scanning" the digits of the two numbers simultaneously from left to right:

2.1 - if we find two unhidden digits and they are different, then no numbers are generalized by both a and b and we return 0

2.2 - if we find two hidden digits, then we multiply q by 2, since of the two general numbers result to both generalize some number, that number can have 1 or 2 in place of "?", therefore for each "?" we double the numbers that can be generalized from both a and b as long as step 2.1 is never true.

3 - if scanned all the digits and step 2.1 was never true, then we return 2^q

Therefore, the nº of numbers both a and b generalize is 0 or 2^q, according to the cases presented above.

答:
Unfortunately, this is impossible to do in polynomial time (unless P=NP, and maybe not even then.) Your problem is equivalent to the problem of counting satisfying assignments to a formula in Disjunctive Normal Form, called the DNF counting problem. DNF counting is Sharp-P-hard, so a polynomial time solution could be used to solve all problems in NP in polynomial time too (and more).

To see the relationship, note that each pattern is equivalent to an AND of several literals. If you take '1' in a position to be a literal, and '2' in that position to be that literal negated, you can convert it to a disjunctive clause.

For example:

1 1 2 ? ?
becomes
(x_1 ∧ x_2 ∧ ¬x_3)

? 1 2 2 ?
becomes
(x_2 ∧ ¬x_3 ∧ ¬x_4)

1 ? 2 ? 1
becomes
(x_1 ∧ ¬x_3 ∧ x_5)
```

The question of how many numbers satisfy at least one of these patterns is exactly the question of how many assignments satisfy at least one of the equivalent clauses.

Title: Unique numbers with missing digits

Body:
I have this problem that I must solve in time that is polynomial in N, K and D given below:

Let N, K be some natural numbers.
Then a, b, c ... are N numbers of exactly K digits each.

a, b, c ... contain only the digits 1 and 2 in some order given by the input.

Although, there have only D digits that are visible, the rest of them being hidden (the hidden digits will be noted with the character "?").

There may be different numbers such that one or more of a, b, c ... are generalizations of the said number:

e.g.

2?122 is a generalization for  21122 and 22122

2?122 is not a generalization for 11111

12??? and ?21?? are both generalizations for 12112

???22 and ???11 cannot be generalizations of the same number

Basically, some number is a generalization of the other if the latter can be one of the "unhidden" versions of the former.

Question:

How many different numbers there are such that at least one of a, b, c or ... is their generalization?***

Quick Reminder:

N = nº of numbers

K = nº of digits in each number

D = nº of visible digits in each number

Conditions & Limitations:

N, K, D are natural numbers

1 ≤ N

1 ≤ D < K

Input / Output snippets for verification of the algorithm:

Input:

    N = 3, K = 5, D = 3

    112??
    ?122?
    1?2?1

Output:

    8

Explanation:

The numbers are 11211, 11212, 11221, 11222, 12211, 12221, 21221, 21222, which are 8 numbers.

11211, 11212, 11221, 11222 are the generalizations of 112??

11221, 11222, 21221, 21222 are the generalizations of ?122?

11211, 11221, 12211, 12221 are the generalizations of 1?2?1

Input:

    N = 2, K = 3, D = 1

    1??
    ?2?

Output:

    6

Explanation:

The numbers are 111, 112, 121, 122, 221, 222, which are 6 numbers.

From my calculations, I found out that there are 2^(K-D) possible numbers in total that have a as their generalization, 2^(K-D) possible numbers in total that have b as their generalization etc., leaving me with N*2^(K-D) numbers.

My big problem is that I found cases where a number has multiple generalizations and therefore it repeats inside N*2^(K-D), so the real nº of different numbers will be, in this case, something smaller than N*2^(K-D).

I don't know how to find only the different numbers and I need your help.

Thank you very much!

EDIT: Answer to «n. 1.8e9-where's-my-share m.»'s question from the comments:

If you have two generalisations, can you find out how many numbers they both generalise?

For two given general numbers a and b (general meaning that they both contain "?"), it is possible to find nº of numbers generalised by both a and b in polynomial time by using the following logic:

1 - we declare some variable q = 1

2 - we start "scanning" the digits of the two numbers simultaneously from left to right:

2.1 - if we find two unhidden digits and they are different, then no numbers are generalized by both a and b and we return 0

2.2 - if we find two hidden digits, then we multiply q by 2, since of the two general numbers result to both generalize some number, that number can have 1 or 2 in place of "?", therefore for each "?" we double the numbers that can be generalized from both a and b as long as step 2.1 is never true.

3 - if scanned all the digits and step 2.1 was never true, then we return 2^q

Therefore, the nº of numbers both a and b generalize is 0 or 2^q, according to the cases presented above.

Body:
Unfortunately, this is impossible to do in polynomial time (unless P=NP, and maybe not even then.) Your problem is equivalent to the problem of counting satisfying assignments to a formula in Disjunctive Normal Form, called the DNF counting problem. DNF counting is Sharp-P-hard, so a polynomial time solution could be used to solve all problems in NP in polynomial time too (and more).

To see the relationship, note that each pattern is equivalent to an AND of several literals. If you take '1' in a position to be a literal, and '2' in that position to be that literal negated, you can convert it to a disjunctive clause.

For example:

1 1 2 ? ?
becomes
(x_1 ∧ x_2 ∧ ¬x_3)

? 1 2 2 ?
becomes
(x_2 ∧ ¬x_3 ∧ ¬x_4)

1 ? 2 ? 1
becomes
(x_1 ∧ ¬x_3 ∧ x_5)

The question of how many numbers satisfy at least one of these patterns is exactly the question of how many assignments satisfy at least one of the equivalent clauses.


问:
NextJS: `function` cannot be serialized as JSON. Please only return JSON serializable data types
I have a Firestore collection by the name of "mentor". Each document in the collection contains three fields: "name", "email" and "linkedin".

I want to fetch all the documents in the collection and pass them as props. I want to then access these document fields to be rendered on my page.

I am using getServerSideProps to fetch the Firestore data prior to rendering the page.
My code is as follows:

dashboard.js:

```<code>import nookies from "nookies";
import { onSnapshot, getFirestore, collection, getDocs } from "firebase/firestore";

export default function dashboard({session,mentors}){
       return(
            //rendering each value in the mentors array
          )
}

export async function getServerSideProps(context) {
    try {
      const cookies = nookies.get(context);
      const token = await verifyIdToken(cookies.token);
      if (!token) {
        return {
          redirect: {
            permanent: false,
            destination: "/login",
          },
          props: {},
        };
      }
      const mentors = [];
      const db = getFirestore();
      const querySnapshot = await getDocs(collection(db, "mentor"));
        querySnapshot.forEach((doc) => {
            mentors.push({mentorID: doc.id, mentorData: doc.data})
          });
      return {
        props: {
          session: token,
          mentors,
        },
      };
    } catch (error) {
      context.res.writeHead(302, { location: "/login" });
      context.res.end();
      return { props: {} };
    }
  }
</code>```

However, I am getting the following error in the console:

```<code>error - Error: Error serializing `.mentors[0].mentorData` returned from `getServerSideProps` in "/dashboard".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.
</code>```

How do I fix this? Please excuse me if there is some error in the code. I am relatively new to JS.

答:
doc.data is a function, not actual document data.  See the API documentation for clarity.  You should instead call it in order to get an object with the data in the snapshot.

```<code>mentors.push({mentorID: doc.id, mentorData: doc.data()})
</code>```

Body:
I have a Firestore collection by the name of "mentor". Each document in the collection contains three fields: "name", "email" and "linkedin".

I want to fetch all the documents in the collection and pass them as props. I want to then access these document fields to be rendered on my page.

I am using getServerSideProps to fetch the Firestore data prior to rendering the page.
My code is as follows:

dashboard.js:

import nookies from "nookies";
import { onSnapshot, getFirestore, collection, getDocs } from "firebase/firestore";

export default function dashboard({session,mentors}){
       return(
            //rendering each value in the mentors array
          )
}

export async function getServerSideProps(context) {
    try {
      const cookies = nookies.get(context);
      const token = await verifyIdToken(cookies.token);
      if (!token) {
        return {
          redirect: {
            permanent: false,
            destination: "/login",
          },
          props: {},
        };
      }
      const mentors = [];
      const db = getFirestore();
      const querySnapshot = await getDocs(collection(db, "mentor"));
        querySnapshot.forEach((doc) => {
            mentors.push({mentorID: doc.id, mentorData: doc.data})
          });
      return {
        props: {
          session: token,
          mentors,
        },
      };
    } catch (error) {
      context.res.writeHead(302, { location: "/login" });
      context.res.end();
      return { props: {} };
    }
  }

However, I am getting the following error in the console:

error - Error: Error serializing `.mentors[0].mentorData` returned from `getServerSideProps` in "/dashboard".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.

How do I fix this? Please excuse me if there is some error in the code. I am relatively new to JS.

Body:
doc.data is a function, not actual document data.  See the API documentation for clarity.  You should instead call it in order to get an object with the data in the snapshot.

mentors.push({mentorID: doc.id, mentorData: doc.data()})


问:
Copying relational data from database to database
Edit:  Let me completely rephrase this, because I'm not sure there's an XML way like I was originally describing.

Yet another edit: This needs to be a repeatable process, and it has to be able to be set up in a way that it can be called in C# code.

In database A, I have a set of tables, related by PKs and FKs.  A parent table, with child and grandchild tables, let's say.

I want to copy a set of rows from database A to database B, which has identically named tables and fields.  For each table, I want to insert into the same table in database B.  But I can't be constrained to use the same primary keys.  The copy routine must create new PKs for each row in database B, and must propagate those to the child rows.  I'm keeping the same relations between the data, in other words, but not the same exact PKs and FKs.

How would you solve this?  I'm open to suggestions.  SSIS isn't completely ruled out, but it doesn't look to me like it'll do this exact thing.  I'm also open to a solution in LINQ, or using typed DataSets, or using some XML thing, or just about anything that'll work in SQL Server 2005 and/or C# (.NET 3.5).  The best solution wouldn't require SSIS, and wouldn't require writing a lot of code.  But I'll concede that this "best" solution may not exist.

(I didn't make this task up myself, nor the constraints; this is how it was given to me.)

答:
I have created the same thing with a set of stored procedures.

Database B will have its own primary keys, but store Database A's primary keys, for debuging purposes. It means I can have more than one Database A!

Data is copied via a linked server. Not too fast; SSIS is faster. But SSIS is not for beginners, and it is not easy to code something that works with changing source tables.

And it is easy to call a stored procedure from C#.

OwnerDisplayName: Kyralessa

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kevin Fairchild

OwnerDisplayName: Henrik Staun Poulsen


问:
query.next() returning false
I have used the query.next() function inside my code, but its returning false.
I even checked in the database, there are 4 records present. But the code shows only one.
However if i use query.next() before the code of query.valid() then it doesn't show any record
Please help

```<code>  qDebug() << "entering payment: get all the unchecked invoices for user: " + user;
  QStringList tmp;
  QSqlQuery query(m_storageUserManager->database());
  m_storageUserManager->dumpTable(m_invoiceInfoTable);
  m_storageUserManager->dumpTable(m_invoiceUserTable);
  qDebug()<<"THE NAME OF THE INVOICE USER TABLE_----=-----------------"<<m_invoiceInfoTable;
  qDebug()<<"THE NAME OF THE INVOICE USER TABLE_----=-----------------"<<m_invoiceUserTable;
  query.prepare("SELECT invoice FROM "+ m_invoiceInfoTable +" WHERE invoice = (SELECT
                 invoice FROM "+ m_invoiceUserTable +" WHERE user=:user)");
//  query.prepare("SELECT invoice FROM " + m_invoiceInfoTable + ","+ m_invoiceUserTable +" WHERE " + m_invoiceInfoTable + ".user = " + m_invoiceUserTable + ".:user");
  query.bindValue(":user", user);
  query.exec();
  query.first();
  qDebug()<<"Unchecked invoices done!!! " ;
  if(query.isValid()) {
    do {
      tmp.append(query.value(0).toString());    //as the value returned by value() is a QVariant so we need to change it to String.
    } while(query.next());
  } else
    tmp.append("No Unchecked invoice in the database");
  return tmp;
</code>```

答:
To check if the query was successful you should test the return value of either QSqlQuery::exec() or QSqlQuery::isActive() before trying to call first/next/last (when you pass the query string to the constructor of QSqlQuery, the query is already executed, so, you need to use QSqlQuery::isActive()).

first(), next() and last() return true if they positioned the query on a valid record, you don't have to test isValid() separately. Since first() is a positioning function too, you can read the value without calling next() directly after, unless you want to skip the first record.

Since you may want to add fields from the the "invoice-info" table to your query, I kept the subquery (with IN instead of = as Mat already answered in the comment).

```<code>query.prepare(QString("SELECT invoice FROM %1 WHERE invoice "
                      "IN (SELECT invoice FROM %2 WHERE user=:user)")
              .arg(m_invoiceInfoTable, m_invoiceUserTable));
/*
// Or with an inner join
query.prepare(QString("SELECT %1.invoice FROM %1 "
              "INNER JOIN %2 ON %1.invoice = %2.invoice "
              "WHERE user=:user").arg(m_invoiceInfoTable, m_invoiceUserTable));*/
query.bindValue(":user", user);

if (!query.exec()) {
    tmp.append("Query error: %1" + query.lastError().text());
} else if (!query.first()) {
    tmp.append("No Unchecked invoice in the database");
} else {
    do {
        tmp.append(query.value(0).toString());
    } while(query.next());
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: query.next() returning false

Body:
I have used the query.next() function inside my code, but its returning false.
I even checked in the database, there are 4 records present. But the code shows only one.
However if i use query.next() before the code of query.valid() then it doesn't show any record
Please help

  qDebug() << "entering payment: get all the unchecked invoices for user: " + user;
  QStringList tmp;
  QSqlQuery query(m_storageUserManager->database());
  m_storageUserManager->dumpTable(m_invoiceInfoTable);
  m_storageUserManager->dumpTable(m_invoiceUserTable);
  qDebug()<<"THE NAME OF THE INVOICE USER TABLE_----=-----------------"<<m_invoiceInfoTable;
  qDebug()<<"THE NAME OF THE INVOICE USER TABLE_----=-----------------"<<m_invoiceUserTable;
  query.prepare("SELECT invoice FROM "+ m_invoiceInfoTable +" WHERE invoice = (SELECT
                 invoice FROM "+ m_invoiceUserTable +" WHERE user=:user)");
//  query.prepare("SELECT invoice FROM " + m_invoiceInfoTable + ","+ m_invoiceUserTable +" WHERE " + m_invoiceInfoTable + ".user = " + m_invoiceUserTable + ".:user");
  query.bindValue(":user", user);
  query.exec();
  query.first();
  qDebug()<<"Unchecked invoices done!!! " ;
  if(query.isValid()) {
    do {
      tmp.append(query.value(0).toString());    //as the value returned by value() is a QVariant so we need to change it to String.
    } while(query.next());
  } else
    tmp.append("No Unchecked invoice in the database");
  return tmp;

Body:
To check if the query was successful you should test the return value of either QSqlQuery::exec() or QSqlQuery::isActive() before trying to call first/next/last (when you pass the query string to the constructor of QSqlQuery, the query is already executed, so, you need to use QSqlQuery::isActive()).

first(), next() and last() return true if they positioned the query on a valid record, you don't have to test isValid() separately. Since first() is a positioning function too, you can read the value without calling next() directly after, unless you want to skip the first record.

Since you may want to add fields from the the "invoice-info" table to your query, I kept the subquery (with IN instead of = as Mat already answered in the comment).

query.prepare(QString("SELECT invoice FROM %1 WHERE invoice "
                      "IN (SELECT invoice FROM %2 WHERE user=:user)")
              .arg(m_invoiceInfoTable, m_invoiceUserTable));
/*
// Or with an inner join
query.prepare(QString("SELECT %1.invoice FROM %1 "
              "INNER JOIN %2 ON %1.invoice = %2.invoice "
              "WHERE user=:user").arg(m_invoiceInfoTable, m_invoiceUserTable));*/
query.bindValue(":user", user);

if (!query.exec()) {
    tmp.append("Query error: %1" + query.lastError().text());
} else if (!query.first()) {
    tmp.append("No Unchecked invoice in the database");
} else {
    do {
        tmp.append(query.value(0).toString());
    } while(query.next());
}


问:
How to pass onPress to props.children?
I'm trying to make a wrapper component in react-native that I can pass down all its props to the children it wraps around. What I really want is to pass down all function props down to all its children. It looks something like this below. I want the onPress in Wrapper to be called when the TouchableOpacity is pressed.

I tried this below but it doesn't work

const Wrapper = ({children,...props})=>{
      return <View {...props}>{children}</View>
}

const App = ()=>{
    return (
        <View style={{flex:1}}>
            <Wrapper onPress={()=>{console.log(2)}}>
                <TouchableOpacity/>
            </Wrapper>
        </View>
    )
}
```

答:
 const App = () => {
    return (
        <View style={{ flex: 1 }}>
            <TouchableOpacity onPress={() => {
                // do the action need here here
            }}>

                <Wrapper  >
            </Wrapper>
        </TouchableOpacity>
            </View>
        )
    }
```
<p><strong>I would advise you to use hooks function instead</strong></p>
<p>If you try to reuse functions that are related
** useAdd.js **</p>
<pre class="lang-js prettyprint-override"><code>    export default () => {
        const addFuction(a, b) => {
            // do preprocessing here
            return a + b
        }

        return [addFuction]
    }
</code>```

main componet

    import useAdd from "/useAdd";
    const App = () => {
        const [addFuction] = useAdd()
        return (
            <View style={{ flex: 1 }}>
                <TouchableOpacity onPress={() => {
                   addFuction(4,5)
                }}>
                ...action component...

                </TouchableOpacity>
            </View>
        )
    }
```

console in useAdd hook.... to see visual changes use the react useState

Title: How to pass onPress to props.children?

Body:
 const App = () => {
    return (
        <View style={{ flex: 1 }}>
            <TouchableOpacity onPress={() => {
                // do the action need here here
            }}>

                <Wrapper  >
            </Wrapper>
        </TouchableOpacity>
            </View>
        )
    }

I would advise you to use hooks function instead

If you try to reuse functions that are related
** useAdd.js **

    export default () => {
        const addFuction(a, b) => {
            // do preprocessing here
            return a + b
        }

        return [addFuction]
    }

main componet

    import useAdd from "/useAdd";
    const App = () => {
        const [addFuction] = useAdd()
        return (
            <View style={{ flex: 1 }}>
                <TouchableOpacity onPress={() => {
                   addFuction(4,5)
                }}>
                ...action component...

                </TouchableOpacity>
            </View>
        )
    }

console in useAdd hook.... to see visual changes use the react useState


问:
How can you restrict a method parameter based on an enum?
I feel like this is an anti pattern of some sort, but basically I've got 2 versions of the same type of repo that have the same type of properties and methods. I played with the idea of both an interface and an abstract class but in neither case can I get around what appears to be unnecessary checks. Here's the premise (using abstract class):

```<code>public abstract class BaseRepository
{
    public abstract RepositoryType RepositoryType { get; } //enum of File or DataBase
    public abstract CreateResult CreateItem (Item item);
    public abstract DeleteResult DeleteItemById(Guid Id);
    public abstract Item GetItem(Guid Id);
}

public class Item
{
    public Guid Id { get; }
    public string Name { get; }
    public ItemType ItemType { get; } //enum of File or DataRecord

    //other props...
}

public FileRepository : BaseRepository
{
    public override RepositoryType RepositoryType => RepositoryType.File

    public override CreateResult CreateItem(Item item)
    {
        if(item.ItemType != ItemType.File) throw InvalidOperationException("some error message") //problem is here

        //some logic.
    }

    //other overrides....
}
</code>```

So there's a basic contract created for a repository via the BaseRepository, which is overridden by the FileRepository. An item basically has the same stuff whether it's a File item or a DataRecord item (there could arguably be an IItem interface and then 2 separate Items of DataRecord and File rather than an enum but that still doesn't solve the problem).

The problem is I don't see how I can pass in an Item with only ItemType File to the FileRepository. It feels like there should be a way of making sure that the FileRepository only receives items of type File and that a check shouldn't have to be made to ensure it's got the right type. How can I do this?

答:
Make the repository generic, and introduce types for each type of item. eg:</p>
```<code>public abstract class Item
{

}
public class FileItem : Item
{

}
public abstract class Repository<TItem> where TItem : Item
{
    public virtual string RepositoryType => typeof(TItem).Name;
    public abstract CreateResult CreateItem(TItem item);
    public abstract DeleteResult DeleteItemById(Guid Id);
    public abstract Item GetItem(Guid Id);
}

public class FileRepository : Repository<FileItem>
{
    public override CreateResult CreateItem(FileItem item)
    {
        throw new NotImplementedException();
    }

    public override DeleteResult DeleteItemById(Guid Id)
    {
        throw new NotImplementedException();
    }

    public override Item GetItem(Guid Id)
    {
        throw new NotImplementedException();
    }
}
</code>```

Body:
I feel like this is an anti pattern of some sort, but basically I've got 2 versions of the same type of repo that have the same type of properties and methods. I played with the idea of both an interface and an abstract class but in neither case can I get around what appears to be unnecessary checks. Here's the premise (using abstract class):

public abstract class BaseRepository
{
    public abstract RepositoryType RepositoryType { get; } //enum of File or DataBase
    public abstract CreateResult CreateItem (Item item);
    public abstract DeleteResult DeleteItemById(Guid Id);
    public abstract Item GetItem(Guid Id);
}

public class Item
{
    public Guid Id { get; }
    public string Name { get; }
    public ItemType ItemType { get; } //enum of File or DataRecord

    //other props...
}

public FileRepository : BaseRepository
{
    public override RepositoryType RepositoryType => RepositoryType.File

    public override CreateResult CreateItem(Item item)
    {
        if(item.ItemType != ItemType.File) throw InvalidOperationException("some error message") //problem is here

        //some logic.
    }

    //other overrides....
}

So there's a basic contract created for a repository via the BaseRepository, which is overridden by the FileRepository. An item basically has the same stuff whether it's a File item or a DataRecord item (there could arguably be an IItem interface and then 2 separate Items of DataRecord and File rather than an enum but that still doesn't solve the problem).

The problem is I don't see how I can pass in an Item with only ItemType File to the FileRepository. It feels like there should be a way of making sure that the FileRepository only receives items of type File and that a check shouldn't have to be made to ensure it's got the right type. How can I do this?

Body:
Make the repository generic, and introduce types for each type of item. eg:

public abstract class Item
{

}
public class FileItem : Item
{

}
public abstract class Repository<TItem> where TItem : Item
{
    public virtual string RepositoryType => typeof(TItem).Name;
    public abstract CreateResult CreateItem(TItem item);
    public abstract DeleteResult DeleteItemById(Guid Id);
    public abstract Item GetItem(Guid Id);
}

public class FileRepository : Repository<FileItem>
{
    public override CreateResult CreateItem(FileItem item)
    {
        throw new NotImplementedException();
    }

    public override DeleteResult DeleteItemById(Guid Id)
    {
        throw new NotImplementedException();
    }

    public override Item GetItem(Guid Id)
    {
        throw new NotImplementedException();
    }
}


问:
submit button just refreshes php
```<code><form method="POST">
    <div class="form-outline form-white mb-4">
  <input type="password" name="password" class="form-control" required/>
  <label class="form-label" for="form">Pass</label>
</div>
    <button type="Submit" value="send" class="btn transparent btn-block" style="color: white;">Submit</button>
  </form>

   if (isset($_POST['submit'])) {
      $password=$_POST['password'];

      if ($password=='password') {
        header("location:ari.html");
        exit();
      }
      else
        echo "Incorrect.";
    }
</code>```

I'm beginning php currently and I'm trying to use a login method, but whenever I press my submit button my code refreshes and doesn't move onto the next page I indicated. (location:ari.html)
If I could get help on what I did wrong that would be great thanks.

答:
you should consider using action attribute in form tag and point into some POST url that retrieve your data
use action line this

```<code><form method="POST" action="/ari.php">
</code>```

submit button refresh the page without action attribute it just point to current URL if you dont fill it

Title: submit button just refreshes php

Body:
<form method="POST">

  <input type="password" name="password" class="form-control" required/>
  Pass

    <button type="Submit" value="send" class="btn transparent btn-block" style="color: white;">Submit</button>
  </form>

   if (isset($_POST['submit'])) {
      $password=$_POST['password'];

      if ($password=='password') {
        header("location:ari.html");
        exit();
      }
      else
        echo "Incorrect.";
    }

I'm beginning php currently and I'm trying to use a login method, but whenever I press my submit button my code refreshes and doesn't move onto the next page I indicated. (location:ari.html)
If I could get help on what I did wrong that would be great thanks.

Body:
you should consider using action attribute in form tag and point into some POST url that retrieve your data
use action line this

<form method="POST" action="/ari.php">

submit button refresh the page without action attribute it just point to current URL if you dont fill it


问:
PDF compare on linux command line
I'm looking for a Linux command line tool to compare two PDF files and save the diffs to a PDF outfile. The tool should create diff-pdf's in a batch-process. The PDF files are construction plans, so pure text-compare doesn't work.

Something like:

```<code><tool> file1.pdf file2.pdf -o diff-out.pdf
</code>```

Most of the tools I found convert the PDFs to images and compare them, but only with a GUI.

Any other solution is also welcome.

答:
In 2022, the answers based on applying compare directly to PDF files are not working for me. It seems that this command no longer handles PDFs properly.

However, compare does work when applied to PNG files.

I have adopted bits and pieces from the previous answers to write a different script. In fact, two different scripts, doing slightly different things: ComparePdfs.sh and ComparePdfs2.sh, to be executed on the command line. Both scripts are listed at the end of this answer.

Some caveats

These two scripts are comparing the two PDF files page by page, and each pair of pages is compared purely visually (since the pages are converted to PNG). So the scripts are sensitive only to flat text and flat graphics. If the only difference between the two PDF files concerns some other kind of PDF content—such as logical structuring elements, annotations, form-fields, layers, videos, 3D objects (U3D or PRC), etc.—both scripts will nevertheless report that the two PDFs are the same.

I haven't tried to compare PDFs specifically as far as some of this 'extra' kind of content.

How to tell if two files (PDF or not) have completely identical content

The only other kind of comparison I know how to do is the one that lets us know if the contents of the two PDF files are completely identical in every respect, including the various embedded metadata, such as the creation date, the document’s title (which has nothing to do with any title displayed on the first page), the program used to create the PDF, and so on.

It's the same method that can be used to check if any two files (PDF or not) are bit-by-bit identical.

To do this, all you have to do is compute and compare checksums for the two files. I'm including a script for that as well, called AreIdentical.sh. It is listed at the very end of this question. Here is how to use it.

Suppose the two files are named "my_first_PDF_file.pdf" and "another_PDF_file.pdf". Then, once you execute the following on the command line, the output text will read "same" or "different" depending on whether the two files are the same or different.

```<code>AreIdentical.sh my_first_PDF_file.pdf another_PDF_file.pdf
</code>```

Note that information such as the file's name is not considered when the checksums are computed. The reason is that the name of the file is stored not within the file itself but in the directory entry of the file. So two files may be found to be identical even if their file names are different; see this question. Similarly, the creation date as returned by ls -l (as opposed to the one that's in the PDF's embedded metadata) is also not considered when checksums are computed, for the same reason.

How to use the scripts ComparePdfs.sh and ComparePdfs2.sh

We assume that the two pdf files to be (purely visually) compared, file1.pdf and file2.pdf, are in the working directory.

As an example, assume that they both have 4 pages, and that all pages are identical except page 3.

To do exactly what the OP asked for,

on the command line, we execute

```<code>ComparePdfs2.sh file1.pdf file2.pdf dif_in_files.pdf
</code>```

where I picked a particular name, dif_in_files.pdf, for the outfile. The execution takes a bit of time because for both input PDF files, each individual page must be converted to PNG. The current page being processed is printed in the terminal. At the end, in the working directory, the script will produce the file dif_in_files.pdf, which contains the difference pages for all the pages. Any differences are highlighted in red.

If we are only interested to see the pages that are different, or only interested to see if they are different, then we use ComparePdfs.sh.

On the command line, we execute

```<code>ComparePdfs.sh file1.pdf file2.pdf
</code>```

In the terminal, the script will output the following:

```<code>page_001: same
page_002: same
page_003: different
page_004: same
</code>```

For the pages that turned out different, and only those pages, the script will create files that highlight the differences. In the above example, the script would generate just one file, called difference_page_003.png.

How ComparePdfs.sh works

For each of the two pdf files, we use pdftk to burst it into individual pages, and then convert each page to PNG. Now we consider the PNGs of the first pages of the two files. We create a checksum for each (I chose to use b2sum to do that).

If the checksums are the same, we take the first pages of the two files to be the same.

If the checksums are different, we take the first pages of the two files to be different, and use compare to generate a difference PNG file for them.

We repeat this for each page. At the end, we erase all the .pdf and .png files of the individual pages, except for the difference files.

The scripts

Here is ComparePdfs2.sh.

```<code>#!/bin/bash
file_1="$1"
file_2="$2"
outfile="$3"

# here we set the DPI resolution for the pdftoppm command, which will convert PDF to PNG
resolution=150

# bursting the files into individual pages
pdftk  $file_1  burst  output ${file_1%.*}---page_%03d.pdf
pdftk  $file_2  burst  output ${file_2%.*}---page_%03d.pdf

# this will be a string variable in which we collect that names of .png files to be converted to a single .pdf file
DiffFiles=""

# we loop over the individual pages of the first file
for f1 in `echo ${file_1%.*}---`*.pdf
do

  # f2 is the name of the PDF of the corresponding page of the second file
  f2="${f1/${file_1%.*}/${file_2%.*}}"

  # 'b' is an auxilliary varable used to create the variable 'page'
  b="${f1/${file_1%.*}---/""}"

  # 'page' hold the current page number, e.g. 'page_003'
  page="${b/.pdf/}"

  # print the current page being processed
  echo -n "$page "

  # convert the individual page PDFs to PNGs
  pdftoppm "$f1" "${f1%.*}" -png -r $resolution
  pdftoppm "$f2" "${f2%.*}" -png -r $resolution

  # 'g1' and 'g2' are the names of the two PNG files we just created
  g1=${f1%.*}-1.png
  g2=${f2%.*}-1.png

  # create the difference file for this page
  compare "$g1" "$g2" ${outfile%.*}_"$page".png

  # add the latest name of the difference .png file to the DiffFiles variable
  DiffFiles=$DiffFiles""${outfile%.*}_"$page".png" "
done
echo

# convert the .png difference files to a single .pdf file
convert $DiffFiles $outfile

# clean up
rm -f `echo ${file_1%.*}---page_`* `echo ${file_2%.*}---page_`* `echo ${outfile%.*}_page_`* doc_data.txt
</code>```

Here is ComparePdfs.sh

```<code>#!/bin/bash
file_1="$1"
file_2="$2"

# here we set the DPI resolution for the pdftoppm command, which will convert PDF to PNG
resolution=150

# bursting the files into individual pages
pdftk  $file_1  burst  output ${file_1%.*}---page_%03d.pdf
pdftk  $file_2  burst  output ${file_2%.*}---page_%03d.pdf

# we loop over the individual pages of the first file
for f1 in `echo ${file_1%.*}---`*.pdf
do
  # f2 is the name of the PDF of the corresponding page of the second file
  f2="${f1/${file_1%.*}/${file_2%.*}}"

  # 'b' is an auxilliary varable used to create the variable 'page'
  b="${f1/${file_1%.*}---/""}"

  # 'page' hold the current page number, e.g. 'page_003'
  page="${b/.pdf/}"

  # convert the individual page PDFs to PNGs
  pdftoppm "$f1" "${f1%.*}" -png -r $resolution
  pdftoppm "$f2" "${f2%.*}" -png -r $resolution

  # 'g1' and 'g2' are the names of the two PNG files we just created
  g1=${f1%.*}-1.png
  g2=${f2%.*}-1.png

  # create the checksums for the two PNG files
  B2S_1=$(b2sum "$g1" | awk '{print $1}')
  B2S_2=$(b2sum "$g2" | awk '{print $1}')

  # now we compare the checksums
  if [ "$B2S_1" = "$B2S_2" ]; then
       echo "$page: same";
  else
       echo "$page: different";
       # if the checksums are different, create a difference PNG image
       compare "$g1" "$g2" difference_"$page".png
  fi
done

# clean up
rm -f `echo ${file_1%.*}---page_`* `echo ${file_2%.*}---page_`* doc_data.txt
</code>```

Finally, here is AreIdentical.sh:

```<code>#!/bin/bash
file_1="$1"
file_2="$2"
B2S_1=$(b2sum $file_1 | awk '{print $1}')
B2S_2=$(b2sum $file_2 | awk '{print $1}')
if [ "$B2S_1" = "$B2S_2" ]; then echo "same"; else echo "different"; fi
</code>```

Title: PDF compare on linux command line

Body:
I'm looking for a Linux command line tool to compare two PDF files and save the diffs to a PDF outfile. The tool should create diff-pdf's in a batch-process. The PDF files are construction plans, so pure text-compare doesn't work.

Something like:

<tool> file1.pdf file2.pdf -o diff-out.pdf

Most of the tools I found convert the PDFs to images and compare them, but only with a GUI.

Any other solution is also welcome.

Body:
In 2022, the answers based on applying compare directly to PDF files are not working for me. It seems that this command no longer handles PDFs properly.

However, compare does work when applied to PNG files.

I have adopted bits and pieces from the previous answers to write a different script. In fact, two different scripts, doing slightly different things: ComparePdfs.sh and ComparePdfs2.sh, to be executed on the command line. Both scripts are listed at the end of this answer.

Some caveats

These two scripts are comparing the two PDF files page by page, and each pair of pages is compared purely visually (since the pages are converted to PNG). So the scripts are sensitive only to flat text and flat graphics. If the only difference between the two PDF files concerns some other kind of PDF content—such as logical structuring elements, annotations, form-fields, layers, videos, 3D objects (U3D or PRC), etc.—both scripts will nevertheless report that the two PDFs are the same.

I haven't tried to compare PDFs specifically as far as some of this 'extra' kind of content.

How to tell if two files (PDF or not) have completely identical content

The only other kind of comparison I know how to do is the one that lets us know if the contents of the two PDF files are completely identical in every respect, including the various embedded metadata, such as the creation date, the document’s title (which has nothing to do with any title displayed on the first page), the program used to create the PDF, and so on.

It's the same method that can be used to check if any two files (PDF or not) are bit-by-bit identical.

To do this, all you have to do is compute and compare checksums for the two files. I'm including a script for that as well, called AreIdentical.sh. It is listed at the very end of this question. Here is how to use it.

Suppose the two files are named "my_first_PDF_file.pdf" and "another_PDF_file.pdf". Then, once you execute the following on the command line, the output text will read "same" or "different" depending on whether the two files are the same or different.

AreIdentical.sh my_first_PDF_file.pdf another_PDF_file.pdf

Note that information such as the file's name is not considered when the checksums are computed. The reason is that the name of the file is stored not within the file itself but in the directory entry of the file. So two files may be found to be identical even if their file names are different; see this question. Similarly, the creation date as returned by ls -l (as opposed to the one that's in the PDF's embedded metadata) is also not considered when checksums are computed, for the same reason.

How to use the scripts ComparePdfs.sh and ComparePdfs2.sh

We assume that the two pdf files to be (purely visually) compared, file1.pdf and file2.pdf, are in the working directory.

As an example, assume that they both have 4 pages, and that all pages are identical except page 3.

To do exactly what the OP asked for,

on the command line, we execute

ComparePdfs2.sh file1.pdf file2.pdf dif_in_files.pdf

where I picked a particular name, dif_in_files.pdf, for the outfile. The execution takes a bit of time because for both input PDF files, each individual page must be converted to PNG. The current page being processed is printed in the terminal. At the end, in the working directory, the script will produce the file dif_in_files.pdf, which contains the difference pages for all the pages. Any differences are highlighted in red.

If we are only interested to see the pages that are different, or only interested to see if they are different, then we use ComparePdfs.sh.

On the command line, we execute

ComparePdfs.sh file1.pdf file2.pdf

In the terminal, the script will output the following:

page_001: same
page_002: same
page_003: different
page_004: same

For the pages that turned out different, and only those pages, the script will create files that highlight the differences. In the above example, the script would generate just one file, called difference_page_003.png.

How ComparePdfs.sh works

For each of the two pdf files, we use pdftk to burst it into individual pages, and then convert each page to PNG. Now we consider the PNGs of the first pages of the two files. We create a checksum for each (I chose to use b2sum to do that).

If the checksums are the same, we take the first pages of the two files to be the same.

If the checksums are different, we take the first pages of the two files to be different, and use compare to generate a difference PNG file for them.

We repeat this for each page. At the end, we erase all the .pdf and .png files of the individual pages, except for the difference files.

The scripts

Here is ComparePdfs2.sh.

#!/bin/bash
file_1="$1"
file_2="$2"
outfile="$3"

# here we set the DPI resolution for the pdftoppm command, which will convert PDF to PNG
resolution=150

# bursting the files into individual pages
pdftk  $file_1  burst  output ${file_1%.*}---page_%03d.pdf
pdftk  $file_2  burst  output ${file_2%.*}---page_%03d.pdf

# this will be a string variable in which we collect that names of .png files to be converted to a single .pdf file
DiffFiles=""

# we loop over the individual pages of the first file
for f1 in `echo ${file_1%.*}---`*.pdf
do

  # f2 is the name of the PDF of the corresponding page of the second file
  f2="${f1/${file_1%.*}/${file_2%.*}}"

  # 'b' is an auxilliary varable used to create the variable 'page'
  b="${f1/${file_1%.*}---/""}"

  # 'page' hold the current page number, e.g. 'page_003'
  page="${b/.pdf/}"

  # print the current page being processed
  echo -n "$page "

  # convert the individual page PDFs to PNGs
  pdftoppm "$f1" "${f1%.*}" -png -r $resolution
  pdftoppm "$f2" "${f2%.*}" -png -r $resolution

  # 'g1' and 'g2' are the names of the two PNG files we just created
  g1=${f1%.*}-1.png
  g2=${f2%.*}-1.png

  # create the difference file for this page
  compare "$g1" "$g2" ${outfile%.*}_"$page".png

  # add the latest name of the difference .png file to the DiffFiles variable
  DiffFiles=$DiffFiles""${outfile%.*}_"$page".png" "
done
echo

# convert the .png difference files to a single .pdf file
convert $DiffFiles $outfile

# clean up
rm -f `echo ${file_1%.*}---page_`* `echo ${file_2%.*}---page_`* `echo ${outfile%.*}_page_`* doc_data.txt

Here is ComparePdfs.sh

#!/bin/bash
file_1="$1"
file_2="$2"

# here we set the DPI resolution for the pdftoppm command, which will convert PDF to PNG
resolution=150

# bursting the files into individual pages
pdftk  $file_1  burst  output ${file_1%.*}---page_%03d.pdf
pdftk  $file_2  burst  output ${file_2%.*}---page_%03d.pdf

# we loop over the individual pages of the first file
for f1 in `echo ${file_1%.*}---`*.pdf
do
  # f2 is the name of the PDF of the corresponding page of the second file
  f2="${f1/${file_1%.*}/${file_2%.*}}"

  # 'b' is an auxilliary varable used to create the variable 'page'
  b="${f1/${file_1%.*}---/""}"

  # 'page' hold the current page number, e.g. 'page_003'
  page="${b/.pdf/}"

  # convert the individual page PDFs to PNGs
  pdftoppm "$f1" "${f1%.*}" -png -r $resolution
  pdftoppm "$f2" "${f2%.*}" -png -r $resolution

  # 'g1' and 'g2' are the names of the two PNG files we just created
  g1=${f1%.*}-1.png
  g2=${f2%.*}-1.png

  # create the checksums for the two PNG files
  B2S_1=$(b2sum "$g1" | awk '{print $1}')
  B2S_2=$(b2sum "$g2" | awk '{print $1}')

  # now we compare the checksums
  if [ "$B2S_1" = "$B2S_2" ]; then
       echo "$page: same";
  else
       echo "$page: different";
       # if the checksums are different, create a difference PNG image
       compare "$g1" "$g2" difference_"$page".png
  fi
done

# clean up
rm -f `echo ${file_1%.*}---page_`* `echo ${file_2%.*}---page_`* doc_data.txt

Finally, here is AreIdentical.sh:

#!/bin/bash
file_1="$1"
file_2="$2"
B2S_1=$(b2sum $file_1 | awk '{print $1}')
B2S_2=$(b2sum $file_2 | awk '{print $1}')
if [ "$B2S_1" = "$B2S_2" ]; then echo "same"; else echo "different"; fi


问:
get_or_create() takes exactly 1 argument (2 given)
Last time I checked, (h) one argument:

```<code>for entry in f['entries']:
    h = {'feed':self, 'link': entry['link'],'title':entry['title'],
         'summary':entry['summary'],
         'updated_at':datetime.fromtimestamp(mktime(entry['updated_parsed']))}

    en = Entry.objects.get_or_create(h)
</code>```

This code is failing with the error in the title. What can I check for?

答:
get_or_create takes keyword arguments only. If the arguments are in a dict, you can call it with:

```<code>en = Entry.objects.get_or_create(**h)
</code>```

Or you can put the keyword arguments directly:

```<code>en = Entry.objects.get_or_create(name=value, ....)
</code>```

The reason the error message told you that you supplied two arguments is that there is an implicit self parameter passed to the function.

Body:
Last time I checked, (h) one argument:

for entry in f['entries']:
    h = {'feed':self, 'link': entry['link'],'title':entry['title'],
         'summary':entry['summary'],
         'updated_at':datetime.fromtimestamp(mktime(entry['updated_parsed']))}

    en = Entry.objects.get_or_create(h)

This code is failing with the error in the title. What can I check for?

Body:
get_or_create takes keyword arguments only. If the arguments are in a dict, you can call it with:

en = Entry.objects.get_or_create(**h)

Or you can put the keyword arguments directly:

en = Entry.objects.get_or_create(name=value, ....)

The reason the error message told you that you supplied two arguments is that there is an implicit self parameter passed to the function.


问:
Creating isometric dot background in css
Desired outcome:

I want to create a background made with isometric dots. I've tried combining linear gradients to no avail. I don't want to use an image as that means I can't have dynamic foreground/background colors.

答:
You need radial-gradient() here:

html {
  height:100%;

  --s: 30px; /* control the space between circles */
             /*        v-- the radius of circle */
  --g: radial-gradient(5px at 25% 50%,red 96%,#0000);
  background: var(--g),var(--g) var(--s) calc(var(--s)/2);
  background-size: calc(2*var(--s)) var(--s);
}```


问:
Why is my for loop not transferring all list items to my dictionary (PYTHON)
I have 3 lists: year, list1, list2.
I want to create a dictionary with {year1: list_item1, year2: list_item2, etc..}
My code:

```<code>list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]

years = []
for i in range(2018,2024):
    years.append(i)

predicted_change = {}
n = 0
while n < 6:
    for i in years:
        for t in list1:
            for e in list2:
                predicted_change[i] = t
                n += 1
    break

predicted_change
</code>```

Results: {2018: 5, 2019: 5, 2020: 5, 2021: 5, 2022: 5, 2023: 5}

Any ideas? I was looking for {2018: 1, 2019: 2, 2020: 3, etc...}
Thanks!

答:
If you just want to combine two lists into a dictionary, where one list provides the key and the other list is the value, you can just do this

list1 = [1,2,3,4,5]
years = list(range(2018,2024))

predicted_change = {y:v for y,v in zip(years,list1)}

print(predicted_change)
```
<p>which gives</p>
```{2018: 1, 2019: 2, 2020: 3, 2021: 4, 2022: 5}
```
<p><em>Note</em>: It is unclear in your example what the second list is supposed to do... If you were wanting to combine the entries from both lists, you could do something like this</p>
<pre class="lang-py prettyprint-override"><code>list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
years = list(range(2018,2024))

predicted_change = {y:[lv1, lv2] for y,lv1,lv2 in zip(years,list1,list2)}

print(predicted_change)
</code>```

which creates a list of values for each "year" from the two lists

```<code>{2018: [1, 6], 2019: [2, 7], 2020: [3, 8], 2021: [4, 9], 2022: [5, 10]}
</code>```

Body:
I have 3 lists: year, list1, list2.
I want to create a dictionary with {year1: list_item1, year2: list_item2, etc..}
My code:

list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]

years = []
for i in range(2018,2024):
    years.append(i)

predicted_change = {}
n = 0
while n < 6:
    for i in years:
        for t in list1:
            for e in list2:
                predicted_change[i] = t
                n += 1
    break

predicted_change

Results: {2018: 5, 2019: 5, 2020: 5, 2021: 5, 2022: 5, 2023: 5}

Any ideas? I was looking for {2018: 1, 2019: 2, 2020: 3, etc...}
Thanks!

Body:
If you just want to combine two lists into a dictionary, where one list provides the key and the other list is the value, you can just do this

list1 = [1,2,3,4,5]
years = list(range(2018,2024))

predicted_change = {y:v for y,v in zip(years,list1)}

print(predicted_change)

which gives

{2018: 1, 2019: 2, 2020: 3, 2021: 4, 2022: 5}

Note: It is unclear in your example what the second list is supposed to do... If you were wanting to combine the entries from both lists, you could do something like this

list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]
years = list(range(2018,2024))

predicted_change = {y:[lv1, lv2] for y,lv1,lv2 in zip(years,list1,list2)}

print(predicted_change)

which creates a list of values for each "year" from the two lists

{2018: [1, 6], 2019: [2, 7], 2020: [3, 8], 2021: [4, 9], 2022: [5, 10]}


问:
How to make responsive circle border around an element?

    "use strict";

    const body = document.body;
    const bgColorsBody = ["#ffb457", "#ff96bd", "#9999fb", "#ffe797", "#cffff1"];
    const menu = body.querySelector(".menu");
    const menuItems = menu.querySelectorAll(".menu__item");
    const menuBorder = menu.querySelector(".menu__border");
    let activeItem = menu.querySelector(".active");

    function clickItem(item, index) {

        menu.style.removeProperty("--timeOut");

        if (activeItem == item) return;

        if (activeItem) {
            activeItem.classList.remove("active");
        }

        item.classList.add("active");
        body.style.backgroundColor = bgColorsBody[index];
        activeItem = item;
        offsetMenuBorder(activeItem, menuBorder);

    }

    function offsetMenuBorder(element, menuBorder) {

        const offsetActiveItem = element.getBoundingClientRect();
        const left = Math.floor(offsetActiveItem.left - menu.offsetLeft - (menuBorder.offsetWidth - offsetActiveItem.width) / 2) + "px";
        menuBorder.style.transform = `translate3d(${left}, 0 , 0)`;

    }

    offsetMenuBorder(activeItem, menuBorder);

    menuItems.forEach((item, index) => {

        item.addEventListener("click", () => clickItem(item, index));

    })

    window.addEventListener("resize", () => {
        offsetMenuBorder(activeItem, menuBorder);
        menu.style.setProperty("--timeOut", "none");
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    html {
        box-sizing: border-box;
        --bgColorMenu: #1d1d27;
        --duration: .7s;
    }

    html *,
    html *::before,
    html *::after {
        box-sizing: inherit;
    }

    body {
        margin: 0;
        display: flex;
        height: 100vh;
        overflow: hidden;
        align-items: center;
        justify-content: center;
        background-color: #ffb457;
        -webkit-tap-highlight-color: transparent;
        transition: background-color var(--duration);
    }

    .border {
        width: 100px;
        height: 100px;
    }

    .border svg {
        content: "";
        position: absolute !important;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 1;
        stroke-width: 5px;
        fill: none;
        stroke-dasharray: 3000;
        stroke-dashoffset: 3000;
        transition: stroke-dashoffset 2s;
    }

    .border svg circle {
        width: 100%;
        height: 100%;
    }

    .border:hover svg {
        transition: stroke-dashoffset 6s;
        stroke-dashoffset: 0;
    }

    .menu {
        margin: 0;
        display: flex;
        /* Works well with 100% width  */
        width: 32.05em;
        font-size: 1.5em;
        padding: 0 2.85em;
        position: relative;
        align-items: center;
        justify-content: center;
        background-color: var(--bgColorMenu);
    }

    .menu__item {
        all: unset;
        flex-grow: 1;
        z-index: 100;
        display: flex;
        cursor: pointer;
        position: relative;
        border-radius: 50%;
        align-items: center;
        will-change: transform;
        justify-content: center;
        padding: 0.55em 0 0.85em;
        transition: transform var(--timeOut, var(--duration));
    }

    .menu__item::before {
        content: "";
        z-index: -1;
        width: 4.2em;
        height: 4.2em;
        border-radius: 50%;
        position: absolute;
        transform: scale(0);
        transition: background-color var(--duration), transform var(--duration);
    }

    .menu__item.active {
        transform: translate3d(0, -.8em, 0);
    }

    .menu__item.active::before {
        transform: scale(1);
        background-color: var(--bgColorItem);
    }

    .icon {
        width: 2.6em;
        height: 2.6em;
        stroke: white;
        fill: transparent;
        stroke-width: 1pt;
        stroke-miterlimit: 10;
        stroke-linecap: round;
        stroke-linejoin: round;
        stroke-dasharray: 400;
    }

    .menu__item.active .icon {
        animation: strok 1.5s reverse;
    }

    @keyframes strok {
        100% {
            stroke-dashoffset: 400;
        }
    }

    .menu__border {
        left: 0;
        bottom: 99%;
        width: 10.9em;
        height: 2.4em;
        position: absolute;
        clip-path: url(#menu);
        will-change: transform;
        background-color: var(--bgColorMenu);
        transition: transform var(--timeOut, var(--duration));
    }

    .svg-container {
        width: 0;
        height: 0;
    }

    @media screen and (max-width: 50em) {
        .menu {
            font-size: .8em;
        }
    }</code>```

        <svg>
        <defs>
       <linearGradient x1="0%" y1="0%" x2="100%" y2="0%">
         <stop offset="0%" style="stop-color:#f093fb;stop-opacity:1" />
         <stop offset="100%" style="stop-color:#f5576c;stop-opacity:1" />
       </linearGradient>
     </defs>
          <circle cx="23" cy="26" r="25" stroke="black" stroke-width="3">
      </svg>

    <menu class="menu">

        <button class="menu__item active" style="--bgColorItem: #ff8c00;">
      <svg class="icon" viewBox="0 0 24 24">
        <path d="M3.8,6.6h16.4"/>
        <path d="M20.2,12.1H3.8"/>
        <path d="M3.8,17.5h16.4"/>
      </svg>
    </button>

        <button class="menu__item" style="--bgColorItem: #f54888;">
      <svg class="icon" viewBox="0 0 24 24">
        <path  d="M6.7,4.8h10.7c0.3,0,0.6,0.2,0.7,0.5l2.8,7.3c0,0.1,0,0.2,0,0.3v5.6c0,0.4-0.4,0.8-0.8,0.8H3.8
        C3.4,19.3,3,19,3,18.5v-5.6c0-0.1,0-0.2,0.1-0.3L6,5.3C6.1,5,6.4,4.8,6.7,4.8z"/>
        <path  d="M3.4,12.9H8l1.6,2.8h4.9l1.5-2.8h4.6"/>
      </svg>
    </button>

        <button class="menu__item" style="--bgColorItem: #4343f5;">
      <svg class="icon" viewBox="0 0 24 24">
      <path  d="M3.4,11.9l8.8,4.4l8.4-4.4"/>
      <path  d="M3.4,16.2l8.8,4.5l8.4-4.5"/>
      <path  d="M3.7,7.8l8.6-4.5l8,4.5l-8,4.3L3.7,7.8z"/>
    </svg>
    </button>

        <button class="menu__item" style="--bgColorItem: #e0b115;">
      <svg class="icon" viewBox="0 0 24 24" >
        <path  d="M5.1,3.9h13.9c0.6,0,1.2,0.5,1.2,1.2v13.9c0,0.6-0.5,1.2-1.2,1.2H5.1c-0.6,0-1.2-0.5-1.2-1.2V5.1
          C3.9,4.4,4.4,3.9,5.1,3.9z"/>
        <path  d="M4.2,9.3h15.6"/>
        <path  d="M9.1,9.5v10.3"/>
    </svg>
    </button>

        <button class="menu__item" style="--bgColorItem:#65ddb7;">
      <svg class="icon" viewBox="0 0 24 24" >
        <path  d="M5.1,3.9h13.9c0.6,0,1.2,0.5,1.2,1.2v13.9c0,0.6-0.5,1.2-1.2,1.2H5.1c-0.6,0-1.2-0.5-1.2-1.2V5.1
          C3.9,4.4,4.4,3.9,5.1,3.9z"/>
        <path  d="M5.5,20l9.9-9.9l4.7,4.7"/>
        <path  d="M10.4,8.8c0,0.9-0.7,1.6-1.6,1.6c-0.9,0-1.6-0.7-1.6-1.6C7.3,8,8,7.3,8.9,7.3C9.7,7.3,10.4,8,10.4,8.8z"/>
      </svg>
    </button>

    </menu>

        <svg viewBox="0 0 202.9 45.5">
      <clipPath id="menu" clipPathUnits="objectBoundingBox" transform="scale(0.0049285362247413 0.021978021978022)">
        <path  d="M6.7,45.5c5.7,0.1,14.1-0.4,23.3-4c5.7-2.3,9.9-5,18.1-10.5c10.7-7.1,11.8-9.2,20.6-14.3c5-2.9,9.2-5.2,15.2-7
          c7.1-2.1,13.3-2.3,17.6-2.1c4.2-0.2,10.5,0.1,17.6,2.1c6.1,1.8,10.2,4.1,15.2,7c8.8,5,9.9,7.1,20.6,14.3c8.3,5.5,12.4,8.2,18.1,10.5
          c9.2,3.6,17.6,4.2,23.3,4H6.7z"/>
      </clipPath>
    </svg>

```

(First run the code) In above code, I want to make the .border circle animation (when you run code and enter the mouse into the page, you can see the border on the top left) around the .menu__item circles after click.
when the user clicked on the buttons I want to make that border with animation somehow around the menu buttons but I do not know how to do this responsively.

答:
You could create a reusable svg <symbol> and add it to your icon elements like so:

```<code><!-- circle symbol -->
<svg class="svgHidden" viewBox="0 0 24 24" aria-hidden="true">
  <symbol id="circle-ani" overflow="visible">
    <circle fill="none" cx="50%" cy="50%" r="70%">
  </symbol>
</svg>
</code>```

Modified icon:

```<code>  <button class="menu__item active" style="--bgColorItem: #ff8c00;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M3.8,6.6h16.4" />
      <path d="M20.2,12.1H3.8" />
      <path d="M3.8,17.5h16.4" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>
</code>```

Additional css

You will need to make sure, the overflow is visible, since the circle element is exceeding the boundaries of your icon's viewBox:

```<code>.svgHidden{
  position:absolute;
  width:0;
  height:0;
  overflow:hidden;
}

.menu__item svg{
  overflow:visible
}

.circle{
  stroke-width:0
}
.menu__item.active
.circle{
  stroke-width:1.5
}
</code>```

Modified example

"use strict";

const body = document.body;
const bgColorsBody = ["#ffb457", "#ff96bd", "#9999fb", "#ffe797", "#cffff1"];
const menu = body.querySelector(".menu");
const menuItems = menu.querySelectorAll(".menu__item");
const menuBorder = menu.querySelector(".menu__border");
let activeItem = menu.querySelector(".active");

function clickItem(item, index) {

  menu.style.removeProperty("--timeOut");

  if (activeItem == item) return;

  if (activeItem) {
    activeItem.classList.remove("active");
  }

  item.classList.add("active");
  body.style.backgroundColor = bgColorsBody[index];
  activeItem = item;
  offsetMenuBorder(activeItem, menuBorder);

}

function offsetMenuBorder(element, menuBorder) {

  const offsetActiveItem = element.getBoundingClientRect();
  const left = Math.floor(offsetActiveItem.left - menu.offsetLeft - (menuBorder.offsetWidth - offsetActiveItem.width) / 2) + "px";
  menuBorder.style.transform = `translate3d(${left}, 0 , 0)`;

}

offsetMenuBorder(activeItem, menuBorder);

menuItems.forEach((item, index) => {

  item.addEventListener("click", () => clickItem(item, index));

})

window.addEventListener("resize", () => {
  offsetMenuBorder(activeItem, menuBorder);
  menu.style.setProperty("--timeOut", "none");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  box-sizing: border-box;
  --bgColorMenu: #1d1d27;
  --duration: .7s;
}

html *,
html *::before,
html *::after {
  box-sizing: inherit;
}

body {
  margin: 0;
  display: flex;
  height: 100vh;
  overflow: hidden;
  align-items: center;
  justify-content: center;
  background-color: #ffb457;
  -webkit-tap-highlight-color: transparent;
  transition: background-color var(--duration);
}

.border {
  width: 100px;
  height: 100px;
}

.border svg {
  content: "";
  position: absolute !important;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 1;
  stroke-width: 5px;
  fill: none;
  stroke-dasharray: 3000;
  stroke-dashoffset: 3000;
  transition: stroke-dashoffset 2s;
}

.border svg circle {
  width: 100%;
  height: 100%;
}

.border:hover svg {
  transition: stroke-dashoffset 6s;
  stroke-dashoffset: 0;
}

.menu {
  margin: 0;
  display: flex;
  /* Works well with 100% width  */
  width: 32.05em;
  font-size: 1.5em;
  padding: 0 2.85em;
  position: relative;
  align-items: center;
  justify-content: center;
  background-color: var(--bgColorMenu);
}

.menu__item {
  all: unset;
  flex-grow: 1;
  z-index: 100;
  display: flex;
  cursor: pointer;
  position: relative;
  border-radius: 50%;
  align-items: center;
  will-change: transform;
  justify-content: center;
  padding: 0.55em 0 0.85em;
  transition: transform var(--timeOut, var(--duration));
}

.menu__item::before {
  content: "";
  z-index: -1;
  width: 4.2em;
  height: 4.2em;
  border-radius: 50%;
  position: absolute;
  transform: scale(0);
  transition: background-color var(--duration), transform var(--duration);
}

.menu__item.active {
  transform: translate3d(0, -.8em, 0);
}

.menu__item.active::before {
  transform: scale(1);
  background-color: var(--bgColorItem);
}

.icon {
  width: 2.6em;
  height: 2.6em;
  stroke: white;
  fill: transparent;
  stroke-width: 1pt;
  stroke-miterlimit: 10;
  stroke-linecap: round;
  stroke-linejoin: round;
  stroke-dasharray: 400;
}

.menu__item.active .icon {
  animation: strok 1.5s reverse;
}

@keyframes strok {
  100% {
    stroke-dashoffset: 400;
  }
}

.menu__border {
  left: 0;
  bottom: 99%;
  width: 10.9em;
  height: 2.4em;
  position: absolute;
  clip-path: url(#menu);
  will-change: transform;
  background-color: var(--bgColorMenu);
  transition: transform var(--timeOut, var(--duration));
}

.svg-container {
  width: 0;
  height: 0;
}

@media screen and (max-width: 50em) {
  .menu {
    font-size: .8em;
  }
}

.svgHidden {
  position: absolute;
  width: 0;
  height: 0;
  overflow: hidden;
}

.menu__item svg {
  overflow: visible
}

.circle {
  stroke-width: 0
}

.menu__item.active .circle {
  stroke-width: 1.5
}</code>```

<svg class="svgHidden" viewBox="0 0 24 24" aria-hidden="true">
  <symbol id="circle-ani" overflow="visible">
    <circle fill="none" cx="50%" cy="50%" r="70%">
  </symbol>
</svg>

<menu class="menu">
  <button class="menu__item active" style="--bgColorItem: #ff8c00;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M3.8,6.6h16.4" />
      <path d="M20.2,12.1H3.8" />
      <path d="M3.8,17.5h16.4" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

  <button class="menu__item" style="--bgColorItem: #f54888;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M6.7,4.8h10.7c0.3,0,0.6,0.2,0.7,0.5l2.8,7.3c0,0.1,0,0.2,0,0.3v5.6c0,0.4-0.4,0.8-0.8,0.8H3.8
        C3.4,19.3,3,19,3,18.5v-5.6c0-0.1,0-0.2,0.1-0.3L6,5.3C6.1,5,6.4,4.8,6.7,4.8z" />
      <path d="M3.4,12.9H8l1.6,2.8h4.9l1.5-2.8h4.6" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

  <button class="menu__item" style="--bgColorItem: #4343f5;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M3.4,11.9l8.8,4.4l8.4-4.4" />
      <path d="M3.4,16.2l8.8,4.5l8.4-4.5" />
      <path d="M3.7,7.8l8.6-4.5l8,4.5l-8,4.3L3.7,7.8z" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

  <button class="menu__item" style="--bgColorItem: #e0b115;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M5.1,3.9h13.9c0.6,0,1.2,0.5,1.2,1.2v13.9c0,0.6-0.5,1.2-1.2,1.2H5.1c-0.6,0-1.2-0.5-1.2-1.2V5.1
          C3.9,4.4,4.4,3.9,5.1,3.9z" />
      <path d="M4.2,9.3h15.6" />
      <path d="M9.1,9.5v10.3" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

  <button class="menu__item" style="--bgColorItem:#65ddb7;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M5.1,3.9h13.9c0.6,0,1.2,0.5,1.2,1.2v13.9c0,0.6-0.5,1.2-1.2,1.2H5.1c-0.6,0-1.2-0.5-1.2-1.2V5.1
          C3.9,4.4,4.4,3.9,5.1,3.9z" />
      <path d="M5.5,20l9.9-9.9l4.7,4.7" />
      <path d="M10.4,8.8c0,0.9-0.7,1.6-1.6,1.6c-0.9,0-1.6-0.7-1.6-1.6C7.3,8,8,7.3,8.9,7.3C9.7,7.3,10.4,8,10.4,8.8z" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

</menu>

  <svg viewBox="0 0 202.9 45.5">
    <clipPath id="menu" clipPathUnits="objectBoundingBox" transform="scale(0.0049285362247413 0.021978021978022)">
      <path d="M6.7,45.5c5.7,0.1,14.1-0.4,23.3-4c5.7-2.3,9.9-5,18.1-10.5c10.7-7.1,11.8-9.2,20.6-14.3c5-2.9,9.2-5.2,15.2-7
          c7.1-2.1,13.3-2.3,17.6-2.1c4.2-0.2,10.5,0.1,17.6,2.1c6.1,1.8,10.2,4.1,15.2,7c8.8,5,9.9,7.1,20.6,14.3c8.3,5.5,12.4,8.2,18.1,10.5
          c9.2,3.6,17.6,4.2,23.3,4H6.7z" />
    </clipPath>
  </svg>

```

Body:
    "use strict";

    const body = document.body;
    const bgColorsBody = ["#ffb457", "#ff96bd", "#9999fb", "#ffe797", "#cffff1"];
    const menu = body.querySelector(".menu");
    const menuItems = menu.querySelectorAll(".menu__item");
    const menuBorder = menu.querySelector(".menu__border");
    let activeItem = menu.querySelector(".active");

    function clickItem(item, index) {

        menu.style.removeProperty("--timeOut");

        if (activeItem == item) return;

        if (activeItem) {
            activeItem.classList.remove("active");
        }

        item.classList.add("active");
        body.style.backgroundColor = bgColorsBody[index];
        activeItem = item;
        offsetMenuBorder(activeItem, menuBorder);

    }

    function offsetMenuBorder(element, menuBorder) {

        const offsetActiveItem = element.getBoundingClientRect();
        const left = Math.floor(offsetActiveItem.left - menu.offsetLeft - (menuBorder.offsetWidth - offsetActiveItem.width) / 2) + "px";
        menuBorder.style.transform = `translate3d(${left}, 0 , 0)`;

    }

    offsetMenuBorder(activeItem, menuBorder);

    menuItems.forEach((item, index) => {

        item.addEventListener("click", () => clickItem(item, index));

    })

    window.addEventListener("resize", () => {
        offsetMenuBorder(activeItem, menuBorder);
        menu.style.setProperty("--timeOut", "none");
    });

    html {
        box-sizing: border-box;
        --bgColorMenu: #1d1d27;
        --duration: .7s;
    }

    html *,
    html *::before,
    html *::after {
        box-sizing: inherit;
    }

    body {
        margin: 0;
        display: flex;
        height: 100vh;
        overflow: hidden;
        align-items: center;
        justify-content: center;
        background-color: #ffb457;
        -webkit-tap-highlight-color: transparent;
        transition: background-color var(--duration);
    }

    .border {
        width: 100px;
        height: 100px;
    }

    .border svg {
        content: "";
        position: absolute !important;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 1;
        stroke-width: 5px;
        fill: none;
        stroke-dasharray: 3000;
        stroke-dashoffset: 3000;
        transition: stroke-dashoffset 2s;
    }

    .border svg circle {
        width: 100%;
        height: 100%;
    }

    .border:hover svg {
        transition: stroke-dashoffset 6s;
        stroke-dashoffset: 0;
    }

    .menu {
        margin: 0;
        display: flex;
        /* Works well with 100% width  */
        width: 32.05em;
        font-size: 1.5em;
        padding: 0 2.85em;
        position: relative;
        align-items: center;
        justify-content: center;
        background-color: var(--bgColorMenu);
    }

    .menu__item {
        all: unset;
        flex-grow: 1;
        z-index: 100;
        display: flex;
        cursor: pointer;
        position: relative;
        border-radius: 50%;
        align-items: center;
        will-change: transform;
        justify-content: center;
        padding: 0.55em 0 0.85em;
        transition: transform var(--timeOut, var(--duration));
    }

    .menu__item::before {
        content: "";
        z-index: -1;
        width: 4.2em;
        height: 4.2em;
        border-radius: 50%;
        position: absolute;
        transform: scale(0);
        transition: background-color var(--duration), transform var(--duration);
    }

    .menu__item.active {
        transform: translate3d(0, -.8em, 0);
    }

    .menu__item.active::before {
        transform: scale(1);
        background-color: var(--bgColorItem);
    }

    .icon {
        width: 2.6em;
        height: 2.6em;
        stroke: white;
        fill: transparent;
        stroke-width: 1pt;
        stroke-miterlimit: 10;
        stroke-linecap: round;
        stroke-linejoin: round;
        stroke-dasharray: 400;
    }

    .menu__item.active .icon {
        animation: strok 1.5s reverse;
    }

    @keyframes strok {
        100% {
            stroke-dashoffset: 400;
        }
    }

    .menu__border {
        left: 0;
        bottom: 99%;
        width: 10.9em;
        height: 2.4em;
        position: absolute;
        clip-path: url(#menu);
        will-change: transform;
        background-color: var(--bgColorMenu);
        transition: transform var(--timeOut, var(--duration));
    }

    .svg-container {
        width: 0;
        height: 0;
    }

    @media screen and (max-width: 50em) {
        .menu {
            font-size: .8em;
        }
    }

        <svg>
        <defs>
       <linearGradient x1="0%" y1="0%" x2="100%" y2="0%">
         <stop offset="0%" style="stop-color:#f093fb;stop-opacity:1" />
         <stop offset="100%" style="stop-color:#f5576c;stop-opacity:1" />
       </linearGradient>
     </defs>
          <circle cx="23" cy="26" r="25" stroke="black" stroke-width="3">
      </svg>

    <menu class="menu">

        <button class="menu__item active" style="--bgColorItem: #ff8c00;">
      <svg class="icon" viewBox="0 0 24 24">
        <path d="M3.8,6.6h16.4"/>
        <path d="M20.2,12.1H3.8"/>
        <path d="M3.8,17.5h16.4"/>
      </svg>
    </button>

        <button class="menu__item" style="--bgColorItem: #f54888;">
      <svg class="icon" viewBox="0 0 24 24">
        <path  d="M6.7,4.8h10.7c0.3,0,0.6,0.2,0.7,0.5l2.8,7.3c0,0.1,0,0.2,0,0.3v5.6c0,0.4-0.4,0.8-0.8,0.8H3.8
        C3.4,19.3,3,19,3,18.5v-5.6c0-0.1,0-0.2,0.1-0.3L6,5.3C6.1,5,6.4,4.8,6.7,4.8z"/>
        <path  d="M3.4,12.9H8l1.6,2.8h4.9l1.5-2.8h4.6"/>
      </svg>
    </button>

        <button class="menu__item" style="--bgColorItem: #4343f5;">
      <svg class="icon" viewBox="0 0 24 24">
      <path  d="M3.4,11.9l8.8,4.4l8.4-4.4"/>
      <path  d="M3.4,16.2l8.8,4.5l8.4-4.5"/>
      <path  d="M3.7,7.8l8.6-4.5l8,4.5l-8,4.3L3.7,7.8z"/>
    </svg>
    </button>

        <button class="menu__item" style="--bgColorItem: #e0b115;">
      <svg class="icon" viewBox="0 0 24 24" >
        <path  d="M5.1,3.9h13.9c0.6,0,1.2,0.5,1.2,1.2v13.9c0,0.6-0.5,1.2-1.2,1.2H5.1c-0.6,0-1.2-0.5-1.2-1.2V5.1
          C3.9,4.4,4.4,3.9,5.1,3.9z"/>
        <path  d="M4.2,9.3h15.6"/>
        <path  d="M9.1,9.5v10.3"/>
    </svg>
    </button>

        <button class="menu__item" style="--bgColorItem:#65ddb7;">
      <svg class="icon" viewBox="0 0 24 24" >
        <path  d="M5.1,3.9h13.9c0.6,0,1.2,0.5,1.2,1.2v13.9c0,0.6-0.5,1.2-1.2,1.2H5.1c-0.6,0-1.2-0.5-1.2-1.2V5.1
          C3.9,4.4,4.4,3.9,5.1,3.9z"/>
        <path  d="M5.5,20l9.9-9.9l4.7,4.7"/>
        <path  d="M10.4,8.8c0,0.9-0.7,1.6-1.6,1.6c-0.9,0-1.6-0.7-1.6-1.6C7.3,8,8,7.3,8.9,7.3C9.7,7.3,10.4,8,10.4,8.8z"/>
      </svg>
    </button>

    </menu>

        <svg viewBox="0 0 202.9 45.5">
      <clipPath id="menu" clipPathUnits="objectBoundingBox" transform="scale(0.0049285362247413 0.021978021978022)">
        <path  d="M6.7,45.5c5.7,0.1,14.1-0.4,23.3-4c5.7-2.3,9.9-5,18.1-10.5c10.7-7.1,11.8-9.2,20.6-14.3c5-2.9,9.2-5.2,15.2-7
          c7.1-2.1,13.3-2.3,17.6-2.1c4.2-0.2,10.5,0.1,17.6,2.1c6.1,1.8,10.2,4.1,15.2,7c8.8,5,9.9,7.1,20.6,14.3c8.3,5.5,12.4,8.2,18.1,10.5
          c9.2,3.6,17.6,4.2,23.3,4H6.7z"/>
      </clipPath>
    </svg>

(First run the code) In above code, I want to make the .border circle animation (when you run code and enter the mouse into the page, you can see the border on the top left) around the .menu__item circles after click.
when the user clicked on the buttons I want to make that border with animation somehow around the menu buttons but I do not know how to do this responsively.

Body:
You could create a reusable svg <symbol> and add it to your icon elements like so:

<!-- circle symbol -->
<svg class="svgHidden" viewBox="0 0 24 24" aria-hidden="true">
  <symbol id="circle-ani" overflow="visible">
    <circle fill="none" cx="50%" cy="50%" r="70%">
  </symbol>
</svg>

Modified icon:

  <button class="menu__item active" style="--bgColorItem: #ff8c00;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M3.8,6.6h16.4" />
      <path d="M20.2,12.1H3.8" />
      <path d="M3.8,17.5h16.4" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

Additional css

You will need to make sure, the overflow is visible, since the circle element is exceeding the boundaries of your icon's viewBox:

.svgHidden{
  position:absolute;
  width:0;
  height:0;
  overflow:hidden;
}

.menu__item svg{
  overflow:visible
}

.circle{
  stroke-width:0
}
.menu__item.active
.circle{
  stroke-width:1.5
}

Modified example

"use strict";

const body = document.body;
const bgColorsBody = ["#ffb457", "#ff96bd", "#9999fb", "#ffe797", "#cffff1"];
const menu = body.querySelector(".menu");
const menuItems = menu.querySelectorAll(".menu__item");
const menuBorder = menu.querySelector(".menu__border");
let activeItem = menu.querySelector(".active");

function clickItem(item, index) {

  menu.style.removeProperty("--timeOut");

  if (activeItem == item) return;

  if (activeItem) {
    activeItem.classList.remove("active");
  }

  item.classList.add("active");
  body.style.backgroundColor = bgColorsBody[index];
  activeItem = item;
  offsetMenuBorder(activeItem, menuBorder);

}

function offsetMenuBorder(element, menuBorder) {

  const offsetActiveItem = element.getBoundingClientRect();
  const left = Math.floor(offsetActiveItem.left - menu.offsetLeft - (menuBorder.offsetWidth - offsetActiveItem.width) / 2) + "px";
  menuBorder.style.transform = `translate3d(${left}, 0 , 0)`;

}

offsetMenuBorder(activeItem, menuBorder);

menuItems.forEach((item, index) => {

  item.addEventListener("click", () => clickItem(item, index));

})

window.addEventListener("resize", () => {
  offsetMenuBorder(activeItem, menuBorder);
  menu.style.setProperty("--timeOut", "none");
});

html {
  box-sizing: border-box;
  --bgColorMenu: #1d1d27;
  --duration: .7s;
}

html *,
html *::before,
html *::after {
  box-sizing: inherit;
}

body {
  margin: 0;
  display: flex;
  height: 100vh;
  overflow: hidden;
  align-items: center;
  justify-content: center;
  background-color: #ffb457;
  -webkit-tap-highlight-color: transparent;
  transition: background-color var(--duration);
}

.border {
  width: 100px;
  height: 100px;
}

.border svg {
  content: "";
  position: absolute !important;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 1;
  stroke-width: 5px;
  fill: none;
  stroke-dasharray: 3000;
  stroke-dashoffset: 3000;
  transition: stroke-dashoffset 2s;
}

.border svg circle {
  width: 100%;
  height: 100%;
}

.border:hover svg {
  transition: stroke-dashoffset 6s;
  stroke-dashoffset: 0;
}

.menu {
  margin: 0;
  display: flex;
  /* Works well with 100% width  */
  width: 32.05em;
  font-size: 1.5em;
  padding: 0 2.85em;
  position: relative;
  align-items: center;
  justify-content: center;
  background-color: var(--bgColorMenu);
}

.menu__item {
  all: unset;
  flex-grow: 1;
  z-index: 100;
  display: flex;
  cursor: pointer;
  position: relative;
  border-radius: 50%;
  align-items: center;
  will-change: transform;
  justify-content: center;
  padding: 0.55em 0 0.85em;
  transition: transform var(--timeOut, var(--duration));
}

.menu__item::before {
  content: "";
  z-index: -1;
  width: 4.2em;
  height: 4.2em;
  border-radius: 50%;
  position: absolute;
  transform: scale(0);
  transition: background-color var(--duration), transform var(--duration);
}

.menu__item.active {
  transform: translate3d(0, -.8em, 0);
}

.menu__item.active::before {
  transform: scale(1);
  background-color: var(--bgColorItem);
}

.icon {
  width: 2.6em;
  height: 2.6em;
  stroke: white;
  fill: transparent;
  stroke-width: 1pt;
  stroke-miterlimit: 10;
  stroke-linecap: round;
  stroke-linejoin: round;
  stroke-dasharray: 400;
}

.menu__item.active .icon {
  animation: strok 1.5s reverse;
}

@keyframes strok {
  100% {
    stroke-dashoffset: 400;
  }
}

.menu__border {
  left: 0;
  bottom: 99%;
  width: 10.9em;
  height: 2.4em;
  position: absolute;
  clip-path: url(#menu);
  will-change: transform;
  background-color: var(--bgColorMenu);
  transition: transform var(--timeOut, var(--duration));
}

.svg-container {
  width: 0;
  height: 0;
}

@media screen and (max-width: 50em) {
  .menu {
    font-size: .8em;
  }
}

.svgHidden {
  position: absolute;
  width: 0;
  height: 0;
  overflow: hidden;
}

.menu__item svg {
  overflow: visible
}

.circle {
  stroke-width: 0
}

.menu__item.active .circle {
  stroke-width: 1.5
}

<!-- circle element -->
<svg class="svgHidden" viewBox="0 0 24 24" aria-hidden="true">
  <symbol id="circle-ani" overflow="visible">
    <circle fill="none" cx="50%" cy="50%" r="70%">
  </symbol>
</svg>

<menu class="menu">
  <button class="menu__item active" style="--bgColorItem: #ff8c00;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M3.8,6.6h16.4" />
      <path d="M20.2,12.1H3.8" />
      <path d="M3.8,17.5h16.4" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

  <button class="menu__item" style="--bgColorItem: #f54888;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M6.7,4.8h10.7c0.3,0,0.6,0.2,0.7,0.5l2.8,7.3c0,0.1,0,0.2,0,0.3v5.6c0,0.4-0.4,0.8-0.8,0.8H3.8
        C3.4,19.3,3,19,3,18.5v-5.6c0-0.1,0-0.2,0.1-0.3L6,5.3C6.1,5,6.4,4.8,6.7,4.8z" />
      <path d="M3.4,12.9H8l1.6,2.8h4.9l1.5-2.8h4.6" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

  <button class="menu__item" style="--bgColorItem: #4343f5;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M3.4,11.9l8.8,4.4l8.4-4.4" />
      <path d="M3.4,16.2l8.8,4.5l8.4-4.5" />
      <path d="M3.7,7.8l8.6-4.5l8,4.5l-8,4.3L3.7,7.8z" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

  <button class="menu__item" style="--bgColorItem: #e0b115;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M5.1,3.9h13.9c0.6,0,1.2,0.5,1.2,1.2v13.9c0,0.6-0.5,1.2-1.2,1.2H5.1c-0.6,0-1.2-0.5-1.2-1.2V5.1
          C3.9,4.4,4.4,3.9,5.1,3.9z" />
      <path d="M4.2,9.3h15.6" />
      <path d="M9.1,9.5v10.3" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

  <button class="menu__item" style="--bgColorItem:#65ddb7;">
    <svg class="icon" viewBox="0 0 24 24">
      <path d="M5.1,3.9h13.9c0.6,0,1.2,0.5,1.2,1.2v13.9c0,0.6-0.5,1.2-1.2,1.2H5.1c-0.6,0-1.2-0.5-1.2-1.2V5.1
          C3.9,4.4,4.4,3.9,5.1,3.9z" />
      <path d="M5.5,20l9.9-9.9l4.7,4.7" />
      <path d="M10.4,8.8c0,0.9-0.7,1.6-1.6,1.6c-0.9,0-1.6-0.7-1.6-1.6C7.3,8,8,7.3,8.9,7.3C9.7,7.3,10.4,8,10.4,8.8z" />
      <use class="circle" href="#circle-ani" />
    </svg>
  </button>

  <div class="menu__border"></div>

</menu>

<div class="svg-container">
  <svg viewBox="0 0 202.9 45.5">
    <clipPath id="menu" clipPathUnits="objectBoundingBox" transform="scale(0.0049285362247413 0.021978021978022)">
      <path d="M6.7,45.5c5.7,0.1,14.1-0.4,23.3-4c5.7-2.3,9.9-5,18.1-10.5c10.7-7.1,11.8-9.2,20.6-14.3c5-2.9,9.2-5.2,15.2-7
          c7.1-2.1,13.3-2.3,17.6-2.1c4.2-0.2,10.5,0.1,17.6,2.1c6.1,1.8,10.2,4.1,15.2,7c8.8,5,9.9,7.1,20.6,14.3c8.3,5.5,12.4,8.2,18.1,10.5
          c9.2,3.6,17.6,4.2,23.3,4H6.7z" />
    </clipPath>
  </svg>
</div>


问:
Suddenly can't run TestNG tests from ant ([testng] Caused by: java.lang.ClassNotFoundException: com.beust.jcommander.ParameterException)
I am using ant and TestNG 6.1.1, and I had my tests working just fine yesterday.  Today when I try to run the tests I get a NoClassDefFoundError involving com/beust/jcommander/ParamException.  Here is the output:

```<code>[copy] Copying 1 file to /Users/djohnson/src/webapp/components/build/tmp
[testng] Exception in thread "main" java.lang.NoClassDefFoundError: com/beust/jcommander/ParameterException
[testng] Caused by: java.lang.ClassNotFoundException: com.beust.jcommander.ParameterException
[testng]    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
[testng]    at java.security.AccessController.doPrivileged(Native Method)
[testng]    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
[testng]    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
[testng]    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
[testng]    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
[testng] The tests failed.
</code>```

Here is the .xml file I'm using:

```<code><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Single Method Suite">
  <test name="Single Method Test">
    <classes>
      <class name="DhcpTest">
        <methods>
          <exclude name=".*" />
          <include name="setGetEnabledTest" />
        </methods>
      </class>
    </classes>
  </test>
</suite>
</code>```

I've also specified the complete path for the class with no luck.  I've checked the classpath and everything seems fine, does anyone have any ideas on this?

答: If you're using ant, JCommander should be inside testng.jar, so I'm thinking your testng.jar file might be corrupt.</p>

Body:
I am using ant and TestNG 6.1.1, and I had my tests working just fine yesterday.  Today when I try to run the tests I get a NoClassDefFoundError involving com/beust/jcommander/ParamException.  Here is the output:

[copy] Copying 1 file to /Users/djohnson/src/webapp/components/build/tmp
[testng] Exception in thread "main" java.lang.NoClassDefFoundError: com/beust/jcommander/ParameterException
[testng] Caused by: java.lang.ClassNotFoundException: com.beust.jcommander.ParameterException
[testng]    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
[testng]    at java.security.AccessController.doPrivileged(Native Method)
[testng]    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
[testng]    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
[testng]    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
[testng]    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
[testng] The tests failed.

Here is the .xml file I'm using:

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Single Method Suite">
  <test name="Single Method Test">
    <classes>
      <class name="DhcpTest">
        <methods>
          <exclude name=".*" />
          <include name="setGetEnabledTest" />
        </methods>
      </class>
    </classes>
  </test>
</suite>

I've also specified the complete path for the class with no luck.  I've checked the classpath and everything seems fine, does anyone have any ideas on this?