问:
Does google drive protect against zip bombs?
Considering that xlsx can be used as a zip bomb and drive api can convert it into a sheet, I am wondering if there are any checks to prevent a conversion in case of a zip bomb? I have tried checking the docs but did not find any relevant information there. I did not find any such info on Stack overflow either.</p>

答:
The answer is no, Google Drive does not protect you from zip bombs.

Today, I verified that Google Drive will upload and store a zip bomb. Google Drive scans files under 100 MB for known viruses. I am not sure how Google classifies a zip bomb for storage and if the scanner will detect the zip bomb in the future. In the short term, the zip bomb is not flagged in Google Drive.

Google Chrome and Firefox detect zip bombs and prevent their download. Microsoft Edge permitted the download of the zip bomb.

Using the Google Drive integration with Windows Explorer (Windows 10 Professional) permitted the download of a zip bomb stored in Google Drive.

Most antivirus software will quarantine zip bombs during file scans and during downloads.

Therefore, you will need to implement additional strategies to protect systems from zip bombs.


来源: stackexchange

问:
Why is this string being overwritten instead of being concatenated?
I'm just writing a little script to create some fake discord names.

To do this, I took a couple of .csv files with adjectives and nouns, imported them into vectors, and concatenated them. Ex:

```<code>vector<string> noun;
vector<string> adj;
infile.open("english-adjectives.txt");

  while(infile.good()){
    getline(infile,x);
    adj.push_back(x);
  }

  infile.close();

  shuffle(begin(adj), end(adj), rng);
</code>```

I did the same thing for nouns, and then tried to concatenate them with a number, but I got a really weird result.

```<code>for (unsigned int i = 0; i < adj.size(); i++){
    string temp;
    temp.append(adj[i]);
    temp.append(noun[i]);
    discord.push_back(temp);
  }

  for (unsigned int i = 0; i < discord.size(); i++){
    cout << discord[i]  << "#0001" << "\n";
  }
</code>```

output:

```<code>#0001icresearch
#0001downstairs
#0001edfiddle
</code>```

When I remove the "#0001" part, it prints just fine.

```<code>honoredfiddle
wanderby
deliciousofficial
</code>```

Any ideas on why this is happening? I checked the newline chars in all my .csv files, and it's formatted for Unix, so I have no idea why this is happening.

答:
Answer from Jerry Jeremiah's comment

Your CSV file was made on Windows and has Windows line endings. But
yhe computer you are running this on uses UNIX style line endings so
each line in the CSV has a \r at the end that is not being removed.
There are multiple ways of removing the \r from the CSV file - or you
could even do it inside this program after reading the data.

Took it into notepad++, edited the newlines to be just LF, and that fixed it.

ContentLicense: CC BY-SA 4.0

Body:
I'm just writing a little script to create some fake discord names.

To do this, I took a couple of .csv files with adjectives and nouns, imported them into vectors, and concatenated them. Ex:

vector<string> noun;
vector<string> adj;
infile.open("english-adjectives.txt");

  while(infile.good()){
    getline(infile,x);
    adj.push_back(x);
  }

  infile.close();

  shuffle(begin(adj), end(adj), rng);

I did the same thing for nouns, and then tried to concatenate them with a number, but I got a really weird result.

for (unsigned int i = 0; i < adj.size(); i++){
    string temp;
    temp.append(adj[i]);
    temp.append(noun[i]);
    discord.push_back(temp);
  }

  for (unsigned int i = 0; i < discord.size(); i++){
    cout << discord[i]  << "#0001" << "\n";
  }

output:

#0001icresearch
#0001downstairs
#0001edfiddle

When I remove the "#0001" part, it prints just fine.

honoredfiddle
wanderby
deliciousofficial

Any ideas on why this is happening? I checked the newline chars in all my .csv files, and it's formatted for Unix, so I have no idea why this is happening.


问:
Apache Beam BigqueryIO.Write getSuccessfulInserts not working
We are creating a simple apache beam pipeline which inserts data into a bigquery table and We are trying to get the tableRows which have been successfully Inserted into the table and tableRows which are errored, the code is as shown in the screenshot

According to the following documentation:
https://beam.apache.org/releases/javadoc/2.33.0/org/apache/beam/sdk/io/gcp/bigquery/WriteResult.html
BigQueryIO.writeTableRows() returns a WriteResult object which has getSuccessfulInserts() which will return a PCollection<TableRow> which contains the TableRows that have been successfully inserted and getFailedInserts() will return another PCollection<TableRow> which contains the TableRows that have been failed.

But when we are testing the pipeline getFailedInserts() seems to be working, it is getting the TableRows which are failed, but getSuccessfulInserts() is always getting an empty PCollection we have tried everything but it doesn't seem to work. Are we missing something here?

Thanks in Advance.

答: This is a bug introduced in the Apache Beam 2.36.0 release following some refactoring. The fix is in https://github.com/apache/beam/pull/16768 and will be in the 2.37.0 release.</p>


问:
ESlint rules conflict
I'm doing es lint for my project, below is part of the .eslintrc.json

```<code>{
    "extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "plugins": [
        "@typescript-eslint"
    ],
    "rules": {
        "@typescript-eslint/explicit-function-return-type": ["error"]
    }
}
</code>```

When the lint runs, it captures a warning: ESLint: missing return type on function.(@typescript-eslint/explicit-module-boundary-types): line number

I guess it's because the typescript-eslint/explicit-module-boundary-types is inherited from the extends and used before my typescript-eslint/explicit-function-return-type so it's showing up as a warning instead of an error.

The documentation https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md says

If you wish to make sure all functions have explicit return types, as opposed to only t
he module boundaries, you can use explicit-function-return-type

is there any way to use explicit-function-return-type first, for all functions no matter exported functions or not? I don't want to disable the explicit-module-boundary-types because it also checks parameter type.

答:
run npm run lint in terminal yields correct result. Reports both warning by explicit-module-boundary-types and error by explicit-function-return-type for same function.

In WebStorm problems panel I could only saw a warning by explicit-module-boundary-types

Title: ESlint rules conflict

Body:
I'm doing es lint for my project, below is part of the .eslintrc.json

{
    "extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "plugins": [
        "@typescript-eslint"
    ],
    "rules": {
        "@typescript-eslint/explicit-function-return-type": ["error"]
    }
}

When the lint runs, it captures a warning: ESLint: missing return type on function.(@typescript-eslint/explicit-module-boundary-types): line number

I guess it's because the typescript-eslint/explicit-module-boundary-types is inherited from the extends and used before my typescript-eslint/explicit-function-return-type so it's showing up as a warning instead of an error.

The documentation https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md says

If you wish to make sure all functions have explicit return types, as opposed to only t
he module boundaries, you can use explicit-function-return-type

is there any way to use explicit-function-return-type first, for all functions no matter exported functions or not? I don't want to disable the explicit-module-boundary-types because it also checks parameter type.


问:
What causes 'The provided key element does not match the schema' error?
Thanks a lot.

I'm using glue for migrating one dynamodb table to another table in the same region.
However I've got this error.

An error occurred while calling o97.pyWriteDynamicFrame. The provided
key element does not match the schema (Service: AmazonDynamoDBv2;
Status Code: 400; Error Code: ValidationException; Request ID:
O7T8OP9M14IGOQFL9HOJP; Proxy: null)

The source dynamodb table items are simply like this.

```<code>{
  "Item": {
    "memNo": {
      "S": "b"
    }
  }
}
{
  "Item": {
    "memNo": {
      "S": "a"
    }
  }
}
{
  "Item": {
    "memNo": {
      "S": "cde"
    }
  }
}
</code>```

And both source and target table have just one partition key.

```<code>memNo (String)
</code>```

and I turned on PITR option for source table, and exported to S3 bucket.
so the source data is now .gz file.

And this is the Glue code

```<code>import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

args = getResolvedOptions(sys.argv, ["JOB_NAME"])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args["JOB_NAME"], args)

# Script generated for node Data Catalog table
DataCatalogtable_node1 = glueContext.create_dynamic_frame.from_catalog(
    database="dynamotest",
    table_name="w5dllnzmzq7kdhj5oo4epg476a_json_gz",
    transformation_ctx="DataCatalogtable_node1",
)

# Script generated for node Apply Mapping
ApplyMapping_node1644253291017 = ApplyMapping.apply(
    frame=DataCatalogtable_node1,
    mappings=[("item.memNo.S", "string", "memNo", "string")],
    transformation_ctx="ApplyMapping_node1644253291017",
)

glueContext.write_dynamic_frame_from_options(
    frame=DataCatalogtable_node1,
    connection_type="dynamodb",
    connection_options={
        "dynamodb.output.tableName": "TargetTable"
    }
)

job.commit()
</code>```

Whenever I try, Glue job says 'The provided key element does not match the schema' error.

How do I fix it?

答:
I've found that mapping function is not attached to writing function.

```<code>glueContext.write_dynamic_frame_from_options(
    frame=DataCatalogtable_node1,
</code>```

above block should be below

```<code>glueContext.write_dynamic_frame_from_options(
    frame= ApplyMapping_node1644253291017,
</code>```

Body:
Thanks a lot.

I'm using glue for migrating one dynamodb table to another table in the same region.
However I've got this error.

An error occurred while calling o97.pyWriteDynamicFrame. The provided
key element does not match the schema (Service: AmazonDynamoDBv2;
Status Code: 400; Error Code: ValidationException; Request ID:
O7T8OP9M14IGOQFL9HOJP; Proxy: null)

The source dynamodb table items are simply like this.

{
  "Item": {
    "memNo": {
      "S": "b"
    }
  }
}
{
  "Item": {
    "memNo": {
      "S": "a"
    }
  }
}
{
  "Item": {
    "memNo": {
      "S": "cde"
    }
  }
}

And both source and target table have just one partition key.

memNo (String)

and I turned on PITR option for source table, and exported to S3 bucket.
so the source data is now .gz file.

And this is the Glue code

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

args = getResolvedOptions(sys.argv, ["JOB_NAME"])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args["JOB_NAME"], args)

# Script generated for node Data Catalog table
DataCatalogtable_node1 = glueContext.create_dynamic_frame.from_catalog(
    database="dynamotest",
    table_name="w5dllnzmzq7kdhj5oo4epg476a_json_gz",
    transformation_ctx="DataCatalogtable_node1",
)

# Script generated for node Apply Mapping
ApplyMapping_node1644253291017 = ApplyMapping.apply(
    frame=DataCatalogtable_node1,
    mappings=[("item.memNo.S", "string", "memNo", "string")],
    transformation_ctx="ApplyMapping_node1644253291017",
)

glueContext.write_dynamic_frame_from_options(
    frame=DataCatalogtable_node1,
    connection_type="dynamodb",
    connection_options={
        "dynamodb.output.tableName": "TargetTable"
    }
)

job.commit()

Whenever I try, Glue job says 'The provided key element does not match the schema' error.

How do I fix it?

Body:
I've found that mapping function is not attached to writing function.

glueContext.write_dynamic_frame_from_options(
    frame=DataCatalogtable_node1,

above block should be below

glueContext.write_dynamic_frame_from_options(
    frame= ApplyMapping_node1644253291017,


问:
How do I change the font style of text displayed on hover with CSS?
I feel like this should be an easy one but nothing I'm doing seems to be working. I may be targeting the element wrong or may be inputting the wrong CSS - I'm fairly new to the coding side of things so any help would be appreciated.

This is for a Wordpress site (page in question is here)

For the CSS component I have tried the following

```<code>.project.small.effect-1 .details.has-skills .text {
font-family: 'Oswald'}
</code>```

and

```<code>.project.small .title {
font-family: 'Oswald'}
</code>```

I've also tried adding !important to override any stylings set by the WP theme but that doesn't seem to be doing the trick either.

Is there something that I'm overlooking here?

答:
Just use CSS:hover Selector. See the snippet below:

p{
  font-family: Arial;
}

p:hover{
  font-family: Courier;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>The text that will be modified.</p></code>```

More on :hover selector here.

Body:
I feel like this should be an easy one but nothing I'm doing seems to be working. I may be targeting the element wrong or may be inputting the wrong CSS - I'm fairly new to the coding side of things so any help would be appreciated.

This is for a Wordpress site (page in question is here)

For the CSS component I have tried the following

.project.small.effect-1 .details.has-skills .text {
font-family: 'Oswald'}

and

.project.small .title {
font-family: 'Oswald'}

I've also tried adding !important to override any stylings set by the WP theme but that doesn't seem to be doing the trick either.

Is there something that I'm overlooking here?

Body:
Just use CSS:hover Selector. See the snippet below:

p{
  font-family: Arial;
}

p:hover{
  font-family: Courier;
}

<p>The text that will be modified.</p>

More on :hover selector here.


问:
How can I remove/delete a HTML element using JavaScript?
I'm creating a warning paragraph that shows an error if the email is incorrect, is empty, or if it was sent. And what happens is that after showing the first warning, I want to cancel the creation of another one, so that doesn't pile up.

The current option I'm trying is to remove the warning if it already exists, otherwise, it can be created. But I don't know why it's not happening.

JS:

const input = document.querySelector('#emailInput');
const form = document.querySelector('#myForm')
const button = document.querySelector('#notify')
const validRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

form.addEventListener('submit', function (e){
    e.preventDefault()
});

button.addEventListener('click', validateEmail)

function validateEmail(){
    let inputValue = input.value;
    if(inputValue.match(validRegex)){
        createWarning('Email sent!')
    }
    else if(inputValue == ''){
        createWarning('Please provide an email!');
    }
    else{
        createWarning('Please provid a valid email address')
    }
}

function createWarning(message){
    let warning = document.createElement('p');
    if (document.getElementById(warning) == null){
        warning.innerHTML = message;
        warning.classList.add('warning');
        warning.setAttribute('id','warning');
        input.insertAdjacentElement('afterend',warning);
    }

    else{
        const error = getElementById(warning)
        error.remove()
    }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;600;700&display=swap');

*{
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

body{
    background-color: whitesmoke;
    font-size: 20px;
    font-family: 'Libre Franklin', sans-serif;
    display: flex;
    flex-direction: column;
    align-content: space-between;
    height: 100vh;
}

.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    height: 100%;
}

.title{
    display: flex;
    align-items: center;
    justify-content: center;
}

.company-name{
    font-family: 'Libre Franklin', sans-serif;
    font-weight: 700;
    font-size: 20px;
}

.dot{
    color: hsl(223, 87%, 63%);
}

.intro{
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: space-between;
    gap: 15px;
    justify-content: space-between;
}

.subtitle h2{
    font-weight: 600;
    font-size: 20px;
}

.launching{
    color: rgba(190, 160, 83, 0.602);
    font-weight: 200;
}

.paragraph p{
    font-weight: 300;
    font-size: 14px;
    color: rgb(41, 37, 0);
}

form{
    display: flex;
    align-items: center;
    align-content: space-between;
    flex-direction: column;
}

#emailInput{
    border-radius: 50px;
    border: 1px solid hsl(223, 100%, 88%);
    width: 100%;
    padding: 10px 35px;
    font-family: 'Libre Franklin', sans-serif;
}

.warning{
    color: hsl(354, 100%, 66%);
    font-size: small;
    font-family: 'Libre Franklin', sans-serif;
    margin: 5px;
}

#emailInput:focus{
    outline: none;
}

#notify{
    background-color: hsl(223, 87%, 63%);
    color: whitesmoke;
    border-radius: 50px;
    padding: 10px 20px;
    width: 100%;
    border: 1px solid rgba(88, 78, 78, 0);
    font-weight: bold;
    margin-top: 15px;
}

.social-media{
    width: 200px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-content: space-between;
    justify-items: center;
}

.around{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border: 1px solid hsla(0, 0%, 59%, 0.192);
    border-radius: 50%;
    width: 30px;
    height: 30px;
}
.fab{
    color: hsl(223, 87%, 63%);
    font-size: medium;
}

.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">

  <title>Frontend Mentor | Ping coming soon page</title>

PING.

We are launching soon!

Subscribe and get notified

        <form id="myForm" name="myForm">
          <input type="email" id="emailInput" name="emailInput" placeholder="Your email address...">
          <button type="submit" id="notify">Notify Me</button>
        </form>

      Challenge by Frontend Mentor.
      Coded by Henrique Bortolim.

```

答:
Call getElementById from document and use the string-based ID for 'warning' instead of the reference to the element as your argument to document.getElementById()  Corrected code is below:

const input = document.querySelector('#emailInput');
const form = document.querySelector('#myForm')
const button = document.querySelector('#notify')
const validRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

form.addEventListener('submit', function (e){
    e.preventDefault()
});

button.addEventListener('click', validateEmail)

function validateEmail(){
    let inputValue = input.value;
    if(inputValue.match(validRegex)){
        createWarning('Email sent!')
    }
    else if(inputValue == ''){
        createWarning('Please provide an email!');
    }
    else{
        createWarning('Please provid a valid email address')
    }
}

function createWarning(message){
    let warning = document.createElement('p');
    let warningId = 'warning';
    if (document.getElementById(warningId) == null) {
        warning.innerHTML = message;
        warning.classList.add('warning');
        warning.setAttribute('id', warningId);
        input.insertAdjacentElement('afterend',warning);
    }
    else {
        const error = document.getElementById(warningId)
        error.remove()
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;600;700&display=swap');

*{
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

body{
    background-color: whitesmoke;
    font-size: 20px;
    font-family: 'Libre Franklin', sans-serif;
    display: flex;
    flex-direction: column;
    align-content: space-between;
    height: 100vh;
}

.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    height: 100%;
}

.title{
    display: flex;
    align-items: center;
    justify-content: center;
}

.company-name{
    font-family: 'Libre Franklin', sans-serif;
    font-weight: 700;
    font-size: 20px;
}

.dot{
    color: hsl(223, 87%, 63%);
}

.intro{
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: space-between;
    gap: 15px;
    justify-content: space-between;
}

.subtitle h2{
    font-weight: 600;
    font-size: 20px;
}

.launching{
    color: rgba(190, 160, 83, 0.602);
    font-weight: 200;
}

.paragraph p{
    font-weight: 300;
    font-size: 14px;
    color: rgb(41, 37, 0);
}

form{
    display: flex;
    align-items: center;
    align-content: space-between;
    flex-direction: column;
}

#emailInput{
    border-radius: 50px;
    border: 1px solid hsl(223, 100%, 88%);
    width: 100%;
    padding: 10px 35px;
    font-family: 'Libre Franklin', sans-serif;
}

.warning{
    color: hsl(354, 100%, 66%);
    font-size: small;
    font-family: 'Libre Franklin', sans-serif;
    margin: 5px;
}

#emailInput:focus{
    outline: none;
}

#notify{
    background-color: hsl(223, 87%, 63%);
    color: whitesmoke;
    border-radius: 50px;
    padding: 10px 20px;
    width: 100%;
    border: 1px solid rgba(88, 78, 78, 0);
    font-weight: bold;
    margin-top: 15px;
}

.social-media{
    width: 200px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-content: space-between;
    justify-items: center;
}

.around{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border: 1px solid hsla(0, 0%, 59%, 0.192);
    border-radius: 50%;
    width: 30px;
    height: 30px;
}
.fab{
    color: hsl(223, 87%, 63%);
    font-size: medium;
}

.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">

  <title>Frontend Mentor | Ping coming soon page</title>

PING.

We are launching soon!

Subscribe and get notified

        <form id="myForm" name="myForm">
          <input type="email" id="emailInput" name="emailInput" placeholder="Your email address...">
          <button type="submit" id="notify">Notify Me</button>
        </form>

      Challenge by Frontend Mentor.
      Coded by Henrique Bortolim.

```

Body:
I'm creating a warning paragraph that shows an error if the email is incorrect, is empty, or if it was sent. And what happens is that after showing the first warning, I want to cancel the creation of another one, so that doesn't pile up.

The current option I'm trying is to remove the warning if it already exists, otherwise, it can be created. But I don't know why it's not happening.

JS:

const input = document.querySelector('#emailInput');
const form = document.querySelector('#myForm')
const button = document.querySelector('#notify')
const validRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

form.addEventListener('submit', function (e){
    e.preventDefault()
});

button.addEventListener('click', validateEmail)

function validateEmail(){
    let inputValue = input.value;
    if(inputValue.match(validRegex)){
        createWarning('Email sent!')
    }
    else if(inputValue == ''){
        createWarning('Please provide an email!');
    }
    else{
        createWarning('Please provid a valid email address')
    }
}

function createWarning(message){
    let warning = document.createElement('p');
    if (document.getElementById(warning) == null){
        warning.innerHTML = message;
        warning.classList.add('warning');
        warning.setAttribute('id','warning');
        input.insertAdjacentElement('afterend',warning);
    }

    else{
        const error = getElementById(warning)
        error.remove()
    }

}

@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;600;700&display=swap');

*{
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

body{
    background-color: whitesmoke;
    font-size: 20px;
    font-family: 'Libre Franklin', sans-serif;
    display: flex;
    flex-direction: column;
    align-content: space-between;
    height: 100vh;
}

.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    height: 100%;
}

.title{
    display: flex;
    align-items: center;
    justify-content: center;
}

.company-name{
    font-family: 'Libre Franklin', sans-serif;
    font-weight: 700;
    font-size: 20px;
}

.dot{
    color: hsl(223, 87%, 63%);
}

.intro{
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: space-between;
    gap: 15px;
    justify-content: space-between;
}

.subtitle h2{
    font-weight: 600;
    font-size: 20px;
}

.launching{
    color: rgba(190, 160, 83, 0.602);
    font-weight: 200;
}

.paragraph p{
    font-weight: 300;
    font-size: 14px;
    color: rgb(41, 37, 0);
}

form{
    display: flex;
    align-items: center;
    align-content: space-between;
    flex-direction: column;
}

#emailInput{
    border-radius: 50px;
    border: 1px solid hsl(223, 100%, 88%);
    width: 100%;
    padding: 10px 35px;
    font-family: 'Libre Franklin', sans-serif;
}

.warning{
    color: hsl(354, 100%, 66%);
    font-size: small;
    font-family: 'Libre Franklin', sans-serif;
    margin: 5px;
}

#emailInput:focus{
    outline: none;
}

#notify{
    background-color: hsl(223, 87%, 63%);
    color: whitesmoke;
    border-radius: 50px;
    padding: 10px 20px;
    width: 100%;
    border: 1px solid rgba(88, 78, 78, 0);
    font-weight: bold;
    margin-top: 15px;
}

.social-media{
    width: 200px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-content: space-between;
    justify-items: center;
}

.around{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border: 1px solid hsla(0, 0%, 59%, 0.192);
    border-radius: 50%;
    width: 30px;
    height: 30px;
}
.fab{
    color: hsl(223, 87%, 63%);
    font-size: medium;
}

.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">

  <title>Frontend Mentor | Ping coming soon page</title>

PING.

We are launching soon!

Subscribe and get notified

        <form id="myForm" name="myForm">
          <input type="email" id="emailInput" name="emailInput" placeholder="Your email address...">
          <button type="submit" id="notify">Notify Me</button>
        </form>

      Challenge by Frontend Mentor.
      Coded by Henrique Bortolim.

Body:
Call getElementById from document and use the string-based ID for 'warning' instead of the reference to the element as your argument to document.getElementById()  Corrected code is below:

const input = document.querySelector('#emailInput');
const form = document.querySelector('#myForm')
const button = document.querySelector('#notify')
const validRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

form.addEventListener('submit', function (e){
    e.preventDefault()
});

button.addEventListener('click', validateEmail)

function validateEmail(){
    let inputValue = input.value;
    if(inputValue.match(validRegex)){
        createWarning('Email sent!')
    }
    else if(inputValue == ''){
        createWarning('Please provide an email!');
    }
    else{
        createWarning('Please provid a valid email address')
    }
}

function createWarning(message){
    let warning = document.createElement('p');
    let warningId = 'warning';
    if (document.getElementById(warningId) == null) {
        warning.innerHTML = message;
        warning.classList.add('warning');
        warning.setAttribute('id', warningId);
        input.insertAdjacentElement('afterend',warning);
    }
    else {
        const error = document.getElementById(warningId)
        error.remove()
    }
}

@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;600;700&display=swap');

*{
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

body{
    background-color: whitesmoke;
    font-size: 20px;
    font-family: 'Libre Franklin', sans-serif;
    display: flex;
    flex-direction: column;
    align-content: space-between;
    height: 100vh;
}

.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    height: 100%;
}

.title{
    display: flex;
    align-items: center;
    justify-content: center;
}

.company-name{
    font-family: 'Libre Franklin', sans-serif;
    font-weight: 700;
    font-size: 20px;
}

.dot{
    color: hsl(223, 87%, 63%);
}

.intro{
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: space-between;
    gap: 15px;
    justify-content: space-between;
}

.subtitle h2{
    font-weight: 600;
    font-size: 20px;
}

.launching{
    color: rgba(190, 160, 83, 0.602);
    font-weight: 200;
}

.paragraph p{
    font-weight: 300;
    font-size: 14px;
    color: rgb(41, 37, 0);
}

form{
    display: flex;
    align-items: center;
    align-content: space-between;
    flex-direction: column;
}

#emailInput{
    border-radius: 50px;
    border: 1px solid hsl(223, 100%, 88%);
    width: 100%;
    padding: 10px 35px;
    font-family: 'Libre Franklin', sans-serif;
}

.warning{
    color: hsl(354, 100%, 66%);
    font-size: small;
    font-family: 'Libre Franklin', sans-serif;
    margin: 5px;
}

#emailInput:focus{
    outline: none;
}

#notify{
    background-color: hsl(223, 87%, 63%);
    color: whitesmoke;
    border-radius: 50px;
    padding: 10px 20px;
    width: 100%;
    border: 1px solid rgba(88, 78, 78, 0);
    font-weight: bold;
    margin-top: 15px;
}

.social-media{
    width: 200px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-content: space-between;
    justify-items: center;
}

.around{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border: 1px solid hsla(0, 0%, 59%, 0.192);
    border-radius: 50%;
    width: 30px;
    height: 30px;
}
.fab{
    color: hsl(223, 87%, 63%);
    font-size: medium;
}

.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">
  <script src="https://kit.fontawesome.com/b5c693247f.js" crossorigin="anonymous"></script>
  <title>Frontend Mentor | Ping coming soon page</title>
</head>
<body>
  <div class="container">
    <div class="title">
      <h1 class="company-name">PING<span class="dot">.</span></h1>
    </div>
    <div class="intro">
      <div class="subtitle"><h2><span class="launching">We are launching</span> soon!</h2></div>
      <div class="paragraph"><p>Subscribe and get notified</p></div>
      <div class="form-container">
        <form id="myForm" name="myForm">
          <input type="email" id="emailInput" name="emailInput" placeholder="Your email address...">
          <button type="submit" id="notify">Notify Me</button>
        </form>
      </div>
    </div>
    <div class="img-container">
      <img src="images/illustration-dashboard.png" alt="Dashboard Image" width="300" height="250">
    </div>
    <div class="social-media">
      <div class="around"><i class="fab fa-facebook-f"></i></div>
      <div class="around"><i class="fab fa-twitter"></i></div>
      <div class="around"><i class="fab fa-instagram"></i></div>
    </div>
  </div>

  <footer>
    <p class="attribution">
      Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>.
      Coded by <a href="https://github.com/HBortolim">Henrique Bortolim</a>.
    </p>
  </footer>
  <script src="app.js"></script>
</body>
</html>


问:
Apache Spark Structured Streaming - not writing to checkpoint location
i have a simple Apache Spark Structured Streaming python code, which reads data from Kafka, and writes the messages to console.

i've setup checkpoint location, however the code is not writing to checkpoint..
any ideas why ?

Here is the code:

```<code>from pyspark.sql import SparkSession, Window

spark = SparkSession.builder.appName('StructuredStreaming_KafkaProducer').getOrCreate()
# os.environ["SPARK_HOME"] = "/Users/karanalang/Documents/Technology/spark-3.2.0-bin-hadoop3.2"
# os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages org.apache.spark:spark-sql-kafka-0-10_2.13:3.2.0'

# kafkaBrokers='localhost:9092'
kafkaBrokers='<host>:<port>'
topic = "my-topic"
# bootstrap.servers=my-cluster-lb-ssl-cert-kafka-bootstrap:9093
security_protocol="SSL"
ssl_truststore_location="/Users/karanalang/Documents/Technology/strimzi/gcp_certs_nov28/ca.p12"
ssl_truststore_password="<pwd_1>"
ssl_keystore_location="/Users/karanalang/Documents/Technology/strimzi/gcp_certs_nov28/user.p12"
ssl_keystore_password="<pwd_2>"
consumerGroupId = "my-group"

spark.sparkContext.setLogLevel("ERROR")

df = spark.read.format('kafka')\
    .option("kafka.bootstrap.servers",kafkaBrokers)\
    .option("kafka.security.protocol","SSL") \
    .option("kafka.ssl.truststore.location",ssl_truststore_location) \
    .option("kafka.ssl.truststore.password",ssl_truststore_password) \
    .option("kafka.ssl.keystore.location", ssl_keystore_location)\
    .option("kafka.ssl.keystore.password", ssl_keystore_password)\
    .option("subscribe", topic) \
    .option("kafka.group.id", consumerGroupId)\
    .option("startingOffsets", "earliest") \
    .load()

query = df.selectExpr("CAST(value AS STRING)") \
    .write \
    .format("console") \
    .option("numRows",100)\
    .option("checkpointLocation", "~/PycharmProjects/Kafka/checkpoint/") \
    .option("outputMode", "complete")\
    .save("output")
</code>```

答:
According to offical doc, this checkpoint location has to be a path in an HDFS compatible file system, and can be set as an option in the DataStreamWriter when starting a query. But in your code, it's local path on driver, so after restart of streaming job, it will be lost.

For details, please refer https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#recovering-from-failures-with-checkpointing

Body:
i have a simple Apache Spark Structured Streaming python code, which reads data from Kafka, and writes the messages to console.

i've setup checkpoint location, however the code is not writing to checkpoint..
any ideas why ?

Here is the code:

from pyspark.sql import SparkSession, Window

spark = SparkSession.builder.appName('StructuredStreaming_KafkaProducer').getOrCreate()
# os.environ["SPARK_HOME"] = "/Users/karanalang/Documents/Technology/spark-3.2.0-bin-hadoop3.2"
# os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages org.apache.spark:spark-sql-kafka-0-10_2.13:3.2.0'

# kafkaBrokers='localhost:9092'
kafkaBrokers='<host>:<port>'
topic = "my-topic"
# bootstrap.servers=my-cluster-lb-ssl-cert-kafka-bootstrap:9093
security_protocol="SSL"
ssl_truststore_location="/Users/karanalang/Documents/Technology/strimzi/gcp_certs_nov28/ca.p12"
ssl_truststore_password="<pwd_1>"
ssl_keystore_location="/Users/karanalang/Documents/Technology/strimzi/gcp_certs_nov28/user.p12"
ssl_keystore_password="<pwd_2>"
consumerGroupId = "my-group"

spark.sparkContext.setLogLevel("ERROR")

df = spark.read.format('kafka')\
    .option("kafka.bootstrap.servers",kafkaBrokers)\
    .option("kafka.security.protocol","SSL") \
    .option("kafka.ssl.truststore.location",ssl_truststore_location) \
    .option("kafka.ssl.truststore.password",ssl_truststore_password) \
    .option("kafka.ssl.keystore.location", ssl_keystore_location)\
    .option("kafka.ssl.keystore.password", ssl_keystore_password)\
    .option("subscribe", topic) \
    .option("kafka.group.id", consumerGroupId)\
    .option("startingOffsets", "earliest") \
    .load()

query = df.selectExpr("CAST(value AS STRING)") \
    .write \
    .format("console") \
    .option("numRows",100)\
    .option("checkpointLocation", "~/PycharmProjects/Kafka/checkpoint/") \
    .option("outputMode", "complete")\
    .save("output")


问:
returning a value from postgresql delete that impacts 0 rows
is it possible to return a value from a delete statement in postgres when no rows were deleted?

Example:

-- Create a table
create table dummy(id int);
```
<pre class="lang-sql prettyprint-override"><code>delete from dummy where id = 999 returning <ANSWER HERE>
-- Desired output = "1"
</code>```

What I've tried:

delete from dummy where id = 999 returning 1
-- returns: null
```

答:
The principle of using RETURNING after a DELETE command is that - RETURNING gets only deleted records. If the RETURNING will get records on the not deleted process, then this is will be an illogical or abnormal situation.

But, you can use a logical process for doing this. For example, using the UNION command we can add one record to the result of RETURNING. So, when records are deleted we are getting deleted records + one record of UNION. When records are not be deleted we get only one record of the UNION command.

Example query for about this process:

```<code>with del_table as
(
    delete from test.test
    where id = 4100
    returning id, title
)
select id, title from del_table
union all
select 100, 'test';

Result:
id      title
----------------
4100    TestData
100     test
</code>```

Body:
is it possible to return a value from a delete statement in postgres when no rows were deleted?

Example:

-- Create a table
create table dummy(id int);

delete from dummy where id = 999 returning <ANSWER HERE>
-- Desired output = "1"

What I've tried:

delete from dummy where id = 999 returning 1
-- returns: null

Body:
The principle of using RETURNING after a DELETE command is that - RETURNING gets only deleted records. If the RETURNING will get records on the not deleted process, then this is will be an illogical or abnormal situation.

But, you can use a logical process for doing this. For example, using the UNION command we can add one record to the result of RETURNING. So, when records are deleted we are getting deleted records + one record of UNION. When records are not be deleted we get only one record of the UNION command.

Example query for about this process:

with del_table as
(
    delete from test.test
    where id = 4100
    returning id, title
)
select id, title from del_table
union all
select 100, 'test';

Result:
id      title
----------------
4100    TestData
100     test


问:
What is the reasoning behind github access tokens?
And are they more secure or less secure than SSH key pairs.

I am using these instead of SSH key pairs, as referenced on github.  And it appears to me that they are just randomized complex passwords.

I authenticate now by putting my username / token in, instead of my username / password.  I don't see how this can provide better security than a password.

I'm not opposed to using them, but they just seem like auto-generated passwords.  It would also appear they are less secure than SSH.

答:
There are a couple reasons for using GitHub access tokens instead of passwords:

Tokens are pseudorandomly generated, so performing a brute-force guessing attack is infeasible.

Tokens have a fixed form, which lets them be recognized by secret-scanning software, which can then alert the user or revoke them.

Tokens can be more narrowly scoped than passwords and therefore they can be expired or revoked easily in case of compromise without worrying about compromising the entire account.

However, they are still a bearer credential: you have to pass them to the remote system just like a password.

SSH keys are more secure because they use asymmetric cryptography.  When the SSH session is created, a one-time shared secret is derived, and your key is only used to sign data derived from that secret.  You never send your keys over the connection, and consequently, as long as you keep your private key safe, even an attack who can compromise the other side cannot compromise your keys.

As VonC noted, tokens are used over HTTPS and SSH keys are used over SSH, so they aren't interchangeable.


问:
digitalocean api : get droplets without tag name
How can I get droplets without having tag-name using cli reference?

```<code>doctl compute droplet list --tag-name "what should be provided here"
</code>```

Tried:

```<code>doctl compute droplet list --tag-name ""

doctl compute droplet list --tag-name ''
</code>```

答:
I think (haven't tried) that you can't test for the absence of a tag.

doctl compute droplet list only accepts a single --tag_name and so I assume (!?) the (server) implementation filters the list of Droplets by those that include the tag value.

What you may (!?) be able to do is to list everything as JSON and then post-filter the results for those with empty ([]) tags.

Body:
How can I get droplets without having tag-name using cli reference?

doctl compute droplet list --tag-name "what should be provided here"

Tried:

doctl compute droplet list --tag-name ""

doctl compute droplet list --tag-name ''


问:
How to use Karate continueOnStepFailure to assert each Json field values
The goal is to do soft assertion on each JSON field.

```<code>    * def KAFKA_TOPIC = "topic1"
    * def kafkaExpected = {field1:"value1",field2:"value2",field3:"value3"}
    * def kafkaActual = {"topic1":[{field1:"value1",field2:"x",field3:"y"}]}

    * configure continueOnStepFailure = { enabled: true, continueAfter: false, keywords: ['match'] }

    * match (kafkaActual[KAFKA_TOPIC]) == ['#(kafkaExpected)'] <-- do we have one-liner like this to do soft assertions on all fields?

    * configure continueOnStepFailure = false

Output:
$[0].field2 | not equal (STRING:STRING)
      'x'
      'value2'
</code>```

Instead of doing it 1 by 1.

```<code>    * match (kafkaActual[KAFKA_TOPIC])[0].field1 == kafkaExpected.field1
    * match (kafkaActual[KAFKA_TOPIC])[0].field2 == kafkaExpected.field2
    * match (kafkaActual[KAFKA_TOPIC])[0].field3 == kafkaExpected.field3

Output:
match failed: EQUALS
  $ | not equal (STRING:STRING)
  'x'
  'value2'
match failed: EQUALS
  $ | not equal (STRING:STRING)
  'y'
  'value3'
</code>```

And whats weird is that on terminal logs it only printed one assertion, either on both approach.

```<code>  $ | not equal (STRING:STRING)
  'y'
  'value3'
</code>```

Trying to use Karate.forEach but seems like not the right path.

答:
Found a solution from this link provided by Peter. I just need to transform the JSON to list of key, value format and use it as data source.

```<code>From:
{field1:"value1",field2:"value2",field3:"value3"}

Transformed To:
[{key:"field1",value:"value1"},{key:"field2",value:"value2"},{key:"field3",value:"value3"}]
</code>```

Function used and usage:

```<code> * def input = INPUT
 * def func =
  """
    function(obj){
      var output = [];
      for (var i in obj) {
        output.push({key: i, value: obj[i]});
      }
      return output
    }
  """

    * json kafkaAttributes = func(input)
    * configure continueOnStepFailure = { enabled: true, continueAfter: false, keywords: ['match'] }
    * karate.call('kafka.feature@validateFieldsAndValues',kafkaAttributes)
    * configure continueOnStepFailure = false

@validateFieldsAndValues
Scenario:
    * match (response[KAFKA_TOPIC][0][key]) contains value
</code>```

Body:
The goal is to do soft assertion on each JSON field.

    * def KAFKA_TOPIC = "topic1"
    * def kafkaExpected = {field1:"value1",field2:"value2",field3:"value3"}
    * def kafkaActual = {"topic1":[{field1:"value1",field2:"x",field3:"y"}]}

    * configure continueOnStepFailure = { enabled: true, continueAfter: false, keywords: ['match'] }

    * match (kafkaActual[KAFKA_TOPIC]) == ['#(kafkaExpected)'] <-- do we have one-liner like this to do soft assertions on all fields?

    * configure continueOnStepFailure = false

Output:
$[0].field2 | not equal (STRING:STRING)
      'x'
      'value2'

Instead of doing it 1 by 1.

    * match (kafkaActual[KAFKA_TOPIC])[0].field1 == kafkaExpected.field1
    * match (kafkaActual[KAFKA_TOPIC])[0].field2 == kafkaExpected.field2
    * match (kafkaActual[KAFKA_TOPIC])[0].field3 == kafkaExpected.field3

Output:
match failed: EQUALS
  $ | not equal (STRING:STRING)
  'x'
  'value2'
match failed: EQUALS
  $ | not equal (STRING:STRING)
  'y'
  'value3'

And whats weird is that on terminal logs it only printed one assertion, either on both approach.

  $ | not equal (STRING:STRING)
  'y'
  'value3'

Trying to use Karate.forEach but seems like not the right path.

Body:
Found a solution from this link provided by Peter. I just need to transform the JSON to list of key, value format and use it as data source.

From:
{field1:"value1",field2:"value2",field3:"value3"}

Transformed To:
[{key:"field1",value:"value1"},{key:"field2",value:"value2"},{key:"field3",value:"value3"}]

Function used and usage:

 * def input = INPUT
 * def func =
  """
    function(obj){
      var output = [];
      for (var i in obj) {
        output.push({key: i, value: obj[i]});
      }
      return output
    }
  """

    * json kafkaAttributes = func(input)
    * configure continueOnStepFailure = { enabled: true, continueAfter: false, keywords: ['match'] }
    * karate.call('kafka.feature@validateFieldsAndValues',kafkaAttributes)
    * configure continueOnStepFailure = false

@validateFieldsAndValues
Scenario:
    * match (response[KAFKA_TOPIC][0][key]) contains value


问:
Psudo-Random Number Prediction
I am building a program using various methods of generating psudo random numbers. With reasonable results. I of course get better results (statistically speaking), if I use either the inbuilt random number generator in visual C#, or some other formal psudo random code where the method is not known to me. This is not my question.

My question is, given any of the methods used, and given the fact that any computer generated random number is done according to a specified formula and code logic, it is not by definition truly random. Hense the term psudo random.

Given that fact, is it possible to accurately predict what the number will be. Or at least predict it more accurately than a good guess. My research says that anything guessed correctly up to 73% of the time is really only good guessing. So in order to be considered accurate prediction, it must be able to show correct "guesses" more than 73% of the time in order to say it is not a guess.

Assume we dont know the seed, or if we do know the seed, then we dont know the formula used to get the result from the seed.

The below was edited after I accepted an answer and is for future people woundering what I meant.

up to 73% is a "good guesser" - the accepted answer says there is no such thing. So I will clarify.

In the context of the documentary that I watched they weighted things as follows (my words not direct quotes of the program):

Below 37% is just plain wrong (or a poor guesser).

37% to 63% is the expected range of a normal persons ability to guess, some poorly some well. On average it comes to around 50%.

Really "good guessers", were able to break the 63% barrier and sometimes by a large amount either because they knew what their counterparts (in the case of twins) might answer and therefore answered likewise, or had some other system (in the case of fortune tellers and the like).

Tests were done to determine these systems and it was found that comming close to the 73% barrier by anyone was almost impossible, and it was simply impossible to do it on a regular basis (i.e. more than once) showing that they got lucky the first time round. So anyone who got more than 63% but less than 73% on a regular basis was simply labeled a "good guesser".

One of the answers below suggest if you flip a coin 4 times and you guess right 3 out of 4 times you get 75%. But to do it 10 or 100 times is much more difficult. In the explanation above, the first case would show you were able to predict the future accurately enough to make a difference. Continuing with the same test under the same conditions, ie another 4 flips, and another 4. Would almost always bring the person well below the 73% mark showing them to be at best a "good guesser".

I only mention this to clarify. Its not actually part of the question. Thank you all for your answers and suggestions.

答:
Based on the conversations in the comments, I think there may be some misconceptions about probability at work here.

You mentioned being able to guess coin flips correctly about 61% over a fairly large (100) number of trials. This suggests your coin flips are probably biased -- not truly 50/50. The fact that you don't do as well when your girlfriend flips the coin also points to this conclusion. If the coin toss is fair, it cannot be influenced by your guess any more than your guess can be influenced by a (future) coin toss. If you guess heads, there is a 50% chance you will be right. Same if you guess tails.

There is no such thing as a "good" guesser, but guesses are sometimes lucky.

You also wrote that a 10% correct-guess rate on a dice roll "equates somehow to well in excess of 51% when the numbers are crunched properly".

You have the right idea here -- it's unreasonable to expect someone to guess a dice roll half the time. In fact, they should guess correctly roughly 1 in 6 times -- about 17%. If someone is able to guess significantly better than 17% over a long series of trials, either they got really lucky (and with a bit of math, you could say exactly how lucky) or the dice are weighted.

So what about this 73% number that's been floating around? Just as you'd expect to predict about 50% of coin tosses or 17% of dice rolls, it's possible the makers of the documentary determined that 73% was the "right number" to use in this particular context. One way they might have come by this number is to have first done a test run to see how well non-twin siblings could predict each others' responses. If these tests showed a 73% success rate, then identical twins would have to beat this to prove they can do better than mere siblings. There are plenty of technical details being glossed over here (in particular, how do we distinguish between twins who are actually better, and twins who just happened to get lucky?), but that's the general idea.

The answer to your actual question: No, you can't predict the next number a cryptographically secure pseudorandom number generator will spit out. If you happen to guess correctly, you just got lucky. (Or you've discovered a previously unknown weakness in the algorithm).

ContentLicense: CC BY-SA 3.0

Title: Psudo-Random Number Prediction


问:
Steam web api to get game data. PHP & JSON
I am looking for a steam web API to get info about games. Im trying to use this:
$api_url_rust = "http://steamspy.com/api.php?request=appdetails&appid=252490";

$json2 = json_decode(file_get_contents($api_url_rust), true);

But I keep getting an error: Failed to open stream: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP

I don't think it has something with the way I have PHP installed. I tried running it on my schools server and I still gives me an error. Any idea how I can fix this or another API I could use? I also have other steam web API's that work fine.

Heres an example of one this is working correctly:
$api_url_playerData = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=$api_key&steamids=$steamid";

$json = json_decode(file_get_contents($api_url_playerData), true);

echo "Account Name: ". $json["response"]["players"][0]["personaname"] . "-----";

答:
So you want to consume a JSON response from an API served over SSL wihtout checking the SSL certificate. It is unsafe and not recommended.

File wrappers (in php especially) are not always enough to connect to another external webservice|microservice. You need to configure your php client to handle SSL properly OR you can do what you need safely only with building a SSL http client with php|java|python|go|etc., and load the JSON response.

It is exactly the same for any API, handshake properly with them and you can do what you need.


问:
How do I use the length of another column in Pandas as a slice argument
I am trying to remove rows from a dataframe where the first sequence of letters in the Ref column are equal to the Product column.

For example, for the input:

```<code>+---------+---------------+
| Product | Provision Ref |
+---------+---------------+
| DVX     | DVX9251       |
+---------+---------------+
| CDV     | 22CDV95       |
+---------+---------------+
| TV      | TV12369       |
+---------+---------------+
| TV      | 992TV15       |
+---------+---------------+
</code>```

Desired output:

```<code>+---------+---------------+
| Product | Provision Ref |
+---------+---------------+
| CDV     | 22CDV95       |
+---------+---------------+
| TV      | 992TV15       |
+---------+---------------+
</code>```

I have tried both of the following pieces of code but they are not working

```<code>df = df.loc[df['Provision Ref'].str[0:df['Product'].map(len)] != df['Product']]
df = df.loc[df['Provision Ref'].str[0:int(df['Product'].map(len))] != df['Product']]
</code>```

答:
Try this:

```<code>filtered = df[df.groupby('Product', sort=False).apply(lambda g: g['Provision Ref'].str.startswith(g['Product'].iloc[0])).tolist()]
</code>```

Output:

```<code>>>> filtered
  Product Provision Ref
0     DVX       DVX9251
2      TV       TV12369
</code>```

More readable but less efficient:

```<code>filtered = df[df.apply(lambda x: x['Provision Ref'].startswith(x['Product']), axis=1)]
</code>```

Another method, probably more efficient if the items of Product have few unique lengths (e.g. most are either 2, 3 or 4 chars long, etc.):

```<code>filtered = df[df.groupby(df['Product'].str.len(), sort=False).apply(lambda x: x['Provision Ref'].str[:len(x['Product'].iloc[0])] == x['Product']).tolist()]
</code>```

Body:
I am trying to remove rows from a dataframe where the first sequence of letters in the Ref column are equal to the Product column.

For example, for the input:

+---------+---------------+
| Product | Provision Ref |
+---------+---------------+
| DVX     | DVX9251       |
+---------+---------------+
| CDV     | 22CDV95       |
+---------+---------------+
| TV      | TV12369       |
+---------+---------------+
| TV      | 992TV15       |
+---------+---------------+

Desired output:

+---------+---------------+
| Product | Provision Ref |
+---------+---------------+
| CDV     | 22CDV95       |
+---------+---------------+
| TV      | 992TV15       |
+---------+---------------+

I have tried both of the following pieces of code but they are not working

df = df.loc[df['Provision Ref'].str[0:df['Product'].map(len)] != df['Product']]
df = df.loc[df['Provision Ref'].str[0:int(df['Product'].map(len))] != df['Product']]

Body:
Try this:

filtered = df[df.groupby('Product', sort=False).apply(lambda g: g['Provision Ref'].str.startswith(g['Product'].iloc[0])).tolist()]

Output:

>>> filtered
  Product Provision Ref
0     DVX       DVX9251
2      TV       TV12369

More readable but less efficient:

filtered = df[df.apply(lambda x: x['Provision Ref'].startswith(x['Product']), axis=1)]

Another method, probably more efficient if the items of Product have few unique lengths (e.g. most are either 2, 3 or 4 chars long, etc.):

filtered = df[df.groupby(df['Product'].str.len(), sort=False).apply(lambda x: x['Provision Ref'].str[:len(x['Product'].iloc[0])] == x['Product']).tolist()]


问:
How to set d3 stroke width
At the moment the following draws two lines, but I can't seem to change the width:

```<code>var a = [23,50];
for (b = 0; b < a.length; b++) {
  var stripe = vis.selectAll("line.stripep")
    .data(connections.filter(function(d,i) { return i == a[b];  }))
    .enter().append("svg:line")
      .attr("class", "stripe")
      .attr("stroke", function(d) { return "#000000"; })
      .attr("stroke-linecap", 'round')
      .attr("stroke-width", 500)
      .attr("x1", function(d) { return x(d.station1.longitude); })
      .attr("y1", function(d) { return y(d.station1.latitude); })
      .attr("x2", function(d) { return x(d.station2.longitude); })
      .attr("y2", function(d) { return y(d.station2.latitude); })
}
</code>```

I want to set the width of the two black lines to 500.

At the moment I am trying:

```<code>.attr("stroke-width", 500)
</code>```

I have also tried:

```<code>.attr("stroke-width",  function(d) { return "500"; })
</code>```

This also did not work. What is the correct way to do this?

答:
Change .attr to .style, and it should work

.style("stroke-width",  function(d) { return "500"; })

Title: How to set d3 stroke width

Body:
At the moment the following draws two lines, but I can't seem to change the width:

var a = [23,50];
for (b = 0; b < a.length; b++) {
  var stripe = vis.selectAll("line.stripep")
    .data(connections.filter(function(d,i) { return i == a[b];  }))
    .enter().append("svg:line")
      .attr("class", "stripe")
      .attr("stroke", function(d) { return "#000000"; })
      .attr("stroke-linecap", 'round')
      .attr("stroke-width", 500)
      .attr("x1", function(d) { return x(d.station1.longitude); })
      .attr("y1", function(d) { return y(d.station1.latitude); })
      .attr("x2", function(d) { return x(d.station2.longitude); })
      .attr("y2", function(d) { return y(d.station2.latitude); })
}

I want to set the width of the two black lines to 500.

At the moment I am trying:

.attr("stroke-width", 500)

I have also tried:

.attr("stroke-width",  function(d) { return "500"; })

This also did not work. What is the correct way to do this?


问:
Bazel - best documentation for which providers are used by any given rule?
I am writing a custom rule that takes inputs from cc_library, cc_binary, apple_static_library, and a few other platform-specific rules. I'd like to view each API given to me via referencing ctx.attr.foo inside the custom rule's implementation function.

There is a list of providers here https://docs.bazel.build/versions/master/skylark/lib/skylark-provider.html but it doesn't say which rules are using them.

Is there a best practice for viewing what these rules are providing me, or does it require going through the source for each one?

答:
This is how you get all providers and output groups from a target:</p>
```<code>bazel cquery my_target --output=starlark --starlark:expr="providers(target)"
</code>```

Body:
This is how you get all providers and output groups from a target:

bazel cquery my_target --output=starlark --starlark:expr="providers(target)"


问:
how to remove back command from LWUIT
I am trying to make an application using LWUIT Now i got a problem with back command from resource editor there are a back command in all forms and i cant find them in generated code </p>

<p>Can anyone please provide me reference or sample code for removing the Back command.   </p>

答: Just invoke setBackCommandEnabled(false) in the state machine to disable the automatic back command navigation logic.

Title: how to remove back command from LWUIT

Body:
I am trying to make an application using LWUIT Now i got a problem with back command from resource editor there are a back command in all forms and i cant find them in generated code

Can anyone please provide me reference or sample code for removing the Back command.


问:
Hardhat node, error in browser on localhost
I'm trying to debug & test a smart contract I developed, however doing so on testnets takes a lot of time and I wanted to test properly on local node.

I can create the node and deploy the contract, transfer from account to another in metamask, every thing works fine, except when I go to http://127.0.0.1:8545/  in browser, I get this error:

```<code>{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error: Unexpected end of JSON input"}}
</code>```

I've tried both brave & chrome, I tried creating a different hardhat project, same error.

What can I do?
Thanks!

答:
This is an expected output. It's a response to the empty request body:

```<code># request
curl 'http://127.0.0.1:8545/' --data-raw ''
</code>```
```<code># response
{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error: Unexpected end of JSON input"}}
</code>```

If you sent a valid JSON-RPC request body (which is generally not possible from the browser address bar, unless you have installed some kind of browser extension), you'd get a valid response:

```<code># request
curl 'http://127.0.0.1:8545' --data-raw '{"jsonrpc":"2.0","method":"net_listening","params":[],"id":1}'
</code>```
```<code># response
{"jsonrpc":"2.0","id":1,"result":true}
</code>```

Body:
I'm trying to debug & test a smart contract I developed, however doing so on testnets takes a lot of time and I wanted to test properly on local node.

I can create the node and deploy the contract, transfer from account to another in metamask, every thing works fine, except when I go to http://127.0.0.1:8545/  in browser, I get this error:

{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error: Unexpected end of JSON input"}}

I've tried both brave & chrome, I tried creating a different hardhat project, same error.

What can I do?
Thanks!

Body:
This is an expected output. It's a response to the empty request body:

# request
curl 'http://127.0.0.1:8545/' --data-raw ''

# response
{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error: Unexpected end of JSON input"}}

If you sent a valid JSON-RPC request body (which is generally not possible from the browser address bar, unless you have installed some kind of browser extension), you'd get a valid response:

# request
curl 'http://127.0.0.1:8545' --data-raw '{"jsonrpc":"2.0","method":"net_listening","params":[],"id":1}'

# response
{"jsonrpc":"2.0","id":1,"result":true}


问:
Search Query help - Condition Card Builder - KQL?
I’m trying to get a proper search done by the IT department. I have been told that they use condition card builder and Kusto query language.

I need to search for “wordA” near 5 words of “wordB” (either before or after)

They say they can’t do it, but I can in other programs.

I was told that ‘around’ means ‘and’
That there was no ‘near’command
‘W/5’ wasn’t a search command

Is there a command to do my search? I have other issues with the database administrator, such as I gave a list of people who the emails should be from and the results were not from the individuals, but they were CC in the message.

答:
The query

(wordA NEAR(5) wordB)(senderauthor=fromemailaddress)

can be copied and pasted into the keyword section of the condition card builder.

Connect, build and run the search in PowerShell:

connect-ippssession

new-compliancesearch -name "Near Search" -description "search using NEAR" -exchangelocation mailbox@domain.com -contentmatchquery '(wordA NEAR(5) wordB)(senderauthor=fromemailaddress)'

start-compliancesearch "NEAR Search"

mailbox@domain.com is the mailbox to search - it can also be a distribution list (which will search all member mailboxes).


问:
Is there anyway to shorten the amount of lines used for having multiple turtles?
So I'm trying to make a program where I want to have many turtles. But I was wondering if instead of writing every single name to instate a new turtle being made, I could make it as short as one line if it's possible on Python turtle. I just want to do this to make the program shorter and easier to understand because looking at say 20 lines of 20 different turtles would not look good. Also, I don't want to use clones as each turtle needs to have something specific to it and will have different variables set to it.</p>
```<code>import turtle

a1 = turtle.Turtle()
b1 = turtle.Turtle()
c1 = turtle.Turtle()
d1 = turtle.Turtle()
a2 = turtle.Turtle()
b2 = turtle.Turtle()
c2 = turtle.Turtle()
d2 = turtle.Turtle()
a3 = turtle.Turtle()
b3 = turtle.Turtle()
c3 = turtle.Turtle()
d3 = turtle.Turtle()
</code>```

答:
```<code>turtles_list = []
for t in range (10): # number of turtles is 10
    turtles_list.append(turtle.Turtle())
</code>```

After that you can access the needed turtle with an index number.

Body:
So I'm trying to make a program where I want to have many turtles. But I was wondering if instead of writing every single name to instate a new turtle being made, I could make it as short as one line if it's possible on Python turtle. I just want to do this to make the program shorter and easier to understand because looking at say 20 lines of 20 different turtles would not look good. Also, I don't want to use clones as each turtle needs to have something specific to it and will have different variables set to it.

import turtle

a1 = turtle.Turtle()
b1 = turtle.Turtle()
c1 = turtle.Turtle()
d1 = turtle.Turtle()
a2 = turtle.Turtle()
b2 = turtle.Turtle()
c2 = turtle.Turtle()
d2 = turtle.Turtle()
a3 = turtle.Turtle()
b3 = turtle.Turtle()
c3 = turtle.Turtle()
d3 = turtle.Turtle()

Body:
turtles_list = []
for t in range (10): # number of turtles is 10
    turtles_list.append(turtle.Turtle())

After that you can access the needed turtle with an index number.


问:
How to reduce video size with java/kotlin on Android?
I want reduce the video size at Android Studio and for upload to PlayStore needs to be compatible for 64 bits arquitecture, I tried before with ffmpeg and it compress mp4 succefully but take longer time and this solution with  3gp not include the audio. Theres another option or library to compress mp4 and 3gp with audio and video?</p>

答:
You may like to use the following library, right now it is actively maintained and may help with the latest android apis.

https://github.com/AbedElazizShe/LightCompressor

Usage as follows  (Java)

```<code>implementation 'com.github.AbedElazizShe:LightCompressor:1.1.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'

public static void compressVideo(Context context,
                                  Activity activity,
                                  ArrayList<Uri> videoUris) {

    VideoCompressor.start(context,
                          // => This is required
                          videoUris,
                          // => Source can be provided as content uris
                          true,
                          // => isStreamable
                          Environment.DIRECTORY_MOVIES,
                          // => the directory to save the compressed video(s)
                          new CompressionListener() {
                              @Override
                              public void onSuccess(int i,
                                                    long l,
                                                    @org.jetbrains.annotations.Nullable String s) {

                                  // On Compression success
                                  Log.d("TAG",
                                        "videoCompress i: " +i);

                                  Log.d("TAG",
                                        "videoCompress l: " +l);

                                  Log.d("TAG",
                                        "videoCompress s: " +s);

                              }

                              @Override
                              public void onStart(int i) {

                                  // Compression start

                              }

                              @Override
                              public void onFailure(int index,
                                                    String failureMessage) {
                                  // On Failure
                              }

                              @Override
                              public void onProgress(int index,
                                                     float progressPercent) {
                                  // Update UI with progress value
                                  activity.runOnUiThread(new Runnable() {
                                      public void run() {
                                      }
                                  });
                              }

                              @Override
                              public void onCancelled(int index) {
                                  // On Cancelled
                              }
                          },
                          new Configuration(VideoQuality.LOW,
                                            24, /*frameRate: int, or null*/
                                            false, /*isMinBitrateCheckEnabled*/
                                            null, /*videoBitrate: int, or null*/
                                            false, /*disableAudio: Boolean, or null*/
                                            false, /*keepOriginalResolution: Boolean, or null*/
                                            360.0, /*videoWidth: Double, or null*/
                                            480.0 /*videoHeight: Double, or null*/));

}
</code>```

Configuration values

```<code>VideoQuality: VERY_HIGH (original-bitrate * 0.6) , HIGH (original-bitrate * 0.4), MEDIUM (original-bitrate * 0.3), LOW (original-bitrate * 0.2), OR VERY_LOW (original-bitrate * 0.1)

isMinBitrateCheckEnabled: this means, don't compress if bitrate is less than 2mbps

frameRate: any fps value

videoBitrate: any custom bitrate value

disableAudio: true/false to generate a video without audio. False by default.

keepOriginalResolution: true/false to tell the library not to change the resolution.

videoWidth: custom video width.

videoHeight: custom video height.
</code>```

Body:
You may like to use the following library, right now it is actively maintained and may help with the latest android apis.

https://github.com/AbedElazizShe/LightCompressor

Usage as follows  (Java)

implementation 'com.github.AbedElazizShe:LightCompressor:1.1.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3'

public static void compressVideo(Context context,
                                  Activity activity,
                                  ArrayList<Uri> videoUris) {

    VideoCompressor.start(context,
                          // => This is required
                          videoUris,
                          // => Source can be provided as content uris
                          true,
                          // => isStreamable
                          Environment.DIRECTORY_MOVIES,
                          // => the directory to save the compressed video(s)
                          new CompressionListener() {
                              @Override
                              public void onSuccess(int i,
                                                    long l,
                                                    @org.jetbrains.annotations.Nullable String s) {

                                  // On Compression success
                                  Log.d("TAG",
                                        "videoCompress i: " +i);

                                  Log.d("TAG",
                                        "videoCompress l: " +l);

                                  Log.d("TAG",
                                        "videoCompress s: " +s);

                              }

                              @Override
                              public void onStart(int i) {

                                  // Compression start

                              }

                              @Override
                              public void onFailure(int index,
                                                    String failureMessage) {
                                  // On Failure
                              }

                              @Override
                              public void onProgress(int index,
                                                     float progressPercent) {
                                  // Update UI with progress value
                                  activity.runOnUiThread(new Runnable() {
                                      public void run() {
                                      }
                                  });
                              }

                              @Override
                              public void onCancelled(int index) {
                                  // On Cancelled
                              }
                          },
                          new Configuration(VideoQuality.LOW,
                                            24, /*frameRate: int, or null*/
                                            false, /*isMinBitrateCheckEnabled*/
                                            null, /*videoBitrate: int, or null*/
                                            false, /*disableAudio: Boolean, or null*/
                                            false, /*keepOriginalResolution: Boolean, or null*/
                                            360.0, /*videoWidth: Double, or null*/
                                            480.0 /*videoHeight: Double, or null*/));

}

Configuration values

VideoQuality: VERY_HIGH (original-bitrate * 0.6) , HIGH (original-bitrate * 0.4), MEDIUM (original-bitrate * 0.3), LOW (original-bitrate * 0.2), OR VERY_LOW (original-bitrate * 0.1)

isMinBitrateCheckEnabled: this means, don't compress if bitrate is less than 2mbps

frameRate: any fps value

videoBitrate: any custom bitrate value

disableAudio: true/false to generate a video without audio. False by default.

keepOriginalResolution: true/false to tell the library not to change the resolution.

videoWidth: custom video width.

videoHeight: custom video height.


问:
how can i get text with requests?
huh, im getting this returned:

[
 Titoli alternativi: OP
 Autore: Eiichiro Oda
 Data di Uscita Jap: 20 Ottobre 1999
 Genere: Azione, Avventura, Commedia, Drammatico, Fantasy, Superpoteri, Shounen
 Durata: 24 min
 Episodi: ??? – (In Corso)
 Trama: Monkey D. Rufy è

but im only able to get each text-title, it's returned as a string so i can't access each of them and use regex, is there any elegant method to do it?

```<code>r = requests.get("https://www.animeuniverse.it/one-piece-ita-streaming-download/")
    status = (r.ok); titles = []; descs= []#returns true if status code is <400> (no errors)
    if status == True:
        try:
            with open("index.html","x")as f:
                f.write(r.text)
        except:
            os.remove("index.html")
            with open("index.html","x")as f:
                f.write(r.text)
        with open("index.html", "r") as f:
            r = BeautifulSoup(f, "html.parser")

            info_data = r.find_all(class_="info")
            #info_data = list(info_data)
            #print (info_data)
            #print (len(info_data))
            #print (type(info_data))
            #print (info_data[0])
</code>```

答:
huh, fixed it anyway, didn't need any cloudflare bypass or else, here's the fix:</p>
```<code>            info_data = r.find_all(class_="info-anime")
            info_data = str(info_data)
            info_data = info_data.splitlines()
            info_data.pop(0)
            for data in info_data:
                # print (data)
                # print ("============")
                try:
                    data = re.search('</span>(.+?)<', data).group(1)
                    if len(data) > 100:
                        plot.append(data)
                    #print (data)
                    else:
                        descs.append(data)
                except AttributeError:
                    data = data[:-7]
                    plot.append(data)
</code>```

Title: how can i get text with requests?

Body:
huh, im getting this returned:

[
 Titoli alternativi: OP
 Autore: Eiichiro Oda
 Data di Uscita Jap: 20 Ottobre 1999
 Genere: Azione, Avventura, Commedia, Drammatico, Fantasy, Superpoteri, Shounen
 Durata: 24 min
 Episodi: ??? – (In Corso)
 Trama: Monkey D. Rufy è

but im only able to get each text-title, it's returned as a string so i can't access each of them and use regex, is there any elegant method to do it?

r = requests.get("https://www.animeuniverse.it/one-piece-ita-streaming-download/")
    status = (r.ok); titles = []; descs= []#returns true if status code is <400> (no errors)
    if status == True:
        try:
            with open("index.html","x")as f:
                f.write(r.text)
        except:
            os.remove("index.html")
            with open("index.html","x")as f:
                f.write(r.text)
        with open("index.html", "r") as f:
            r = BeautifulSoup(f, "html.parser")

            info_data = r.find_all(class_="info")
            #info_data = list(info_data)
            #print (info_data)
            #print (len(info_data))
            #print (type(info_data))
            #print (info_data[0])

Body:
huh, fixed it anyway, didn't need any cloudflare bypass or else, here's the fix:

            info_data = r.find_all(class_="info-anime")
            info_data = str(info_data)
            info_data = info_data.splitlines()
            info_data.pop(0)
            for data in info_data:
                # print (data)
                # print ("============")
                try:
                    data = re.search('</span>(.+?)<', data).group(1)
                    if len(data) > 100:
                        plot.append(data)
                    #print (data)
                    else:
                        descs.append(data)
                except AttributeError:
                    data = data[:-7]
                    plot.append(data)


问:
Is there an easy way to allow an html document to scroll left and right?
I was making a webpage with a spiderweb style design, meaning content would move out and to the left and right as the user browsed.

I want the user to be able to scroll to the left and to the right as they please.

However, I noticed that it's impossible to scroll to the left while using direction:ltr. To fix this, I tried using direction:rtl on html and direction:ltr on the body. However, when I do this, it becomes unable to scroll to the right. There is the option of putting a margin-left: var(--left-content-width,0) modifier on html, but this sacrifices internet explorer 11 compatability, and makes it much harder to keep track of all the content on the left of the viewport. Is there an  easy way to scroll left and right (preferably using just css, but javascript is not out of the question), or are we doomed to constant margin updates forever?

答: You can use this: overflow-x: scroll;. If anything overflows off of the screen the user can scroll to see it.


问:
How do I get IRBRC running on Win32 for Ruby console?
Can anyone suggest some troubleshooting approaches for getting IRBRC running under Win32?  The rails console is an awesome tool and I'm attempting to extend it with more functionality.

For instance, I would like the what_method gem to load automatically.  The gem is installed but it does not load:

```<code>C:\...\trunk>ruby script\console
Loading development environment (Rails 2.3.2)
>> 3.45.what? 3
NoMethodError: undefined method `what?' for 3.45:Float
        from (irb):1
>> require 'what_methods'
=> ["DummyOut", "WhatMethods"]
>> 3.34.what? 3
3.34.round_with_precision == 3
...
=> ["round_with_precision", "round", "prec_i", ... "round_without_precision"]
>>
</code>```

My environment is setup as

```<code>C:\...\trunk>dir %HOME%
 Volume in drive C is OS
...
06/21/2009  10:29 AM    <DIR>          .
06/21/2009  09:28 AM               118 .irbrc
...
</code>```

Environment variable path IRBRC = %HOME%\.irbrc

.irbrc file

```<code>require 'irb/completion'
require 'map_by_method'
require 'what_methods'
require 'pp'
IRB.conf[:AUTO_INDENT]=true
</code>```

I've read the following references

http://railscasts.com/episodes/48-console-tricks

http://drnicwilliams.com/2006/10/12/my-irbrc-for-consoleirb/#irbrc_win32

http://groups.google.com/group/ruby-talk-google/browse_thread/thread/23fe3980a5a4816e

http://www.nabble.com/.irbrc-on-Windows-td23954309.html

答:
Use Pry: http://pry.github.com

Lets you:

view method source code

view method documentation (not using RI so you dont have to pre-generate it)

pop in and out of different contexts

syntax highlighting

gist integration

view and replay history

open editors to edit method using edit-method obj.my_method syntax

A tonne more great and original features

View the screencast on that link above, it also works with Rails. :)

ContentLicense: CC BY-SA 2.5

Body:
Can anyone suggest some troubleshooting approaches for getting IRBRC running under Win32?  The rails console is an awesome tool and I'm attempting to extend it with more functionality.

For instance, I would like the what_method gem to load automatically.  The gem is installed but it does not load:

C:\...\trunk>ruby script\console
Loading development environment (Rails 2.3.2)
>> 3.45.what? 3
NoMethodError: undefined method `what?' for 3.45:Float
        from (irb):1
>> require 'what_methods'
=> ["DummyOut", "WhatMethods"]
>> 3.34.what? 3
3.34.round_with_precision == 3
...
=> ["round_with_precision", "round", "prec_i", ... "round_without_precision"]
>>

My environment is setup as

C:\...\trunk>dir %HOME%
 Volume in drive C is OS
...
06/21/2009  10:29 AM    <DIR>          .
06/21/2009  09:28 AM               118 .irbrc
...

Environment variable path IRBRC = %HOME%\.irbrc

.irbrc file

require 'irb/completion'
require 'map_by_method'
require 'what_methods'
require 'pp'
IRB.conf[:AUTO_INDENT]=true

I've read the following references

http://railscasts.com/episodes/48-console-tricks

http://drnicwilliams.com/2006/10/12/my-irbrc-for-consoleirb/#irbrc_win32

http://groups.google.com/group/ruby-talk-google/browse_thread/thread/23fe3980a5a4816e

http://www.nabble.com/.irbrc-on-Windows-td23954309.html


问:
With all the available problems that have been categorized and their time complexities deduced, so why haven't anyone solved NP vs P yet?
We have problems proved to be in classes P, NP, co-NP, NP-Complete, and NP-Hard. These problems have their time complexities deduced too. I am wondering if I am missing any key information on the topic.</p>

答:
One of the standard tricks for solving this sort of problem is what's called using an "oracle".  Suppose we could ask the oracle a question about a specific class of problems, and in one step it would answer "yes" or "no".  It becomes reasonable to ask "What sort of problems are in P for a machine with this oracle"?  "What sort of problems are in NP for a machine with this Oracle.

It has been shown that there are oracles for which P=NP.  It has been shown that there are oracles for which P≠NP.  Most of the techniques we know for proving hardness should give the same result, no. matter what oracle is used.


问:
flex items will not stretch and when they unide it moves all my other items in a div
I am trying to get an input box to stretch the full width of the screen, but due to the items, it is div'd with above it only takes up a small amount and when it unhides it also drags the items above with it. I've tried flex-stretch, align-items: stretch, etc etc etc and nothing seems to work. I even gave it a div by itself and I couldn't get it to work.

If you click the Reply button in the code below it will show you my exact issue:

document.getElementById("reply64").addEventListener('click', (e) => {
  document.getElementById("reply64").classList.toggle("blue");
  document.getElementById("reply_form64").classList.toggle("open");
});

document.getElementById("reply71").addEventListener('click', (e) => {
  document.getElementById("reply71").classList.toggle("blue");
  document.getElementById("submit_reply71").classList.toggle("open");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.lk{
    display: flex;
    margin-bottom: 5px;
    font-size: 14px;
    gap: 5px;
}

.profile_image{
    width: 30px;
    height: 30px;
    border-radius: 50%;
}

.user{
    background: grey;
    padding: 10px;
    border-radius: 20px;
}

.reply-body{
    width: 100%;
    flex-shrink: 0;
}

.reply {
    display: flex;
    justify-content: legacy left;
    gap: 10px;
}

.thumb.open, .vl.open, .form-hidden.open{
    display: flex;
}

.form-hidden{
    display: none;
}

.blue{
    color: blue;
}</code>```

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
      <link href="/static/css/style.css" rel="stylesheet">

      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

jon 2 days ago

hi dawg!

          1

Reply

      <form id="reply_form64" class="form-hidden">

        <input class="cmt-reply" type="text" placeholder="Write a reply2">
      </form>

jon 2 hours ago

yo

          0

Reply

      <form id="submit_reply71" class="form-hidden">

          <input class="comment_input" id="comment_input" maxlength="1024" name="body" placeholder="Write a comment3" required="" type="text" value="">

      </form>

```

答:
Hiding the error on your reply button sample... I see the following:

the input and form are all children of an unnamed div with a default width (none specified).

If you set that parent's width to 100%, then your input, which also lacks a width: 100%, will stretch, like so:

You will then need to define what you want to do with your gray chat box but, just keep in mind:

You cannot expect elements to stretch to the full width of anything if they have no specified reason to do so. Check the default width value (auto):

https://developer.mozilla.org/en-US/docs/Web/CSS/width

A child cannot normally grow beyond the limitations of its parent, specially by default, auto width on your input and auto width on its div parent...will never lead to 100% width. You ought to be specific.

EXTRA

To adjust the content of the .user div based on the size of the content, you can try max-content, which would make your examples look like this:

https://blog.logrocket.com/understanding-min-content-max-content-fit-content-css/

Please read this article, it explains in detail max-content, min-content, fit-content, pro's and con's, etc.

Body:
I am trying to get an input box to stretch the full width of the screen, but due to the items, it is div'd with above it only takes up a small amount and when it unhides it also drags the items above with it. I've tried flex-stretch, align-items: stretch, etc etc etc and nothing seems to work. I even gave it a div by itself and I couldn't get it to work.

If you click the Reply button in the code below it will show you my exact issue:

document.getElementById("reply64").addEventListener('click', (e) => {
  document.getElementById("reply64").classList.toggle("blue");
  document.getElementById("reply_form64").classList.toggle("open");
});

document.getElementById("reply71").addEventListener('click', (e) => {
  document.getElementById("reply71").classList.toggle("blue");
  document.getElementById("submit_reply71").classList.toggle("open");
});

.lk{
    display: flex;
    margin-bottom: 5px;
    font-size: 14px;
    gap: 5px;
}

.profile_image{
    width: 30px;
    height: 30px;
    border-radius: 50%;
}

.user{
    background: grey;
    padding: 10px;
    border-radius: 20px;
}

.reply-body{
    width: 100%;
    flex-shrink: 0;
}

.reply {
    display: flex;
    justify-content: legacy left;
    gap: 10px;
}

.thumb.open, .vl.open, .form-hidden.open{
    display: flex;
}

.form-hidden{
    display: none;
}

.blue{
    color: blue;
}

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
      <link href="/static/css/style.css" rel="stylesheet">

      <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

jon 2 days ago

hi dawg!

          1

Reply

      <form id="reply_form64" class="form-hidden">

        <input class="cmt-reply" type="text" placeholder="Write a reply2">
      </form>

jon 2 hours ago

yo

          0

Reply

      <form id="submit_reply71" class="form-hidden">

          <input class="comment_input" id="comment_input" maxlength="1024" name="body" placeholder="Write a comment3" required="" type="text" value="">

      </form>


问:
System.Text.Json.JsonDocument.Parse array of objects
I am trying to parse below json using System.Text.Json.JsonDocument

```<code>[
    {
        "Name" : "Test 2",
        "NumberOfComponents" : 1,
        "IsActive" : true,
        "CreatedBy" : "bsharma"
    },
    {
        "Name" : "Test 2",
        "NumberOfComponents" : 1,
        "IsActive" : true,
        "CreatedBy" : "bsharma"
    }
]
</code>```

The code to parse:

```<code> using var jsonDoc = JsonDocument.Parse(inputStream, _jsonDocumentOptions);
</code>```

The parsing fails with error:

```<code>System.Text.Json.JsonReaderException
  HResult=0x80131500
  Message='[' is an invalid start of a property name. Expected a '"'. LineNumber: 1 | BytePositionInLine: 4.
  Source=System.Text.Json
  StackTrace:
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
   at System.Text.Json.Utf8JsonReader.Read()
   at System.Text.Json.JsonDocument.Parse(ReadOnlySpan`1 utf8JsonSpan, Utf8JsonReader reader, MetadataDb& database, StackRowStack& stack)
   at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory`1 utf8Json, JsonReaderOptions readerOptions, Byte[] extraRentedBytes)
   at System.Text.Json.JsonDocument.Parse(Stream utf8Json, JsonDocumentOptions options)
</code>```

The json input is being sent in via an http request. The error message indicates to put the array in a property in form { "values" : [ .. ] }, which solves the problem. Is there a way to get a JsonDocument instance for the original json or the original json is invalid?

EDIT:
The json comes from serializing an array:

```<code>    var jsonOptions = new JsonSerializerOptions
    {
        WriteIndented = true
    };

    var pocos = new Container[]
    {
        new Container { Name= "Test 2", NumberOfComponents = 2, IsActive = true ,CreatedBy = "bsharma" },
        new Container { Name= "Test 2", NumberOfComponents = 2, IsActive = true ,CreatedBy = "bsharma" }
    };
    var json = JsonSerializer.Serialize(pocos, jsonOptions);
</code>```

答:
.NET 6 has added a new namespace System.Text.Json.Nodes which allows access random access to Json values in a similar manner to Newtonsoft.Json JArray and JObject.

You can use JsonNode.Parse() to parse Json from a stream (or string or JsonReader) to a JsonArray.

```<code>// parse from stream, string, utf8JsonReader
JsonArray? array = JsonNode.Parse(stream)?.AsArray();

// access values
string name = array[0]["Name"].ToString();
int number = (int) item["NumberOfComponents"];

// or iterate
foreach (var item in array)
{
    string name = item["Name"].ToString();
    int componentCount = (int) item["NumberOfComponents"];
    bool isActive = (bool) item["IsActive"];

    Console.WriteLine($"Name:{name}, #comps:{componentCount}, Active:{isActive}");
}

// serialize
var jsonString = array.ToJsonString();

// deserialize to defined class
List<Item> items = array.Deserialize<List<Item>>();
</code>```

The addition of JsonObject, JsonArray and JsonNode makes working with Json in System.Text.Json a little easier if you just want to quickly access or modify the Json.

Also see my answer to Equivalent of JObject in System.Text.Json for details on JsonObject.

Body:
I am trying to parse below json using System.Text.Json.JsonDocument

[
    {
        "Name" : "Test 2",
        "NumberOfComponents" : 1,
        "IsActive" : true,
        "CreatedBy" : "bsharma"
    },
    {
        "Name" : "Test 2",
        "NumberOfComponents" : 1,
        "IsActive" : true,
        "CreatedBy" : "bsharma"
    }
]

The code to parse:

 using var jsonDoc = JsonDocument.Parse(inputStream, _jsonDocumentOptions);

The parsing fails with error:

System.Text.Json.JsonReaderException
  HResult=0x80131500
  Message='[' is an invalid start of a property name. Expected a '"'. LineNumber: 1 | BytePositionInLine: 4.
  Source=System.Text.Json
  StackTrace:
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
   at System.Text.Json.Utf8JsonReader.Read()
   at System.Text.Json.JsonDocument.Parse(ReadOnlySpan`1 utf8JsonSpan, Utf8JsonReader reader, MetadataDb& database, StackRowStack& stack)
   at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory`1 utf8Json, JsonReaderOptions readerOptions, Byte[] extraRentedBytes)
   at System.Text.Json.JsonDocument.Parse(Stream utf8Json, JsonDocumentOptions options)

The json input is being sent in via an http request. The error message indicates to put the array in a property in form { "values" : [ .. ] }, which solves the problem. Is there a way to get a JsonDocument instance for the original json or the original json is invalid?

EDIT:
The json comes from serializing an array:

    var jsonOptions = new JsonSerializerOptions
    {
        WriteIndented = true
    };

    var pocos = new Container[]
    {
        new Container { Name= "Test 2", NumberOfComponents = 2, IsActive = true ,CreatedBy = "bsharma" },
        new Container { Name= "Test 2", NumberOfComponents = 2, IsActive = true ,CreatedBy = "bsharma" }
    };
    var json = JsonSerializer.Serialize(pocos, jsonOptions);

Body:
.NET 6 has added a new namespace System.Text.Json.Nodes which allows access random access to Json values in a similar manner to Newtonsoft.Json JArray and JObject.

You can use JsonNode.Parse() to parse Json from a stream (or string or JsonReader) to a JsonArray.

// parse from stream, string, utf8JsonReader
JsonArray? array = JsonNode.Parse(stream)?.AsArray();

// access values
string name = array[0]["Name"].ToString();
int number = (int) item["NumberOfComponents"];

// or iterate
foreach (var item in array)
{
    string name = item["Name"].ToString();
    int componentCount = (int) item["NumberOfComponents"];
    bool isActive = (bool) item["IsActive"];

    Console.WriteLine($"Name:{name}, #comps:{componentCount}, Active:{isActive}");
}

// serialize
var jsonString = array.ToJsonString();

// deserialize to defined class
List<Item> items = array.Deserialize<List<Item>>();

The addition of JsonObject, JsonArray and JsonNode makes working with Json in System.Text.Json a little easier if you just want to quickly access or modify the Json.

Also see my answer to Equivalent of JObject in System.Text.Json for details on JsonObject.