问:
ElasticSearch - Adjacency matrix & Sum
I'm currently learning Elastic, I've created this dataset on french presidentials elections from 1965 to 2017 and I want to query the sum of all the documents matching "tour" = 1 and "election" = 1974.

I've done this, but it's not working, what I did wrong ?

{
  "size": 0,
  "aggs": {
    "somme_blancs_nuls": {
      "sum": {
        "field": "blancs_nuls",
        "aggs": {
          "interactions": {
            "adjacency_matrix": {
              "filters": {
                "grpA": {
                  "match": {
                    "tour": 1
                  }
                },
                "grpB": {
                  "match": {
                    "election": 1974
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
```
<p>Here's my mapping and a sample document.</p>
<pre class="lang-json prettyprint-override"><code>// Mapping
{
    "properties": {
        "election": {
            "type": "integer"
        },
        "tour": {
            "type": "integer"
        },
        "code": {
            "type": "text"
        },
        "libelle": {
            "type": "text",
            "fields": {
                "keyword": {
                    "type":"keyword"
                }
            }
        },
        "inscrits": {
            "type": "long"
        },
        "votants": {
            "type": "long"
        },
        "exprimes": {
            "type": "long"
        },
        "abstentions": {
            "type": "long"
        },
        "blancs_nuls": {
            "type": "long"
        },
        "candidats": {
            "type": "nested",
            "properties": {
                "nom": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type":"keyword"
                        }
                    }
                },
                "parti": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type":"keyword"
                        }
                    }
                },
                "votes": {
                    "type": "long"
                }
            }
        }
    }
}
</code>```

// Sample
{
    "election": 1965,
    "tour": 1,
    "code": "1",
    "libelle": "AIN",
    "inscrits": 206496,
    "votants": 166986,
    "exprimes": 165555,
    "abstentions": 39510,
    "blancs_nuls": 1431,
    "candidats": [
        {
        "nom": "François MITTERRAND",
        "parti": "CIR",
        "votes": 50418
        },
        {
        "nom": "Charles DE GAULLE",
        "parti": "UNR",
        "votes": 71246
        },
        {
        "nom": "Jean LECANUET",
        "parti": "MRP",
        "votes": 30416
        },
        {
        "nom": "Jean-Louis TIXIER-VIGNANCOUR",
        "parti": "EXD",
        "votes": 8317
        },
        {
        "nom": "Pierre MARCILHACY",
        "parti": "DVD",
        "votes": 3006
        },
        {
        "nom": "Marcel BARBU",
        "parti": "DIV",
        "votes": 2152
        }
    ]
}
```

Thanks in advance :)

答:
You can use a combination of the search query with aggregations

You need to use a boolean query to find all the documents matching "tour" = 1 and "election" = 1974, and then use sum aggregation to find the sum of blancs_nuls field on the matching documents

```<code>{
    "size":0,
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "tour": 1
                    }
                },
                {
                    "match": {
                        "election": 1974
                    }
                }
            ]
        }
    },
    "aggs": {
        "balancs_sum": {
            "sum": {
                "field": "blancs_nuls"
            }
        }
    }
}
</code>```

Search Response will be

```<code>"aggregations": {
        "balancs_sum": {
            "value": 2862.0
        }
    }
</code>```

Title: ElasticSearch - Adjacency matrix & Sum

Body:
I'm currently learning Elastic, I've created this dataset on french presidentials elections from 1965 to 2017 and I want to query the sum of all the documents matching "tour" = 1 and "election" = 1974.

I've done this, but it's not working, what I did wrong ?

{
  "size": 0,
  "aggs": {
    "somme_blancs_nuls": {
      "sum": {
        "field": "blancs_nuls",
        "aggs": {
          "interactions": {
            "adjacency_matrix": {
              "filters": {
                "grpA": {
                  "match": {
                    "tour": 1
                  }
                },
                "grpB": {
                  "match": {
                    "election": 1974
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Here's my mapping and a sample document.

// Mapping
{
    "properties": {
        "election": {
            "type": "integer"
        },
        "tour": {
            "type": "integer"
        },
        "code": {
            "type": "text"
        },
        "libelle": {
            "type": "text",
            "fields": {
                "keyword": {
                    "type":"keyword"
                }
            }
        },
        "inscrits": {
            "type": "long"
        },
        "votants": {
            "type": "long"
        },
        "exprimes": {
            "type": "long"
        },
        "abstentions": {
            "type": "long"
        },
        "blancs_nuls": {
            "type": "long"
        },
        "candidats": {
            "type": "nested",
            "properties": {
                "nom": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type":"keyword"
                        }
                    }
                },
                "parti": {
                    "type": "text",
                    "fields": {
                        "keyword": {
                            "type":"keyword"
                        }
                    }
                },
                "votes": {
                    "type": "long"
                }
            }
        }
    }
}

// Sample
{
    "election": 1965,
    "tour": 1,
    "code": "1",
    "libelle": "AIN",
    "inscrits": 206496,
    "votants": 166986,
    "exprimes": 165555,
    "abstentions": 39510,
    "blancs_nuls": 1431,
    "candidats": [
        {
        "nom": "François MITTERRAND",
        "parti": "CIR",
        "votes": 50418
        },
        {
        "nom": "Charles DE GAULLE",
        "parti": "UNR",
        "votes": 71246
        },
        {
        "nom": "Jean LECANUET",
        "parti": "MRP",
        "votes": 30416
        },
        {
        "nom": "Jean-Louis TIXIER-VIGNANCOUR",
        "parti": "EXD",
        "votes": 8317
        },
        {
        "nom": "Pierre MARCILHACY",
        "parti": "DVD",
        "votes": 3006
        },
        {
        "nom": "Marcel BARBU",
        "parti": "DIV",
        "votes": 2152
        }
    ]
}

Thanks in advance :)

Body:
You can use a combination of the search query with aggregations

You need to use a boolean query to find all the documents matching "tour" = 1 and "election" = 1974, and then use sum aggregation to find the sum of blancs_nuls field on the matching documents

{
    "size":0,
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "tour": 1
                    }
                },
                {
                    "match": {
                        "election": 1974
                    }
                }
            ]
        }
    },
    "aggs": {
        "balancs_sum": {
            "sum": {
                "field": "blancs_nuls"
            }
        }
    }
}

Search Response will be

"aggregations": {
        "balancs_sum": {
            "value": 2862.0
        }
    }


来源: stackexchange

问:
Can't specify JWKSet URL when validating confidential token coming from Azure AD
Connecting to Azure AD v2.0 endpoint I cannot validate my token which jwt.io and jwt.ms declare as valid

A public token is no problem:

```<code>IDTokenValidator validator = new IDTokenValidator(issuer, clientId, JWSAlgorithm.RS256, jwkSetUrl);
IDTokenClaimsSet validatedClaimsSet;
try {
    validatedClaimsSet = validator.validate(jwt, null);
} catch (BadJOSEException | JOSEException e) {
    LOGGER.error(e.getMessage());
    return;
}
</code>```

but validating a token coming from a confidential client will throw the exception

```<code>Signed JWT rejected: Another algorithm expected, or no matching key(s) found
</code>```

with the following code

```<code>IDTokenValidator validator = new IDTokenValidator(issuer, clientId, JWSAlgorithm.RS256, new Secret(authMethod.getSecret()));
</code>```

No matching keys are found because (JWKMatcher.java:1258)

keytype does not match: OCT instead of RSA

use is null

ops is null

It seems an inadequate JWKSet is created from the secret in ImmutableSecret.java:47 but I seem to lack understanding as to how the secret can contain the necessary data found in the jwks_uri from Azure

Any advice would be appreciated

答:
Validating an ID token works the same way for both public and confidential clients. So just get rid of the secret parameter and your code will work - using the token's signing public key.

The secret parameter is for JWTs that are signed with a symmetric algorithm such as HMACSHA256 - which is almost never a good idea. More about this topic in JWT Security Best Practices.

ContentLicense: CC BY-SA 4.0

Body:
Connecting to Azure AD v2.0 endpoint I cannot validate my token which jwt.io and jwt.ms declare as valid

A public token is no problem:

IDTokenValidator validator = new IDTokenValidator(issuer, clientId, JWSAlgorithm.RS256, jwkSetUrl);
IDTokenClaimsSet validatedClaimsSet;
try {
    validatedClaimsSet = validator.validate(jwt, null);
} catch (BadJOSEException | JOSEException e) {
    LOGGER.error(e.getMessage());
    return;
}

but validating a token coming from a confidential client will throw the exception

Signed JWT rejected: Another algorithm expected, or no matching key(s) found

with the following code

IDTokenValidator validator = new IDTokenValidator(issuer, clientId, JWSAlgorithm.RS256, new Secret(authMethod.getSecret()));

No matching keys are found because (JWKMatcher.java:1258)

keytype does not match: OCT instead of RSA

use is null

ops is null

It seems an inadequate JWKSet is created from the secret in ImmutableSecret.java:47 but I seem to lack understanding as to how the secret can contain the necessary data found in the jwks_uri from Azure

Any advice would be appreciated


问:
How to open a file in another app via an Intent using an URI?
In my app, I have several file Uri (NOT URI) store. These are of the form:

```<code>content://com.android.providers.downloads.documents/document/427
</code>```

My intention is, once I click a button, open one of these Uri in a file reader (may it be MS Word, Excel, PDF Reader... depending on the extension and device).

I am currently trying this snippet:

```<code>                val file = File(Uri.parse(uri).path!!)
                val myMime: MimeTypeMap = MimeTypeMap.getSingleton()
                val newIntent = Intent(Intent.ACTION_VIEW)

                val mimeType: String = myMime.getMimeTypeFromExtension(file.extension).toString()
                newIntent.setDataAndType(
                    FileProvider.getUriForFile(applicationContext, "${applicationContext.packageName}.provider", file), mimeType)
                newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                newIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                try {
                    startActivity(newIntent)
                } catch (e: ActivityNotFoundException) {
                }
</code>```

But every time I try to open it, I get:

```<code>java.lang.IllegalArgumentException: Failed to find configured root that contains /document/427
</code>```

Could you please tell me what am I missing? No answers I've found here targeted my problem. Thanks in advance!

UPDATE
Thanks to @CommonsWare help, I managed to avoid an Exception, my code now looks like this:

```<code>val newIntent = Intent(Intent.ACTION_VIEW)
newIntent.addCategory(Intent.CATEGORY_OPENABLE)
newIntent.data = Uri.parse(uri)
newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
newIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
try {
    startActivity(newIntent)
} catch (e: ActivityNotFoundException) {
    Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show()
}
</code>```

I'm getting the Uri from here:

```<code>val fileResultLauncher =      registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    viewModel.uploadFile(result, false)
            }

fileFab.setOnClickListener {
    val intent = Intent()
    intent.type = "application/*"
    intent.action = Intent.ACTION_OPEN_DOCUMENT
    fileResultLauncher.launch(intent)
}
</code>```

Unfortunately, I'm getting a NoActivityFoundException

答:
Get rid of:

val file = File(Uri.parse(uri).path!!)
```
<p>...and replace your <code>setDataAndType()</code> call with:</p>
<pre class="lang-kotlin prettyprint-override"><code>newIntent.setDataAndType(Uri.parse(uri), mimeType)
</code>```

Body:
In my app, I have several file Uri (NOT URI) store. These are of the form:

content://com.android.providers.downloads.documents/document/427

My intention is, once I click a button, open one of these Uri in a file reader (may it be MS Word, Excel, PDF Reader... depending on the extension and device).

I am currently trying this snippet:

                val file = File(Uri.parse(uri).path!!)
                val myMime: MimeTypeMap = MimeTypeMap.getSingleton()
                val newIntent = Intent(Intent.ACTION_VIEW)

                val mimeType: String = myMime.getMimeTypeFromExtension(file.extension).toString()
                newIntent.setDataAndType(
                    FileProvider.getUriForFile(applicationContext, "${applicationContext.packageName}.provider", file), mimeType)
                newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                newIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                try {
                    startActivity(newIntent)
                } catch (e: ActivityNotFoundException) {
                }

But every time I try to open it, I get:

java.lang.IllegalArgumentException: Failed to find configured root that contains /document/427

Could you please tell me what am I missing? No answers I've found here targeted my problem. Thanks in advance!

UPDATE
Thanks to @CommonsWare help, I managed to avoid an Exception, my code now looks like this:

val newIntent = Intent(Intent.ACTION_VIEW)
newIntent.addCategory(Intent.CATEGORY_OPENABLE)
newIntent.data = Uri.parse(uri)
newIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
newIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
try {
    startActivity(newIntent)
} catch (e: ActivityNotFoundException) {
    Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show()
}

I'm getting the Uri from here:

val fileResultLauncher =      registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    viewModel.uploadFile(result, false)
            }

fileFab.setOnClickListener {
    val intent = Intent()
    intent.type = "application/*"
    intent.action = Intent.ACTION_OPEN_DOCUMENT
    fileResultLauncher.launch(intent)
}

Unfortunately, I'm getting a NoActivityFoundException

Body:
Get rid of:

val file = File(Uri.parse(uri).path!!)

...and replace your setDataAndType() call with:

newIntent.setDataAndType(Uri.parse(uri), mimeType)


问:
Shuffle DataFrame rows
I have the following DataFrame:

```<code>    Col1  Col2  Col3  Type
0      1     2     3     1
1      4     5     6     1
...
20     7     8     9     2
21    10    11    12     2
...
45    13    14    15     3
46    16    17    18     3
...
</code>```

The DataFrame is read from a CSV file. All rows which have Type 1 are on top, followed by the rows with Type 2, followed by the rows with Type 3, etc.

I would like to shuffle the order of the DataFrame's rows so that all Type's are mixed. A possible result could be:

```<code>    Col1  Col2  Col3  Type
0      7     8     9     2
1     13    14    15     3
...
20     1     2     3     1
21    10    11    12     2
...
45     4     5     6     1
46    16    17    18     3
...
</code>```

How can I achieve this?

答:
Shuffle the DataFrame using sample() by passing the frac parameter.
Save the shuffled DataFrame to a new variable.

```<code>new_variable = DataFrame.sample(frac=1)
</code>```

Title: Shuffle DataFrame rows

Body:
I have the following DataFrame:

    Col1  Col2  Col3  Type
0      1     2     3     1
1      4     5     6     1
...
20     7     8     9     2
21    10    11    12     2
...
45    13    14    15     3
46    16    17    18     3
...

The DataFrame is read from a CSV file. All rows which have Type 1 are on top, followed by the rows with Type 2, followed by the rows with Type 3, etc.

I would like to shuffle the order of the DataFrame's rows so that all Type's are mixed. A possible result could be:

    Col1  Col2  Col3  Type
0      7     8     9     2
1     13    14    15     3
...
20     1     2     3     1
21    10    11    12     2
...
45     4     5     6     1
46    16    17    18     3
...

How can I achieve this?

Body:
Shuffle the DataFrame using sample() by passing the frac parameter.
Save the shuffled DataFrame to a new variable.

new_variable = DataFrame.sample(frac=1)


问:
What does git name-rev do?
According to git name-rev doc ,

Finds symbolic names suitable for human digestion for revisions given
  in any format parsable by git rev-parse.

But I could not understand this. What is the use of this command ? How is it different from git describe command ? I think that both also does the same thing -  give a SHA1 Id , gives us back the nearest reference name to it ?

答:
You have another illustration of git name-rev with Git 2.36 (Q2 2022), in the examples section of this fix:

"git name-rev --stdin"(man) does not behave like usual --stdin at all.

Start the process of renaming it to --annotate-stdin.

See commit a258571, commit 34ae3b7 (05 Jan 2022) by John Cai (john-cai).

(Merged by Junio C Hamano -- gitster -- in commit d9976b1, 09 Feb 2022)

name-rev: deprecate --stdin in favor of --annotate-stdin

Signed-off-by: "John Cai"

Introduce a --annotate-stdin that is functionally equivalent of --stdin.

--stdin does not behave as --stdin in other subcommands, such as pack-objects whereby it takes one argument per line.

Since --stdin can be a confusing and misleading name, rename it to --annotate-stdin.

This change adds a warning to --stdin warning that it will be removed in the future.

git name-rev now includes in its man page:

--annotate-stdin

git name-rev now includes in its man page:

altogether.

For example:

$ cat sample.txt

An abbreviated revision 2ae0a9cb82 will not be substituted.
The full name after substitution is 2ae0a9cb8298185a94e5998086f380a355dd8907,
while its tree object is 70d105cc79e63b81cfdcb08a15297c23e60b07ad

$ git name-rev --annotate-stdin <sample.txt

An abbreviated revision 2ae0a9cb82 will not be substituted.
The full name after substitution is 2ae0a9cb8298185a94e5998086f380a355dd8907 (master),
while its tree object is 70d105cc79e63b81cfdcb08a15297c23e60b07ad

$ git name-rev --name-only --annotate-stdin <sample.txt

An abbreviated revision 2ae0a9cb82 will not be substituted.
The full name after substitution is master,
while its tree object is 70d105cc79e63b81cfdcb08a15297c23e60b07ad
```
<h2><code>--stdin</code></h2>
<p>This option is deprecated in favor of '<code>git name-rev --annotate-stdin</code>'.<br />
They are functionally equivalent.</p>
</blockquote>
<hr />
<p>Git 2.36 (Q2 2022) also adds finishing touches to the "<code>name-rev --annotate-stdin</code>".</p>
<p>See commit d271892 (15 Feb 2022) by John Cai (<code>john-cai</code>).<br />
<sup>(Merged by Junio C Hamano -- <code>gitster</code> -- in commit 294f296, 25 Feb 2022)</sup></p>
<blockquote>
<h2><code>name-rev</code>: replace <code>--stdin</code> with <code>--annotate-stdin</code> in synopsis</h2>
<p><sup>Signed-off-by: John Cai</sup></p>
</blockquote>
<blockquote>
<p>34ae3b7 ("<code>name-rev</code>: deprecate <code>--stdin</code> in favor of <code>--annotate-stdin</code>", 2022-01-05, Git v2.36.0 -- merge listed in batch #2) added <code>--annotate-stdin</code> to replace <code>--stdin</code> as a clearer flag name.</p>
<p>Since <code>--stdin</code> is to be deprecated, we should replace <code>--stdin</code> in the output from <code>git name-rev -h</code>"<sup>(man)</sup>".</p>
</blockquote>
<hr />
<p>And still with Git 2.36 (Q2 2022), "<code>git name-rev</code>"<sup>(man)</sup> learned to use the generation numbers when setting the lower bound of searching commits used to explain the revision, when available, instead of committer time.</p>
<p>See commit 2e8ea40 (11 Mar 2022) by Jacob Keller (<code>jacob-keller</code>).<br />
<sup>(Merged by Junio C Hamano -- <code>gitster</code> -- in commit 94cb657, 23 Mar 2022)</sup></p>
<blockquote>
<h2><code>name-rev</code>: use generation numbers if available</h2>
<p><sup>Signed-off-by: Jacob Keller</sup></p>
</blockquote>
<blockquote>
<p>If a commit in a sequence of linear history has a non-monotonically increasing commit timestamp, <code>git name-rev</code><sup>(man)</sup> might not properly name the commit.</p>
<p>This occurs because <code>name-rev</code> uses a heuristic of the commit date to avoid searching down tags which lead to commits that are older than the named commit.<br />
This is intended to avoid work on larger repositories.</p>
<p>This heuristic impacts <code>git name-rev</code>, and by extension <code>git describe --contains</code><sup>(man)</sup> which is built on top of <code>name-rev</code>.</p>
<p>Further more, if <code>--all</code> or <code>--annotate-stdin</code> is used, the heuristic is not enabled because the full history has to be analyzed anyways.<br />
This results in some confusion if a user sees that <code>--annotate-stdin</code> works but a normal name-rev does not.</p>
<p>If the repository has a commit graph, we can use the generation numbers instead of using the commit dates.<br />
This is essentially the same check except that generation numbers make it exact, where the commit date heuristic could be incorrect due to clock errors.</p>
</blockquote>
<hr />
<p>Note: Git 2.41 (Q2 2023) now stops advertising it in the<code>git name-rev -h</code>" output: the "--stdin" option of "<code>git name-rev</code>"<sup>(man)</sup> has been replaced with the <code>--annotate-stdin</code> option more than a year ago.
We</p>
<p>See commit 9019d7d (06 May 2023) by John Cai (<code>john-cai</code>).<br />
<sup>(Merged by Junio C Hamano -- <code>gitster</code> -- in commit be2fd0e, 15 May 2023)</sup></p>
<blockquote>
<h2><code>name-rev</code>: make --stdin hidden</h2>
<p><sup>Signed-off-by: "John Cai"</sup></p>
</blockquote>
<blockquote>
<p>In 34ae3b7 (<code>name-rev</code>: deprecate --stdin in favor of --annotate-stdin, 2022-01-05, Git v2.36.0-rc0 -- merge listed in batch #2) (name-rev: deprecate <code>--stdin</code> in favor of --annotate-stdin), we renamed <code>--stdin</code> to <code>--annotate-stdin</code> for the sake of a clearer name for the option, and added text that indicates <code>--stdin</code> is deprecated.<br />
The next step is to hide <code>--stdin</code> completely.</p>
<p>Make the option hidden.<br />
Also, update documentation to remove all mentions of <code>--stdin</code>.</p>
</blockquote>
<p><code>git name-rev</code> now includes in its man page:</p>
<blockquote>
```( --all | --annotate-stdin | <commit-ish>... )
```
</blockquote>
<p><code>git name-rev</code> now includes in its man page:</p>
<blockquote>
<p>altogether. This option was called <code>--stdin</code> in older versions
of Git.</p>
</blockquote>
<p><code>git name-rev</code> now includes in its man page:</p>
<blockquote>
```% git log | git name-rev --annotate-stdin
```

Title: What does git name-rev do?

Body:
You have another illustration of git name-rev with Git 2.36 (Q2 2022), in the examples section of this fix:

"git name-rev --stdin"(man) does not behave like usual --stdin at all.

Start the process of renaming it to --annotate-stdin.

See commit a258571, commit 34ae3b7 (05 Jan 2022) by John Cai (john-cai).

(Merged by Junio C Hamano -- gitster -- in commit d9976b1, 09 Feb 2022)

name-rev: deprecate --stdin in favor of --annotate-stdin

Signed-off-by: "John Cai"

Introduce a --annotate-stdin that is functionally equivalent of --stdin.

--stdin does not behave as --stdin in other subcommands, such as pack-objects whereby it takes one argument per line.

Since --stdin can be a confusing and misleading name, rename it to --annotate-stdin.

This change adds a warning to --stdin warning that it will be removed in the future.

git name-rev now includes in its man page:

--annotate-stdin

git name-rev now includes in its man page:

altogether.

For example:

$ cat sample.txt

An abbreviated revision 2ae0a9cb82 will not be substituted.
The full name after substitution is 2ae0a9cb8298185a94e5998086f380a355dd8907,
while its tree object is 70d105cc79e63b81cfdcb08a15297c23e60b07ad

$ git name-rev --annotate-stdin <sample.txt

An abbreviated revision 2ae0a9cb82 will not be substituted.
The full name after substitution is 2ae0a9cb8298185a94e5998086f380a355dd8907 (master),
while its tree object is 70d105cc79e63b81cfdcb08a15297c23e60b07ad

$ git name-rev --name-only --annotate-stdin <sample.txt

An abbreviated revision 2ae0a9cb82 will not be substituted.
The full name after substitution is master,
while its tree object is 70d105cc79e63b81cfdcb08a15297c23e60b07ad

--stdin

This option is deprecated in favor of 'git name-rev --annotate-stdin'.

They are functionally equivalent.

Git 2.36 (Q2 2022) also adds finishing touches to the "name-rev --annotate-stdin".

See commit d271892 (15 Feb 2022) by John Cai (john-cai).

(Merged by Junio C Hamano -- gitster -- in commit 294f296, 25 Feb 2022)

name-rev: replace --stdin with --annotate-stdin in synopsis

Signed-off-by: John Cai

34ae3b7 ("name-rev: deprecate --stdin in favor of --annotate-stdin", 2022-01-05, Git v2.36.0 -- merge listed in batch #2) added --annotate-stdin to replace --stdin as a clearer flag name.

Since --stdin is to be deprecated, we should replace --stdin in the output from git name-rev -h"(man)".

And still with Git 2.36 (Q2 2022), "git name-rev"(man) learned to use the generation numbers when setting the lower bound of searching commits used to explain the revision, when available, instead of committer time.

See commit 2e8ea40 (11 Mar 2022) by Jacob Keller (jacob-keller).

(Merged by Junio C Hamano -- gitster -- in commit 94cb657, 23 Mar 2022)

name-rev: use generation numbers if available

Signed-off-by: Jacob Keller

If a commit in a sequence of linear history has a non-monotonically increasing commit timestamp, git name-rev(man) might not properly name the commit.

This occurs because name-rev uses a heuristic of the commit date to avoid searching down tags which lead to commits that are older than the named commit.

This is intended to avoid work on larger repositories.

This heuristic impacts git name-rev, and by extension git describe --contains(man) which is built on top of name-rev.

Further more, if --all or --annotate-stdin is used, the heuristic is not enabled because the full history has to be analyzed anyways.

This results in some confusion if a user sees that --annotate-stdin works but a normal name-rev does not.

If the repository has a commit graph, we can use the generation numbers instead of using the commit dates.

This is essentially the same check except that generation numbers make it exact, where the commit date heuristic could be incorrect due to clock errors.

Note: Git 2.41 (Q2 2023) now stops advertising it in thegit name-rev -h" output: the "--stdin" option of "git name-rev"(man) has been replaced with the --annotate-stdin option more than a year ago.
We

See commit 9019d7d (06 May 2023) by John Cai (john-cai).

(Merged by Junio C Hamano -- gitster -- in commit be2fd0e, 15 May 2023)

name-rev: make --stdin hidden

Signed-off-by: "John Cai"

In 34ae3b7 (name-rev: deprecate --stdin in favor of --annotate-stdin, 2022-01-05, Git v2.36.0-rc0 -- merge listed in batch #2) (name-rev: deprecate --stdin in favor of --annotate-stdin), we renamed --stdin to --annotate-stdin for the sake of a clearer name for the option, and added text that indicates --stdin is deprecated.

The next step is to hide --stdin completely.

Make the option hidden.

Also, update documentation to remove all mentions of --stdin.

git name-rev now includes in its man page:

( --all | --annotate-stdin | <commit-ish>... )

git name-rev now includes in its man page:

altogether. This option was called --stdin in older versions
of Git.

git name-rev now includes in its man page:

% git log | git name-rev --annotate-stdin


问:
How might I get the script filename from within that script?
I'm pretty sure the answer is no, but thought I'd ask anyway.

If my site references a scripted named "whatever.js", is it possible to get "whatever.js" from within that script? Like:

```<code>var scriptName = ???

if (typeof jQuery !== "function") {
    throw new Error(
        "jQuery's script needs to be loaded before " +
        scriptName + ". Check the <script> tag order.");
}
</code>```

Probably more trouble than it's worth for dependency checking, but what the hell.

答:
You can return a list of script elements in the page:

```<code>var scripts = document.getElementsByTagName("script");
</code>```

And then evaluate each one and retrieve its location:

```<code>var location;

for(var i=0; i<scripts.length;++i) {
   location = scripts[i].src;

   //Do stuff with the script location here
}
</code>```

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Body:
I'm pretty sure the answer is no, but thought I'd ask anyway.

If my site references a scripted named "whatever.js", is it possible to get "whatever.js" from within that script? Like:

var scriptName = ???

if (typeof jQuery !== "function") {
    throw new Error(
        "jQuery's script needs to be loaded before " +
        scriptName + ". Check the

Body:
You can return a list of script elements in the page:

var scripts = document.getElementsByTagName("script");

And then evaluate each one and retrieve its location:

var location;

for(var i=0; i<scripts.length;++i) {
   location = scripts[i].src;

   //Do stuff with the script location here
}

OwnerDisplayName: Perspx


问:
Some python argparse usage questions: retrieving arguments
Some questions that I couldn't figure out from reading the docs and some other questions.

1: I was stumped by "how do I actually retrieve the arguments" so I looked around and someone suggested to use the __dict __ function to access it like a dictionary. Which works, but is that the only way? This seems like a rather common thing but it doesn't appear to be anywhere obvious in the docs. If I missed it, maybe someone can point it out? It definitely wasn't at the top.

2: argparse was introduced in 2.7, but some people refuse to get newer versions of python and continue to stick to older ones like 2.5, 2.6 for reasons unknown to me. My solution for dealing with them is to take the argparse module and put it in my own script directory. Is there any problem with this solution? It seems to be working at least.

答:
You can use the parse_args() function to retrieve parameters. For example:

```<code>parser = argparse.ArgumentParser(description="Test")
parser.add_argument('command')

parameters = parser.parse_args()
cmd = parameters.command
</code>```

To answer your second question, it's not recommended that you do this. Simply adding the module won't be sufficient since you might run into dependency issues (ie, internally, argparse may require something else that was only made available in 2.7). The older, but deprecated version of this is optparse.

ContentLicense: CC BY-SA 3.0

Body:
You can use the parse_args() function to retrieve parameters. For example:

parser = argparse.ArgumentParser(description="Test")
parser.add_argument('command')

parameters = parser.parse_args()
cmd = parameters.command

To answer your second question, it's not recommended that you do this. Simply adding the module won't be sufficient since you might run into dependency issues (ie, internally, argparse may require something else that was only made available in 2.7). The older, but deprecated version of this is optparse.


问:
Python KivyMD. How to run two functions in turn by clicking on the same button?
That is, he pressed the button, function No. 1 started, pressed again, function No. started.2 pressed again and again function No. 1 and so on... How to do it with a single MDFloatingActionButton?</p>
```<code>from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.uix.button.button import MDFloatingActionButton

KV = '''
MDFloatLayout:

    MDFloatingActionButton:
        icon: "flashlight"
        pos_hint: {'center_x': .5, 'center_y': .5}
        on_release: app.foo1() and app.foo2()

        '''

class Test(MDApp):
    def build(self):
        screen = Builder.load_string(KV)
        return screen

    def foo1(self):
        print("foo1")

    def foo2(self):
        print("foo2")

Test().run()
</code>```

答:
```<code> MDFloatingActionButton:
    icon: "flashlight"
    pos_hint: {'center_x': .5, 'center_y': .5}
    on_release:
        app.foo1()
        app.foo2()
</code>```

That should do it

Edit:
sorry, it seems like i misunderstood your question. here's how you should do it

```<code>from kivymd.app import MDApp
from kivy.lang import Builder

KV = '''
MDFloatLayout:
    MDFloatingActionButton:
        icon: "flashlight"
        pos_hint: {'center_x': .5, 'center_y': .5}
        on_release: app.button_on_release()

'''

class Test(MDApp):
    release_count = 0
    def build(self):
        screen = Builder.load_string(KV)
        return screen

    def button_on_release(self):
        if self.release_count == 0:
            self.foo1()
            self.release_count += 1
            return

        if self.release_count == 1:
            self.foo2()

            self.release_count = 0
            return

    def foo1(self):
        print("foo1")

    def foo2(self):
        print("foo2")

Test().run()
</code>```

Body:
That is, he pressed the button, function No. 1 started, pressed again, function No. started.2 pressed again and again function No. 1 and so on... How to do it with a single MDFloatingActionButton?

from kivymd.app import MDApp
from kivy.lang import Builder
from kivymd.uix.button.button import MDFloatingActionButton

KV = '''
MDFloatLayout:

    MDFloatingActionButton:
        icon: "flashlight"
        pos_hint: {'center_x': .5, 'center_y': .5}
        on_release: app.foo1() and app.foo2()

        '''

class Test(MDApp):
    def build(self):
        screen = Builder.load_string(KV)
        return screen

    def foo1(self):
        print("foo1")

    def foo2(self):
        print("foo2")

Test().run()

Body:
 MDFloatingActionButton:
    icon: "flashlight"
    pos_hint: {'center_x': .5, 'center_y': .5}
    on_release:
        app.foo1()
        app.foo2()

That should do it

Edit:
sorry, it seems like i misunderstood your question. here's how you should do it

from kivymd.app import MDApp
from kivy.lang import Builder

KV = '''
MDFloatLayout:
    MDFloatingActionButton:
        icon: "flashlight"
        pos_hint: {'center_x': .5, 'center_y': .5}
        on_release: app.button_on_release()

'''

class Test(MDApp):
    release_count = 0
    def build(self):
        screen = Builder.load_string(KV)
        return screen

    def button_on_release(self):
        if self.release_count == 0:
            self.foo1()
            self.release_count += 1
            return

        if self.release_count == 1:
            self.foo2()

            self.release_count = 0
            return

    def foo1(self):
        print("foo1")

    def foo2(self):
        print("foo2")

Test().run()


问:
view pdf without downloading using dompdf
I generated a PDF using the dompdf library and used this:

```<code>$dompdf->stream('my.pdf',array('Attachment'=>0));
</code>```

to force the browser to let the user view the PDF before downloading. But it's not working. A Google search isn't bringing up any answers either. Can anyone help?

答:
Try this

```<code>$dompdf->stream("", array("Attachment" => false));
</code>```

Instead of

```<code>$dompdf->stream();
</code>```

It worked for me

Body:
I generated a PDF using the dompdf library and used this:

$dompdf->stream('my.pdf',array('Attachment'=>0));

to force the browser to let the user view the PDF before downloading. But it's not working. A Google search isn't bringing up any answers either. Can anyone help?

Body:
Try this

$dompdf->stream("", array("Attachment" => false));

Instead of

$dompdf->stream();

It worked for me


问:
react-native-maps conditional markers
I have a map of markers that renders each marker in an array of coordinates. I am trying to render markers conditionally based on a key I give the marker. You can see exactly how I am trying to do this by looking at my snack example here or I have posted the code below.

Thank you, I appreciate it more than you know.

```<code>export default class Map extends React.Component {
  markers = [];
  state = {
    coordinates: [
      {
        name: '1',
        latitude: 36.212111515965525,
        longitude: -81.67527588876025,
        status: 'busy',
      },
      {
        name: '2',
        latitude: 36.21754431261142,
        longitude: -81.68598350040361,
        status: 'open',
      },
      {
        name: '3',
        latitude: 36.21744712906634,
        longitude: -81.68168562889075,
        status: 'busy',
      },
      {
        name: '4',
        latitude: 36.219352000280495,
        longitude: -81.68559146421954,
        status: 'open',
      },
    ],
  };

  render() {
    return (
      <View style={{ ...StyleSheet.absoluteFillObject }}>
        <MapView
          style={styles.map}
          provider={PROVIDER_GOOGLE}
          showsUserLocation={true}
          showsMyLocationButton={true}
          ref={(map) => (this._map = map)}
          initialRegion={{
            latitude: 36.212111515965525,
            longitude: -81.67527588876025,
            latitudeDelta: 0.05,
            longitudeDelta: 0.05
          }}>
          {this.state.coordinates.map((marker, index) => (
            if(marker.status == 'busy'){
            <Marker
              key={marker.name}
              ref={(ref) => {this.markers[index] = ref;}}
              onPress={() => this.onMarkerPress(marker, index)}
              coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
              }}>
              <Image
                source={require('./assets/blueMarker.png')}
                style={{ height: scale(50), width: scale(50) }}
              />
            </Marker>
            } else {
               <Marker
              key={marker.name}
              ref={(ref) => {this.markers[index] = ref;}}
              onPress={() => this.onMarkerPress(marker, index)}
              coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
              }}>
            </Marker>
            }

          ))}
        </MapView>
      </View>
    );
  }
}

</code>```

答:
Here, In JSX we are allowed to render components only.

If We have to render something conditionally, we can use ternary operators for that.

Here I can see in the code that you have used If...Else...

Solution for your code:

```<code>{
    this.state.coordinates.map((marker, index) => (
        marker.status == 'busy'
        ?
            <Marker
                key={marker.name}
                ref={(ref) => {this.markers[index] = ref;}}
                onPress={() => this.onMarkerPress(marker, index)}
                coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
                }}>
                <Image
                source={require('./assets/blueMarker.png')}
                style={{ height: scale(50), width: scale(50) }}
                />
            </Marker>
        :
            <Marker
                key={marker.name}
                ref={(ref) => {this.markers[index] = ref;}}
                onPress={() => this.onMarkerPress(marker, index)}
                coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
                }}>
            </Marker>
    ))
}
</code>```

Title: react-native-maps conditional markers

Body:
I have a map of markers that renders each marker in an array of coordinates. I am trying to render markers conditionally based on a key I give the marker. You can see exactly how I am trying to do this by looking at my snack example here or I have posted the code below.

Thank you, I appreciate it more than you know.

export default class Map extends React.Component {
  markers = [];
  state = {
    coordinates: [
      {
        name: '1',
        latitude: 36.212111515965525,
        longitude: -81.67527588876025,
        status: 'busy',
      },
      {
        name: '2',
        latitude: 36.21754431261142,
        longitude: -81.68598350040361,
        status: 'open',
      },
      {
        name: '3',
        latitude: 36.21744712906634,
        longitude: -81.68168562889075,
        status: 'busy',
      },
      {
        name: '4',
        latitude: 36.219352000280495,
        longitude: -81.68559146421954,
        status: 'open',
      },
    ],
  };

  render() {
    return (
      <View style={{ ...StyleSheet.absoluteFillObject }}>
        <MapView
          style={styles.map}
          provider={PROVIDER_GOOGLE}
          showsUserLocation={true}
          showsMyLocationButton={true}
          ref={(map) => (this._map = map)}
          initialRegion={{
            latitude: 36.212111515965525,
            longitude: -81.67527588876025,
            latitudeDelta: 0.05,
            longitudeDelta: 0.05
          }}>
          {this.state.coordinates.map((marker, index) => (
            if(marker.status == 'busy'){
            <Marker
              key={marker.name}
              ref={(ref) => {this.markers[index] = ref;}}
              onPress={() => this.onMarkerPress(marker, index)}
              coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
              }}>
              <Image
                source={require('./assets/blueMarker.png')}
                style={{ height: scale(50), width: scale(50) }}
              />
            </Marker>
            } else {
               <Marker
              key={marker.name}
              ref={(ref) => {this.markers[index] = ref;}}
              onPress={() => this.onMarkerPress(marker, index)}
              coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
              }}>
            </Marker>
            }

          ))}
        </MapView>
      </View>
    );
  }
}

Body:
Here, In JSX we are allowed to render components only.

If We have to render something conditionally, we can use ternary operators for that.

Here I can see in the code that you have used If...Else...

Solution for your code:

{
    this.state.coordinates.map((marker, index) => (
        marker.status == 'busy'
        ?
            <Marker
                key={marker.name}
                ref={(ref) => {this.markers[index] = ref;}}
                onPress={() => this.onMarkerPress(marker, index)}
                coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
                }}>
                <Image
                source={require('./assets/blueMarker.png')}
                style={{ height: scale(50), width: scale(50) }}
                />
            </Marker>
        :
            <Marker
                key={marker.name}
                ref={(ref) => {this.markers[index] = ref;}}
                onPress={() => this.onMarkerPress(marker, index)}
                coordinate={{
                latitude: marker.latitude,
                longitude: marker.longitude,
                }}>
            </Marker>
    ))
}


问:
Is there a more efficient way than this way of if statements in python?
I wonder (and I think there must be) if there is another way of comparing variables and changing them, because if I used "or" in the if statements, I don't have any way of determining which card made the statement True.</p>
```<code>def card_value(card_one, card_two):

    if card_one == 'A':
        card_one = 11

    if card_two == 'A':
        card_two == 11

    if card_one in ('K', 'J', 'Q'):
        card_one = 10

    if card_two in ('K', 'J', 'Q'):
        card_two = 10
</code>```

答:
It seems that card_one and card_two exist in a scope outside of the function card_value, so assigning them values within card_value won't be possible without re-declaring them as global variables within card_value. To treat this and simplify card_value, may I suggest re-writing card_value to take in any card and return the desired score?

```<code>def card_value(card):

    if card == 'A':
        return 11

    elif card in ('K', 'J', 'Q'):
        return 10

def main():
    card_one = 'A'
    card_two = 'Q'

    card_one_points = card_value(card_one)
    card_two_points = card_value(card_two)

main()

</code>```

Body:
I wonder (and I think there must be) if there is another way of comparing variables and changing them, because if I used "or" in the if statements, I don't have any way of determining which card made the statement True.

def card_value(card_one, card_two):

    if card_one == 'A':
        card_one = 11

    if card_two == 'A':
        card_two == 11

    if card_one in ('K', 'J', 'Q'):
        card_one = 10

    if card_two in ('K', 'J', 'Q'):
        card_two = 10

Body:
It seems that card_one and card_two exist in a scope outside of the function card_value, so assigning them values within card_value won't be possible without re-declaring them as global variables within card_value. To treat this and simplify card_value, may I suggest re-writing card_value to take in any card and return the desired score?

def card_value(card):

    if card == 'A':
        return 11

    elif card in ('K', 'J', 'Q'):
        return 10

def main():
    card_one = 'A'
    card_two = 'Q'

    card_one_points = card_value(card_one)
    card_two_points = card_value(card_two)

main()


问:
Standardizing output in google sheet with reference sheet
This is my computatiom sheet: (https://docs.google.com/spreadsheets/d/e/2PACX-1vSR3jhKH7FNfuqo_VcemDUoZGNtoUJttCQz8XF0r7c8Qyyc4PWQqqHyxanalb5etA/pubhtml?gid=6282745&single=true)

```<code>Name              Country       Region  Unique Region   Region Count    Sales Representative
Mr Action Taker   Dubai         EMEA    EMEA                  5          Eashwari
Mr Responsible    Bangalore     APAC    APAC                  7          Chetan
Mr Careful guy    Mumbai        APAC    AMER                  3          Khushi
</code>```

The unique region is computed by UNIQUE function which is giving me the list of unique regions from the inputs that i receive one by one. If a new region is added, the unique list will be appended automatically.

The region count is the count of regions in my input. I have use the MOD function to assign the lead to a sales rep in a chronological fashion so that even distribution is achieved.

In the above sheet, my region count increases by 1 as soon as a new entry is added into the input sheet. When that happens, a sales rep is assigned automatically.

Each region has 4 sales rep.

Now, i have an output sheet below. (https://docs.google.com/spreadsheets/d/e/2PACX-1vSR3jhKH7FNfuqo_VcemDUoZGNtoUJttCQz8XF0r7c8Qyyc4PWQqqHyxanalb5etA/pubhtml?gid=1954161251&single=true)

```<code>Name of the Lead    Team    Sales Representative    Notes:
Mr Action Taker     EMEA                            We want to upgrade our subscription
</code>```

Now, I want to show the sales rep in the output sheet which i have computed in the computation sheet. This shall not change if my computation sheet is updated whenever new entry comes in.
The sales rep shall be from his region team.

答:
use:</p>
```<code>=INDEX(IFNA(VLOOKUP(A2:A&" "&B2:B, {
 IMPORTRANGE("url_or_id_of_spreadsheet", "Part 2 Computation Sheet!A2:A")&" "&
 IMPORTRANGE("url_or_id_of_spreadsheet", "Part 2 Computation Sheet!C2:C"),
 IMPORTRANGE("url_or_id_of_spreadsheet", "Part 2 Computation Sheet!F2:F")}, 2, 0)))
</code>```

Body:
This is my computatiom sheet: (https://docs.google.com/spreadsheets/d/e/2PACX-1vSR3jhKH7FNfuqo_VcemDUoZGNtoUJttCQz8XF0r7c8Qyyc4PWQqqHyxanalb5etA/pubhtml?gid=6282745&single=true)

Name              Country       Region  Unique Region   Region Count    Sales Representative
Mr Action Taker   Dubai         EMEA    EMEA                  5          Eashwari
Mr Responsible    Bangalore     APAC    APAC                  7          Chetan
Mr Careful guy    Mumbai        APAC    AMER                  3          Khushi

The unique region is computed by UNIQUE function which is giving me the list of unique regions from the inputs that i receive one by one. If a new region is added, the unique list will be appended automatically.

The region count is the count of regions in my input. I have use the MOD function to assign the lead to a sales rep in a chronological fashion so that even distribution is achieved.

In the above sheet, my region count increases by 1 as soon as a new entry is added into the input sheet. When that happens, a sales rep is assigned automatically.

Each region has 4 sales rep.

Now, i have an output sheet below. (https://docs.google.com/spreadsheets/d/e/2PACX-1vSR3jhKH7FNfuqo_VcemDUoZGNtoUJttCQz8XF0r7c8Qyyc4PWQqqHyxanalb5etA/pubhtml?gid=1954161251&single=true)

Name of the Lead    Team    Sales Representative    Notes:
Mr Action Taker     EMEA                            We want to upgrade our subscription

Now, I want to show the sales rep in the output sheet which i have computed in the computation sheet. This shall not change if my computation sheet is updated whenever new entry comes in.
The sales rep shall be from his region team.

Body:
use:

=INDEX(IFNA(VLOOKUP(A2:A&" "&B2:B, {
 IMPORTRANGE("url_or_id_of_spreadsheet", "Part 2 Computation Sheet!A2:A")&" "&
 IMPORTRANGE("url_or_id_of_spreadsheet", "Part 2 Computation Sheet!C2:C"),
 IMPORTRANGE("url_or_id_of_spreadsheet", "Part 2 Computation Sheet!F2:F")}, 2, 0)))


问:
How to print values in dataframes column by their indexes?
I have a dataframe:

```<code>id   value
742  aa
1711 bb
1731 qq
1799 ff
2741 pp

</code>```

id is the index column. I want to print only those values from column "value" which are in this list: [742, 1731, 1799]. So the output must be:

```<code>aa
qq
ff
</code>```

How to do that?

I tried this:

```<code>for i in [742, 1731, 1799]:
    print(df[df.index == i]["value"])
</code>```

but the output is:

```<code>value
742    aa
Name: value, dtype: object
value
1731    qq
Name: value, dtype: object
value
1799    ff
Name: value, dtype: object
</code>```

答:
Use .set_index to declare 'id' as the index, then .loc[...] to specify the list of indices you're interested in.

df = pd.DataFrame({'id': [8, 13, 21, 34, 55, 89], 'val': 'for sale baby shoes never worn'.split()}).set_index('id')

print(df)
#       val
# id
# 8     for
# 13   sale
# 21   baby
# 34  shoes
# 55  never
# 89   worn

print(df.loc[[13,89]])
#      val
# id
# 13  sale
# 89  worn
```

Body:
I have a dataframe:

id   value
742  aa
1711 bb
1731 qq
1799 ff
2741 pp

id is the index column. I want to print only those values from column "value" which are in this list: [742, 1731, 1799]. So the output must be:

aa
qq
ff

How to do that?

I tried this:

for i in [742, 1731, 1799]:
    print(df[df.index == i]["value"])

but the output is:

value
742    aa
Name: value, dtype: object
value
1731    qq
Name: value, dtype: object
value
1799    ff
Name: value, dtype: object


问:
How to highlight text using javascript
Can someone help me with a javascript function that can highlight text on a web page.
And the requirement is to - highlight only once, not like highlight all occurrences of the text as we do in case of search.</p>

答:
I think this code is better because highlight all repeated character

function highlight(text) {
  var inputText = document.getElementById("inputText");
  var innerHTML = inputText.innerHTML;
  var index = innerHTML.indexOf(text);
  if (index >= 0) {
     inputText.innerHTML=innerHTML.split(text).join(''+text+'');
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlight {
  background-color: yellow;
}</code>```

<button onclick="highlight('fox')">Highlight</button>

  The fox went over the fence fox fox fox wen fox

```

Title: How to highlight text using javascript

Body:
I think this code is better because highlight all repeated character

function highlight(text) {
  var inputText = document.getElementById("inputText");
  var innerHTML = inputText.innerHTML;
  var index = innerHTML.indexOf(text);
  if (index >= 0) {
     inputText.innerHTML=innerHTML.split(text).join('<span class="highlight">'+text+'</span>');
  }
}

.highlight {
  background-color: yellow;
}

<button onclick="highlight('fox')">Highlight</button>

<div id="inputText">
  The fox went over the fence fox fox fox wen fox
</div>


问:
Python _ Project Euler Question 2 - Why my answer code is wrong?
Q: By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

My Code:

```<code>x = 1
y = 2
ans = 0
evens = []
while x <= 4000000:
    ans = x + y
    x = y
    y = ans
    if ans % 2 == 0:
        evens.append(ans)
print(sum(evens))
</code>```

My result is 4613730 while it should be 4613732.
What am I don't understand here?

答:
You are skipping over 2.

ans is first checked with the value of 3.

ans = x + y is 3 since you start with x = 1 and y = 2

Body:
Q: By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

My Code:

x = 1
y = 2
ans = 0
evens = []
while x <= 4000000:
    ans = x + y
    x = y
    y = ans
    if ans % 2 == 0:
        evens.append(ans)
print(sum(evens))

My result is 4613730 while it should be 4613732.
What am I don't understand here?


问:
Scaling data in RFECV with scikit-learn
It is common to scale the training and testing data separately before training and predicting progress of a classification task.

I want to embed the aforementioned process in RFECV which runs CV tests thus I tried the following:

Do
X_scaled = preprocessing.scale(X) in the first place, where X is the whole data set. By doing so, training and testing data are not scaled separately, which is not considered.

The other way I tried is to pass:

```<code>scaling_svm = Pipeline([('scaler', preprocessing.StandardScaler()),
                        ('svm',LinearSVC(penalty=penalty, dual=False, class_weight='auto'))])
</code>```

as parameter to the argument in RFECV :

```<code>rfecv = RFECV(estimator=scaling_svm, step=1, cv=StratifiedKFold(y, 7),
                  scoring=score, verbose=0)
</code>```

However, I got an error since RFECV needs the estimator to have attribute .coef_.
What should I suppose to do? Any help would be appreciated.

答:
A bit late to the party, admittedly, but if anyone is interested you can create a customised pipeline as follows:

```<code>from sklearn.pipeline import Pipeline
class RfePipeline(Pipeline):
    @property
    def coef_(self):
        return self._final_estimator.coef_
</code>```

And then replace Pipeline with RfePipeline in your code.

See similar question here.

Title: Scaling data in RFECV with scikit-learn

Body:
It is common to scale the training and testing data separately before training and predicting progress of a classification task.

I want to embed the aforementioned process in RFECV which runs CV tests thus I tried the following:

Do
X_scaled = preprocessing.scale(X) in the first place, where X is the whole data set. By doing so, training and testing data are not scaled separately, which is not considered.

The other way I tried is to pass:

scaling_svm = Pipeline([('scaler', preprocessing.StandardScaler()),
                        ('svm',LinearSVC(penalty=penalty, dual=False, class_weight='auto'))])

as parameter to the argument in RFECV :

rfecv = RFECV(estimator=scaling_svm, step=1, cv=StratifiedKFold(y, 7),
                  scoring=score, verbose=0)

However, I got an error since RFECV needs the estimator to have attribute .coef_.
What should I suppose to do? Any help would be appreciated.

Body:
A bit late to the party, admittedly, but if anyone is interested you can create a customised pipeline as follows:

from sklearn.pipeline import Pipeline
class RfePipeline(Pipeline):
    @property
    def coef_(self):
        return self._final_estimator.coef_

And then replace Pipeline with RfePipeline in your code.

See similar question here.


问:
Default value of input field causes alignment problem
I am trying to build a timer and I am also trying to use SVG in particular. I have an input field that might not be sized properly but I am using alignment to deal with this problem.
However, my code seems to break if I put in a default value or even try to use javaScript to set the value once the page loads. This does not work and I am unable to type in the visible region. However, if I delete the data already in there using the delete key or if I simply don't put in a default value and type the values, the alignment seems to work just fine. Here is the code I have with the default values:

body{
    background-color: black;
}
#input1, textarea{
    text-align: right;
    background-color: black;
    fill: black;
    padding: 0;
    border: none;
}

#input1 ,text{
    color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg height="100vh" width="100vw">
        <circle r="25%" cx="50%" cy="50%" fill-opacity="100%" stroke="green" stroke-width="7"></circle>
            <!--TODO: add handling to button-->
        <foreignObject x="31.5%" y="42%" width="16%" height="16%" fill="black" stroke-width="0">
            <div xmlns="http://www.w3.org/1999/xhtml">
                <label>
                    <input id ="input1" style="font-size: 450%; color: white" maxlength="2" value="05">
                </label>
            </div>
        </foreignObject>
<svg></code>```

In the above code, if you remove the input, the alignment fixes itself and it stays fixed even for future updates using javaScript.

Please see the output in a full page view. Is there a reason why this happening and is there a fix I can use?

Note:The field is to the left of the center of the circle, it's just not visible because it is black.

答:
I'm not definitely sure, but I think the problem that's causing the alignment of the text problem in the input field is due to the value of the width attribute of your foreignObject element.

As you can see, the font-size of your input element is relatively so much bigger than the foreignObject can fit. That is why the text alignment is acting weird.

So basically, I could say that the value in the input field is not shown or wrongly aligned because of the width of the foreignObject element that is not proportional to the font-size of your input element and thus, it is somehow "hidden". Therefore, what I tried to do was mess around with the width attribute in the foreignObject element.

Original values:
<foreignObject x="31.5%" y="42%" width="16%" height="100%" fill="black" stroke-width="0">

After changing the width attribute of foreignObject:
<foreignObject x="31.5%" y="42%" width="100%" height="100%" fill="black" stroke-width="0">

Hope this gives you at least a little bit of idea, just in case it didn't really answer your question.

Body:
I am trying to build a timer and I am also trying to use SVG in particular. I have an input field that might not be sized properly but I am using alignment to deal with this problem.
However, my code seems to break if I put in a default value or even try to use javaScript to set the value once the page loads. This does not work and I am unable to type in the visible region. However, if I delete the data already in there using the delete key or if I simply don't put in a default value and type the values, the alignment seems to work just fine. Here is the code I have with the default values:

body{
    background-color: black;
}
#input1, textarea{
    text-align: right;
    background-color: black;
    fill: black;
    padding: 0;
    border: none;
}

#input1 ,text{
    color: white;
}

<svg height="100vh" width="100vw">
        <circle r="25%" cx="50%" cy="50%" fill-opacity="100%" stroke="green" stroke-width="7"></circle>

        <foreignObject x="31.5%" y="42%" width="16%" height="16%" fill="black" stroke-width="0">

                    <input id ="input1" style="font-size: 450%; color: white" maxlength="2" value="05">

        </foreignObject>
<svg>

In the above code, if you remove the input, the alignment fixes itself and it stays fixed even for future updates using javaScript.

Please see the output in a full page view. Is there a reason why this happening and is there a fix I can use?

Note:The field is to the left of the center of the circle, it's just not visible because it is black.


问:
My Flutter App is not running after adding cloud_firebase package
Recently I have added firebase to my flutter project. To use firebase database services I have added cloud_firebase package. But after adding this package my app is not running and giving me an exception:

```<code>BUILD FAILED in 31s
The plugin cloud_firestore requires a higher Android SDK version.
Fix this issue by adding the following to the file C:\Users\Jaguar\Desktop\AppDevelopment\acadmt\android\app\build.gradle:
android {
  defaultConfig {
    minSdkVersion 19
  }
}
Note that your app won't be available to users running Android SDKs below 19.
Alternatively, try to find a version of this plugin that supports these lower versions of the Android SDK.
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

The exception message is also suggesting following suggestions:

```<code>Suggestion: use a compatible library with a minSdk of at most 16,
        or increase this project's minSdk version to at least 19,
        or use tools:overrideLibrary="io.flutter.plugins.firebase.firestore" to force usage (may lead to runtime failures)
</code>```

I have tried the first two suggestions but still, the app is not working.

答:
```<code>android {
  defaultConfig {
    minSdkVersion 21
    targetSdkVersion 30
  }
}
</code>```
<p>Result:  Running with sound null safety </p>

Body:
Recently I have added firebase to my flutter project. To use firebase database services I have added cloud_firebase package. But after adding this package my app is not running and giving me an exception:

BUILD FAILED in 31s
The plugin cloud_firestore requires a higher Android SDK version.
Fix this issue by adding the following to the file C:\Users\Jaguar\Desktop\AppDevelopment\acadmt\android\app\build.gradle:
android {
  defaultConfig {
    minSdkVersion 19
  }
}
Note that your app won't be available to users running Android SDKs below 19.
Alternatively, try to find a version of this plugin that supports these lower versions of the Android SDK.
Exception: Gradle task assembleDebug failed with exit code 1

The exception message is also suggesting following suggestions:

Suggestion: use a compatible library with a minSdk of at most 16,
        or increase this project's minSdk version to at least 19,
        or use tools:overrideLibrary="io.flutter.plugins.firebase.firestore" to force usage (may lead to runtime failures)

I have tried the first two suggestions but still, the app is not working.

Body:
android {
  defaultConfig {
    minSdkVersion 21
    targetSdkVersion 30
  }
}

Result:  Running with sound null safety


问:
Change Text Box Color using Required Field Validator. No Extender Controls Please
I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button</p>

答:
I know this is old, but I have another modified combination from Dillie-O and Alexander.  This uses jQuery with the blur event to remove the style when validation succeeds.</p>

```<code>function validateFields() {
    try {
        var count = 0;
        var hasFocus = false;

        for (var i = 0; i < Page_Validators.length; i++) {
            var val = Page_Validators[i];
            var ctrl = document.getElementById(val.controltovalidate);

            validateField(ctrl, val);

            if (!val.isvalid) { count++; }
            if (!val.isvalid && hasFocus === false) {
                ctrl.focus(); hasFocus = true;
            }
        }

        if (count == 0) {
            hasFocus = false;
        }
    }
    catch (err) { }
}

function validateField(ctrl, val)
{
    $(ctrl).blur(function () { validateField(ctrl, val); });

    if (ctrl != null && $(ctrl).is(':disabled') == false) { // && ctrl.style != null
        val.isvalid ? $(ctrl).removeClass("error") : $(ctrl).addClass("error");
    }

    if ($(ctrl).hasClass('rdfd_') == true) { //This is a RadNumericTextBox
        var rtxt = document.getElementById(val.controltovalidate + '_text');
        val.isvalid ? $(rtxt).removeClass("error") : $(rtxt).addClass("error");
    }
}
</code>```

OwnerDisplayName: Badmate

LastEditorDisplayName: Pax Diablo

Body:
I know this is old, but I have another modified combination from Dillie-O and Alexander.  This uses jQuery with the blur event to remove the style when validation succeeds.

function validateFields() {
    try {
        var count = 0;
        var hasFocus = false;

        for (var i = 0; i < Page_Validators.length; i++) {
            var val = Page_Validators[i];
            var ctrl = document.getElementById(val.controltovalidate);

            validateField(ctrl, val);

            if (!val.isvalid) { count++; }
            if (!val.isvalid && hasFocus === false) {
                ctrl.focus(); hasFocus = true;
            }
        }

        if (count == 0) {
            hasFocus = false;
        }
    }
    catch (err) { }
}

function validateField(ctrl, val)
{
    $(ctrl).blur(function () { validateField(ctrl, val); });

    if (ctrl != null && $(ctrl).is(':disabled') == false) { // && ctrl.style != null
        val.isvalid ? $(ctrl).removeClass("error") : $(ctrl).addClass("error");
    }

    if ($(ctrl).hasClass('rdfd_') == true) { //This is a RadNumericTextBox
        var rtxt = document.getElementById(val.controltovalidate + '_text');
        val.isvalid ? $(rtxt).removeClass("error") : $(rtxt).addClass("error");
    }
}


问:
Should I release persistableUriPermission when a new storage location is chosen
I let my user select the directory, where to store the file output of my app, using the ACTION_OPEN_DOCUMENT_TREE Intent.
When the user has selected a directory, I am persisting the uri permissions
(contentResolver.takePersistableUriPermission), so I can use this directory without further bothering the user.

The user is later on allowed to change that directory, so that the location, where my app is storing the files changes.
Should I release the uri permissions for the previously used directory?
What are the consequences of not caring about that?

答:
What are the consequences of not caring about that?

There is a limit of how many persistable permissions your app can hold. For a long time, it was 128. Android 11 raised it to 512, and it seems to be 512 for Android 12 as well.

Should I release the uri permissions for the previously used directory?

Ideally, yes, just so you do not wind up with a "leak" of those grants and cause yourself problems in the future.


问:
Laravel boolean validation based on others column
I want to validate the is_default column based on domain_id. The condition is for every domain_id there can be only one(single) 1; others multiple will be 0 (zero).

I try to make a rule in Laravel that's like the following. But It's not working; I know it's wrong. So what would be the best query?

```<code>$query = Restaurant::where($attribute, $value)
    ->where('domain_user.domain_id', request()->get('domain_id'));
</code>```

答:
Here is something you might want:

```<code>function updateDefault($domain_id, $name) {
    //updating default domain with given name
    Restoraunt::where('domain_id',$domain_id)->where('name', $name)->first()->update(['is_default' => 1]);

    //setting all other models with same domain_id to 0
    Restoraunt::where('domain_id', $domain_id)->where('name', '!=', $name)->update(['is_default' => 0]);

}
</code>```

If you for example use updateDefault(1, 'ABC - 2') results would be :

Body:
I want to validate the is_default column based on domain_id. The condition is for every domain_id there can be only one(single) 1; others multiple will be 0 (zero).

I try to make a rule in Laravel that's like the following. But It's not working; I know it's wrong. So what would be the best query?

$query = Restaurant::where($attribute, $value)
    ->where('domain_user.domain_id', request()->get('domain_id'));

Body:
Here is something you might want:

function updateDefault($domain_id, $name) {
    //updating default domain with given name
    Restoraunt::where('domain_id',$domain_id)->where('name', $name)->first()->update(['is_default' => 1]);

    //setting all other models with same domain_id to 0
    Restoraunt::where('domain_id', $domain_id)->where('name', '!=', $name)->update(['is_default' => 0]);

}

If you for example use updateDefault(1, 'ABC - 2') results would be :


问:
How can I obtain 2D slices from a 3D NIfti volume?
I'm currently using the following code to convert DCM slices into NIfti images:

```<code>import dicom2nifti
import os

dicom2nifti.convert_directory("input_path", "output_path", compression=True, reorient=True)
</code>```

This code will generate a 3D NIfti volume.

How can I obtain all the slices from this 3D NIfti volume?

答:
Use the package nibabel. A simple working example opens your NIfTI file as a numpy 3D matrix, which can use for your processing needs:

```<code>import nibabel as nib
import numpy as np
import matplotlib.plot as plt

my_nifti = nib.load('YOURNIFTIFILE.nii').get_fdata()

# get the shape of your NIfTI
my_nifti.shape

# access it as 3D numpy array
nifti_slice = my_nifti[:,:,59]

# display the slice
plt.imshow(nifti_slice)
plt.show()
</code>```

Body:
I'm currently using the following code to convert DCM slices into NIfti images:

import dicom2nifti
import os

dicom2nifti.convert_directory("input_path", "output_path", compression=True, reorient=True)

This code will generate a 3D NIfti volume.

How can I obtain all the slices from this 3D NIfti volume?

Body:
Use the package nibabel. A simple working example opens your NIfTI file as a numpy 3D matrix, which can use for your processing needs:

import nibabel as nib
import numpy as np
import matplotlib.plot as plt

my_nifti = nib.load('YOURNIFTIFILE.nii').get_fdata()

# get the shape of your NIfTI
my_nifti.shape

# access it as 3D numpy array
nifti_slice = my_nifti[:,:,59]

# display the slice
plt.imshow(nifti_slice)
plt.show()


问:
How can I stop isNaN from returning an error for a blank field?
EDIT:

Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,

When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?

I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!

答:
You should try writing a checkNumber function that takes the entered value as its argument (rather than referring directly to each field inside the function). Something like this:

```<code>var checkNumber = function (testval) {
  if ( isNaN(testval) ) {
    alert('Bad!');
    // clean up field? highlight in red? etc.
  } else {
    // call your calculation function
  }
}
</code>```

Then bind that function to the keyup event of each form field. There are a number of ways to do this. Look into addEventListener(), or the binding features of a framework like jQuery (.delegate() or .keyup(), e.g.).

Note that if you do bind the function to the event, you won't have to explicitly pass in the value argument. You should be able to work with a field's value within the function via this.value. So you'd have something like this:

```<code>var checkNumber = function () {
  if ( isNaN( this.value ) ) {
    alert('Bad!');
    // clean up field? highlight in red? etc.
  } else {
    // call your calculation function
  }
}
</code>```

And then (with a naive binding approach by ID):

```<code>document.getElementById('id_of_a_field').addEventListener('keyup', checkNumber, true);
</code>```

Body:
You should try writing a checkNumber function that takes the entered value as its argument (rather than referring directly to each field inside the function). Something like this:

var checkNumber = function (testval) {
  if ( isNaN(testval) ) {
    alert('Bad!');
    // clean up field? highlight in red? etc.
  } else {
    // call your calculation function
  }
}

Then bind that function to the keyup event of each form field. There are a number of ways to do this. Look into addEventListener(), or the binding features of a framework like jQuery (.delegate() or .keyup(), e.g.).

Note that if you do bind the function to the event, you won't have to explicitly pass in the value argument. You should be able to work with a field's value within the function via this.value. So you'd have something like this:

var checkNumber = function () {
  if ( isNaN( this.value ) ) {
    alert('Bad!');
    // clean up field? highlight in red? etc.
  } else {
    // call your calculation function
  }
}

And then (with a naive binding approach by ID):

document.getElementById('id_of_a_field').addEventListener('keyup', checkNumber, true);


问:
How do you output text to an Editor (for prining) in PySimpleGUI?
I have written a program using Tkinter and then, the same program using PySimpleGUI. When I run a report in the Tk program in outputs the data to the console and also opens an editor and lists the formatted data so that it can be printed. The PySimpleGUI program also outputs the data to the console and opens the editor but does not populate it. Can anyone see what the 'problem/solution' may be? I have only shown the code related to the report writer for brevity. I suspect that the problem lies in the last approximately 6 lines.

Secondly, if I use a popup_get_date() it produces a date in the wrong format (I want 'yyyy-MM-dd'. Is there a way to tell the popup to produce the date in the correct format? For example I want the following to happen: window['ELEMENT].update(sg.popup_get_date()) to put a formatted date into the Element.

import PySimpleGUI as sg
import tkinter as tk
from tkinter import ttk
from tkcalendar import Calendar, DateEntry
import sqlite3
import datetime as dt
import time
from prettytable import PrettyTable
import subprocess, sys
from tkinter.filedialog import askopenfilename

def income_by_cat_report():

    income_by_cat_layout=[

        [sg.Push(),sg.T('Income by category and date',font=40, text_color='blue'),sg.Push()],
        [sg.T('Select the category'),sg.Combo(I_Analyse_data,size=(15,1),key='-INCAT-',enable_events=True,tooltip='Please select a category from the dropdown box')],
        [sg.T('Select a Start date:'),sg.CalendarButton('Calendar',  target='-STARTDT-', key='_STDATE_',format='%Y-%m-%d'),sg.In(key='-STARTDT-',size=10)],
        [sg.T('Select an End date:'),sg.CalendarButton('Calendar',  target='-ENDDT-', key='_ENDATE_',format='%Y-%m-%d'),sg.In(key='-ENDDT-',size=10)],
        [sg.Button('Quit',size=8,button_color='red'),sg.Push(),sg.Button('Run',size=8,button_color='green',key='-RUN-')]

    ]

    income_by_cat_report=sg.Window('Income by category Report',income_by_cat_layout,modal=True)

    while True:

        event,values=income_by_cat_report.read()
        if event in (None, 'Quit'):
            break
        elif event == '-RUN-':

            import subprocess
            total = 0
            proc=subprocess.Popen(['/usr/bin/idle-python3.9',"FSCashBook.txt"])

            c_Category=values['-INCAT-']
            s_Date=values['-STARTDT-']
            e_Date=values['-ENDDT-']

            print('The category selected is ' + c_Category)
            print('The start date is: ' + s_Date)
            print('The end date is: ' + e_Date)

            Sql=("SELECT tDate as Report_Date, tAnalysis as Category,tDesc as Description,Details as Details, printf('%,.2f',fAmnt) as Spend FROM FSCashBook WHERE tAnalysis = ?" +
                "AND tDate >= ?  AND tDate <= ? order by ID Asc ")

            Sql1=("SELECT tAnalysis, SUM(fAmnt) as TotalSpend FROM FSCashBook WHERE tAnalysis = ?"
                      "AND tDate >= ?  AND tDate <= ? order  by Id Desc LIMIT 1")

            conn = sqlite3.connect(r'/home/bushbug/Databases/FSCashBook')
            curs = conn.cursor()
            curs1=conn.cursor()
            curs2=conn.cursor()

            curs.execute(Sql,(c_Category,s_Date,e_Date))
            curs1.execute(Sql1,(c_Category,s_Date,e_Date))
            col_names = [cn[0] for cn in curs.description]
            rows = curs.fetchall()

            try:

                print(rows[0])

            except IndexError:

                sg.popup('No data to process!','There is no data to retrieve for the report. Please check your dates!')

                break

            """Category below is the analysis group eg. Surgery, Toenail, Ffingernails etc"""

            x = PrettyTable(col_names,left_padding_width=0)
            x.title='Data for ' +c_Category+', date range from '+s_Date +' to '+e_Date
            #x.set_style=(MSWORD_FRIENDLY)
            x._max_width = {"Date":10, "Category":15, "Description":15, "Procedure":20,"Fee Income" :10}
            x.field_names=["Date","Category ","Patient","Procdure","Income Amount"]
            # x.align = "r"
            # x.align[col_names[0]] = "l"
            x.align['Date'] = 'l'
            x.align['Category']='l'
            x.align['Description']='l'
            x.align['Details']='l'
            x.align['Spend Amount']='r'

            x.padding_width = 1

            for row in rows:

                x.add_row(row)

            result=curs1.execute(Sql1,(c_Category,s_Date,e_Date))

            for row in result:

                TotalSpend=float(row[1])

                x.add_row(["","","","",""])
                x.add_row(["==========","=======","=========","==========","=========="])

                x.add_row(["TOTALS","","", "",str(round(float(TotalSpend),2))])

            tabstring = x.get_string()

            output=open("IncomeReports.txt","w")
            output.write(tabstring)
            print(tabstring)
            output.close()
            conn.close()

    income_by_cat_report.close()
```

答:
Why not print directly?

In one of my programs that has to work both on POSIX systems and ms-windows, I have the following:

```<code>if __name__ == "__main__":
    # Platform specific set-up
    if os.name == "nt":
        from win32api import ShellExecute

        home = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"]

        def _printfile(fn):
            """Print the given file using the default printer."""
            rv = ShellExecute(0, "print", fn, None, home, 0)
            if 0 < rv <= 32:
                messagebox.showerror("Printing failed", f"Error code: {rv}")

    elif os.name == "posix":
        from subprocess import run

        def _printfile(fn):
            """Print the given file using “lpr”."""
            cp = run(["lpr", fn])
            if cp.returncode != 0:
                messagebox.showerror("Printing failed", f"Error code: {cp.returncode}")

    else:

        def _printfile(fn):
            """Report that printing is not supported."""
            messagebox.showinfo("Printing", "Printing is not supported on this OS.")
</code>```

So now _printfile is specific to the operating system it is running on. It can be used to print the content that has been written to a (temporary) file.

Body:
Why not print directly?

In one of my programs that has to work both on POSIX systems and ms-windows, I have the following:

if __name__ == "__main__":
    # Platform specific set-up
    if os.name == "nt":
        from win32api import ShellExecute

        home = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"]

        def _printfile(fn):
            """Print the given file using the default printer."""
            rv = ShellExecute(0, "print", fn, None, home, 0)
            if 0 < rv <= 32:
                messagebox.showerror("Printing failed", f"Error code: {rv}")

    elif os.name == "posix":
        from subprocess import run

        def _printfile(fn):
            """Print the given file using “lpr”."""
            cp = run(["lpr", fn])
            if cp.returncode != 0:
                messagebox.showerror("Printing failed", f"Error code: {cp.returncode}")

    else:

        def _printfile(fn):
            """Report that printing is not supported."""
            messagebox.showinfo("Printing", "Printing is not supported on this OS.")

So now _printfile is specific to the operating system it is running on. It can be used to print the content that has been written to a (temporary) file.


问:
flutter build ios --release fatal error: module 'add_2_calendar' not found
I want to make a release for my project who work perefctly in dev mode.

When I make only  flutter ios build it works fine

but flutter build ios --release doesn't work

the error message

```<code>youssefdahar@MacBook-Pro-van-Youssef devs % flutter build ios --release
Building com.example.mental for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: X6BX32XBYP
Running pod install...                                           1 022ms
Running Xcode build...
 └─Compiling, linking and signing...                      1 163ms
Xcode build done.                                           47,6s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    Writing result bundle at path:
        /var/folders/n7/4j0kgb856bl9z75hy71rfmj80000gn/T/flutter_tools.TVo200/flutter_ios_build_temp_dirNtfcgE/temporary_xcresult_bundle

    /Users/youssefdahar/devs/ios/Runner/GeneratedPluginRegistrant.m:12:9: fatal error: module 'add_2_calendar' not found
    @import add_2_calendar;
     ~~~~~~~^~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Planning
    note: Build preparation complete
    note: Building targets in dependency order

    Result bundle written to path:
        /var/folders/n7/4j0kgb856bl9z75hy71rfmj80000gn/T/flutter_tools.TVo200/flutter_ios_build_temp_dirNtfcgE/temporary_xcresult_bundle

It appears that your application still contains the default signing identifier.
Try replacing 'com.example' with your signing id in Xcode:
  open ios/Runner.xcworkspace
Encountered error while building for device.
</code>```

I saw in the in the internet that i have to clean project and pod folder and file and reinstall, i tried many times but in vain

thanks in advance for your help

答:
Finally I figured out that pod init and install doesn't work correctly because the file podfile generate by pod init is not the same as podfile generated by flutter run.

The solution is I deleted all pod file and folder and lock and ran flutter run once

Body:
I want to make a release for my project who work perefctly in dev mode.

When I make only  flutter ios build it works fine

but flutter build ios --release doesn't work

the error message

youssefdahar@MacBook-Pro-van-Youssef devs % flutter build ios --release
Building com.example.mental for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: X6BX32XBYP
Running pod install...                                           1 022ms
Running Xcode build...
 └─Compiling, linking and signing...                      1 163ms
Xcode build done.                                           47,6s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    Writing result bundle at path:
        /var/folders/n7/4j0kgb856bl9z75hy71rfmj80000gn/T/flutter_tools.TVo200/flutter_ios_build_temp_dirNtfcgE/temporary_xcresult_bundle

    /Users/youssefdahar/devs/ios/Runner/GeneratedPluginRegistrant.m:12:9: fatal error: module 'add_2_calendar' not found
    @import add_2_calendar;
     ~~~~~~~^~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Planning
    note: Build preparation complete
    note: Building targets in dependency order

    Result bundle written to path:
        /var/folders/n7/4j0kgb856bl9z75hy71rfmj80000gn/T/flutter_tools.TVo200/flutter_ios_build_temp_dirNtfcgE/temporary_xcresult_bundle

It appears that your application still contains the default signing identifier.
Try replacing 'com.example' with your signing id in Xcode:
  open ios/Runner.xcworkspace
Encountered error while building for device.

I saw in the in the internet that i have to clean project and pod folder and file and reinstall, i tried many times but in vain

thanks in advance for your help


答:
```<code>for i in df:
    if i.index in [742, 1731, 1799]:
        # print(i.value)
        # print(i["value"])
</code>```

Title: How to print values in dataframes column by their indexes?


问:
jooq query nested object
with jOOQ's amazing Multiset Operator we are able to query and map nested lists into pojo objects. Now I try to find a way to also map a single nested object. So for example, I have a composed custom pojo class like:

```<code>public class CourseComposite {
  private String courseName;
  private Teacher teacher;
  private List<Student> students;
  ...
}
</code>```

and I want to query and fetch it in one single step. So my current working solution is:

```<code>static final List<? extends Field<?>> TEACHER_SUB_COLUMNS = Arrays.stream(TEACHER.fields()).map(f -> f.as("teacher." + f.getName())).collect(toList());

List<CourseComposite> getCourses() {
  return this.ctx()
      .select(COURSE.NAME.as("courseName"))
      .select(TEACHER_SUB_COLUMNS)
      .select(multiset(selectFrom(STUDENT).where(STUDENT.ID_COURSE.eq(COURSE.ID))).as("students"))
      .from(COURSE).innerJoin(TEACHER).on(COURSE.ID.eq(TEACHER.ID_COURSE))
      .where(...)
      .fetchInto(CourseComposite.class);
}

</code>```

That includes a preinitialised Field list TEACHER_SUB_COLUMNS with the purpose, to somehow tell JOOQ to map the Teacher object from "teacher.*" columns.

I am now wondering if there is a slightly more intuitive solution in this regard. I have tried to work with the row operator, but got no working solution so far.

e.g.

```<code>List<CourseComposite> getCourses() {
  return this.ctx()
      .select(COURSE.NAME.as("courseName"))
      .select(TEACHER_SUB_COLUMNS)
      .select(row(TEACHER.fields()).as("teacher"))
      .select(multiset(selectFrom(STUDENT).where(STUDENT.ID_COURSE.eq(COURSE.ID))).as("students"))
      .from(COURSE).innerJoin(TEACHER).on(COURSE.ID.eq(TEACHER.ID_COURSE))
      .where(...)
      .fetchInto(CourseComposite.class);
}
</code>```

Maybe someone has a tip? :)

答:
You're probably looking for feature request #4727, where Table<R> would extend SelectField<R> to allow for conveniently using Table expressions directly. With that in place, you could write things like:

Result<Record3<String, TeacherRecord, Result<StudentRecord>>> result =
ctx().select(COURSE.NAME, TEACHER, multiset(...))
     .from(...)
     .fetch();
```

As of jOOQ 3.16, there's no such convenience yet (though this is being worked on).

Title: jooq query nested object

Body:
with jOOQ's amazing Multiset Operator we are able to query and map nested lists into pojo objects. Now I try to find a way to also map a single nested object. So for example, I have a composed custom pojo class like:

public class CourseComposite {
  private String courseName;
  private Teacher teacher;
  private List<Student> students;
  ...
}

and I want to query and fetch it in one single step. So my current working solution is:

static final List<? extends Field<?>> TEACHER_SUB_COLUMNS = Arrays.stream(TEACHER.fields()).map(f -> f.as("teacher." + f.getName())).collect(toList());

List<CourseComposite> getCourses() {
  return this.ctx()
      .select(COURSE.NAME.as("courseName"))
      .select(TEACHER_SUB_COLUMNS)
      .select(multiset(selectFrom(STUDENT).where(STUDENT.ID_COURSE.eq(COURSE.ID))).as("students"))
      .from(COURSE).innerJoin(TEACHER).on(COURSE.ID.eq(TEACHER.ID_COURSE))
      .where(...)
      .fetchInto(CourseComposite.class);
}

That includes a preinitialised Field list TEACHER_SUB_COLUMNS with the purpose, to somehow tell JOOQ to map the Teacher object from "teacher.*" columns.

I am now wondering if there is a slightly more intuitive solution in this regard. I have tried to work with the row operator, but got no working solution so far.

e.g.

List<CourseComposite> getCourses() {
  return this.ctx()
      .select(COURSE.NAME.as("courseName"))
      .select(TEACHER_SUB_COLUMNS)
      .select(row(TEACHER.fields()).as("teacher"))
      .select(multiset(selectFrom(STUDENT).where(STUDENT.ID_COURSE.eq(COURSE.ID))).as("students"))
      .from(COURSE).innerJoin(TEACHER).on(COURSE.ID.eq(TEACHER.ID_COURSE))
      .where(...)
      .fetchInto(CourseComposite.class);
}

Maybe someone has a tip? :)

Body:
You're probably looking for feature request #4727, where Table<R> would extend SelectField<R> to allow for conveniently using Table expressions directly. With that in place, you could write things like:

Result<Record3<String, TeacherRecord, Result<StudentRecord>>> result =
ctx().select(COURSE.NAME, TEACHER, multiset(...))
     .from(...)
     .fetch();

As of jOOQ 3.16, there's no such convenience yet (though this is being worked on).


问:
MySQL REGEXP matching positive numbers
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

```<code>REGEXP '[^-,][0-9]+'
</code>```

but this pulls -886 as 88 matches the regexp

答:
you probably does not require regex

```<code>COL not like '-%' AND COL not like '%,-%'
</code>```

however, this is the bad example of storing into incorrect data type,

split , and store into multiple rows ...and you can save some time for handling something like this question

Title: MySQL REGEXP matching positive numbers

Body:
I have a column varchar[25] with this data inside :

886,-886

-886

0,-1234

1234

(empty)

0

the numbers might change in size from a 1 digit to a n digits.
and I need to be able to pull any row that has at least one positive number in it

I was thinking that something like

REGEXP '[^-,][0-9]+'

but this pulls -886 as 88 matches the regexp

Body:
you probably does not require regex

COL not like '-%' AND COL not like '%,-%'

however, this is the bad example of storing into incorrect data type,

split , and store into multiple rows ...and you can save some time for handling something like this question