问:
Get unique values and their occurrence out of one dataframe into a new dataframe using Pandas DataFrame
I want to turn my dataframe with non-distinct values underneath each column header into a dataframe with distinct values underneath each column header with next to it their occurrence in their particular column. An example:

My initial dataframe is visible underneath:

```<code>A       B       C       D
0       CEN     T2      56
2       DECEN   T2      45
3       ONBEK   T2      84
NaN     CEN     T1      59
3       NaN     T1      87
NaN     NaN     T2      NaN
0       NaN     NaN     98
NaN     CEN     NaN     23
NaN     CEN     T1      65
</code>```

where A, B, C and D are the column headers with each 9 values underneath it (blanks included).

My preferred output dataframe should look like: (first a column of unique values for each column in the original dataframe and next to it their occurrence in that particular column)

```<code>A       B       C       D       A       B       C       D
0       CEN     T2      56      2       4       4       1
2       DECEN   T1      45      1       1       3       1
3       ONBEK   NaN     84      2       1       NaN     1
Nan     NaN     NaN     59      NaN     NaN     NaN     1
NaN     NaN     NaN     87      NaN     NaN     NaN     1
NaN     NaN     NaN     98      NaN     NaN     NaN     1
NaN     NaN     NaN     23      NaN     NaN     NaN     1
NaN     NaN     NaN     65      NaN     NaN     NaN     1
</code>```

where A, B, C and D are the column headers with underneath them first the distinct values for each column from the original .csv-file and next to it the occurence of each element in their particular column.

Anybody ideas?

The code below is used to get the unique values out of each column into a new dataframe. I tried to do something with .value_counts to get the occurrence in each column but there I failed to get it into one dataframe again with the unique values..

```<code>df
new_df=pd.concat([pd.Series(df[i].unique()) for i in df.columns], axis=1)
new_df.columns=df.columns
new_df
</code>```

答:
The difficult part is keeping values of columns in each row aligned. To do this, you need to construct a new dataframe from unique, and pd.concat on with value_counts map to each column of this new dataframe.

```<code>new_df = (pd.DataFrame([df[c].unique() for c in df], index=df.columns).T
            .dropna(how='all'))

df_final = pd.concat([new_df, *[new_df[c].map(df[c].value_counts()).rename(f'{c}_Count')
                                   for c in  df]], axis=1).reset_index(drop=True)

Out[1580]:
     A      B    C   D  A_Count  B_Count  C_Count  D_Count
0    0    CEN   T2  56      2.0      4.0      4.0        1
1    2  DECEN   T1  45      1.0      1.0      3.0        1
2    3  ONBEK  NaN  84      2.0      1.0      NaN        1
3  NaN    NaN  NaN  59      NaN      NaN      NaN        1
4  NaN    NaN  NaN  87      NaN      NaN      NaN        1
5  NaN    NaN  NaN  98      NaN      NaN      NaN        1
6  NaN    NaN  NaN  23      NaN      NaN      NaN        1
7  NaN    NaN  NaN  65      NaN      NaN      NaN        1
</code>```

If you only need to keep alignment between each pair of column and its count such as A - A_Count, B - B_Count..., it simply just use value_counts with reset_index some commands to change axis names

```<code>cols = df.columns.tolist() + (df.columns + '_Count').tolist()
new_df = pd.concat([df[col].value_counts(sort=False).rename_axis(col).reset_index(name=f'{col}_Count')
                        for col in df], axis=1).reindex(new_cols, axis=1)

Out[1501]:
     A      B    C     D  A_Count  B_Count  C_Count  D_Count
0  0.0  ONBEK   T2  56.0      2.0      1.0      4.0        1
1  2.0    CEN   T1  45.0      1.0      4.0      3.0        1
2  3.0  DECEN  NaN  84.0      2.0      1.0      NaN        1
3  NaN    NaN  NaN  59.0      NaN      NaN      NaN        1
4  NaN    NaN  NaN  87.0      NaN      NaN      NaN        1
5  NaN    NaN  NaN  98.0      NaN      NaN      NaN        1
6  NaN    NaN  NaN  23.0      NaN      NaN      NaN        1
7  NaN    NaN  NaN  65.0      NaN      NaN      NaN        1
</code>```

Body:
I want to turn my dataframe with non-distinct values underneath each column header into a dataframe with distinct values underneath each column header with next to it their occurrence in their particular column. An example:

My initial dataframe is visible underneath:

A       B       C       D
0       CEN     T2      56
2       DECEN   T2      45
3       ONBEK   T2      84
NaN     CEN     T1      59
3       NaN     T1      87
NaN     NaN     T2      NaN
0       NaN     NaN     98
NaN     CEN     NaN     23
NaN     CEN     T1      65

where A, B, C and D are the column headers with each 9 values underneath it (blanks included).

My preferred output dataframe should look like: (first a column of unique values for each column in the original dataframe and next to it their occurrence in that particular column)

A       B       C       D       A       B       C       D
0       CEN     T2      56      2       4       4       1
2       DECEN   T1      45      1       1       3       1
3       ONBEK   NaN     84      2       1       NaN     1
Nan     NaN     NaN     59      NaN     NaN     NaN     1
NaN     NaN     NaN     87      NaN     NaN     NaN     1
NaN     NaN     NaN     98      NaN     NaN     NaN     1
NaN     NaN     NaN     23      NaN     NaN     NaN     1
NaN     NaN     NaN     65      NaN     NaN     NaN     1

where A, B, C and D are the column headers with underneath them first the distinct values for each column from the original .csv-file and next to it the occurence of each element in their particular column.

Anybody ideas?

The code below is used to get the unique values out of each column into a new dataframe. I tried to do something with .value_counts to get the occurrence in each column but there I failed to get it into one dataframe again with the unique values..

df
new_df=pd.concat([pd.Series(df[i].unique()) for i in df.columns], axis=1)
new_df.columns=df.columns
new_df

Body:
The difficult part is keeping values of columns in each row aligned. To do this, you need to construct a new dataframe from unique, and pd.concat on with value_counts map to each column of this new dataframe.

new_df = (pd.DataFrame([df[c].unique() for c in df], index=df.columns).T
            .dropna(how='all'))

df_final = pd.concat([new_df, *[new_df[c].map(df[c].value_counts()).rename(f'{c}_Count')
                                   for c in  df]], axis=1).reset_index(drop=True)

Out[1580]:
     A      B    C   D  A_Count  B_Count  C_Count  D_Count
0    0    CEN   T2  56      2.0      4.0      4.0        1
1    2  DECEN   T1  45      1.0      1.0      3.0        1
2    3  ONBEK  NaN  84      2.0      1.0      NaN        1
3  NaN    NaN  NaN  59      NaN      NaN      NaN        1
4  NaN    NaN  NaN  87      NaN      NaN      NaN        1
5  NaN    NaN  NaN  98      NaN      NaN      NaN        1
6  NaN    NaN  NaN  23      NaN      NaN      NaN        1
7  NaN    NaN  NaN  65      NaN      NaN      NaN        1

If you only need to keep alignment between each pair of column and its count such as A - A_Count, B - B_Count..., it simply just use value_counts with reset_index some commands to change axis names

cols = df.columns.tolist() + (df.columns + '_Count').tolist()
new_df = pd.concat([df[col].value_counts(sort=False).rename_axis(col).reset_index(name=f'{col}_Count')
                        for col in df], axis=1).reindex(new_cols, axis=1)

Out[1501]:
     A      B    C     D  A_Count  B_Count  C_Count  D_Count
0  0.0  ONBEK   T2  56.0      2.0      1.0      4.0        1
1  2.0    CEN   T1  45.0      1.0      4.0      3.0        1
2  3.0  DECEN  NaN  84.0      2.0      1.0      NaN        1
3  NaN    NaN  NaN  59.0      NaN      NaN      NaN        1
4  NaN    NaN  NaN  87.0      NaN      NaN      NaN        1
5  NaN    NaN  NaN  98.0      NaN      NaN      NaN        1
6  NaN    NaN  NaN  23.0      NaN      NaN      NaN        1
7  NaN    NaN  NaN  65.0      NaN      NaN      NaN        1


来源: stackexchange

问:
p5.js mousePressed event returns Undefined
I cant get mousePressed to console log the MouseEvent. I'm not even sure if having it in the setup function is the right place?

https://codesandbox.io/embed/withered-monad-jrhyw

```<code>import React from 'react';
import Sketch from 'react-p5';

const App: React.FC = () => {
  const setup = (p5: any) => {
    canvas = p5.createCanvas(window.innerWidth, window.innerHeight);

    canvas.mouseWheel((e: MouseEvent) => {
      console.log(e); // Wheel Event
    });

    canvas.mousePressed((e: MouseEvent) => {
      console.log(e); // Undefined
    });

  };

  const draw = (p5: any) => {
    p5.background(50);
    p5.fill(0);
    p5.rect(25, 25, 50, 50);
  };

  return (
    <React.Fragment>
      <Sketch setup={setup} draw={draw} />
    </React.Fragment>
  );
};

export { App };

</code>```

答: I have answered this question on opened GitHub Issue in order to use only one channel to track this issue and resolve it. Github Issue #16</p>

ContentLicense: CC BY-SA 4.0

Body:
I cant get mousePressed to console log the MouseEvent. I'm not even sure if having it in the setup function is the right place?

https://codesandbox.io/embed/withered-monad-jrhyw

import React from 'react';
import Sketch from 'react-p5';

const App: React.FC = () => {
  const setup = (p5: any) => {
    canvas = p5.createCanvas(window.innerWidth, window.innerHeight);

    canvas.mouseWheel((e: MouseEvent) => {
      console.log(e); // Wheel Event
    });

    canvas.mousePressed((e: MouseEvent) => {
      console.log(e); // Undefined
    });

  };

  const draw = (p5: any) => {
    p5.background(50);
    p5.fill(0);
    p5.rect(25, 25, 50, 50);
  };

  return (
    <React.Fragment>
      <Sketch setup={setup} draw={draw} />
    </React.Fragment>
  );
};

export { App };


问:
Jenkinsfile - add private key credential to terraform
As part of my Jenkinsfile, i am trying to load the secret file i have on my Jenkins machine and use it as a variable to pass into my terraform script. This terraform script is ssh'ing onto my newly provisioned ansible server and generating an Ansible inventory. The problem is loading the private key file into the terraform script as a variable to create the ssh connection from my ephemeral build in Jenkins.

As you can see the load the crediential and store in a terraform var (TF_VAR_private_key) but i am then having trouble loading it into my main.tf terraform script.

Any suggestions or help much appreciated.

Jenkinsfile

```<code>stages {
    stage('Provision Infrastructure') {
        steps {
            // credentialsId loading private key and storing in var
            withCredentials([file(credentialsId: 'ec2user.pem', variable: 'TF_VAR_private_key'),
            [
                $class           : 'AmazonWebServicesCredentialsBinding',
                credentialsId    : "aws_credentials",
                accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
            ]])
            { sh """
                terraform version
                cd ${TERRAFORM_DIR}
                terraform init
                terraform plan
                terraform apply -input=false -auto-approve
            """ }
        }
    }
</code>```

main.tf

```<code>resource "null_resource" "inventories" {

  triggers {
    template = "${template_file.inventory.rendered}"
  }
  connection {
    type = "ssh"
    host = "${element(aws_instance.ansible.*.private_ip, 0)}"
    user = "ec2-user"
    private_key = "${file("${var.private_key}")}"
    agent = false
    timeout = "1m"
  }

  provisioner "remote-exec" {
    inline = [
      "echo '${template_file.inventory.rendered}' > /tmp/inventory"
    ]
  }
}
</code>```

Error:

Can't run remote-exec as private key file not found.

答:
I tried a few ways, this is what works:

Jenkinsfile

```<code>withCredentials([sshUserPrivateKey(
    credentialsId: 'e4dd944e-5fef-4109-801c-b478d41af2d7',
    keyFileVariable: 'SSH_KEY')])
{
    sh 'cp "$SSH_KEY" files/jenkins-aws.pem'
    sh 'terraform plan -out tfplan'
}
</code>```

You need to copy the credentials file to some place terraform can access within the workspace. Then use it normally within your terraform:

main.tf

```<code>variable "ssh_private_key_file" {
  default = "files/jenkins-aws.pem"
}

locals {
  ssh_private_key_content = file(var.ssh_private_key_file)
}
</code>```

Body:
As part of my Jenkinsfile, i am trying to load the secret file i have on my Jenkins machine and use it as a variable to pass into my terraform script. This terraform script is ssh'ing onto my newly provisioned ansible server and generating an Ansible inventory. The problem is loading the private key file into the terraform script as a variable to create the ssh connection from my ephemeral build in Jenkins.

As you can see the load the crediential and store in a terraform var (TF_VAR_private_key) but i am then having trouble loading it into my main.tf terraform script.

Any suggestions or help much appreciated.

Jenkinsfile

stages {
    stage('Provision Infrastructure') {
        steps {
            // credentialsId loading private key and storing in var
            withCredentials([file(credentialsId: 'ec2user.pem', variable: 'TF_VAR_private_key'),
            [
                $class           : 'AmazonWebServicesCredentialsBinding',
                credentialsId    : "aws_credentials",
                accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
            ]])
            { sh """
                terraform version
                cd ${TERRAFORM_DIR}
                terraform init
                terraform plan
                terraform apply -input=false -auto-approve
            """ }
        }
    }

main.tf

resource "null_resource" "inventories" {

  triggers {
    template = "${template_file.inventory.rendered}"
  }
  connection {
    type = "ssh"
    host = "${element(aws_instance.ansible.*.private_ip, 0)}"
    user = "ec2-user"
    private_key = "${file("${var.private_key}")}"
    agent = false
    timeout = "1m"
  }

  provisioner "remote-exec" {
    inline = [
      "echo '${template_file.inventory.rendered}' > /tmp/inventory"
    ]
  }
}

Error:

Can't run remote-exec as private key file not found.

Body:
I tried a few ways, this is what works:

Jenkinsfile

withCredentials([sshUserPrivateKey(
    credentialsId: 'e4dd944e-5fef-4109-801c-b478d41af2d7',
    keyFileVariable: 'SSH_KEY')])
{
    sh 'cp "$SSH_KEY" files/jenkins-aws.pem'
    sh 'terraform plan -out tfplan'
}

You need to copy the credentials file to some place terraform can access within the workspace. Then use it normally within your terraform:

main.tf

variable "ssh_private_key_file" {
  default = "files/jenkins-aws.pem"
}

locals {
  ssh_private_key_content = file(var.ssh_private_key_file)
}


问:
Save image to internal storage
I want to save some images in internal storage. Here is my code:

```<code>Bitmap bitmap = ((BitmapDrawable)iv_add.getDrawable()).getBitmap();
            File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
            file = new File(file, "UniqueFileName"+".jpg");
            try{
                OutputStream stream = null;
                stream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
                stream.flush();
                stream.close();
            }catch (IOException e)
            {
                e.printStackTrace();
            }
</code>```

As I understood, the picture needs to go into internal_storage/android/data/project_name/file. When I choose a picture from my gallery and click the button to save it, nothing happens and the program starts lagging. What can I do?

答:
This line is your problem.

```<code>ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
</code>```

You are not supposed to create the context wrapper yourself.

```<code>        File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
        file = new File(file, "UniqueFileName"+".jpg");
        try{
            OutputStream stream = null;
            stream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
            stream.flush();
            stream.close();
        }catch (IOException e)
        {
            e.printStackTrace();
        }
</code>```

Title: Save image to internal storage

Body:
I want to save some images in internal storage. Here is my code:

Bitmap bitmap = ((BitmapDrawable)iv_add.getDrawable()).getBitmap();
            File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
            file = new File(file, "UniqueFileName"+".jpg");
            try{
                OutputStream stream = null;
                stream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
                stream.flush();
                stream.close();
            }catch (IOException e)
            {
                e.printStackTrace();
            }

As I understood, the picture needs to go into internal_storage/android/data/project_name/file. When I choose a picture from my gallery and click the button to save it, nothing happens and the program starts lagging. What can I do?

Body:
This line is your problem.

ContextWrapper wrapper = new ContextWrapper(getApplicationContext());

You are not supposed to create the context wrapper yourself.

        File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
        file = new File(file, "UniqueFileName"+".jpg");
        try{
            OutputStream stream = null;
            stream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
            stream.flush();
            stream.close();
        }catch (IOException e)
        {
            e.printStackTrace();
        }


问:
OPTIMIZE table and ANALYZE table MySQL 5.6 for query performance
There are lot of questions/answers on this site related to optimize table and analyze table.

Question:If we want to do DDL/DML/SELECT fast, without thinking space even if we have fragmentation on table, can we do only analyze table command. because we have 500GB size table and storage engine is innodb it's taking time to optimize table command.

As per MySQL Documentation, OPTIMIZE TABLE and ANALYZE TABLE

Optimize table reorganizes the physical storage of table data and associated index data, to reduce storage space and improve I/O efficiency when accessing the table.

Analyze table performs a key distribution analysis and stores the distribution for the named table or tables

I think, Table stats is up to date no need to optimize table if we are not concern about space used by empty block.

答:
Correct. OPTIMIZE TABLE copies the data to a new tablespace, and rebuilds indexes. This takes a long time for a large table.

Defragmenting an InnoDB table doesn't improve performance much, since internally the pages are typically stored out of order regardless. That is, for InnoDB to return the "next row," it may have to follow a pointer from the current page to another page, which might be physically far away from the current page. Since this is the normal behavior of InnoDB in a non-fragmented tablespace, it might not make any difference if the pages in between are occupied or blank.

It might help to defragment a tablespace if it results in more efficiently packed pages, so the pages cached in the buffer pool represent a greater subset of the rows and indexes for the table.

Analyze table doesn't take a long time, and doesn't take longer for a large table. It reads a fixed number of pages as a sample of the table, and estimates index cardinality and average row size and some other stats based on this. By default, this samples 8 or 20 pages, depending on whether persistent stats are enabled.

The way analyze table helps performance is that it updates statistics that the optimizer uses to choose indexes for a given query. If the updated statistics don't make any material difference to the choice of index, it won't have any effect on performance. It only matters if the new statistics would result in the optimizer choosing a more favorable index.


问:
How can I turn this jquery into a function?
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the href> tag somewhere.

html code

```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="linkpage.htm" class="newslink1">Link 1</a></li>
    <li><a href="linkpage.htm" class="newslink2">Link 2</a></li>
    <li><a href="linkpage.htm" class="newslink3">Link 3</a></li>
</ul>
</code>```

jquery

```<code>$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});
</code>```

答:
Here is a good example:

http://jsfiddle.net/maniator/tac3t/

JS:

```<code>$('a.newslink').live('mouseover', function() {
    $('img#storyimg').attr("src", $(this).attr('ref'));
});
</code>```

HTML:

```<code><img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="#" class="newslink" ref="1.jpg">Link 1</a></li>
    <li><a href="#" class="newslink" ref="2.jpg">Link 2</a></li>
    <li><a href="#" class="newslink" ref="3.jpg">Link 3</a></li>
</ul>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to turn the below jquery code into a function so i could add links to the list and not have to touch the jquery. I'm assuming I will have to put the image name into the  tag somewhere.

html code

Link 1

Link 2

Link 3

jquery

$('a.newslink1').bind('mouseover', function() {
    $('img#storyimg').attr("src", "1.png");
});
$('a.newslink2').bind('mouseover', function() {
    $('img#storyimg').attr("src", "2.png");
});
$('a.newslink3').bind('mouseover', function() {
    $('img#storyimg').attr("src", "3.png");
});

Body:
Here is a good example:

http://jsfiddle.net/maniator/tac3t/

JS:

$('a.newslink').live('mouseover', function() {
    $('img#storyimg').attr("src", $(this).attr('ref'));
});

HTML:

<img id="storyimg" src="1.png" alt="img" />
<ul class="sb_menu">
    <li><a href="#" class="newslink" ref="1.jpg">Link 1</a></li>
    <li><a href="#" class="newslink" ref="2.jpg">Link 2</a></li>
    <li><a href="#" class="newslink" ref="3.jpg">Link 3</a></li>
</ul>


问:
How to format ZonedDateTime to yyyy-MM-ddZ
I need to turn ZonedDateTime to XML Date data type, of format yyyy-MM-ddZ. For example: 2020-02-14Z. I try to use DateTimeFormatter.ofPattern("yyyy-MM-ddZ") but the output is: 2020-02-14+0000. Which DateTimeFormatter pattern should I use to get the desired result?

答:
You should use DateTimeFormatter.ofPattern("yyyy-MM-dd'Z'"). Here is what i got:

```<code>LocalDate localDate = LocalDate.now();
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.of("EST5EDT"));
System.out.println("Not formatted:" + zonedDateTime);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'Z'");
System.out.println("Formatted:" + formatter.format(zonedDateTime));
</code>```

Not formatted:2020-02-14T00:00-05:00[EST5EDT]

Formatted:2020-02-14Z

Body:
You should use DateTimeFormatter.ofPattern("yyyy-MM-dd'Z'"). Here is what i got:

LocalDate localDate = LocalDate.now();
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.of("EST5EDT"));
System.out.println("Not formatted:" + zonedDateTime);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'Z'");
System.out.println("Formatted:" + formatter.format(zonedDateTime));

Not formatted:2020-02-14T00:00-05:00[EST5EDT]

Formatted:2020-02-14Z


问:
React - Add query string via text input on change
I have a simple text input and I need to pass a query string to the URL from that input value but I am not sure how to do it.

Here's a sample code
https://codesandbox.io/s/ecstatic-shadow-4nxlu

答:
I think you can pass the input value to URL something like this. Hope this helps

https://codesandbox.io/s/eager-haze-o8hj9

```<code>import "./styles.css";

export default function App() {
  const handleChange = e => {
    const inputValueToUrl = encodeURI(e.target.value);
    window.location.href = inputValueToUrl
    console.log(e.target.value);
  };

  // This is how I am currently using in my app
  // Note: I am passing ids as props from the parent component.

  // const AUUrl = `/about/user?ids=${ids}`;
  // const endCodeAUUrl = encodeURI(AUUrl);
  // const viewUserClick = () => {
  //   if (ids.length) {
  //    window.location.href = endCodedAUUrl;
  //   }
  // };

  return (
    <div className="App">
      <label>Simple Text Inpunt</label>
      <br />
      <br />
      <input type="text" onChange={handleChange} />
    </div>
  );
}
</code>```

Body:
I think you can pass the input value to URL something like this. Hope this helps

https://codesandbox.io/s/eager-haze-o8hj9

import "./styles.css";

export default function App() {
  const handleChange = e => {
    const inputValueToUrl = encodeURI(e.target.value);
    window.location.href = inputValueToUrl
    console.log(e.target.value);
  };

  // This is how I am currently using in my app
  // Note: I am passing ids as props from the parent component.

  // const AUUrl = `/about/user?ids=${ids}`;
  // const endCodeAUUrl = encodeURI(AUUrl);
  // const viewUserClick = () => {
  //   if (ids.length) {
  //    window.location.href = endCodedAUUrl;
  //   }
  // };

  return (
    <div className="App">
      <label>Simple Text Inpunt</label>
      <br />
      <br />
      <input type="text" onChange={handleChange} />
    </div>
  );
}


问:
SwiftUI - Size of an UI element
How do I get the size (width/height) of an UI element after its been rendered and pass it back to the parent for re-rendering?

Example:
The parent view (ChatMessage) contains a RoundedRectangle on which a Text is placed from the child view (ChatMessageContent) - chat bubble style.

The issue is that I do not know the size of the Text when rendering the parent as the Text might have 5, 6, etc. lines depending on the length of the message text.

```<code>struct ChatMessage: View {

    @State var message: Message
    @State var messageHeight: CGFloat = 28

    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 8)
                .fill(Color.red).opacity(0.9)
                .frame(width: 480, height: self.messageHeight)
            ChatMessageContent(message: self.$message, messageHeight: self.$messageHeight)
                .frame(width: 480, height: self.messageHeight)
        }
    }
}

struct ChatMessageContent: View {

    @Binding var message: Message
    @Binding var messageHeight: CGFloat

    var body: some View {
        GeometryReader { geometry in
            Text(self.message.message)
                .lineLimit(nil)
                .multilineTextAlignment(.center)
                .onAppear {self.messageHeight = geometry.size.height; print(geometry.size.height}
        }
    }
}
</code>```

In the provided example, the messageHeight stays at 28 and does not get adjusted on the parent.    I'd want the messageHeight to change to the actual height of the Text element depending on how many lines of text it displays.

E.g. two lines -> messageHeight = 42, three lines -> messageHeight = 56.

How do I get the actual size of an UI Element (in this case a Text), as GeometryReader does not appear to do the trick? It also reads geometry.size.height = 28 (that gets passed from the parent view).

答:
First, it's worth understanding that in the case of filling a RoundedRectangle behind a Text, you don't need to measure the text or send the size up the view hierarchy. You can configure it to choose a height that fits its content exactly. Then add the RoundedRectangle using the .background modifier. Example:

```<code>import SwiftUI
import PlaygroundSupport

let message = String(NotificationCenter.default.debugDescription.prefix(300))
PlaygroundPage.current.setLiveView(
    Text(message)
        .fixedSize(horizontal: false, vertical: true)
        .padding(12)
        .frame(width: 480)
        .background(
            RoundedRectangle(cornerRadius: 8)
                .fill(Color.red.opacity(0.9))
    )
    .padding(12)
)
</code>```

Result:

Okay, but sometimes you really do need to measure a view and pass its size up the hierarchy. In SwiftUI, a view can send information up the hierarchy in something called a “preference”. Apple hasn't thoroughly documented the preference system yet, but some people have figured it out. In particular, kontiki has described it starting with this article at swiftui-lab. (Every article at swiftui-lab is great.)

So let's make up an example where we really do need to use a preference. ConversationView shows a list of messages, each one labeled with its sender:

```<code>struct Message {
    var sender: String
    var body: String
}

struct MessageView: View {
    var message: Message
    var body: some View {
        HStack(alignment: .bottom, spacing: 3) {
            Text(message.sender + ":").padding(2)
            Text(message.body)
                .fixedSize(horizontal: false, vertical: true).padding(6)
                .background(Color.blue.opacity(0.2))
        }
    }
}

struct ConversationView: View {
    var messages: [Message]
    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            ForEach(messages.indices) { i in
                MessageView(message: self.messages[i])
            }
        }
    }
}

let convo: [Message] = [
    .init(sender: "Peanutsmasher", body: "How do I get the size (width/height) of an UI element after its been rendered and pass it back to the parent for re-rendering?"),
    .init(sender: "Rob", body: "First, it's worth understanding blah blah blah…"),
]

PlaygroundPage.current.setLiveView(
    ConversationView(messages: convo)
        .frame(width: 480)
        .padding(12)
        .border(Color.black)
        .padding(12)
)
</code>```

It looks like this:

We'd really like to have the left edges of those message bubbles aligned. That means we need to make the sender Texts have the same width. We'll do it by extending View with a new modifier, .equalWidth(). We'll apply the modifier to the sender Text like this:

```<code>struct MessageView: View {
    var message: Message
    var body: some View {
        HStack(alignment: .bottom, spacing: 3) {
            Text(message.sender + ":").padding(2)
                .equalWidth(alignment: .trailing) // <-- THIS IS THE NEW MODIFIER
            Text(message.body)
                .fixedSize(horizontal: false, vertical: true).padding(6)
                .background(Color.blue.opacity(0.2))
        }
    }
}
</code>```

And up in ConversationView, we'll define the “domain” of the equal-width views using another new modifier, .equalWidthHost().

```<code>struct ConversationView: View {
    var messages: [Message]
    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            ForEach(messages.indices) { i in
                MessageView(message: self.messages[i])
            }
        } //
            .equalWidthHost() // <-- THIS IS THE NEW MODIFIER
    }
}
</code>```

Before we can implement these modifiers, we need to define a PreferenceKey (which we will use to pass the widths up the view hierarchy from the Texts to the host) and an EnvironmentKey (which we will use to pass the chosen width down from the host to the Texts).

A type conforms to PreferenceKey by defining a defaultValue for the preference, and a method for combining two values. Here's ours:

```<code>struct EqualWidthKey: PreferenceKey {
    static var defaultValue: CGFloat? { nil }

    static func reduce(value: inout CGFloat?, nextValue: () -> CGFloat?) {
        switch (value, nextValue()) {
        case (_, nil): break
        case (nil, let next): value = next
        case (let a?, let b?): value = max(a, b)
        }
    }
}
</code>```

A type conforms to EnvironmentKey by defining a defaultValue. Since EqualWidthKey already does that, we can reuse our PreferenceKey as an EnvironmentKey:

```<code>extension EqualWidthKey: EnvironmentKey { }
</code>```

We also need to add an accessor to EnvironmentValues:

```<code>extension EnvironmentValues {
    var equalWidth: CGFloat? {
        get { self[EqualWidthKey.self] }
        set { self[EqualWidthKey.self] = newValue }
    }
}
</code>```

Now we can implement a ViewModifier that sets the preference to the width of its content, and applies the environment width to its content:

```<code>struct EqualWidthModifier: ViewModifier {
    var alignment: Alignment
    @Environment(\.equalWidth) var equalWidth

    func body(content: Content) -> some View {
        return content
            .background(
                GeometryReader { proxy in
                    Color.clear
                        .preference(key: EqualWidthKey.self, value: proxy.size.width)
                }
            )
            .frame(width: equalWidth, alignment: alignment)
    }
}
</code>```

By default, GeometryReader fills as much space as its parent gives it. That's not what we want to measure, so we put the GeometryReader in a background modifier, because a background view is always the size of its foreground content.

We can implement the equalWidth modifier on View using this EqualWidthModifier type:

```<code>extension View {
    func equalWidth(alignment: Alignment) -> some View {
        return self.modifier(EqualWidthModifier(alignment: alignment))
    }
}
</code>```

Next, we implement another ViewModifier for the host. This modifier puts the known width (if any) in the environment, and updates the known width when SwiftUI computes the final preference value:

```<code>struct EqualWidthHost: ViewModifier {
    @State var width: CGFloat? = nil

    func body(content: Content) -> some View {
        return content
            .environment(\.equalWidth, width)
            .onPreferenceChange(EqualWidthKey.self) { self.width = $0 }
    }
}
</code>```

Now we can implement the equalWidthHost modifier:

```<code>struct Message {
    var sender: String
    var body: String
}

struct MessageView: View {
    var message: Message
    var body: some View {
        HStack(alignment: .bottom, spacing: 3) {
            Text(message.sender + ":").padding(2)
            Text(message.body)
                .fixedSize(horizontal: false, vertical: true).padding(6)
                .background(Color.blue.opacity(0.2))
        }
    }
}

struct ConversationView: View {
    var messages: [Message]
    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            ForEach(messages.indices) { i in
                MessageView(message: self.messages[i])
            }
        }
    }
}

let convo: [Message] = [
    .init(sender: "Peanutsmasher", body: "How do I get the size (width/height) of an UI element after its been rendered and pass it back to the parent for re-rendering?"),
    .init(sender: "Rob", body: "First, it's worth understanding blah blah blah…"),
]

PlaygroundPage.current.setLiveView(
    ConversationView(messages: convo)
        .frame(width: 480)
        .padding(12)
        .border(Color.black)
        .padding(12)
)
</code>```0

And at last we can see the result:

You can find the final playground code in this gist.

Title: SwiftUI - Size of an UI element

Body:
How do I get the size (width/height) of an UI element after its been rendered and pass it back to the parent for re-rendering?

Example:
The parent view (ChatMessage) contains a RoundedRectangle on which a Text is placed from the child view (ChatMessageContent) - chat bubble style.

The issue is that I do not know the size of the Text when rendering the parent as the Text might have 5, 6, etc. lines depending on the length of the message text.

struct ChatMessage: View {

    @State var message: Message
    @State var messageHeight: CGFloat = 28

    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 8)
                .fill(Color.red).opacity(0.9)
                .frame(width: 480, height: self.messageHeight)
            ChatMessageContent(message: self.$message, messageHeight: self.$messageHeight)
                .frame(width: 480, height: self.messageHeight)
        }
    }
}

struct ChatMessageContent: View {

    @Binding var message: Message
    @Binding var messageHeight: CGFloat

    var body: some View {
        GeometryReader { geometry in
            Text(self.message.message)
                .lineLimit(nil)
                .multilineTextAlignment(.center)
                .onAppear {self.messageHeight = geometry.size.height; print(geometry.size.height}
        }
    }
}

In the provided example, the messageHeight stays at 28 and does not get adjusted on the parent.    I'd want the messageHeight to change to the actual height of the Text element depending on how many lines of text it displays.

E.g. two lines -> messageHeight = 42, three lines -> messageHeight = 56.

How do I get the actual size of an UI Element (in this case a Text), as GeometryReader does not appear to do the trick? It also reads geometry.size.height = 28 (that gets passed from the parent view).

Body:
First, it's worth understanding that in the case of filling a RoundedRectangle behind a Text, you don't need to measure the text or send the size up the view hierarchy. You can configure it to choose a height that fits its content exactly. Then add the RoundedRectangle using the .background modifier. Example:

import SwiftUI
import PlaygroundSupport

let message = String(NotificationCenter.default.debugDescription.prefix(300))
PlaygroundPage.current.setLiveView(
    Text(message)
        .fixedSize(horizontal: false, vertical: true)
        .padding(12)
        .frame(width: 480)
        .background(
            RoundedRectangle(cornerRadius: 8)
                .fill(Color.red.opacity(0.9))
    )
    .padding(12)
)

Result:

Okay, but sometimes you really do need to measure a view and pass its size up the hierarchy. In SwiftUI, a view can send information up the hierarchy in something called a “preference”. Apple hasn't thoroughly documented the preference system yet, but some people have figured it out. In particular, kontiki has described it starting with this article at swiftui-lab. (Every article at swiftui-lab is great.)

So let's make up an example where we really do need to use a preference. ConversationView shows a list of messages, each one labeled with its sender:

struct Message {
    var sender: String
    var body: String
}

struct MessageView: View {
    var message: Message
    var body: some View {
        HStack(alignment: .bottom, spacing: 3) {
            Text(message.sender + ":").padding(2)
            Text(message.body)
                .fixedSize(horizontal: false, vertical: true).padding(6)
                .background(Color.blue.opacity(0.2))
        }
    }
}

struct ConversationView: View {
    var messages: [Message]
    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            ForEach(messages.indices) { i in
                MessageView(message: self.messages[i])
            }
        }
    }
}

let convo: [Message] = [
    .init(sender: "Peanutsmasher", body: "How do I get the size (width/height) of an UI element after its been rendered and pass it back to the parent for re-rendering?"),
    .init(sender: "Rob", body: "First, it's worth understanding blah blah blah…"),
]

PlaygroundPage.current.setLiveView(
    ConversationView(messages: convo)
        .frame(width: 480)
        .padding(12)
        .border(Color.black)
        .padding(12)
)

It looks like this:

We'd really like to have the left edges of those message bubbles aligned. That means we need to make the sender Texts have the same width. We'll do it by extending View with a new modifier, .equalWidth(). We'll apply the modifier to the sender Text like this:

struct MessageView: View {
    var message: Message
    var body: some View {
        HStack(alignment: .bottom, spacing: 3) {
            Text(message.sender + ":").padding(2)
                .equalWidth(alignment: .trailing) // <-- THIS IS THE NEW MODIFIER
            Text(message.body)
                .fixedSize(horizontal: false, vertical: true).padding(6)
                .background(Color.blue.opacity(0.2))
        }
    }
}

And up in ConversationView, we'll define the “domain” of the equal-width views using another new modifier, .equalWidthHost().

struct ConversationView: View {
    var messages: [Message]
    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            ForEach(messages.indices) { i in
                MessageView(message: self.messages[i])
            }
        } //
            .equalWidthHost() // <-- THIS IS THE NEW MODIFIER
    }
}

Before we can implement these modifiers, we need to define a PreferenceKey (which we will use to pass the widths up the view hierarchy from the Texts to the host) and an EnvironmentKey (which we will use to pass the chosen width down from the host to the Texts).

A type conforms to PreferenceKey by defining a defaultValue for the preference, and a method for combining two values. Here's ours:

struct EqualWidthKey: PreferenceKey {
    static var defaultValue: CGFloat? { nil }

    static func reduce(value: inout CGFloat?, nextValue: () -> CGFloat?) {
        switch (value, nextValue()) {
        case (_, nil): break
        case (nil, let next): value = next
        case (let a?, let b?): value = max(a, b)
        }
    }
}

A type conforms to EnvironmentKey by defining a defaultValue. Since EqualWidthKey already does that, we can reuse our PreferenceKey as an EnvironmentKey:

extension EqualWidthKey: EnvironmentKey { }

We also need to add an accessor to EnvironmentValues:

extension EnvironmentValues {
    var equalWidth: CGFloat? {
        get { self[EqualWidthKey.self] }
        set { self[EqualWidthKey.self] = newValue }
    }
}

Now we can implement a ViewModifier that sets the preference to the width of its content, and applies the environment width to its content:

struct EqualWidthModifier: ViewModifier {
    var alignment: Alignment
    @Environment(\.equalWidth) var equalWidth

    func body(content: Content) -> some View {
        return content
            .background(
                GeometryReader { proxy in
                    Color.clear
                        .preference(key: EqualWidthKey.self, value: proxy.size.width)
                }
            )
            .frame(width: equalWidth, alignment: alignment)
    }
}

By default, GeometryReader fills as much space as its parent gives it. That's not what we want to measure, so we put the GeometryReader in a background modifier, because a background view is always the size of its foreground content.

We can implement the equalWidth modifier on View using this EqualWidthModifier type:

extension View {
    func equalWidth(alignment: Alignment) -> some View {
        return self.modifier(EqualWidthModifier(alignment: alignment))
    }
}

Next, we implement another ViewModifier for the host. This modifier puts the known width (if any) in the environment, and updates the known width when SwiftUI computes the final preference value:

struct EqualWidthHost: ViewModifier {
    @State var width: CGFloat? = nil

    func body(content: Content) -> some View {
        return content
            .environment(\.equalWidth, width)
            .onPreferenceChange(EqualWidthKey.self) { self.width = $0 }
    }
}

Now we can implement the equalWidthHost modifier:

extension View {
    func equalWidthHost() -> some View {
        return self.modifier(EqualWidthHost())
    }
}

And at last we can see the result:

You can find the final playground code in this gist.


问:
Why does InputStreamReader throw a NPE when reading from a jar?
I'm trying to iterate over the class files in a known directory using streams. The ultimate goal is to obtain the class names for all classes that exist in a particular package, then load the classes at runtime and use reflection to obtain the names & values of all the static constants. This works when I run the program from source on my machine, but when I run it as a jar the BufferedReader throws a NPE from both ready() and readLine(). Here's the code (with error handling & best practices omitted for brevity):

```<code>private void printClassNamesInPackage(final String strPackage) throws Exception {
    // The returned implementation of InputStream seems to be at fault
    final InputStream       packageStream = getClass().getClassLoader().getResourceAsStream( strPackage );
    final InputStreamReader streamReader  = new InputStreamReader( packageStream );
    final BufferedReader    reader        = new BufferedReader( streamReader );
    // Throws NPE from inside ready() - SEE STACKTRACE BELOW
    // reader.ready()
    String strLine;
    // Throws NPE from inside readLine() -  SEE STACKTRACE BELOW
    while ( null != (strLine = reader.readLine()) ) {
        System.out.println( strLine );
    }
}
</code>```

The stacktrace from reader.ready():

```<code>java.lang.NullPointerException
    at java.io.FilterInputStream.available(FilterInputStream.java:142)
    at sun.nio.cs.StreamDecoder.inReady(StreamDecoder.java:343)
    at sun.nio.cs.StreamDecoder.implReady(StreamDecoder.java:351)
    at sun.nio.cs.StreamDecoder.ready(StreamDecoder.java:165)
    at java.io.InputStreamReader.ready(InputStreamReader.java:178)
    at java.io.BufferedReader.ready(BufferedReader.java:436)
</code>```

The stacktrace from reader.readLine():

```<code>java.lang.NullPointerException
    at java.io.FilterInputStream.read(FilterInputStream.java:116)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
</code>```

Stepping through the execution reveals the following InputStream implementations:

From source: java.io.ByteArrayInputStream

From jar: sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream

Looking further into JarURLInputStream I find that the inherited (from FilterInputStream) field InputStream in is null, which leads to the resulting NPE.

Unfortunately, that's as deep as I was able to get in the debugger.

Any ideas on how to properly do this? What am I missing or doing wrong? Thank you!

答:
Folders don't return an InputStream with some list of all files or something. Use JarInputStream to extract the JAR programmatically. You can find an example here. For reference, here's a slight modified extract of relevance:

```<code>public static List<String> getClassNamesInPackage(String jarName, String packageName) throws IOException {
    JarInputStream jarFile = new JarInputStream(new FileInputStream(jarName));
    packageName = packageName.replace(".", "/");
    List<String> classes = new ArrayList<String>();

    try {
        for (JarEntry jarEntry; (jarEntry = jarFile.getNextJarEntry()) != null;) {
            if ((jarEntry.getName().startsWith(packageName)) && (jarEntry.getName().endsWith(".class"))) {
                classes.add(jarEntry.getName().replace("/", "."));
            }
        }
    } finally {
        jarFile.close();
    }

    return classes;
}
</code>```

Body:
I'm trying to iterate over the class files in a known directory using streams. The ultimate goal is to obtain the class names for all classes that exist in a particular package, then load the classes at runtime and use reflection to obtain the names & values of all the static constants. This works when I run the program from source on my machine, but when I run it as a jar the BufferedReader throws a NPE from both ready() and readLine(). Here's the code (with error handling & best practices omitted for brevity):

private void printClassNamesInPackage(final String strPackage) throws Exception {
    // The returned implementation of InputStream seems to be at fault
    final InputStream       packageStream = getClass().getClassLoader().getResourceAsStream( strPackage );
    final InputStreamReader streamReader  = new InputStreamReader( packageStream );
    final BufferedReader    reader        = new BufferedReader( streamReader );
    // Throws NPE from inside ready() - SEE STACKTRACE BELOW
    // reader.ready()
    String strLine;
    // Throws NPE from inside readLine() -  SEE STACKTRACE BELOW
    while ( null != (strLine = reader.readLine()) ) {
        System.out.println( strLine );
    }
}

The stacktrace from reader.ready():

java.lang.NullPointerException
    at java.io.FilterInputStream.available(FilterInputStream.java:142)
    at sun.nio.cs.StreamDecoder.inReady(StreamDecoder.java:343)
    at sun.nio.cs.StreamDecoder.implReady(StreamDecoder.java:351)
    at sun.nio.cs.StreamDecoder.ready(StreamDecoder.java:165)
    at java.io.InputStreamReader.ready(InputStreamReader.java:178)
    at java.io.BufferedReader.ready(BufferedReader.java:436)

The stacktrace from reader.readLine():

java.lang.NullPointerException
    at java.io.FilterInputStream.read(FilterInputStream.java:116)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)

Stepping through the execution reveals the following InputStream implementations:

From source: java.io.ByteArrayInputStream

From jar: sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream

Looking further into JarURLInputStream I find that the inherited (from FilterInputStream) field InputStream in is null, which leads to the resulting NPE.

Unfortunately, that's as deep as I was able to get in the debugger.

Any ideas on how to properly do this? What am I missing or doing wrong? Thank you!

Body:
Folders don't return an InputStream with some list of all files or something. Use JarInputStream to extract the JAR programmatically. You can find an example here. For reference, here's a slight modified extract of relevance:

public static List<String> getClassNamesInPackage(String jarName, String packageName) throws IOException {
    JarInputStream jarFile = new JarInputStream(new FileInputStream(jarName));
    packageName = packageName.replace(".", "/");
    List<String> classes = new ArrayList<String>();

    try {
        for (JarEntry jarEntry; (jarEntry = jarFile.getNextJarEntry()) != null;) {
            if ((jarEntry.getName().startsWith(packageName)) && (jarEntry.getName().endsWith(".class"))) {
                classes.add(jarEntry.getName().replace("/", "."));
            }
        }
    } finally {
        jarFile.close();
    }

    return classes;
}


问:
Display data in nice format in Python for elementary classroom project
I am working on a project to use in an elementary school where teachers and students will submit a list of adjectives and nouns that we will then use in a creative LEGO build challenge each week.

I am trying to learn python so please bear with me. I created a program asking people to submit 26 adjectives and 10 nouns. I want to take the screenshot and use as a the guide for the kids to build with.

I am not sure how to create a table or other structure to display the information all on one screen and more readable.

I would love any help! My code is below.

```<code>print("Thank you for helping with a creative LEGO project")
print("Please remember to keep words school safe and readable for elementary students")

adj1 = input("Give me a adjective ")
adj2 = input("Give me a adjective ")
adj3 = input("Give me a adjective ")
adj4 = input("Give me a adjective ")
adj5 = input("Give me a adjective ")
adj6 = input("Give me a adjective ")
adj7 = input("Give me a adjective ")
adj8 = input("Give me a adjective ")
adj9 = input("Give me a adjective ")
adj10 = input("Give me a adjective ")
adj11 = input("Give me a adjective ")
adj12 = input("Give me a adjective ")
adj13 = input("Give me a adjective ")
adj14 = input("Give me a adjective ")
adj15 = input("Give me a adjective ")
adj16 = input("Give me a adjective ")
adj17 = input("Give me a adjective ")
adj18 = input("Give me a adjective ")
adj19 = input("Give me a adjective ")
adj20 = input("Give me a adjective ")
adj21 = input("Give me a adjective ")
adj22 = input("Give me a adjective ")
adj23 = input("Give me a adjective ")
adj24 = input("Give me a adjective ")
adj25 = input("Give me a adjective ")
adj26 = input("Give me a adjective ")

print("Nice job coming up with all of those adjectives")
print("Now we are moving on to nouns")
print("Here we go!")

noun1 = input("Give me a noun ")
noun2 = input("Give me a noun ")
noun3 = input("Give me a noun ")
noun4 = input("Give me a noun ")
noun5 = input("Give me a noun ")
noun6 = input("Give me a noun ")
noun7 = input("Give me a noun ")
noun8 = input("Give me a noun ")
noun9 = input("Give me a noun ")
noun10 = input("Give me a noun ")

print("A = " + adj1)
print("B = " + adj2)
print("C = " + adj3)
print("D = " + adj4)
print("E = " + adj5)
print("F = " + adj6)
print("G = " + adj7)
print("H = " + adj8)
print("I = " + adj9)
print("J = " + adj10)
print("K = " + adj11)
print("L = " + adj12)
print("M = " + adj13)
print("N = " + adj14)
print("O = " + adj15)
print("P = " + adj16)
print("Q = " + adj17)
print("R = " + adj18)
print("S = " + adj19)
print("T = " + adj20)
print("U = " + adj21)
print("V = " + adj22)
print("W = " + adj23)
print("X = " + adj24)
print("Y = " + adj25)
print("Z = " + adj26)

print("1-3 = " + noun1)
print("4-6 = " + noun2)
print("7-9 = " + noun3)
print("10-12 = " + noun4)
print("13-15 = " + noun5)
print("16-18 = " + noun6)
print("19-21 = " + noun7)
print("22-25 = " + noun8)
print("26-28 = " + noun9)
print("29-31 = " + noun10)
</code>```

答:
First you can synthetize your code (in fact you can ever more condensate that below with intentions lists) :

```<code>adjectives_list = []
for ka in range(0,26):
     print(" Give me an adjective ")
     adjectives_list.append(input())
nouns_list = []
for kn in range(0,10):
    print(" Give me a noun ")
    nouns_list.append(input())
</code>```

After it's not so clear what you're trying to do for me. If it's possible you have some data manipulation, pandas library can be a good option. If it's just about printing, it's a matter of tast, but I would a write a function doing the job, maybe from a class representing the problem you're working on, if necessary.

Body:
I am working on a project to use in an elementary school where teachers and students will submit a list of adjectives and nouns that we will then use in a creative LEGO build challenge each week.

I am trying to learn python so please bear with me. I created a program asking people to submit 26 adjectives and 10 nouns. I want to take the screenshot and use as a the guide for the kids to build with.

I am not sure how to create a table or other structure to display the information all on one screen and more readable.

I would love any help! My code is below.

print("Thank you for helping with a creative LEGO project")
print("Please remember to keep words school safe and readable for elementary students")

adj1 = input("Give me a adjective ")
adj2 = input("Give me a adjective ")
adj3 = input("Give me a adjective ")
adj4 = input("Give me a adjective ")
adj5 = input("Give me a adjective ")
adj6 = input("Give me a adjective ")
adj7 = input("Give me a adjective ")
adj8 = input("Give me a adjective ")
adj9 = input("Give me a adjective ")
adj10 = input("Give me a adjective ")
adj11 = input("Give me a adjective ")
adj12 = input("Give me a adjective ")
adj13 = input("Give me a adjective ")
adj14 = input("Give me a adjective ")
adj15 = input("Give me a adjective ")
adj16 = input("Give me a adjective ")
adj17 = input("Give me a adjective ")
adj18 = input("Give me a adjective ")
adj19 = input("Give me a adjective ")
adj20 = input("Give me a adjective ")
adj21 = input("Give me a adjective ")
adj22 = input("Give me a adjective ")
adj23 = input("Give me a adjective ")
adj24 = input("Give me a adjective ")
adj25 = input("Give me a adjective ")
adj26 = input("Give me a adjective ")

print("Nice job coming up with all of those adjectives")
print("Now we are moving on to nouns")
print("Here we go!")

noun1 = input("Give me a noun ")
noun2 = input("Give me a noun ")
noun3 = input("Give me a noun ")
noun4 = input("Give me a noun ")
noun5 = input("Give me a noun ")
noun6 = input("Give me a noun ")
noun7 = input("Give me a noun ")
noun8 = input("Give me a noun ")
noun9 = input("Give me a noun ")
noun10 = input("Give me a noun ")

print("A = " + adj1)
print("B = " + adj2)
print("C = " + adj3)
print("D = " + adj4)
print("E = " + adj5)
print("F = " + adj6)
print("G = " + adj7)
print("H = " + adj8)
print("I = " + adj9)
print("J = " + adj10)
print("K = " + adj11)
print("L = " + adj12)
print("M = " + adj13)
print("N = " + adj14)
print("O = " + adj15)
print("P = " + adj16)
print("Q = " + adj17)
print("R = " + adj18)
print("S = " + adj19)
print("T = " + adj20)
print("U = " + adj21)
print("V = " + adj22)
print("W = " + adj23)
print("X = " + adj24)
print("Y = " + adj25)
print("Z = " + adj26)

print("1-3 = " + noun1)
print("4-6 = " + noun2)
print("7-9 = " + noun3)
print("10-12 = " + noun4)
print("13-15 = " + noun5)
print("16-18 = " + noun6)
print("19-21 = " + noun7)
print("22-25 = " + noun8)
print("26-28 = " + noun9)
print("29-31 = " + noun10)

Body:
First you can synthetize your code (in fact you can ever more condensate that below with intentions lists) :

adjectives_list = []
for ka in range(0,26):
     print(" Give me an adjective ")
     adjectives_list.append(input())
nouns_list = []
for kn in range(0,10):
    print(" Give me a noun ")
    nouns_list.append(input())

After it's not so clear what you're trying to do for me. If it's possible you have some data manipulation, pandas library can be a good option. If it's just about printing, it's a matter of tast, but I would a write a function doing the job, maybe from a class representing the problem you're working on, if necessary.


问:
Pass ID to Modal form box on page
I have read a bunch of SO posts on how to do this but I am unable to get it to work with my script.  Maybe someone smarter than me can see what Im missing here.

I am trying to pass the ID to the modal box. The user will then input notes and it will update in the DB.

```<code>echo "<td>" . $Agent_ID. "<br><a href='' class='btn btn-default btn-rounded mb-4' data-note-id='". $id . "' data-toggle='modal' id='" . $id . "' data-target='#notes'>Add Notes</a></td>";
</code>```

My Modal

```<code><div class="modal fade" id="notes" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
  aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Notes</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <form method="post">
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <i class="fas fa-envelope prefix grey-text"></i>

          <textarea name="note" value="" placeholder="Type Your Note Here" id="defaultForm-email" class="form-control validate"></textarea>

        </div>
      </div>
      <div class="modal-footer d-flex justify-content-center">
        <button type="submit" class="btn btn-default">Submit</button>
      </div>
    </form>

    </div>
  </div>
</div>

</code>```

My JS

```<code><script>

$('#notes').on('show.bs.modal', function(e) {
    var note = $(e.relatedTarget).data('note-id');
    $(e.currentTarget).find('input[name="note"]').val(note);
});

</script>
</code>```

I tried this as well as you can see its very similar
http://jsfiddle.net/k7FC2/

答:
You can do:

```<code>var thisID
$('a').click(e=>{
  thisID = e.currentTarget.id
   console.log(thisID)
})
</code>```

Now, you can use the id variable anywhere in your code (thisID)

Title: Pass ID to Modal form box on page

Body:
I have read a bunch of SO posts on how to do this but I am unable to get it to work with my script.  Maybe someone smarter than me can see what Im missing here.

I am trying to pass the ID to the modal box. The user will then input notes and it will update in the DB.

echo "" . $Agent_ID. "
Add Notes	";

My Modal

Notes

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

      <form method="post">

          <textarea name="note" value="" placeholder="Type Your Note Here" id="defaultForm-email" class="form-control validate"></textarea>

        <button type="submit" class="btn btn-default">Submit</button>

    </form>

My JS

I tried this as well as you can see its very similar
http://jsfiddle.net/k7FC2/

Body:
You can do:

var thisID
$('a').click(e=>{
  thisID = e.currentTarget.id
   console.log(thisID)
})

Now, you can use the id variable anywhere in your code (thisID)


问:
How does sizeof work for int types?
I have a small program which compares </p>

<p>(1) sizeof,
(2) numeric_limits::digits,
(3) and the results of a loop </p>

<p>in an effort to make sure they all report the same thing regarding the size of the "int types" on any C++ implementation.  However because I don't know about the internals of sizeof, I have to wonder if it is just reporting numeric_limits::digits.  Thanks </p>

答:
Most likely sizeof() on most compilers causes the compiler to look the given type (or object's type) up in its internal type table and insert a literal for that type's defined size into the code it generates. This would happen at compile time, not runtime.

To answer the question in the comments, there isn't any language-defined access to the compiler's internals in C++ (outside of things like sizeof() itself, of course). The only similar language I know of that lets you do stuff like that is Ada, which provides ASIS for writing compiler-independent code analysis tools.

Title: How does sizeof work for int types?

Body:
I have a small program which compares

(1) sizeof,
(2) numeric_limits::digits,
(3) and the results of a loop

in an effort to make sure they all report the same thing regarding the size of the "int types" on any C++ implementation.  However because I don't know about the internals of sizeof, I have to wonder if it is just reporting numeric_limits::digits.  Thanks


问:
Web service differences between REST and RPC
I have a web service that accepts JSON parameters and have specific URLs for methods, e.g.:

```<code>http://IP:PORT/API/getAllData?p={JSON}
</code>```

This is definitely not REST as it is not stateless. It takes cookies into account and has its own session.

Is it RPC? What is the difference between RPC and REST?

答:
There are bunch of good answers here. I would still refer you to this google blog as it does a really good job of discussing the differences between RPC & REST and captures something that I didn't read in any of the answers here.

I would quote a paragraph from the same link that stood out to me:

REST itself is a description of the design principles that underpin HTTP and the world-wide web. But because HTTP is the only commercially important REST API, we can mostly avoid discussing REST and just focus on HTTP. This substitution is useful because there is a lot of confusion and variability in what people think REST means in the context of APIs, but there is much greater clarity and agreement on what HTTP itself is. The HTTP model is the perfect inverse of the RPC model—in the RPC model, the addressable units are procedures, and the entities of the problem domain are hidden behind the procedures. In the HTTP model, the addressable units are the entities themselves and the behaviors of the system are hidden behind the entities as side-effects of creating, updating, or deleting them.

Body:
I have a web service that accepts JSON parameters and have specific URLs for methods, e.g.:

http://IP:PORT/API/getAllData?p={JSON}

This is definitely not REST as it is not stateless. It takes cookies into account and has its own session.

Is it RPC? What is the difference between RPC and REST?


问:
Find count of each consecutive characters
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

```<code>str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)
</code>```

答:
Regular expression to the rescue ?</p>

```<code>var myString = "aaaabbccaa";

var pattern = @"(\w)\1*";
var regExp = new Regex(pattern);
var matches = regExp.Matches(myString);

var tab = matches.Select(x => String.Format("{0}{1}", x.Value.First(), x.Value.Length));
var result = String.Join("", tab);
</code>```

Body:
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)

Body:
Regular expression to the rescue ?

var myString = "aaaabbccaa";

var pattern = @"(\w)\1*";
var regExp = new Regex(pattern);
var matches = regExp.Matches(myString);

var tab = matches.Select(x => String.Format("{0}{1}", x.Value.First(), x.Value.Length));
var result = String.Join("", tab);


问:
change background color in another blade using variable in laravel blade
I'm working with Laravel right now and can't figure out how I can apply different background colors on page that i want ..

Actually, I want to change the background of my page which I convert to PDF

here is my route

```<code>Route::get('/form/{slug}/pdf/{id}/{color?}', ['as' => 'generate.pdfColor', 'uses' => 'OriginController@changeColor']);
</code>```

here is my function of the controller

```<code>public function changeColor(Request $request, $slug, $id = null, $myColor){
    $colors=[
        1=> ['color'=>'#1e90ff'],
        2=> ['color'=>'#2ecc71'],
        3=> ['color'=>'#e84118'],
        4=> ['color'=>'#222D32'],
        5=> ['color'=>'#ffcccc'],
        6=> ['color'=>'#910000']
    ];
    return  view('layouts.modules.student_pdf',['data'=>$colors[$myColor]]);
}
</code>```

here is my link to sending parameter of the color
in this example  1 is (#1e90ff)

```<code><a  target="_blank" href='<?php echo e(route('generate.pdfColor', ['slug' => 'student', 'id' => '56', 'color' => '1'])); ?>'>
    <i class='fa fa-file-pdf-o 2x avatar'></i>
     change color
</a>
</code>```

and this my page cv_pdf.blade.php that i want to change the bg

```<code> <!-- left -->
    <div class="left" id="left_pdf" style="background:{{data['color']}}  ; " >
     ..............
    </div>
</code>```

答:
change function changeColor like below:

```<code>public function changeColor(Request $request, $slug, $id = null, $myColor){
   //just change return line like below
   return  view('layouts.modules.student_pdf')->with(['color' => $colors[$myColor]['color']]);
}
</code>```

and in page_cv_pdf.blade.php do as follows:

```<code><div class="left" id="left_pdf" style="background-color:{{$color}};" >
      ..............
</div>
</code>```

Body:
I'm working with Laravel right now and can't figure out how I can apply different background colors on page that i want ..

Actually, I want to change the background of my page which I convert to PDF

here is my route

Route::get('/form/{slug}/pdf/{id}/{color?}', ['as' => 'generate.pdfColor', 'uses' => 'OriginController@changeColor']);

here is my function of the controller

public function changeColor(Request $request, $slug, $id = null, $myColor){
    $colors=[
        1=> ['color'=>'#1e90ff'],
        2=> ['color'=>'#2ecc71'],
        3=> ['color'=>'#e84118'],
        4=> ['color'=>'#222D32'],
        5=> ['color'=>'#ffcccc'],
        6=> ['color'=>'#910000']
    ];
    return  view('layouts.modules.student_pdf',['data'=>$colors[$myColor]]);
}

here is my link to sending parameter of the color
in this example  1 is (#1e90ff)

<a  target="_blank" href='<?php echo e(route('generate.pdfColor', ['slug' => 'student', 'id' => '56', 'color' => '1'])); ?>'>

     change color

and this my page cv_pdf.blade.php that i want to change the bg

     ..............

Body:
change function changeColor like below:

public function changeColor(Request $request, $slug, $id = null, $myColor){
   //just change return line like below
   return  view('layouts.modules.student_pdf')->with(['color' => $colors[$myColor]['color']]);
}

and in page_cv_pdf.blade.php do as follows:

<div class="left" id="left_pdf" style="background-color:{{$color}};" >
      ..............
</div>


问:
Scala spark: Efficient check if condition is matched anywhere?
What I want is roughly equivalent to

```<code>df.where(<condition>).count() != 0
</code>```

But I'm pretty sure it's not quite smart enough to stop once it finds any such violation. I would expect some sort of aggregator to be able to do this, but I haven't found one? I could do it with a max and some sort of conversion, but again I don't think it would necessarily know to quit (not being specific to bool, I'm not sure if understands no value is larger than true).

More specifically, I want to check if a column contains only a single element. Right now my best idea is to do this is by grabbing the first value and comparing everything.

答:
I would try this option, it should be much faster:

```<code>df.where(<condition>).head(1).isEmpty
</code>```

You can also try to define your conditions on a row together with scala's exists (which stops at the first occurence of true):

```<code>df.mapPartitions(rows => if(rows.exists(row => <condition>)) Iterator(1) else Iterator.empty).isEmpty
</code>```

At the end you should benchmark the alternatives

Body:
What I want is roughly equivalent to

df.where(<condition>).count() != 0

But I'm pretty sure it's not quite smart enough to stop once it finds any such violation. I would expect some sort of aggregator to be able to do this, but I haven't found one? I could do it with a max and some sort of conversion, but again I don't think it would necessarily know to quit (not being specific to bool, I'm not sure if understands no value is larger than true).

More specifically, I want to check if a column contains only a single element. Right now my best idea is to do this is by grabbing the first value and comparing everything.

Body:
I would try this option, it should be much faster:

df.where(<condition>).head(1).isEmpty

You can also try to define your conditions on a row together with scala's exists (which stops at the first occurence of true):

df.mapPartitions(rows => if(rows.exists(row => <condition>)) Iterator(1) else Iterator.empty).isEmpty

At the end you should benchmark the alternatives


问:
Custom HTTP Errors in IIS 7
I'm trying to handle 403 and 404 errors in my web app.  I have read MS instructions and applied on my server.  IIS7 manager effectively handles this by editing my web.config as:

```<code><httpRedirect enabled="false" destination="/MySite" httpResponseStatus="Temporary" />
   <httpErrors>
      <remove statusCode="404" subStatusCode="-1" />
      <remove statusCode="403" subStatusCode="-1" />
      <error statusCode="403" prefixLanguageFilePath="" path="/mySite/Error.aspx" responseMode="ExecuteURL" />
       <error statusCode="404" prefixLanguageFilePath="" path="/mySite/Error.aspx" responseMode="ExecuteURL" />
   </httpErrors>
</code>```

It does handle requests like http://www.mysite/fictiousURL.aspx but won't work on http://www.mysite/fictiousURLTest.html.  It seems to only be able to handle aspx requests.

I've also tried http://www.15seconds.com/issue/030102.htm by adding this configuration <customErrors mode="On" defaultRedirect="/mysite/error.aspx" /> in the system.web node.

Anyone know a)  Why is IIS7 only handling the aspx and b)  Anyone know how to handle universal requsts like http://www.mysite/fictiousURLTest.html?

Thanks, Bill N

答:
See my response given here:  IIS7 and HTTP status code handling

It looks like you may need to set

```<code>  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>
</code>```

Title: Custom HTTP Errors in IIS 7

Body:
I'm trying to handle 403 and 404 errors in my web app.  I have read MS instructions and applied on my server.  IIS7 manager effectively handles this by editing my web.config as:

<httpRedirect enabled="false" destination="/MySite" httpResponseStatus="Temporary" />
   <httpErrors>
      <remove statusCode="404" subStatusCode="-1" />
      <remove statusCode="403" subStatusCode="-1" />
      <error statusCode="403" prefixLanguageFilePath="" path="/mySite/Error.aspx" responseMode="ExecuteURL" />
       <error statusCode="404" prefixLanguageFilePath="" path="/mySite/Error.aspx" responseMode="ExecuteURL" />
   </httpErrors>

It does handle requests like http://www.mysite/fictiousURL.aspx but won't work on http://www.mysite/fictiousURLTest.html.  It seems to only be able to handle aspx requests.

I've also tried http://www.15seconds.com/issue/030102.htm by adding this configuration <customErrors mode="On" defaultRedirect="/mysite/error.aspx" /> in the system.web node.

Anyone know a)  Why is IIS7 only handling the aspx and b)  Anyone know how to handle universal requsts like http://www.mysite/fictiousURLTest.html?

Thanks, Bill N

Body:
See my response given here:  IIS7 and HTTP status code handling

It looks like you may need to set

  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>


问:
Apply filter to search in django
I want to search a user name in the database and list all the results of the search in another page.
In this page, on the listed results, I want to apply some filtering.
It sounds like a simple thing to do but I am having difficulties.
I am using django-filters.

in the home.html I have my search

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
<form action = {% url 'users:index' %} method="get">
    {% csrf_token %}

        <div class="d-flex justify-content-center">
            <div>
                <input class="form-control" type="text" name="search"
                       placeholder="Search a user...">
            </div>
            <div>
                <button class="btn btn-dark" type="submit" name="action">Search</button>
            </div>
        </div>
</form>
</body>
</html>
</code>```

The results are listed in index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Users App</title>
</head>
<body>

<form method="GET">
    {{ filter.form }}
    <button type="submit" >Search</button>
</form>
{% if filter.qs %}
    <ul>
    {% for user in filter.qs %}
        <li><a href="{% url 'users:detail' user.id %}">{{ user.name }}, {{ user.nationality }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No users available.</p>
{% endif %}
</body>
</html>
</code>```

now if I try to apply the filter off filter.form I get the error Cannot use None as a query value.
Here are the views.py:

```<code># Create your views here.
def home(request):
    return render(request, 'users/home.html')

class UserListView(ListView):
    model = User
    template_name = 'users/index.html'
    # queryset = User.objects.filter(name__icontains='Bruno') same as
    def get_queryset(self):  # new
        query = self.request.GET.get('search')
        return User.objects.filter(name__icontains=query)
    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = UserFilter(self.request.GET, queryset=self.get_queryset())
        return context

</code>```

urls.py

```<code>app_name = 'users'
urlpatterns = [
    path('home/', views.home, name='home'),
    path('', views.UserListView.as_view(), name='index'),
    path('<int:user_id>/', views.detail, name='detail'),
]

</code>```

filters.py

```<code>import django_filters as filters
from .models import User
class UserFilter(filters.FilterSet):
    class Meta:
        model = User
        fields = ('name', 'surname',)
</code>```

the problem is that after the search as been sent with a POST method, if I try to use again the UserListView view  the command self.request.GET.get('search') returns an empty object.

How can I filter on the results of the search? Is there a way to save the search query such that the filter is applied only on the searched items?

答:
If your results view also has the same filtering fields, then you can just pass again the previously used parameters to that view.

Something like this:

views.py

def results_view(request):
    results = []
    # Your search/filtering code here...
    query = request.GET.get('query')
    return render(request, 'results.html', {
        'results': results,
        'query': query
    })
```

<p><strong>results.html</strong></p>

<pre class="lang-html prettyprint-override"><code><form>
    <input name="query" value="{% if query %}{{ query }}{% endif %}" />
</form>
</code>```

Title: Apply filter to search in django

Body:
I want to search a user name in the database and list all the results of the search in another page.
In this page, on the listed results, I want to apply some filtering.
It sounds like a simple thing to do but I am having difficulties.
I am using django-filters.

in the home.html I have my search

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Home</title>

<form action = {% url 'users:index' %} method="get">
    {% csrf_token %}

                <input class="form-control" type="text" name="search"
                       placeholder="Search a user...">

                <button class="btn btn-dark" type="submit" name="action">Search</button>

</form>

The results are listed in index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Users App</title>

<form method="GET">
    {{ filter.form }}
    <button type="submit" >Search</button>
</form>
{% if filter.qs %}

    {% for user in filter.qs %}

{{ user.name }}, {{ user.nationality }}

    {% endfor %}

{% else %}

No users available.

{% endif %}

now if I try to apply the filter off filter.form I get the error Cannot use None as a query value.
Here are the views.py:

# Create your views here.
def home(request):
    return render(request, 'users/home.html')

class UserListView(ListView):
    model = User
    template_name = 'users/index.html'
    # queryset = User.objects.filter(name__icontains='Bruno') same as
    def get_queryset(self):  # new
        query = self.request.GET.get('search')
        return User.objects.filter(name__icontains=query)
    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = UserFilter(self.request.GET, queryset=self.get_queryset())
        return context

urls.py

app_name = 'users'
urlpatterns = [
    path('home/', views.home, name='home'),
    path('', views.UserListView.as_view(), name='index'),
    path('<int:user_id>/', views.detail, name='detail'),
]

filters.py

import django_filters as filters
from .models import User
class UserFilter(filters.FilterSet):
    class Meta:
        model = User
        fields = ('name', 'surname',)

the problem is that after the search as been sent with a POST method, if I try to use again the UserListView view  the command self.request.GET.get('search') returns an empty object.

How can I filter on the results of the search? Is there a way to save the search query such that the filter is applied only on the searched items?

Body:
If your results view also has the same filtering fields, then you can just pass again the previously used parameters to that view.

Something like this:

views.py

def results_view(request):
    results = []
    # Your search/filtering code here...
    query = request.GET.get('query')
    return render(request, 'results.html', {
        'results': results,
        'query': query
    })

results.html

<form>
    <input name="query" value="{% if query %}{{ query }}{% endif %}" />
</form>


问:
Android Emulator Can't Use WebCam as Camera
I'm using AVD to set up a device. End goal is to click on the camera app and it uses the laptop's webcam. I don't even care what device, target, etc. I have to use. I just want one that works, and I'm willing to start from scratch.

If I emulate the camera, it works. When I have the camera set to Webcam0 in the AVD setup, the red light next to the webcam turns on and this is the image I get:

EDIT: For whatever reason, it's working now. The only thing I've done since the last time I verified it wasn't working was open the Lenovo - Web Conferencing app and clicked to show my video image. Since then it has worked.

答: I was in a similar situation and the problem was also not in the Android emulator. I forgot to check the camera on my host system. (https://stackoverflow.com/a/60232825/11130103)</p>


问:
Can i use docking panel in Autodesk forge for both viewers?
Example on Photo

I have two viewers to compare models. I created a docking panel for properties, and I want this panel to float in two viewers. Is it possible and who will tell you how to do it?

答:
There are two options:

Option1:

Use the 'Autodesk.SplitScreen' extension, which will render up to 4 regions. You load it like this..

```<code>loadExtension('Autodesk.SplitScreen');
</code>```

This simple extension can set up to four cameras, and render four regions. By default, it's just two (left and right).  Here's the source code for how the core of it works, just in case you want to write your own...

https://autodeskviewer.com/viewers/latest/extensions/SplitScreen/SplitScreen.js

```<code>this.renderScenePart = function (scene) {

// Left
if (shouldRenderForViewport[0]) {
  this.renderer.setViewport(0, vpVertStart, vpWidth, vpHeight);
  this.context.renderScenePart.apply(this.context, arguments);
}

// Right
if (shouldRenderForViewport[1]) {
  this.renderer.setViewport(vpWidth, vpVertStart, vpWidth, vpHeight);
  this.context.renderScenePart.apply(this.context, arguments);
}

// Bottom left
if (shouldRenderForViewport[2]) {
  this.renderer.setViewport(0, 0, vpWidth, vpHeight);
  this.context.renderScenePart.apply(this.context, arguments);
}

// Bottom right
if (shouldRenderForViewport[3]) {
  this.renderer.setViewport(vpWidth, 0, vpWidth, vpHeight);
  this.context.renderScenePart.apply(this.context, arguments);
}

this.renderer.setViewport(0, 0, this.width, this.height);
this.renderer.enableViewportOnOffscreenTargets(false);
</code>```

Option2:

For something more advanced, and specific to just 2D, you could also try the 'Autodesk.Viewing.PixelCompare' extension.  Here's a blog post with much more detail and a demo...

BLOG: https://forge.autodesk.com/blog/compare-two-2d-documents-using-forge-viewer

Body:
There are two options:

Option1:

Use the 'Autodesk.SplitScreen' extension, which will render up to 4 regions. You load it like this..

loadExtension('Autodesk.SplitScreen');

This simple extension can set up to four cameras, and render four regions. By default, it's just two (left and right).  Here's the source code for how the core of it works, just in case you want to write your own...

https://autodeskviewer.com/viewers/latest/extensions/SplitScreen/SplitScreen.js

this.renderScenePart = function (scene) {

// Left
if (shouldRenderForViewport[0]) {
  this.renderer.setViewport(0, vpVertStart, vpWidth, vpHeight);
  this.context.renderScenePart.apply(this.context, arguments);
}

// Right
if (shouldRenderForViewport[1]) {
  this.renderer.setViewport(vpWidth, vpVertStart, vpWidth, vpHeight);
  this.context.renderScenePart.apply(this.context, arguments);
}

// Bottom left
if (shouldRenderForViewport[2]) {
  this.renderer.setViewport(0, 0, vpWidth, vpHeight);
  this.context.renderScenePart.apply(this.context, arguments);
}

// Bottom right
if (shouldRenderForViewport[3]) {
  this.renderer.setViewport(vpWidth, 0, vpWidth, vpHeight);
  this.context.renderScenePart.apply(this.context, arguments);
}

this.renderer.setViewport(0, 0, this.width, this.height);
this.renderer.enableViewportOnOffscreenTargets(false);

Option2:

For something more advanced, and specific to just 2D, you could also try the 'Autodesk.Viewing.PixelCompare' extension.  Here's a blog post with much more detail and a demo...

BLOG: https://forge.autodesk.com/blog/compare-two-2d-documents-using-forge-viewer


问:
An empty
 tag is automatically getting inserted, how do I get rid of it?
An empty

 tag is getting inserted automatically when the page is rendered, I'm not sure, how to get rid of it. Which is adding unwanted space on the webpage.

I'm not sure how I can get rid of it. I'm trying to set the margin-bottom for the
 to 0px, even that isn't getting applied as well.

I would be really thankful to anyone who could help me with fixing this issue.

Thanks in advance!

Here is the code which renders the HTML block:
The

 tag gets generated dynamically, but not sure, how it is getting generated from the code.

```<code>{% if job_detail.type != '' and job_detail.type is not None or job_detail.age_limit != '' and job_detail.age_limit is not None %}
     <hr />
     <div class="row">
     {% if job_detail.type != '' and job_detail.type is not None %}
       <div class="col-md-6">
         <h3 class="card-title topic-title">JOB TYPE</h3>
         <p class="card-text topic-text last-child">{{ job_detail.type|linebreaks }}</p>
       </div>
     {% endif %}
     {% if job_detail.age_limit != '' and job_detail.age_limit is not None %}
       <div class="col-md-6 mt-4 mt-sm-4 mt-md-0">
         <h3 class="card-title topic-title">AGE LIMIT</h3>
         <p class="card-text topic-text last-child">{{ job_detail.age_limit|linebreaks }}</p>
       </div>
     {% endif %}
     </div>
   {% endif %}
</code>```

答:
You can assign "display:none;" to this empty auto generated blank p tag. I would like to recommend to add a class parent element (.col-md-6) of child ".card-title" and then use p:last-child pseudo element to make it "display:none". It will solve your problem. I have written a snippet for you so that you will get better idea of this approach, but when you will try to implement it please add class as per mentioned on above lines. For the reference purpose add below snippet in the head section of your project : </p>

```<code><style type="text/css">
    .card.mt-2 .card-body.pt-3.pb-3 > .row > .col-md-6 p:last-child {
        display:none;
      }
 </style>
</code>```

Title: An empty <p> tag is automatically getting inserted, how do I get rid of it?

Body:
An empty

 tag is getting inserted automatically when the page is rendered, I'm not sure, how to get rid of it. Which is adding unwanted space on the webpage.

I'm not sure how I can get rid of it. I'm trying to set the margin-bottom for the
 to 0px, even that isn't getting applied as well.

I would be really thankful to anyone who could help me with fixing this issue.

Thanks in advance!

Here is the code which renders the HTML block:
The

 tag gets generated dynamically, but not sure, how it is getting generated from the code.

{% if job_detail.type != '' and job_detail.type is not None or job_detail.age_limit != '' and job_detail.age_limit is not None %}

     {% if job_detail.type != '' and job_detail.type is not None %}

JOB TYPE

{{ job_detail.type|linebreaks }}

     {% endif %}
     {% if job_detail.age_limit != '' and job_detail.age_limit is not None %}

AGE LIMIT

{{ job_detail.age_limit|linebreaks }}

     {% endif %}

   {% endif %}

Body:
You can assign "display:none;" to this empty auto generated blank p tag. I would like to recommend to add a class parent element (.col-md-6) of child ".card-title" and then use p:last-child pseudo element to make it "display:none". It will solve your problem. I have written a snippet for you so that you will get better idea of this approach, but when you will try to implement it please add class as per mentioned on above lines. For the reference purpose add below snippet in the head section of your project :

<style type="text/css">
    .card.mt-2 .card-body.pt-3.pb-3 > .row > .col-md-6 p:last-child {
        display:none;
      }
 </style>


问:
Comparing two sets for equality recursively?
I am pretty new to programming in general and am trying to construct a function that will take as input two sets, which can contain other sets (a (b c) d e (f g (h)), (a b c (d e f)) for example, and returns whether or not they are equal. I am working with scheme if that helps, but am really trying to just visualize how I could do it. Thanks for the help in advance</p>

答:
Two key points:
(a) test for matching type sameness of individual components
(b) test for matching values when you get to the "core" element values

Whatever programming language you use, if we look at a piece of the lists, eg, (a (b c)...) and (a b c ...), we'll note after we see "a" that each is of a different type. The first list follows "a" with a list while the second list follows a with another nonlist element. Languages will likely fail (signal an error of some sort) or else allow you to consider each of these different types similarly but usually provide a way to query the type.

In scheme (and I don't remember exactly), the first list has its car value be a and its cdr value be the list ( (b c) ...). The second list has a car value of a but the cdr returns the list (b c ...). These two cannot be the same unless the language offers a different view of "sameness".

This sort of testing for object type would be the first step to seeing if the lists are the same.

Next, we test the basic element values in corresponding locations within the already verified identical structures. We must traverse the structures the proper way (ie, dependent on the structure details).

The algorithm details of traversing depend on the programming language. Some languages provide more help than others in avoiding mistakes and in testing for sameness.

We can use recursive or iterative approaches. With scheme, and conceptually, recursive is the more natural.

Sample pseudo-code where both type and value are handled by the made up test =?

```<code>function f (l1, l2):
(=? car(l1) car(l2))
and
(f cdr(l1) cdr(l2))
</code>```

We note the recursion. What this does is that, if you get a simple element, it tests for eqality and returns that value. If that function was called directly, then that is the final answer, if it was called recursively, then it sends that answer back up the chain of function calls making some nested (f cdr(l1) cdr(l2)) return false or true and ultimately making the highest level call also return false or potentially still being able to return true (note the "and" requirement and how it works.. true comes only if every part is true, while false happens if any part is false). Similarly, if the function gets a list, then it tests the car part and "and"s this t/f value with whatever it gets when it calls itself again recursively on the rest of the list. Hence, this function handles both lists and nonlists in whatever intricate structure of sublists you feed it. [remember, we assumed that =? managed both the type and value checks, eg, so that (=? b '(b)) would be #f]

[Also, see http://cs.gettysburg.edu/~tneller/cs341/scheme-intro/exercises.html#Equivalence for what you might use to test equivalence.]

Body:
Two key points:
(a) test for matching type sameness of individual components
(b) test for matching values when you get to the "core" element values

Whatever programming language you use, if we look at a piece of the lists, eg, (a (b c)...) and (a b c ...), we'll note after we see "a" that each is of a different type. The first list follows "a" with a list while the second list follows a with another nonlist element. Languages will likely fail (signal an error of some sort) or else allow you to consider each of these different types similarly but usually provide a way to query the type.

In scheme (and I don't remember exactly), the first list has its car value be a and its cdr value be the list ( (b c) ...). The second list has a car value of a but the cdr returns the list (b c ...). These two cannot be the same unless the language offers a different view of "sameness".

This sort of testing for object type would be the first step to seeing if the lists are the same.

Next, we test the basic element values in corresponding locations within the already verified identical structures. We must traverse the structures the proper way (ie, dependent on the structure details).

The algorithm details of traversing depend on the programming language. Some languages provide more help than others in avoiding mistakes and in testing for sameness.

We can use recursive or iterative approaches. With scheme, and conceptually, recursive is the more natural.

Sample pseudo-code where both type and value are handled by the made up test =?

function f (l1, l2):
(=? car(l1) car(l2))
and
(f cdr(l1) cdr(l2))

We note the recursion. What this does is that, if you get a simple element, it tests for eqality and returns that value. If that function was called directly, then that is the final answer, if it was called recursively, then it sends that answer back up the chain of function calls making some nested (f cdr(l1) cdr(l2)) return false or true and ultimately making the highest level call also return false or potentially still being able to return true (note the "and" requirement and how it works.. true comes only if every part is true, while false happens if any part is false). Similarly, if the function gets a list, then it tests the car part and "and"s this t/f value with whatever it gets when it calls itself again recursively on the rest of the list. Hence, this function handles both lists and nonlists in whatever intricate structure of sublists you feed it. [remember, we assumed that =? managed both the type and value checks, eg, so that (=? b '(b)) would be #f]

[Also, see http://cs.gettysburg.edu/~tneller/cs341/scheme-intro/exercises.html#Equivalence for what you might use to test equivalence.]