问:
Why would LIMIT 2 queries work but LIMIT 1 always times out?
I'm using this public Postgres DB of NEAR protocol: https://github.com/near/near-indexer-for-explorer#shared-public-access

postgres://public_readonly:nearprotocol@mainnet.db.explorer.indexer.near.dev/mainnet_explorer

SELECT "public"."receipts"."receipt_id",
    "public"."receipts"."included_in_block_hash",
    "public"."receipts"."included_in_chunk_hash",
    "public"."receipts"."index_in_chunk",
    "public"."receipts"."included_in_block_timestamp",
    "public"."receipts"."predecessor_account_id",
    "public"."receipts"."receiver_account_id",
    "public"."receipts"."receipt_kind",
    "public"."receipts"."originated_from_transaction_hash"
FROM "public"."receipts"
WHERE ("public"."receipts"."receipt_id") IN
        (SELECT "t0"."receipt_id"
            FROM "public"."receipts" AS "t0"
            INNER JOIN "public"."action_receipts" AS "j0" ON ("j0"."receipt_id") = ("t0"."receipt_id")
            WHERE ("j0"."signer_account_id" = 'ryancwalsh.near'
                                        AND "t0"."receipt_id" IS NOT NULL))
ORDER BY "public"."receipts"."included_in_block_timestamp" DESC
LIMIT 1
OFFSET 0
```
<p>always results in:</p>
```ERROR:  canceling statement due to statement timeout
SQL state: 57014
```

But if I change it to LIMIT 2, the query runs in less than 1 second.

How would that ever be the case? Does that mean the database isn't set up well? Or am I doing something wrong?

P.S. The query here was generated via Prisma. findFirst always times out, so I think I might need to change it to findMany as a workaround.

答:
Your query can be simplified /optimized:

SELECT r.receipt_id
     , r.included_in_block_hash
     , r.included_in_chunk_hash
     , r.index_in_chunk
     , r.included_in_block_timestamp
     , r.predecessor_account_id
     , r.receiver_account_id
     , r.receipt_kind
     , r.originated_from_transaction_hash
FROM   public.receipts r
WHERE  EXISTS (
   SELECT FROM public.action_receipts j
   WHERE  j.receipt_id = r.receipt_id
   AND    j.signer_account_id = 'ryancwalsh.near'
   )
ORDER  BY r.included_in_block_timestamp DESC
LIMIT  1;
```
<p>However, that only scratches the surface of your underlying problem.</p>
<p>Like Kirk already commented, Postgres chooses a different query plan for <code>LIMIT 1</code>, obviously ignorant of the fact that there are <strong>only 90 rows</strong> in table <code>action_receipts</code> with <code>signer_account_id = 'ryancwalsh.near'</code>, while both involved tables have more than <strong>220 million rows</strong>, obviously growing steadily.</p>
<p>Changing to <code>LIMIT 2</code> makes a different query plan seem more favorable, hence the observed difference in performance. (So the query planner has the general idea that the filter is very selective, just not close enough for the corner case of <code>LIMIT 1</code>.)</p>
<p>You should have mentioned <strong>cardinalities</strong> to set us on the right track.</p>
<p><em>Knowing</em> that our filter is so selective, we can force a more favorable query plan with a different query:</p>
<pre class="lang-sql prettyprint-override"><code>WITH j AS (
   SELECT receipt_id  -- is PK!
   FROM   public.action_receipts
   WHERE  signer_account_id = 'ryancwalsh.near'
   )
SELECT r.receipt_id
     , r.included_in_block_hash
     , r.included_in_chunk_hash
     , r.index_in_chunk
     , r.included_in_block_timestamp
     , r.predecessor_account_id
     , r.receiver_account_id
     , r.receipt_kind
     , r.originated_from_transaction_hash
FROM   j
JOIN   public.receipts r USING (receipt_id)
ORDER  BY r.included_in_block_timestamp DESC
LIMIT  1;
</code>```

This uses the same query plan for LIMIT 1, and either finishes in under 2 ms in my test:

                                                                         QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=134904.89..134904.89 rows=1 width=223) (actual time=1.750..1.754 rows=1 loops=1)
   CTE j
     ->  Bitmap Heap Scan on action_receipts  (cost=319.46..41564.59 rows=10696 width=44) (actual time=0.058..0.179 rows=90 loops=1)
           Recheck Cond: (signer_account_id = 'ryancwalsh.near'::text)
           Heap Blocks: exact=73
           ->  Bitmap Index Scan on action_receipt_signer_account_id_idx  (cost=0.00..316.79 rows=10696 width=0) (actual time=0.043..0.043 rows=90 loops=1)
                 Index Cond: (signer_account_id = 'ryancwalsh.near'::text)
   ->  Sort  (cost=93340.30..93367.04 rows=10696 width=223) (actual time=1.749..1.750 rows=1 loops=1)
         Sort Key: r.included_in_block_timestamp DESC
         Sort Method: top-N heapsort  Memory: 25kB
         ->  Nested Loop  (cost=0.70..93286.82 rows=10696 width=223) (actual time=0.089..1.705 rows=90 loops=1)
               ->  CTE Scan on j  (cost=0.00..213.92 rows=10696 width=32) (actual time=0.060..0.221 rows=90 loops=1)
               ->  Index Scan using receipts_pkey on receipts r  (cost=0.70..8.70 rows=1 width=223) (actual time=0.016..0.016 rows=1 loops=90)
                     Index Cond: (receipt_id = j.receipt_id)
 Planning Time: 0.281 ms
 Execution Time: 1.801 ms
```
<p>The point is to execute the hugely selective query in the CTE first. Then Postgres does not attempt to walk the index on <code>(included_in_block_timestamp)</code> under the wrong assumption that it would find a matching row soon enough. (It does not.)</p>
<p>The DB at hand runs <strong>Postgres 11</strong>, where CTEs are always optimization barriers. In <strong>Postgres 12</strong> or later add <code>AS MATERIALIZED</code> to the CTE to guarantee the same effect.<br />
Or you could use the <strong>"OFFSET 0 hack"</strong> in any version like this:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT r.receipt_id
     , r.included_in_block_hash
     , r.included_in_chunk_hash
     , r.index_in_chunk
     , r.included_in_block_timestamp
     , r.predecessor_account_id
     , r.receiver_account_id
     , r.receipt_kind
     , r.originated_from_transaction_hash
FROM  (
   SELECT receipt_id  -- is PK!
   FROM   public.action_receipts
   WHERE  signer_account_id = 'ryancwalsh.near'
   OFFSET 0  -- !
   ) j
JOIN   public.receipts r USING (receipt_id)
ORDER  BY r.included_in_block_timestamp DESC
LIMIT  1;
</code>```

Prevents "inlining" of the subquery to the same effect. Finishes in < 2ms.

See:

How to prevent PostgreSQL from rewriting OUTER JOIN queries?

"Fix" the database?

The proper fix depends on the complete picture. The underlying problem is that Postgres overestimates the number of qualifying rows in table action_receipts. The MCV list (most common values) cannot keep up with 220 million rows (and growing). It's most probably not just ANALYZE lagging behind. (Though it could be: autovacuum not properly configured? Rookie mistake?) Depending on the actual cardinalities (data distribution) in action_receipts.signer_account_id and access patterns you could do various things to "fix" it. Two options:

1. Increase n_distinct and STATISTICS

If most values in action_receipts.signer_account_id are equally rare (high cardinality), consider setting a very large n_distinct value for the column. And combine that with a moderately increased STATISTICS target for the same column to counter errors in the other direction (underestimating the number of qualifying rows for common values). Read both answers here:

Postgres sometimes uses inferior index for WHERE a IN (...) ORDER BY b LIMIT N

And:

Very bad query plan in PostgreSQL 9.6

2. Local fix with partial index

If action_receipts.signer_account_id = 'ryancwalsh.near' is special in that it's queried more regularly than others, consider a small partial index for it, to fix just that case. Like:

```<code>CREATE INDEX ON action_receipts (receipt_id)
WHERE signer_account_id = 'ryancwalsh.near';
</code>```

Body:
I'm using this public Postgres DB of NEAR protocol: https://github.com/near/near-indexer-for-explorer#shared-public-access

postgres://public_readonly:nearprotocol@mainnet.db.explorer.indexer.near.dev/mainnet_explorer

SELECT "public"."receipts"."receipt_id",
    "public"."receipts"."included_in_block_hash",
    "public"."receipts"."included_in_chunk_hash",
    "public"."receipts"."index_in_chunk",
    "public"."receipts"."included_in_block_timestamp",
    "public"."receipts"."predecessor_account_id",
    "public"."receipts"."receiver_account_id",
    "public"."receipts"."receipt_kind",
    "public"."receipts"."originated_from_transaction_hash"
FROM "public"."receipts"
WHERE ("public"."receipts"."receipt_id") IN
        (SELECT "t0"."receipt_id"
            FROM "public"."receipts" AS "t0"
            INNER JOIN "public"."action_receipts" AS "j0" ON ("j0"."receipt_id") = ("t0"."receipt_id")
            WHERE ("j0"."signer_account_id" = 'ryancwalsh.near'
                                        AND "t0"."receipt_id" IS NOT NULL))
ORDER BY "public"."receipts"."included_in_block_timestamp" DESC
LIMIT 1
OFFSET 0

always results in:

ERROR:  canceling statement due to statement timeout
SQL state: 57014

But if I change it to LIMIT 2, the query runs in less than 1 second.

How would that ever be the case? Does that mean the database isn't set up well? Or am I doing something wrong?

P.S. The query here was generated via Prisma. findFirst always times out, so I think I might need to change it to findMany as a workaround.

Body:
Your query can be simplified /optimized:

SELECT r.receipt_id
     , r.included_in_block_hash
     , r.included_in_chunk_hash
     , r.index_in_chunk
     , r.included_in_block_timestamp
     , r.predecessor_account_id
     , r.receiver_account_id
     , r.receipt_kind
     , r.originated_from_transaction_hash
FROM   public.receipts r
WHERE  EXISTS (
   SELECT FROM public.action_receipts j
   WHERE  j.receipt_id = r.receipt_id
   AND    j.signer_account_id = 'ryancwalsh.near'
   )
ORDER  BY r.included_in_block_timestamp DESC
LIMIT  1;

However, that only scratches the surface of your underlying problem.

Like Kirk already commented, Postgres chooses a different query plan for LIMIT 1, obviously ignorant of the fact that there are only 90 rows in table action_receipts with signer_account_id = 'ryancwalsh.near', while both involved tables have more than 220 million rows, obviously growing steadily.

Changing to LIMIT 2 makes a different query plan seem more favorable, hence the observed difference in performance. (So the query planner has the general idea that the filter is very selective, just not close enough for the corner case of LIMIT 1.)

You should have mentioned cardinalities to set us on the right track.

Knowing that our filter is so selective, we can force a more favorable query plan with a different query:

WITH j AS (
   SELECT receipt_id  -- is PK!
   FROM   public.action_receipts
   WHERE  signer_account_id = 'ryancwalsh.near'
   )
SELECT r.receipt_id
     , r.included_in_block_hash
     , r.included_in_chunk_hash
     , r.index_in_chunk
     , r.included_in_block_timestamp
     , r.predecessor_account_id
     , r.receiver_account_id
     , r.receipt_kind
     , r.originated_from_transaction_hash
FROM   j
JOIN   public.receipts r USING (receipt_id)
ORDER  BY r.included_in_block_timestamp DESC
LIMIT  1;

This uses the same query plan for LIMIT 1, and either finishes in under 2 ms in my test:

                                                                         QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=134904.89..134904.89 rows=1 width=223) (actual time=1.750..1.754 rows=1 loops=1)
   CTE j
     ->  Bitmap Heap Scan on action_receipts  (cost=319.46..41564.59 rows=10696 width=44) (actual time=0.058..0.179 rows=90 loops=1)
           Recheck Cond: (signer_account_id = 'ryancwalsh.near'::text)
           Heap Blocks: exact=73
           ->  Bitmap Index Scan on action_receipt_signer_account_id_idx  (cost=0.00..316.79 rows=10696 width=0) (actual time=0.043..0.043 rows=90 loops=1)
                 Index Cond: (signer_account_id = 'ryancwalsh.near'::text)
   ->  Sort  (cost=93340.30..93367.04 rows=10696 width=223) (actual time=1.749..1.750 rows=1 loops=1)
         Sort Key: r.included_in_block_timestamp DESC
         Sort Method: top-N heapsort  Memory: 25kB
         ->  Nested Loop  (cost=0.70..93286.82 rows=10696 width=223) (actual time=0.089..1.705 rows=90 loops=1)
               ->  CTE Scan on j  (cost=0.00..213.92 rows=10696 width=32) (actual time=0.060..0.221 rows=90 loops=1)
               ->  Index Scan using receipts_pkey on receipts r  (cost=0.70..8.70 rows=1 width=223) (actual time=0.016..0.016 rows=1 loops=90)
                     Index Cond: (receipt_id = j.receipt_id)
 Planning Time: 0.281 ms
 Execution Time: 1.801 ms

The point is to execute the hugely selective query in the CTE first. Then Postgres does not attempt to walk the index on (included_in_block_timestamp) under the wrong assumption that it would find a matching row soon enough. (It does not.)

The DB at hand runs Postgres 11, where CTEs are always optimization barriers. In Postgres 12 or later add AS MATERIALIZED to the CTE to guarantee the same effect.

Or you could use the "OFFSET 0 hack" in any version like this:

SELECT r.receipt_id
     , r.included_in_block_hash
     , r.included_in_chunk_hash
     , r.index_in_chunk
     , r.included_in_block_timestamp
     , r.predecessor_account_id
     , r.receiver_account_id
     , r.receipt_kind
     , r.originated_from_transaction_hash
FROM  (
   SELECT receipt_id  -- is PK!
   FROM   public.action_receipts
   WHERE  signer_account_id = 'ryancwalsh.near'
   OFFSET 0  -- !
   ) j
JOIN   public.receipts r USING (receipt_id)
ORDER  BY r.included_in_block_timestamp DESC
LIMIT  1;

Prevents "inlining" of the subquery to the same effect. Finishes in < 2ms.

See:

How to prevent PostgreSQL from rewriting OUTER JOIN queries?

"Fix" the database?

The proper fix depends on the complete picture. The underlying problem is that Postgres overestimates the number of qualifying rows in table action_receipts. The MCV list (most common values) cannot keep up with 220 million rows (and growing). It's most probably not just ANALYZE lagging behind. (Though it could be: autovacuum not properly configured? Rookie mistake?) Depending on the actual cardinalities (data distribution) in action_receipts.signer_account_id and access patterns you could do various things to "fix" it. Two options:

1. Increase n_distinct and STATISTICS

If most values in action_receipts.signer_account_id are equally rare (high cardinality), consider setting a very large n_distinct value for the column. And combine that with a moderately increased STATISTICS target for the same column to counter errors in the other direction (underestimating the number of qualifying rows for common values). Read both answers here:

Postgres sometimes uses inferior index for WHERE a IN (...) ORDER BY b LIMIT N

And:

Very bad query plan in PostgreSQL 9.6

2. Local fix with partial index

If action_receipts.signer_account_id = 'ryancwalsh.near' is special in that it's queried more regularly than others, consider a small partial index for it, to fix just that case. Like:

CREATE INDEX ON action_receipts (receipt_id)
WHERE signer_account_id = 'ryancwalsh.near';


来源: stackexchange

问:
Running Debug using Flutter Flavor?
I'm trying to run the debug mode on visual studio code (click "run and debug") for my flutter app, but when I do I'm facing the following issue:

```<code>The Xcode project defines schemes: release, private.

Exception: You must specify a --flavor option to select one of the available schemes.
</code>```

So I have these two "flavours" but I'm not sure how to specify which to use. Normally, running the app through the terminal would require me to specify it as such: flutter run --flavor private but I'm not sure how to do the same for debug. Is there an equivalent command for debug mode?

Would appreciate some help, thanks in advance!

答:
In your launch.json file configurations, you can use this format for your iOS app to run:</p>
```<code>  {
            "name": "production",
            "request": "launch",
            "type": "dart",
            "args": [
                "-t",
                "lib/main_prod.dart",
                "--flavor",
                "prod"
            ]
        }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Running Debug using Flutter Flavor?

Body:
I'm trying to run the debug mode on visual studio code (click "run and debug") for my flutter app, but when I do I'm facing the following issue:

The Xcode project defines schemes: release, private.

Exception: You must specify a --flavor option to select one of the available schemes.

So I have these two "flavours" but I'm not sure how to specify which to use. Normally, running the app through the terminal would require me to specify it as such: flutter run --flavor private but I'm not sure how to do the same for debug. Is there an equivalent command for debug mode?

Would appreciate some help, thanks in advance!

Body:
In your launch.json file configurations, you can use this format for your iOS app to run:

  {
            "name": "production",
            "request": "launch",
            "type": "dart",
            "args": [
                "-t",
                "lib/main_prod.dart",
                "--flavor",
                "prod"
            ]
        }


问:
Bootstrap 5 How to apply different justifications to elements inside div?
I am using Bootstrap 5 to get a layout like the following:

I am using the following html:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="row">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <a href="#"><img src="https://picsum.photos/800/600"></a>
            </div>
            <div class="col-lg-6 col-md-6 col-sm-12">
                <div class="row">
                    <p>Test1</p>
                    <p>Test2</p>
                </div>
                <div class="row">
                    <div class="btn-group">
                        <button type="button" class="btn btn-sm btn-outline-secondary">Button1</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary">Button2</button>
                    </div>
                    <div class="btn-group d-flex justify-content-end">
                        <button type="button" class="btn btn-sm btn-outline-secondary">Button3</button>
                    </div>
                </div>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    </body>
</html>
</code>```

I am having problems in the buttons section, to justify the 3 of them to the bottom, and button3 to the right of the layout.

Any idea how to apply different justifications to the elements inside a div?

答:
Try this:

```<code>            <div class="row">
                <div class="btn-group col-auto me-auto">
                    <button type="button" class="btn btn-sm btn-outline-secondary">Button1</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary">Button2</button>
                </div>
                <div class="btn-group d-flex justify-content-end col-auto">
                    <button type="button" class="btn btn-sm btn-outline-secondary">Button3</button>
                </div>
            </div>
</code>```

Update

```<code>    <!DOCTYPE html>
<html lang="en">
    <head>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="row">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <a href="#"><img src="https://picsum.photos/800/600"></a>
            </div>
            <div class="col-lg-6 col-md-6 col-sm-12 d-flex flex-column">
                <div class="row mb-auto">
                    <p>Test1</p>
                    <p>Test2</p>
                </div>

                  <div class="row">
                      <div class="btn-group col-auto me-auto">
                          <button type="button" class="btn btn-sm btn-outline-secondary">Button1</button>
                          <button type="button" class="btn btn-sm btn-outline-secondary">Button2</button>
                      </div>
                      <div class="btn-group d-flex justify-content-end col-auto">
                          <button type="button" class="btn btn-sm btn-outline-secondary">Button3</button>
                      </div>
                  </div>

            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    </body>
</html>
</code>```

jsfiddle:  https://jsfiddle.net/n0bod2m6/

Body:
I am using Bootstrap 5 to get a layout like the following:

I am using the following html:

<!DOCTYPE html>

        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

Test1

Test2

                        <button type="button" class="btn btn-sm btn-outline-secondary">Button1</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary">Button2</button>

                        <button type="button" class="btn btn-sm btn-outline-secondary">Button3</button>

I am having problems in the buttons section, to justify the 3 of them to the bottom, and button3 to the right of the layout.

Any idea how to apply different justifications to the elements inside a div?

Body:
Try this:

            <div class="row">
                <div class="btn-group col-auto me-auto">
                    <button type="button" class="btn btn-sm btn-outline-secondary">Button1</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary">Button2</button>
                </div>
                <div class="btn-group d-flex justify-content-end col-auto">
                    <button type="button" class="btn btn-sm btn-outline-secondary">Button3</button>
                </div>
            </div>

Update

    <!DOCTYPE html>
<html lang="en">
    <head>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="row">
            <div class="col-lg-6 col-md-6 col-sm-12">
                <a href="#"><img src="https://picsum.photos/800/600"></a>
            </div>
            <div class="col-lg-6 col-md-6 col-sm-12 d-flex flex-column">
                <div class="row mb-auto">
                    <p>Test1</p>
                    <p>Test2</p>
                </div>

                  <div class="row">
                      <div class="btn-group col-auto me-auto">
                          <button type="button" class="btn btn-sm btn-outline-secondary">Button1</button>
                          <button type="button" class="btn btn-sm btn-outline-secondary">Button2</button>
                      </div>
                      <div class="btn-group d-flex justify-content-end col-auto">
                          <button type="button" class="btn btn-sm btn-outline-secondary">Button3</button>
                      </div>
                  </div>

            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    </body>
</html>

jsfiddle:  https://jsfiddle.net/n0bod2m6/


问:
Looping and append to dataframe with column names in Pyhton
I had this challenge of looping through and appending to a data frame in 2 separate columns. I would like the result of col1 and col2 to be appended to the data frame under the columns 'col1' & 'col2'.

What i have so far is the below:

```<code>result = pd.DataFrame(columns = ['col1', 'col2'])
for i in range(5):
    col1 = i + 1
    col2 = i + 100
    result.append(pd.concat([str(col1), col2]))
</code>```

Which outputs:

```<code>TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid
</code>```

My desired output is:

col1
col2

1
101

2
102

3
103

4
104

5
105

答:
If using append here is necessary, you may do

```<code>result = pd.DataFrame(columns = ['col1', 'col2'])
for i in range(5):
    col1 = i + 1
    col2 = i + 100
    result = result.append({'col1': str(col1), 'col2': col2}, ignore_index=True)
</code>```

Otherwise, with concat

```<code>result = pd.concat([
    pd.Series({'col1': str(i + 1), 'col2': i + 100})
        for i in range(5)
], axis=1).transpose()
</code>```

Or I would do this

```<code>result = pd.DataFrame({
    'col1': list(map(str, range(1, 6))),
    'col2': list(range(100, 105)),
})
</code>```

Body:
I had this challenge of looping through and appending to a data frame in 2 separate columns. I would like the result of col1 and col2 to be appended to the data frame under the columns 'col1' & 'col2'.

What i have so far is the below:

result = pd.DataFrame(columns = ['col1', 'col2'])
for i in range(5):
    col1 = i + 1
    col2 = i + 100
    result.append(pd.concat([str(col1), col2]))

Which outputs:

TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

My desired output is:

col1
col2

1
101

2
102

3
103

4
104

5
105

Body:
If using append here is necessary, you may do

result = pd.DataFrame(columns = ['col1', 'col2'])
for i in range(5):
    col1 = i + 1
    col2 = i + 100
    result = result.append({'col1': str(col1), 'col2': col2}, ignore_index=True)

Otherwise, with concat

result = pd.concat([
    pd.Series({'col1': str(i + 1), 'col2': i + 100})
        for i in range(5)
], axis=1).transpose()

Or I would do this

result = pd.DataFrame({
    'col1': list(map(str, range(1, 6))),
    'col2': list(range(100, 105)),
})


问:
Best practice for filling a text range in Google Docs App Script
I use a template in google docs for a letter and I want to fill the letter after the (dynamic) header of the letter automatically via App Scripts. Is there any best practice to set the text always to the same position? I've tried to use a placeholder and replace it. But sometimes I need to replace the text more than one time.</p>

答:
In your situation, how about using NamedRange? Ref

When the NamedRange is used, the script is as follows.

Sample script:

// Create custom menu.
function onOpen() {
  DocumentApp.getUi().createMenu("sample")
    .addItem("1. Install named range", "setNamedRange")
    .addItem("2. Change text by named range", "changeTextByNamedRange")
    .addItem("Delete named range", "deleteNamedRange")
    .addToUi();
}

const nameOfNamedRange = "sample1"; // Please set the name of your named range.

// Set named range.
function setNamedRange() {
  const doc = DocumentApp.getActiveDocument();
  const ele = doc.getCursor().getElement();
  const range = doc.newRange().addElement(ele).build();
  doc.addNamedRange(nameOfNamedRange, range);
}

// Update named range.
function changeTextByNamedRange() {
  const updateText = "updated sample"; // Please set the updated text you want.

  const doc = DocumentApp.getActiveDocument();
  const range = doc.getNamedRanges().find(r => r.getName() == nameOfNamedRange);
  if (!range) {
    throw new Error("No named range. Please install a named range.");
  }
  range.getRange().getRangeElements().forEach(e => e.getElement().asText().setText(updateText));
}

// Delete named range.
function deleteNamedRange() {
  const doc = DocumentApp.getActiveDocument();
  const range = doc.getNamedRanges().find(r => r.getName() == nameOfNamedRange);
  if (!range) return;
  range.remove();
}
```

Usage:

Please set the cursor to the document you want to set the named range.

Run setNamedRange. By this, the point of the current cursor is set as the named range.

When you want to change the text of the named range. Please run changeTextByNamedRange. By this, the updated text is put to the named range as the replacement.

In this case, even when the paragraph is changed and the texts before and after the named range are changed, the named range can be used.

When you want to delete the named range, please run deleteNamedRange.

Testing:

When the above script is run, the following result is obtained.

Reference:

Class NamedRange

Body:
In your situation, how about using NamedRange? Ref

When the NamedRange is used, the script is as follows.

Sample script:

// Create custom menu.
function onOpen() {
  DocumentApp.getUi().createMenu("sample")
    .addItem("1. Install named range", "setNamedRange")
    .addItem("2. Change text by named range", "changeTextByNamedRange")
    .addItem("Delete named range", "deleteNamedRange")
    .addToUi();
}

const nameOfNamedRange = "sample1"; // Please set the name of your named range.

// Set named range.
function setNamedRange() {
  const doc = DocumentApp.getActiveDocument();
  const ele = doc.getCursor().getElement();
  const range = doc.newRange().addElement(ele).build();
  doc.addNamedRange(nameOfNamedRange, range);
}

// Update named range.
function changeTextByNamedRange() {
  const updateText = "updated sample"; // Please set the updated text you want.

  const doc = DocumentApp.getActiveDocument();
  const range = doc.getNamedRanges().find(r => r.getName() == nameOfNamedRange);
  if (!range) {
    throw new Error("No named range. Please install a named range.");
  }
  range.getRange().getRangeElements().forEach(e => e.getElement().asText().setText(updateText));
}

// Delete named range.
function deleteNamedRange() {
  const doc = DocumentApp.getActiveDocument();
  const range = doc.getNamedRanges().find(r => r.getName() == nameOfNamedRange);
  if (!range) return;
  range.remove();
}

Usage:

Please set the cursor to the document you want to set the named range.

Run setNamedRange. By this, the point of the current cursor is set as the named range.

When you want to change the text of the named range. Please run changeTextByNamedRange. By this, the updated text is put to the named range as the replacement.

In this case, even when the paragraph is changed and the texts before and after the named range are changed, the named range can be used.

When you want to delete the named range, please run deleteNamedRange.

Testing:

When the above script is run, the following result is obtained.

Reference:

Class NamedRange


问:
How read Doc or Docx file in java?
I want to read a word file in java

```<code>import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.extractor.*;
import org.apache.poi.hwpf.usermodel.HeaderStories;

import java.io.*;

public class ReadDocFileFromJava {

    public static void main(String[] args) {
        /**This is the document that you want to read using Java.**/
        String fileName = "C:\\Path to file\\Test.doc";

        /**Method call to read the document (demonstrate some useage of POI)**/
        readMyDocument(fileName);

    }
    public static void readMyDocument(String fileName){
        POIFSFileSystem fs = null;
        try {
            fs = new POIFSFileSystem(new FileInputStream(fileName));
            HWPFDocument doc = new HWPFDocument(fs);

            /** Read the content **/
            readParagraphs(doc);

            int pageNumber=1;

            /** We will try reading the header for page 1**/
            readHeader(doc, pageNumber);

            /** Let's try reading the footer for page 1**/
            readFooter(doc, pageNumber);

            /** Read the document summary**/
            readDocumentSummary(doc);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void readParagraphs(HWPFDocument doc) throws Exception{
        WordExtractor we = new WordExtractor(doc);

        /**Get the total number of paragraphs**/
        String[] paragraphs = we.getParagraphText();
        System.out.println("Total Paragraphs: "+paragraphs.length);

        for (int i = 0; i < paragraphs.length; i++) {

            System.out.println("Length of paragraph "+(i +1)+": "+ paragraphs[i].length());
            System.out.println(paragraphs[i].toString());

        }

    }

    public static void readHeader(HWPFDocument doc, int pageNumber){
        HeaderStories headerStore = new HeaderStories( doc);
        String header = headerStore.getHeader(pageNumber);
        System.out.println("Header Is: "+header);

    }

    public static void readFooter(HWPFDocument doc, int pageNumber){
        HeaderStories headerStore = new HeaderStories( doc);
        String footer = headerStore.getFooter(pageNumber);
        System.out.println("Footer Is: "+footer);

    }

    public static void readDocumentSummary(HWPFDocument doc) {
        DocumentSummaryInformation summaryInfo=doc.getDocumentSummaryInformation();
        String category = summaryInfo.getCategory();
        String company = summaryInfo.getCompany();
        int lineCount=summaryInfo.getLineCount();
        int sectionCount=summaryInfo.getSectionCount();
        int slideCount=summaryInfo.getSlideCount();

    enter code here
        System.out.println("---------------------------");
        System.out.println("Category: "+category);
        System.out.println("Company: "+company);
        System.out.println("Line Count: "+lineCount);
        System.out.println("Section Count: "+sectionCount);
        System.out.println("Slide Count: "+slideCount);

    }

}
</code>```

http://sanjaal.com/java/tag/java-and-docx-format/

I want to read a doc or docx file in Java

答:
Here is the code of ReadDoc/docx.java:  This will read a dox/docx file and print its content to the console. you can customize it your way. </p>

```<code>import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How read Doc or Docx file in java?

Body:
I want to read a word file in java

import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.extractor.*;
import org.apache.poi.hwpf.usermodel.HeaderStories;

import java.io.*;

public class ReadDocFileFromJava {

    public static void main(String[] args) {
        /**This is the document that you want to read using Java.**/
        String fileName = "C:\\Path to file\\Test.doc";

        /**Method call to read the document (demonstrate some useage of POI)**/
        readMyDocument(fileName);

    }
    public static void readMyDocument(String fileName){
        POIFSFileSystem fs = null;
        try {
            fs = new POIFSFileSystem(new FileInputStream(fileName));
            HWPFDocument doc = new HWPFDocument(fs);

            /** Read the content **/
            readParagraphs(doc);

            int pageNumber=1;

            /** We will try reading the header for page 1**/
            readHeader(doc, pageNumber);

            /** Let's try reading the footer for page 1**/
            readFooter(doc, pageNumber);

            /** Read the document summary**/
            readDocumentSummary(doc);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void readParagraphs(HWPFDocument doc) throws Exception{
        WordExtractor we = new WordExtractor(doc);

        /**Get the total number of paragraphs**/
        String[] paragraphs = we.getParagraphText();
        System.out.println("Total Paragraphs: "+paragraphs.length);

        for (int i = 0; i < paragraphs.length; i++) {

            System.out.println("Length of paragraph "+(i +1)+": "+ paragraphs[i].length());
            System.out.println(paragraphs[i].toString());

        }

    }

    public static void readHeader(HWPFDocument doc, int pageNumber){
        HeaderStories headerStore = new HeaderStories( doc);
        String header = headerStore.getHeader(pageNumber);
        System.out.println("Header Is: "+header);

    }

    public static void readFooter(HWPFDocument doc, int pageNumber){
        HeaderStories headerStore = new HeaderStories( doc);
        String footer = headerStore.getFooter(pageNumber);
        System.out.println("Footer Is: "+footer);

    }

    public static void readDocumentSummary(HWPFDocument doc) {
        DocumentSummaryInformation summaryInfo=doc.getDocumentSummaryInformation();
        String category = summaryInfo.getCategory();
        String company = summaryInfo.getCompany();
        int lineCount=summaryInfo.getLineCount();
        int sectionCount=summaryInfo.getSectionCount();
        int slideCount=summaryInfo.getSlideCount();

    enter code here
        System.out.println("---------------------------");
        System.out.println("Category: "+category);
        System.out.println("Company: "+company);
        System.out.println("Line Count: "+lineCount);
        System.out.println("Section Count: "+sectionCount);
        System.out.println("Slide Count: "+slideCount);

    }

}

http://sanjaal.com/java/tag/java-and-docx-format/

I want to read a doc or docx file in Java

Body:
Here is the code of ReadDoc/docx.java:  This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}


问:
How to group data by key without $unwind nor $group stage in mongodb aggregation
Can anyone help me to group the data by key without using $unwind nor $group stage ? The reason why I don't want to use $unwind nor $group stage is because I want to be able to use the pipeline in a updateMany(filter, pipeline) operation so the stages I can use are limited to: $addFields (= $set), $project (= $unset) and $replaceRoot (= $replaceWith).

The input data looks like this:

[
  {
    key: "alpha",
    value: {
      name: "foo",
    },
  },
  {
    key: "beta",
    value: {
      name: "bar",
    },
  },
  {
    key: "alpha",
    value: {
      name: "baz",
    },
  },
]
```
<p>The result I would like to get:</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    key: "alpha",
    values: [
      {
        name: "foo",
      },
      {
        name: "baz",
      },
    ],
  },
  {
    key: "beta",
    values: [
      {
        name: "bar",
      },
    ],
  },
]
</code>```

I believe that it's doable by using $reduce but I'm newbie with mongodb aggregation so I'm struggling to accumulate objects in array conditionally.

Thanks

答:
```<code>    [
        {
            $set: {
                keys: { $setUnion: [ "$array.key" ] }

            }
        },

        {
            $set: {
                newarray : {
                    $map : {
                        input : "$keys",
                        in : {
                            key : "$$this",
                            values : {
                                $map : {
                                    input : {
                                        $filter : {
                                            input : "$array",
                                            as : "elem",
                                            cond : {
                                                $eq : [
                                                    "$$elem.key",
                                                    "$$this"
                                                ]
                                            }
                                        }},
                                        as : "vals",
                                        in : {
                                            name : "$$vals.value.name"
                                        }
                                    }

                            }
                        }
                    }
                }
            }
        }
    ]

</code>```

Try it. https://mongoplayground.net/p/m1UUvt5QNgg
Or more compact version: https://mongoplayground.net/p/bFrSiyc5nSc

Body:
Can anyone help me to group the data by key without using $unwind nor $group stage ? The reason why I don't want to use $unwind nor $group stage is because I want to be able to use the pipeline in a updateMany(filter, pipeline) operation so the stages I can use are limited to: $addFields (= $set), $project (= $unset) and $replaceRoot (= $replaceWith).

The input data looks like this:

[
  {
    key: "alpha",
    value: {
      name: "foo",
    },
  },
  {
    key: "beta",
    value: {
      name: "bar",
    },
  },
  {
    key: "alpha",
    value: {
      name: "baz",
    },
  },
]

The result I would like to get:

[
  {
    key: "alpha",
    values: [
      {
        name: "foo",
      },
      {
        name: "baz",
      },
    ],
  },
  {
    key: "beta",
    values: [
      {
        name: "bar",
      },
    ],
  },
]

I believe that it's doable by using $reduce but I'm newbie with mongodb aggregation so I'm struggling to accumulate objects in array conditionally.

Thanks

Body:
    [
        {
            $set: {
                keys: { $setUnion: [ "$array.key" ] }

            }
        },

        {
            $set: {
                newarray : {
                    $map : {
                        input : "$keys",
                        in : {
                            key : "$$this",
                            values : {
                                $map : {
                                    input : {
                                        $filter : {
                                            input : "$array",
                                            as : "elem",
                                            cond : {
                                                $eq : [
                                                    "$$elem.key",
                                                    "$$this"
                                                ]
                                            }
                                        }},
                                        as : "vals",
                                        in : {
                                            name : "$$vals.value.name"
                                        }
                                    }

                            }
                        }
                    }
                }
            }
        }
    ]

Try it. https://mongoplayground.net/p/m1UUvt5QNgg
Or more compact version: https://mongoplayground.net/p/bFrSiyc5nSc


问:
Average using loops
```<code>average = total / count
while PEnd !="Q" :
    total = total + value
    average = 0.0
    value = int(input("Enter an input value: "))
    total = total + value
    count = 1
     value = int(input("Enter an input value: "))
     PEnd = input("Enter character Q to quit or any other character to continue:
    ")
    PEnd = " "
    PEnd = input("Enter character Q to quit or any other character to continue: ")
    total = 0
     count = count + 1
    print("The average is: ", average)
</code>```

Anyone know how to rearrange this code so that when the values that are inputted are 3 4 8 4 , the average is 4.75. have tried rewriting it and getting average as 2 with code below and 4 when count = 0

here's my try:

```<code>PEnd = " "
while PEnd !="Q" :
    value = int(input("Enter an input value: "))
    average = 0.0
    total = 0
    count = 1
    total = total + value
    count = count + 1
    average = total / count

    PEnd = input("Enter character Q to quit or any other character to continue: ")

print("The average is: ", average)
</code>```

答:
Try initializing the variables before you start your while loop (see below).</p>
```<code>PEnd = " "
count = 0
total = 0
while PEnd !="Q" :
    value = int(input("Enter an input value: "))
    total += value
    count += 1
    PEnd = input("Enter character Q to quit or any other character to continue: ")
average = total / count

print("The average is: ", average)
</code>```

Title: Average using loops

Body:
average = total / count
while PEnd !="Q" :
    total = total + value
    average = 0.0
    value = int(input("Enter an input value: "))
    total = total + value
    count = 1
     value = int(input("Enter an input value: "))
     PEnd = input("Enter character Q to quit or any other character to continue:
    ")
    PEnd = " "
    PEnd = input("Enter character Q to quit or any other character to continue: ")
    total = 0
     count = count + 1
    print("The average is: ", average)

Anyone know how to rearrange this code so that when the values that are inputted are 3 4 8 4 , the average is 4.75. have tried rewriting it and getting average as 2 with code below and 4 when count = 0

here's my try:

PEnd = " "
while PEnd !="Q" :
    value = int(input("Enter an input value: "))
    average = 0.0
    total = 0
    count = 1
    total = total + value
    count = count + 1
    average = total / count

    PEnd = input("Enter character Q to quit or any other character to continue: ")

print("The average is: ", average)

Body:
Try initializing the variables before you start your while loop (see below).

PEnd = " "
count = 0
total = 0
while PEnd !="Q" :
    value = int(input("Enter an input value: "))
    total += value
    count += 1
    PEnd = input("Enter character Q to quit or any other character to continue: ")
average = total / count

print("The average is: ", average)


问:
Change canvas width and height without losing the current draw
I'm creating a pixel art app and when I want to save the image from the canvas the image is so small, so it seems pixelated when I want to resize it.

I want to resize it to bigger dimensions, but I don't know how.

This is the code example:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.rect(0, 0, 50, 50);
ctx.fillStyle = 'red';
ctx.fill();

document.write('');

// This is an image with dimensions 108x108px and it seems very bad when i resize it to 300x300px
// I want to download the canvas image with more resolution
```
<pre class="lang-html prettyprint-override"><code><canvas id="myCanvas" width="108" height="108" style="width: 300px; height:300px;">

</canvas>
</code>```

答:
you can create a canvas and put the imageData in it.</p>
```<code>var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.rect(0, 0, 25, 25);
ctx.fillStyle = 'red';
ctx.fill();
ctx.beginPath();
ctx.rect(0, 25, 25, 25);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.beginPath();
ctx.rect(25, 0, 25, 25);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.beginPath();
ctx.rect(25, 25, 25, 25);
ctx.fillStyle = 'green';
ctx.fill();

var c2 = document.createElement("canvas");
c2.width = 50;
c2.height = 50;
var ctx2 = c2.getContext("2d");
var imageData = ctx.getImageData(0, 0, 50, 50);
ctx2.putImageData(imageData, 0, 0);

document.write('<img style="width:300px;" src="' + c2.toDataURL("image/png") + '"/>');
</code>```

Body:
I'm creating a pixel art app and when I want to save the image from the canvas the image is so small, so it seems pixelated when I want to resize it.

I want to resize it to bigger dimensions, but I don't know how.

This is the code example:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.rect(0, 0, 50, 50);
ctx.fillStyle = 'red';
ctx.fill();

document.write('');

// This is an image with dimensions 108x108px and it seems very bad when i resize it to 300x300px
// I want to download the canvas image with more resolution

<canvas id="myCanvas" width="108" height="108" style="width: 300px; height:300px;">

</canvas>

Body:
you can create a canvas and put the imageData in it.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.rect(0, 0, 25, 25);
ctx.fillStyle = 'red';
ctx.fill();
ctx.beginPath();
ctx.rect(0, 25, 25, 25);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.beginPath();
ctx.rect(25, 0, 25, 25);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.beginPath();
ctx.rect(25, 25, 25, 25);
ctx.fillStyle = 'green';
ctx.fill();

var c2 = document.createElement("canvas");
c2.width = 50;
c2.height = 50;
var ctx2 = c2.getContext("2d");
var imageData = ctx.getImageData(0, 0, 50, 50);
ctx2.putImageData(imageData, 0, 0);

document.write('<img style="width:300px;" src="' + c2.toDataURL("image/png") + '"/>');


问:
Is there a way to return one specific table from a webpage that has multiple tables in Python?
I'm having trouble returning one particular table (the one titled 'BRN Substantial Shareholders') from this webpage - https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd

I'm able to return all the tables using the below code.

```<code>html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
all_tables = soup.find_all('table')
</code>```

I've tried two different methods to try and scrape using bs but I can't seem to find a way - am I doing something wrong? Both of these output an empty list.

Method 1

```<code># Scrape the substantial holder list
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

sub_headers = []
sub_holdings = []

for found_table in soup.find_all('table', class_=f'{ticker_code} + "Substantial Shareholders"'):
    sub_headers = found_table.find_all('th').append(sub_headers)
    sub_holdings = found_table.find_all('td').append(sub_holdings)

print(sub_headers)
print(sub_holdings)
</code>```

Method 2

```<code># Scrape the substantial holder list
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

all_headers = soup.find_all("th", class_=f"{ticker_code} Substantial Shareholders")
all_holdings = soup.find_all("tr", class_=f"{ticker_code} Substantial Shareholders")

sub_headers = []
sub_holdings = []

for header in all_headers:
    sub_headers.append(header.text)

for holding in all_holdings:
    holding.append(sub_holdings.text)

print(sub_headers)
print(sub_holdings)
</code>```

答:
Found a much simpler method using below.
sub_table = pd.read_html(current_url, match='Holding') print(sub_table)

Body:
I'm having trouble returning one particular table (the one titled 'BRN Substantial Shareholders') from this webpage - https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd

I'm able to return all the tables using the below code.

html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
all_tables = soup.find_all('table')

I've tried two different methods to try and scrape using bs but I can't seem to find a way - am I doing something wrong? Both of these output an empty list.

Method 1

# Scrape the substantial holder list
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

sub_headers = []
sub_holdings = []

for found_table in soup.find_all('table', class_=f'{ticker_code} + "Substantial Shareholders"'):
    sub_headers = found_table.find_all('th').append(sub_headers)
    sub_holdings = found_table.find_all('td').append(sub_holdings)

print(sub_headers)
print(sub_holdings)

Method 2

# Scrape the substantial holder list
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

all_headers = soup.find_all("th", class_=f"{ticker_code} Substantial Shareholders")
all_holdings = soup.find_all("tr", class_=f"{ticker_code} Substantial Shareholders")

sub_headers = []
sub_holdings = []

for header in all_headers:
    sub_headers.append(header.text)

for holding in all_holdings:
    holding.append(sub_holdings.text)

print(sub_headers)
print(sub_holdings)


问:
Error by changing all the date format in R
I'm trying to change the format from all the dates in one column. I tried it with strftime, as.Date and with parse_date, all giving me some sort of issue. The column includes 2200 different times currently expressed in the following format: Feb-03-2022, it should be expressed as: "%B %d %Y", how could I modify all dates?

```<code>ethereum <- read_csv('ethereum_2022-01-04_2022-02-03.csv')
head(ethereum)
# Changing date format in the dataset
ethereum$Date <- parse_date(ethereum$`Date`, "%d-%b-%y")
head(ethereum$Date)
# Naming the datatype and the timeseries
ds<- ethereum$Date
y<- ethereum$`Close`
df<- data.frame(ds,y)
View(df)

</code>```

When I try with this code, I get the following error:

```<code>Warning: 2200 parsing failures.
row col           expected      actual
  1  -- date like %d-%b-%y Feb-03-2022
  2  -- date like %d-%b-%y Feb-02-2022
  3  -- date like %d-%b-%y Feb-01-2022
  4  -- date like %d-%b-%y Jan-31-2022
  5  -- date like %d-%b-%y Jan-30-2022
... ... .................. ...........
See problems(...) for more details.
</code>```

答:
I assume you are having a packages problem.

Try this example:

```<code>library(parsedate)

## Calling the function
parse_date("Feb-03-2022")

## Specifying the package to avoid masked functions
parsedate::parse_date("Feb-03-2022")

</code>```

In your code would look like this:

```<code>ethereum$Date <- parse_date(ethereum$Date)

</code>```

The package "parsedate", is used to parse from any date format. I don't know if all the 2.2k are in the same format, so my suggestion is to use that. In case you are 100% sure, you can use many other parsing date functions. You can even write one yourself using string processing techniques.

Body:
I'm trying to change the format from all the dates in one column. I tried it with strftime, as.Date and with parse_date, all giving me some sort of issue. The column includes 2200 different times currently expressed in the following format: Feb-03-2022, it should be expressed as: "%B %d %Y", how could I modify all dates?

ethereum <- read_csv('ethereum_2022-01-04_2022-02-03.csv')
head(ethereum)
# Changing date format in the dataset
ethereum$Date <- parse_date(ethereum$`Date`, "%d-%b-%y")
head(ethereum$Date)
# Naming the datatype and the timeseries
ds<- ethereum$Date
y<- ethereum$`Close`
df<- data.frame(ds,y)
View(df)

When I try with this code, I get the following error:

Warning: 2200 parsing failures.
row col           expected      actual
  1  -- date like %d-%b-%y Feb-03-2022
  2  -- date like %d-%b-%y Feb-02-2022
  3  -- date like %d-%b-%y Feb-01-2022
  4  -- date like %d-%b-%y Jan-31-2022
  5  -- date like %d-%b-%y Jan-30-2022
... ... .................. ...........
See problems(...) for more details.

Body:
I assume you are having a packages problem.

Try this example:

library(parsedate)

## Calling the function
parse_date("Feb-03-2022")

## Specifying the package to avoid masked functions
parsedate::parse_date("Feb-03-2022")

In your code would look like this:

ethereum$Date <- parse_date(ethereum$Date)

The package "parsedate", is used to parse from any date format. I don't know if all the 2.2k are in the same format, so my suggestion is to use that. In case you are 100% sure, you can use many other parsing date functions. You can even write one yourself using string processing techniques.


问:
Finding best representative point in a group of latitudes and longitudes
I have a cluster of 10 Latitudes and Longitudes. I want to find the optimal location to do set up a lemonade stand.

So in other words, I need to find the best representative point of the group of latitudes and longitudes.

I’m aware of how to find the centroid (center), but I don’t necessarily want the centroid.

I just want to find what point (latitude, longitude) is best representative of the cluster.

Im a beginning python learner, so I’m having a little trouble finding some approaches. I’d really appreciate it if someone can link sources or name some methods as to how I can do this.

答:
Centroid is basically average of your latitudes and longitudes
so the easiest way to find one is by

latsum = sum(latitudes)
lonsum = sum(longitudes)
centroid = (latsum/len(latitudes) , lonsum/len(longitudes))
```

The sum function does what it says and the len function gives you the length of list which in your case is 10.
Since you mentioned that the best representative is what you need, you might need to clear out any outliers in your data.

https://machinelearningmastery.com/how-to-use-statistics-to-identify-outliers-in-data/

This is a good resource for you to start understanding making data science operations in python.

Body:
Centroid is basically average of your latitudes and longitudes
so the easiest way to find one is by

latsum = sum(latitudes)
lonsum = sum(longitudes)
centroid = (latsum/len(latitudes) , lonsum/len(longitudes))

The sum function does what it says and the len function gives you the length of list which in your case is 10.
Since you mentioned that the best representative is what you need, you might need to clear out any outliers in your data.

https://machinelearningmastery.com/how-to-use-statistics-to-identify-outliers-in-data/

This is a good resource for you to start understanding making data science operations in python.


问:
C++: Wrapping C style array into unique_ptr leads to "double free or corruption"
I have a C function that returns me a C style array. I would like wrap this into more C++ style code, so I don't have to manage its lifetime manually. So, I defined my wrapper as such:

```<code>template <typename T>
class Wrapper {
public:
    std::unique_ptr<T[]> data;

    explicit Wrapper(T data[]) : data(data) {}
};
</code>```

However, when using it as follows:

```<code>int main(int argc, char *argv[])
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // simulate my C style function
    Wrapper<int> wrapped(arr);
    return 0;
}
</code>```

I get

```<code>double free or corruption (out)
Aborted
</code>```

As far as I understand, the only place where arr is destroyed, should be the destructor of std::unique_ptr, which is destroyed as soon as its parent Wrapper is destroyed. What am I missing here?

答:
```<code>int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
</code>```

This variable has automatic storage duration. It will be destroyed at the end of the scope where it is declared.

You pass a pointer to the first element of the automatic array into the constructor. The constructor initialises the unique pointer member to point to the automatic array. In the destructor, the unique pointer is destroyed and its destructor invokes delete[] on the stored pointer. Invoking delete[] on any pointer that was not acquired through new of an array results in undefined behaviour. The pointer in this case points to an automatic array which was not acquired by new[], and therefore the behaviour of the program is undefined.

As far as I understand, the only place where arr is destroyed, should be the destructor of std::unique_ptr

That is not where arr may be destroyed, because arr is an automatic variable.

In conclusion: (Almost) never store pointers to any variables in smart pointers. Only store pointers to dynamic objects, whose deallocation function matches the deleter of the smart pointer. Prefer to create smart pointers using std::make_unique (and related functions) when possible to avoid making this mistake in the future.

I go through them and wrap them into unique_ptr, but I'm not sure how they were allocated.

These two things are not compatible with one another. In order to use a smart pointer, you must know how something is allocated because otherwise you cannot know the corresponding deleter to use with the smart pointer.

I have a C function

C API usually have a pair of allocation and deallocation functions, or they use malloc and expect you to free. The relevant details should be in the documentation of the API.

Body:
I have a C function that returns me a C style array. I would like wrap this into more C++ style code, so I don't have to manage its lifetime manually. So, I defined my wrapper as such:

template <typename T>
class Wrapper {
public:
    std::unique_ptr<T[]> data;

    explicit Wrapper(T data[]) : data(data) {}
};

However, when using it as follows:

int main(int argc, char *argv[])
{
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // simulate my C style function
    Wrapper<int> wrapped(arr);
    return 0;
}

I get

double free or corruption (out)
Aborted

As far as I understand, the only place where arr is destroyed, should be the destructor of std::unique_ptr, which is destroyed as soon as its parent Wrapper is destroyed. What am I missing here?

Body:
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};

This variable has automatic storage duration. It will be destroyed at the end of the scope where it is declared.

You pass a pointer to the first element of the automatic array into the constructor. The constructor initialises the unique pointer member to point to the automatic array. In the destructor, the unique pointer is destroyed and its destructor invokes delete[] on the stored pointer. Invoking delete[] on any pointer that was not acquired through new of an array results in undefined behaviour. The pointer in this case points to an automatic array which was not acquired by new[], and therefore the behaviour of the program is undefined.

As far as I understand, the only place where arr is destroyed, should be the destructor of std::unique_ptr

That is not where arr may be destroyed, because arr is an automatic variable.

In conclusion: (Almost) never store pointers to any variables in smart pointers. Only store pointers to dynamic objects, whose deallocation function matches the deleter of the smart pointer. Prefer to create smart pointers using std::make_unique (and related functions) when possible to avoid making this mistake in the future.

I go through them and wrap them into unique_ptr, but I'm not sure how they were allocated.

These two things are not compatible with one another. In order to use a smart pointer, you must know how something is allocated because otherwise you cannot know the corresponding deleter to use with the smart pointer.

I have a C function

C API usually have a pair of allocation and deallocation functions, or they use malloc and expect you to free. The relevant details should be in the documentation of the API.


问:
Suggestion for shopping cart update
I am working on a shopping on a online store for my brother. I am stuck in the in the process where the buyers cart is updated when he adds items to the basket . I want to know how to remember the buyer (as my bro wants user can buy without sign in,so no case of user id etc)? Should I create a session for him and save it to database?</p>

答:
Yes, you will have to create a session to remember them between clicks, otherwise you will have to tack on some sort of id in the GET parameters.

Take a look at session_start() and the examples they give you: http://php.net/manual/en/function.session-start.php

Small warning, native PHP sessions have a vulnerability to session fixation, which could easily to session hijacking (they would need the session id, but after that, they could fix a session). It is always better to create a wrapper and do your best to ensure the user is who they say they are (via the session id) by comparing IPs and User Agents from previous clicks, stored in $_SESSION, to the current IP and User Agent they are presenting.

I personally recommend setting session.use_only_cookies to 1 to prevent information leaking via the session ID being passed in GET.

Title: Suggestion for shopping cart update


问:
What is the correct path to the C source files for Emacs?
So, way back in January, I went here:

http://emacsformacosx.com/

I downloaded Emacs and have been using it on my Mac and I like it. I've started trying to get into Elisp programming. To learn more, I'd like to look up some functions. So for instance I do:

```<code>C-h f
</code>```

and then type "scroll-down"

This gives me the following text:

```<code>>scroll-down is an interactive built-in function in `window.c'.
>
>It is bound to <kp-prior>, <prior>, C-1, C-x C-1, M-v.
>
>(scroll-down &optional ARG)
>
>Scroll text of selected window down ARG lines.
>If ARG is omitted or nil, scroll down by a near full screen.
>A near full screen is `next-screen-context-lines' less than a full screen.
>Negative ARG means scroll upward.
>If ARG is the atom `-', scroll upward by nearly full screen.
>When calling from a program, supply as argument a number, nil, or `-'.
</code>```

And the text "window.c" is a link. So I click on the link and I get:

```<code>find-function-C-source: The C source file window.c is not available
</code>```

I'm getting this error a lot while doing a lot of different things. Where do I find the right path, and how do I tell Emacs what that path is?

I did just recently install some ELPA packages, so maybe one of them is causing some chaos?

答:
If you didn't manually build Emacs from the source code and patch the C source code, value of source-directory or find-function-C-source-directory would be wrong.

You can manually download Emacs source code, unpack it somewhere and set above two variables accordingly like following

(setq source-directory "/path/to/your-emacs-repo")

;; OR

(setq find-function-C-source-directory "/path/to/your-emacs-repo/src")
```

GNU Emacs source code and development is hosted on savannah.gnu.org. You can find all the tags here and download the one that matches your M-x emacs-version.

Body:
So, way back in January, I went here:

http://emacsformacosx.com/

I downloaded Emacs and have been using it on my Mac and I like it. I've started trying to get into Elisp programming. To learn more, I'd like to look up some functions. So for instance I do:

C-h f

and then type "scroll-down"

This gives me the following text:

>scroll-down is an interactive built-in function in `window.c'.
>
>It is bound to <kp-prior>, <prior>, C-1, C-x C-1, M-v.
>
>(scroll-down &optional ARG)
>
>Scroll text of selected window down ARG lines.
>If ARG is omitted or nil, scroll down by a near full screen.
>A near full screen is `next-screen-context-lines' less than a full screen.
>Negative ARG means scroll upward.
>If ARG is the atom `-', scroll upward by nearly full screen.
>When calling from a program, supply as argument a number, nil, or `-'.

And the text "window.c" is a link. So I click on the link and I get:

find-function-C-source: The C source file window.c is not available

I'm getting this error a lot while doing a lot of different things. Where do I find the right path, and how do I tell Emacs what that path is?

I did just recently install some ELPA packages, so maybe one of them is causing some chaos?

Body:
If you didn't manually build Emacs from the source code and patch the C source code, value of source-directory or find-function-C-source-directory would be wrong.

You can manually download Emacs source code, unpack it somewhere and set above two variables accordingly like following

(setq source-directory "/path/to/your-emacs-repo")

;; OR

(setq find-function-C-source-directory "/path/to/your-emacs-repo/src")

GNU Emacs source code and development is hosted on savannah.gnu.org. You can find all the tags here and download the one that matches your M-x emacs-version.


问:
Infinite pagination with local data
I have a large data set of elements in cache that I need to show, to implement the infinite pagination I thought to do it like this:

```<code>@State var historyPagination: Int = 10
@State var didHistoryPaginationFinishLoading: Bool = false

ScrollView {
    // Some other stuff here

    LazyVStack {
        ForEach(0..<myLocalArrayData.count) { index in
            if(index < historyPagination) {
                MyView(data: data)
            }
        }

        LazyVStack {
            if (historyPagination < myLocalArrayData.count) {
                if(!didHistoryPaginationFinishLoading) {
                    ProgressView()
                            .onAppear {
                                // Execute code with delay
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                    historyPagination += 10
                                    didHistoryPaginationFinishLoading = true
                                }
                            }
                            .onDisappear {
                                if (historyPagination < myLocalArrayData.count) {
                                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                        didHistoryPaginationFinishLoading = false
                                    }
                                }
                            }
                            .padding(.vertical)
                }
            }
        }
    }
}
</code>```

The problem I'm having is that when it gets to the bottom part the spining animation doesn't go away and if I scroll a little bit up and then down I can see when I print the values that historyPagination keeps being added +10 automatically.

EDIT:

This glitch seems to only happen after certain amount of data, for example I tested it with 40 items and works fine, but if I have 200 items it seems bugged. Is there something like with Text("") in a view that you can't have more than x amount (I don't remember how many, 5, 10?) without putting it in a Group.

答:
After some hours hammering the code I found the problem to be in the LazyView. This combo is a bit bugged at the moment: ScrollView + LazyVStack + OnAppear

I removed the LazyVStack from the foreach and it worked as expected. I leave it there once it passes more or less the 40 count in the index it starts loading by itself (very weird behavior...)

This is how the code looks at the end (I think my implementation of loading local data is VERY rustic, if someone wants to improve it please do so)

```<code>ScrollView {
    // Some other stuff here

    ForEach(0..<myLocalArrayData.count) { index in
        if(index < historyPagination) {
            MyView(data: data)
        }
    }

    LazyVStack {
        if (historyPagination < myLocalArrayData.count) {
            if(!didHistoryPaginationFinishLoading) {
                ProgressView()
                        .onAppear {
                            // Execute code with delay
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                historyPagination += 10
                                didHistoryPaginationFinishLoading = true
                            }
                        }
                        .onDisappear {
                            if (historyPagination < myLocalArrayData.count) {
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                    didHistoryPaginationFinishLoading = false
                                }
                            }
                        }
                        .padding(.vertical)
            }
        }
    }
}
</code>```

Title: Infinite pagination with local data

Body:
I have a large data set of elements in cache that I need to show, to implement the infinite pagination I thought to do it like this:

@State var historyPagination: Int = 10
@State var didHistoryPaginationFinishLoading: Bool = false

ScrollView {
    // Some other stuff here

    LazyVStack {
        ForEach(0..<myLocalArrayData.count) { index in
            if(index < historyPagination) {
                MyView(data: data)
            }
        }

        LazyVStack {
            if (historyPagination < myLocalArrayData.count) {
                if(!didHistoryPaginationFinishLoading) {
                    ProgressView()
                            .onAppear {
                                // Execute code with delay
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                    historyPagination += 10
                                    didHistoryPaginationFinishLoading = true
                                }
                            }
                            .onDisappear {
                                if (historyPagination < myLocalArrayData.count) {
                                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                        didHistoryPaginationFinishLoading = false
                                    }
                                }
                            }
                            .padding(.vertical)
                }
            }
        }
    }
}

The problem I'm having is that when it gets to the bottom part the spining animation doesn't go away and if I scroll a little bit up and then down I can see when I print the values that historyPagination keeps being added +10 automatically.

EDIT:

This glitch seems to only happen after certain amount of data, for example I tested it with 40 items and works fine, but if I have 200 items it seems bugged. Is there something like with Text("") in a view that you can't have more than x amount (I don't remember how many, 5, 10?) without putting it in a Group.

Body:
After some hours hammering the code I found the problem to be in the LazyView. This combo is a bit bugged at the moment: ScrollView + LazyVStack + OnAppear

I removed the LazyVStack from the foreach and it worked as expected. I leave it there once it passes more or less the 40 count in the index it starts loading by itself (very weird behavior...)

This is how the code looks at the end (I think my implementation of loading local data is VERY rustic, if someone wants to improve it please do so)

ScrollView {
    // Some other stuff here

    ForEach(0..<myLocalArrayData.count) { index in
        if(index < historyPagination) {
            MyView(data: data)
        }
    }

    LazyVStack {
        if (historyPagination < myLocalArrayData.count) {
            if(!didHistoryPaginationFinishLoading) {
                ProgressView()
                        .onAppear {
                            // Execute code with delay
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                historyPagination += 10
                                didHistoryPaginationFinishLoading = true
                            }
                        }
                        .onDisappear {
                            if (historyPagination < myLocalArrayData.count) {
                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                    didHistoryPaginationFinishLoading = false
                                }
                            }
                        }
                        .padding(.vertical)
            }
        }
    }
}


问:
Module appearing as uninstalled even though it installed
The title says it all basically. I was trying to code a macro to automate responding to emails, set up the main.py. Just wrote the import and a print. Ran and boom.
Here is a screenshot because I cant actually explain it correctly https://imgur.com/a/faAt7fY</p>

答:
Instead of deleting one version of python and keeping the other(as mentioned in the other answer) you can keep both.

For example if I have python 3.9 and python 3.10 I can use environment variables to tell my system which interpreter I want to use.

For windows

There are two ways to do this on windows computers(one way might work on your computer, the other may not).

First Way

To set two interpreters on windows you can search up "control panel" in your windows search bar. Then go to "system and security". On the top right corner their will be a search bar in it type "advanced system settings" till you get something like this:

Click on "advanced system settings". You will get something like this:

Then click on the environment variables button. It will lead you to a popup that will look like this:

Under user variables, click on the "Path" environment variables. Then press the "Edit" button. This will take you to a place where you can add multiple interpreters. You should know the location of your python.exe file to proceed. If you don't know the location I recommend going to the main python website and going to the setup wizard to see the directory it is installed in then you can trash(delete) that setup wizard.

Now that you know the location to all your interpreters you can one be one click on  "New" and add the directories of all your python interpreters(Note: Don't add the python.exe at the end ONLY the directories). Once that is done you can press on "Move Up or Move Down". What this will do is the one that is at the top will be your python interpreter and you can always move it down if you need to use another interpreter(Note: You will only see the results after killing your command prompt and restarting it again. Type python in your command prompt and you can see your python version that you specified in your environment variables).

Second Way

Watch the snippet of this video to learn the second way you can do it on windows.

Mac/Linux

I am not a geek in Linux(In fact I haven't even owned a Mac or Linux in my life). So, my advice would be to just read what I did In Widows way one and just change the         environment variables that you would do for Mac/Linux and there would probably be a way to specify which one is the main or most important directory. Watch this video to do what I did in windows.(Feel free to edit this section to add the Mac/Linux way).

Mac Helpful resources:
https://www.youtube.com/watch?v=PUIE7CPANfo

Back to the Main question!

Now you can just install the package that you want on the python version that you want!


问:
Npm Error - No matching version found for
i clone a project with git, the project was create with ionic 2 but when i execute the command for re-create the node_modules folder i get this error.

```<code>npm install
npm WARN deprecated object-keys@0.2.0: Please update to the latest object-keys
npm ERR! code ETARGET
npm ERR! notarget No matching version found for ionic-native@^3.5.0
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of 'ionic-hello-world'
npm ERR! notarget

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/wihermes/.npm/_logs/2017-06-02T13_58_47_295Z-debug.log
</code>```

NOTE: I already update npm.

Does anyone know how to fix it?

答: Remove node_modules, cache files (normally are at the top of the folder in your editor) and the package-lock.json, then run npm install.</p>

Body:
i clone a project with git, the project was create with ionic 2 but when i execute the command for re-create the node_modules folder i get this error.

npm install
npm WARN deprecated object-keys@0.2.0: Please update to the latest object-keys
npm ERR! code ETARGET
npm ERR! notarget No matching version found for ionic-native@^3.5.0
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of 'ionic-hello-world'
npm ERR! notarget

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/wihermes/.npm/_logs/2017-06-02T13_58_47_295Z-debug.log

NOTE: I already update npm.

Does anyone know how to fix it?


问:
Executable Not Found. xxx.app is not a valid path to an executable file
Details

Executable Not Found
Domain: DVTMachOErrorDomain
Code: 5
Recovery Suggestion: /Users/riber/Library/Developer/Xcode/DerivedData/digitalCurrency-hiyiyrokjaydkiagjimlwohehrtu/Build/Products/Debug-iphonesimulator/digitalCurrency.app is not a valid path to an executable file. Please rebuild the project to ensure that all required executables are created. Check your project settings to ensure that a valid executable will be built.

System Information

macOS Version 11.4 (Build 20F71)
Xcode 12.5 (18205) (Build 12E262)
Timestamp: 2021-06-11T16:34:20+08:00

答:
I'm also get the same error. Let me share how I fix it.

I write cpp code on vscode.

I deleted a .cpp/.h file that I didn't need anymore a few days ago.

Everything nice and happy when I working on vscode.

".app is not a valid path" appeared when i switched back to the xcode to verification function.

I was confused.

(I don't immediately remember my delete operation a few days ago)

The key isn't the dialog showed "Executable Not Found",

Switch to "Issue Navigator" and drag to the bottom...

Now the ERROR shows up in front of U:

Finally the solution is :

TARGETS -> Select your ‘Target' -> Build Phases -> Compile Sources :

Select the ".cpp" file that had been delete, then "Remove Items" by click the second "-" button in the lower left corner.


问:
When generating multiple buttons in C# how do I give each one a separate function?
In my code, I generate one extra label and button every time a different button is clicked. I want it so each button can be programmed with a different function. Ex: If I clicked on generated button1 I would be brought to page 1. If I clicked on generated button2 I would be brought to page 2 etc. What would be the best way to approach this?

Here is my code below:

```<code>if (task1 == false)
            {
                Label taskLabel = new Label();
                taskLabel.Text = taskInput.Text;
                taskLabel.Location = new Point(63, 183);
                taskLabel.BorderStyle = BorderStyle.FixedSingle;
                taskLabel.AutoSize = true;
                page2.Controls.Add(taskLabel);
                labelHeight = taskLabel.Bottom;
                labelWidth = taskLabel.Right;

                Button taskButton  = new Button();
                taskButton.Text = "Let's Go";
                taskButton.Location = new Point(labelWidth + 30, 180);
                taskButton.AutoSize = true;
                page2.Controls.Add(taskButton);
                taskInput.Text = "";
                task1 = true;

            }
            else
            {
                Label taskLabel = new Label();
                taskLabel.Text = taskInput.Text;
                taskLabel.Location = new Point(63, labelHeight + 30);
                taskLabel.BorderStyle = BorderStyle.FixedSingle;
                taskLabel.AutoSize = true;
                page2.Controls.Add(taskLabel);

                Button taskButton = new Button();
                taskButton.Text = "Let's Go";
                labelHeight = taskLabel.Bottom;
                labelWidth = taskLabel.Right;
                taskButton.Location = new Point(labelWidth + 30, labelHeight - 18);
                taskButton.AutoSize = true;
                buttonHeight = taskButton.Top;
                page2.Controls.Add(taskButton);
                taskInput.Text = "";
</code>```

答:
After you create the button you add a handler to the function that you want it to run.</p>
```<code>Button taskButton  = new Button();
taskButton.Click += FunctionYouWantToRun();
</code>```

Body:
In my code, I generate one extra label and button every time a different button is clicked. I want it so each button can be programmed with a different function. Ex: If I clicked on generated button1 I would be brought to page 1. If I clicked on generated button2 I would be brought to page 2 etc. What would be the best way to approach this?

Here is my code below:

if (task1 == false)
            {
                Label taskLabel = new Label();
                taskLabel.Text = taskInput.Text;
                taskLabel.Location = new Point(63, 183);
                taskLabel.BorderStyle = BorderStyle.FixedSingle;
                taskLabel.AutoSize = true;
                page2.Controls.Add(taskLabel);
                labelHeight = taskLabel.Bottom;
                labelWidth = taskLabel.Right;

                Button taskButton  = new Button();
                taskButton.Text = "Let's Go";
                taskButton.Location = new Point(labelWidth + 30, 180);
                taskButton.AutoSize = true;
                page2.Controls.Add(taskButton);
                taskInput.Text = "";
                task1 = true;

            }
            else
            {
                Label taskLabel = new Label();
                taskLabel.Text = taskInput.Text;
                taskLabel.Location = new Point(63, labelHeight + 30);
                taskLabel.BorderStyle = BorderStyle.FixedSingle;
                taskLabel.AutoSize = true;
                page2.Controls.Add(taskLabel);

                Button taskButton = new Button();
                taskButton.Text = "Let's Go";
                labelHeight = taskLabel.Bottom;
                labelWidth = taskLabel.Right;
                taskButton.Location = new Point(labelWidth + 30, labelHeight - 18);
                taskButton.AutoSize = true;
                buttonHeight = taskButton.Top;
                page2.Controls.Add(taskButton);
                taskInput.Text = "";

Body:
After you create the button you add a handler to the function that you want it to run.

Button taskButton  = new Button();
taskButton.Click += FunctionYouWantToRun();


问:
JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than
In my web API when I run project to get data from the database got this error
.net core 3.1

JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.

These are my codes:

my Model

```<code>public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ProductText { get; set; }
    public int ProductCategoryId { get; set; }
    [JsonIgnore]
    public virtual ProductCategory ProductCategory { get; set; }
}
</code>```

my productCategory class is:

```<code>public class ProductCategory
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string CatText { get; set; }
    public string ImagePath { get; set; }
    public int Priority { get; set; }
    public int Viewd { get; set; }
    public string Description { get; set; }
    public bool Active { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime ModifyDate { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}
</code>```

my repo is

```<code>public async Task<IList<Product>> GetAllProductAsync()
    {
        return await  _context.Products.Include(p => p.ProductCategory).ToListAsync();
    }
</code>```

my interface

```<code>public interface IProductRepository
{
   ...
   Task<IList<Product>> GetAllProductAsync();
   ...
}
</code>```

and this is my controller in api project

```<code>[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private readonly IProductRepository _productRepository;

    public ProductsController(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }
    [HttpGet]
    public ActionResult Get()
    {
        return Ok(_productRepository.GetAllProduct());
    }
}
</code>```

When I run API project and put this URL: https://localhost:44397/api/products
I got that error,
I can't resolve it

答:
In .Net 6, you can use System.Text.Json to initialize a startup action with AddControllersWithViews like this in Program.cs,

```<code>using System.Text.Json.Serialization;

builder.Services.AddControllersWithViews()
                .AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
</code>```

also you can use AddMvc like this,

```<code>builder.Services.AddMvc()
                .AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
</code>```

but quote from Ryan

asp.net core 3.0+ template use these new
methodsAddControllersWithViews,AddRazorPages,AddControllers instead of
AddMvc.

I will recommend to use the first solution.

Body:
In my web API when I run project to get data from the database got this error
.net core 3.1

JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.

These are my codes:

my Model

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ProductText { get; set; }
    public int ProductCategoryId { get; set; }
    [JsonIgnore]
    public virtual ProductCategory ProductCategory { get; set; }
}

my productCategory class is:

public class ProductCategory
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string CatText { get; set; }
    public string ImagePath { get; set; }
    public int Priority { get; set; }
    public int Viewd { get; set; }
    public string Description { get; set; }
    public bool Active { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime ModifyDate { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

my repo is

public async Task<IList<Product>> GetAllProductAsync()
    {
        return await  _context.Products.Include(p => p.ProductCategory).ToListAsync();
    }

my interface

public interface IProductRepository
{
   ...
   Task<IList<Product>> GetAllProductAsync();
   ...
}

and this is my controller in api project

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private readonly IProductRepository _productRepository;

    public ProductsController(IProductRepository productRepository)
    {
        _productRepository = productRepository;
    }
    [HttpGet]
    public ActionResult Get()
    {
        return Ok(_productRepository.GetAllProduct());
    }
}

When I run API project and put this URL: https://localhost:44397/api/products
I got that error,
I can't resolve it

Body:
In .Net 6, you can use System.Text.Json to initialize a startup action with AddControllersWithViews like this in Program.cs,

using System.Text.Json.Serialization;

builder.Services.AddControllersWithViews()
                .AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

also you can use AddMvc like this,

builder.Services.AddMvc()
                .AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

but quote from Ryan

asp.net core 3.0+ template use these new
methodsAddControllersWithViews,AddRazorPages,AddControllers instead of
AddMvc.

I will recommend to use the first solution.


问:
Getting TypeError: '(slice(None, None, None), 0)' is an invalid key
Trying to plot the decision Boundary of the k-NN Classifier but is unable to do so getting TypeError: '(slice(None, None, None), 0)' is an invalid key

```<code>h = .01  # step size in the mesh

# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF','#AFAFAF'])
cmap_bold  = ListedColormap(['#FF0000', '#00FF00', '#0000FF','#AFAFAF'])

for weights in ['uniform', 'distance']:
    # we create an instance of Neighbours Classifier and fit the data.
    clf = KNeighborsClassifier(n_neighbors=6, weights=weights)
    clf.fit(X_train, y_train)

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, x_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("4-Class classification (k = %i, weights = '%s')"
              % (n_neighbors, weights))

plt.show()
</code>```

Got this when running not very sure what it means dont think the clf.fit have a problem but I am not sure

```<code>  TypeError                                 Traceback (most recent call last)
<ipython-input-394-bef9b05b1940> in <module>
     12         # Plot the decision boundary. For that, we will assign a color to each
     13         # point in the mesh [x_min, x_max]x[y_min, y_max].
---> 14         x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
     15         y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
     16         xx, yy = np.meshgrid(np.arange(x_min, x_max, h),

~\Miniconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2925             if self.columns.nlevels > 1:
   2926                 return self._getitem_multilevel(key)
-> 2927             indexer = self.columns.get_loc(key)
   2928             if is_integer(indexer):
   2929                 indexer = [indexer]

~\Miniconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2654                                  'backfill or nearest lookups')
   2655             try:
-> 2656                 return self._engine.get_loc(key)
   2657             except KeyError:
   2658                 return self._engine.get_loc(self._maybe_cast_indexer(key))

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

TypeError: '(slice(None, None, None), 0)' is an invalid key
</code>```

答:
When importing the datasets, use .values.

Change:

```<code>X = dataset.iloc[:, 1:3]
</code>```

To:

```<code>X = dataset.iloc[:, 1:3].values
</code>```

Body:
Trying to plot the decision Boundary of the k-NN Classifier but is unable to do so getting TypeError: '(slice(None, None, None), 0)' is an invalid key

h = .01  # step size in the mesh

# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF','#AFAFAF'])
cmap_bold  = ListedColormap(['#FF0000', '#00FF00', '#0000FF','#AFAFAF'])

for weights in ['uniform', 'distance']:
    # we create an instance of Neighbours Classifier and fit the data.
    clf = KNeighborsClassifier(n_neighbors=6, weights=weights)
    clf.fit(X_train, y_train)

    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, x_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure()
    plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.title("4-Class classification (k = %i, weights = '%s')"
              % (n_neighbors, weights))

plt.show()

Got this when running not very sure what it means dont think the clf.fit have a problem but I am not sure

  TypeError                                 Traceback (most recent call last)
<ipython-input-394-bef9b05b1940> in <module>
     12         # Plot the decision boundary. For that, we will assign a color to each
     13         # point in the mesh [x_min, x_max]x[y_min, y_max].
---> 14         x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
     15         y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
     16         xx, yy = np.meshgrid(np.arange(x_min, x_max, h),

~\Miniconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2925             if self.columns.nlevels > 1:
   2926                 return self._getitem_multilevel(key)
-> 2927             indexer = self.columns.get_loc(key)
   2928             if is_integer(indexer):
   2929                 indexer = [indexer]

~\Miniconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2654                                  'backfill or nearest lookups')
   2655             try:
-> 2656                 return self._engine.get_loc(key)
   2657             except KeyError:
   2658                 return self._engine.get_loc(self._maybe_cast_indexer(key))

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

TypeError: '(slice(None, None, None), 0)' is an invalid key

Body:
When importing the datasets, use .values.

Change:

X = dataset.iloc[:, 1:3]

To:

X = dataset.iloc[:, 1:3].values


问:
Node.js: How to create paid node modules?
How to sell node modules?

I need to publish my CMS plugins to NPM and allow users to install them, so some of them could be paid.

How do i do it?

答:
I know this question is very old, but a lot has happened in the past years.

One solution you can use nowadays is basetools.io for selling access to your npm packages. It takes care of invoicing, billing and managing access to your packages.

Full disclosure: I am the founder of basetools.