问:
How to get rid of spaces in a grid css layout and place the elements together one after the other
I am trying to understand how to place elements by using display: grid without explicitly saying how tall the elements are. This is useful for example if you just have some elements and you want to stack them one after the other following a given order but disregarding the height.

So, given a certain number of elements with same width but different height. How can you place them together in a given order with pure css in such a way that there's no space between them. This is an example:

.container {
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}

.box {
  border: solid 1px;
  width: 250px;
}

.box1 {
  height: 1000px;
  background-color: yellow;
  grid-area: b1;
}

.box2 {
  height: 200px;
  background-color: blue;
  grid-area: b2;
}

.box3 {
  height: 250px;
  background-color: green;
  grid-area: b3;
}

.box4 {
  height: 250px;
  background-color: orange;
  grid-area: b4;
}

.box5 {
  height: 600px;
  grid-area: b5;
  background-color: purple;
}

.box6 {
  height: 400px;
  background-color: gray;
  grid-area: b6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box box1">1</div>
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box5">5</div>
  <div class="box box6">6</div>
</div></code>```

答:
You should use fake content while testing a layout, unless your fixed height can match together (left col is box1+box5 = 1600px and col right is 1300px so a 300px gap(s)/difference) : White space are here because of the heights arbitrary given to children.
Your grid woks fine and is fluid :

Tips : For testing, use min-height on children or  the container, else use fake content / htmlIpsum.

Your code with a min-height on the parent only

.container {
  min-height:80vh;/* demo purpose*/
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}

.box {
  border: solid 1px;
  width: 250px;
}

.box1 {

  background-color: yellow;
  grid-area: b1;
}

.box2 {

  background-color: blue;
  grid-area: b2;
}

.box3 {

  background-color: green;
  grid-area: b3;
}

.box4 {

  background-color: orange;
  grid-area: b4;
}

.box5 {

  grid-area: b5;
  background-color: purple;
}

.box6 {

  background-color: gray;
  grid-area: b6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box box1">1</div>
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box5">5</div>
  <div class="box box6">6</div>
</div></code>```

min-height instead height to the children :

.container {
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}

.box {
  border: solid 1px;
  width: 250px;
}

.box1 {
  min-height: 1000px;
  background-color: yellow;
  grid-area: b1;
}

.box2 {
  min-height: 200px;
  background-color: blue;
  grid-area: b2;
}

.box3 {
  min-height: 250px;
  background-color: green;
  grid-area: b3;
}

.box4 {
  min-height: 250px;
  background-color: orange;
  grid-area: b4;
}

.box5 {
  min-height: 600px;
  grid-area: b5;
  background-color: purple;
}

.box6 {
  min-height: 400px;
  background-color: gray;
  grid-area: b6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box box1">1</div>
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box5">5</div>
  <div class="box box6">6</div>
</div></code>```

Body:
I am trying to understand how to place elements by using display: grid without explicitly saying how tall the elements are. This is useful for example if you just have some elements and you want to stack them one after the other following a given order but disregarding the height.

So, given a certain number of elements with same width but different height. How can you place them together in a given order with pure css in such a way that there's no space between them. This is an example:

.container {
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}

.box {
  border: solid 1px;
  width: 250px;
}

.box1 {
  height: 1000px;
  background-color: yellow;
  grid-area: b1;
}

.box2 {
  height: 200px;
  background-color: blue;
  grid-area: b2;
}

.box3 {
  height: 250px;
  background-color: green;
  grid-area: b3;
}

.box4 {
  height: 250px;
  background-color: orange;
  grid-area: b4;
}

.box5 {
  height: 600px;
  grid-area: b5;
  background-color: purple;
}

.box6 {
  height: 400px;
  background-color: gray;
  grid-area: b6;
}

1

2

3

4

5

6

Body:
You should use fake content while testing a layout, unless your fixed height can match together (left col is box1+box5 = 1600px and col right is 1300px so a 300px gap(s)/difference) : White space are here because of the heights arbitrary given to children.
Your grid woks fine and is fluid :

Tips : For testing, use min-height on children or  the container, else use fake content / htmlIpsum.

Your code with a min-height on the parent only

.container {
  min-height:80vh;/* demo purpose*/
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}

.box {
  border: solid 1px;
  width: 250px;
}

.box1 {

  background-color: yellow;
  grid-area: b1;
}

.box2 {

  background-color: blue;
  grid-area: b2;
}

.box3 {

  background-color: green;
  grid-area: b3;
}

.box4 {

  background-color: orange;
  grid-area: b4;
}

.box5 {

  grid-area: b5;
  background-color: purple;
}

.box6 {

  background-color: gray;
  grid-area: b6;
}

<div class="container">
  <div class="box box1">1</div>
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box5">5</div>
  <div class="box box6">6</div>
</div>

min-height instead height to the children :

.container {
  width: 505px;
  border: solid red;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "b1 b2" "b1 b3" "b1 b4" "b1 b6" "b5 b6"
}

.box {
  border: solid 1px;
  width: 250px;
}

.box1 {
  min-height: 1000px;
  background-color: yellow;
  grid-area: b1;
}

.box2 {
  min-height: 200px;
  background-color: blue;
  grid-area: b2;
}

.box3 {
  min-height: 250px;
  background-color: green;
  grid-area: b3;
}

.box4 {
  min-height: 250px;
  background-color: orange;
  grid-area: b4;
}

.box5 {
  min-height: 600px;
  grid-area: b5;
  background-color: purple;
}

.box6 {
  min-height: 400px;
  background-color: gray;
  grid-area: b6;
}

<div class="container">
  <div class="box box1">1</div>
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box5">5</div>
  <div class="box box6">6</div>
</div>


来源: stackexchange

问:
Sequentially select parts of a string similar to ngram
Here is the problem I am trying to solve.

For example there is this string

```<code>my_string = 'jan feb mar'
</code>```

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

```<code>my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']
</code>```

What I tried is below and it is not what I want.

```<code>my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)
</code>```

Please help me out here. Thanks.

答:
What you want is all combinations of all size (1, 2 and 3), combinations keeps order (permutations does the combination in every order)

```<code>from itertools import combinations
print(list(combinations(my_string.split(' '), r=1))) # [('jan',), ('feb',), ('mar',)]
print(list(combinations(my_string.split(' '), r=2))) # [('jan', 'feb'), ('jan', 'mar'), ('feb', 'mar')]
print(list(combinations(my_string.split(' '), r=3))) # [('jan', 'feb', 'mar')]
</code>```

Now you need to do them automatically, so loop on the number of items in the input, and join each word

```<code>from itertools import combinations, chain

# pythonic way
def my_function(values):
    items = my_string.split(" ")
    return list(chain([' '.join(c) for i in range(1,1+len(items)) for c in combinations(items, r=i)]))

# loop way
def my_function(values):
    items = my_string.split(" ")
    result = []
    for i in range(1,1+len(items)):
      comb = combinations(items, r=i)
      result.extend(' '.join(c) for c in comb)
    return result
</code>```

chain is flatten the list of list in one list

CODE DEMO

ContentLicense: CC BY-SA 4.0

Body:
Here is the problem I am trying to solve.

For example there is this string

my_string = 'jan feb mar'

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']

What I tried is below and it is not what I want.

my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)

Please help me out here. Thanks.

Body:
What you want is all combinations of all size (1, 2 and 3), combinations keeps order (permutations does the combination in every order)

from itertools import combinations
print(list(combinations(my_string.split(' '), r=1))) # [('jan',), ('feb',), ('mar',)]
print(list(combinations(my_string.split(' '), r=2))) # [('jan', 'feb'), ('jan', 'mar'), ('feb', 'mar')]
print(list(combinations(my_string.split(' '), r=3))) # [('jan', 'feb', 'mar')]

Now you need to do them automatically, so loop on the number of items in the input, and join each word

from itertools import combinations, chain

# pythonic way
def my_function(values):
    items = my_string.split(" ")
    return list(chain([' '.join(c) for i in range(1,1+len(items)) for c in combinations(items, r=i)]))

# loop way
def my_function(values):
    items = my_string.split(" ")
    result = []
    for i in range(1,1+len(items)):
      comb = combinations(items, r=i)
      result.extend(' '.join(c) for c in comb)
    return result

chain is flatten the list of list in one list

CODE DEMO


问:
how to filter data from array and apply conditions angular8
I am getting below sample data from api dynamically.

Can anyone suggest how to apply condition based on data.

答:
As your providers is array of string and you are just comparing that with string so in all cases it will validate the condition.

So you have to check the strings in the array and compare them with 'All' to properly check the condition.
So your code should look like this:

```<code>if(!this.tabSchemaDetails.schema_context.providers.includes('All')){
     request['schema_context']=this.createConditionsData();
 }
</code>```

Body:
As your providers is array of string and you are just comparing that with string so in all cases it will validate the condition.

So you have to check the strings in the array and compare them with 'All' to properly check the condition.
So your code should look like this:

if(!this.tabSchemaDetails.schema_context.providers.includes('All')){
     request['schema_context']=this.createConditionsData();
 }


问:
Updating the same site with Python's Flask module
Background:

I'm fairly new to developing front end and the Flask module in Python. I am difficulty updating the same page.

What I want to achieve:

There are three parts to what I want to achieve

Part/Step 1: I can create a form such as the one below

Part/Step 2: When the form is filled in as below, and the [verify] button is hit it goes to Step 3

Part/Step 3: Once the verify button is hit, just underneath it the information that was passed gets placed underneath it. There are also two buttons, with [commit] and [cancel] button. If [cancel] is hit, the site resets to as it were in Step 1. If [commit] is hit, it goes to a different website in step 4

Part/Step 4: If [commit] is hit from the image above, another site is retrieved with the following message.

Note:

Happy to share my code, but I just have the empty form in step 1. I can't proceed after that. As mentioned, I'm very new to front end stuff.

Update:
I'm having difficulties with 2 things currently:

When I click [cancel], the whole form shifts to the left (How can I make it centered?)

How can I print multiple things (ideally in a centered table) after hitting the [verify] button

<!DOCTYPE html>

Personnel Details

       Salutation:

        <select name="gender">
          <option value=""></option>
          <option value="male">Mr.</option>
          <option value="female">Ms.</option>
        </select>

       First Name:

       <input id="first_name">

       Middle Name:

          <input id="middle_name">

       Last Name:

          <input id="last_name">

       Email:

          <input id="email">

       DOB:

          <input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31">

            <button onclick="onVerify()">Verify</button>

    <button onclick="onCommit()">Commit</button>
    <button onclick="onCancel()">Cancel</button>

    Committed! :)

```

答:
This is just the minimal code, I have used to just give an idea, how to achieve the similar behavior, with just one input field. You can easily extend this with other fields.

     First Name:
        <input id="name">

        <button onclick="onVerify()">Veryfy</button>

    <button onclick="onCommit()">Commit</button>
    <button onclick="onCancel()">Cancel</button>

    Committed! :)

```

Body:
This is just the minimal code, I have used to just give an idea, how to achieve the similar behavior, with just one input field. You can easily extend this with other fields.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        document.getElementById("verify").style.display = "none";
        document.getElementById("committed").style.display = "none";
    })
    function onVerify() {
        document.getElementById("verifyName").innerHTML = 'First Name: ' + document.getElementById("name").value
        document.getElementById("verify").style.display = "block";
    }
    function onCommit() {
        document.getElementById("form").style.display = "none";
        document.getElementById("verify").style.display = "none";
        document.getElementById("committed").style.display = "block";
    }
    function onCancel() {
        document.getElementById("form").style.display = "block";
        document.getElementById("verify").style.display = "none";
        document.getElementById("name").value = ""
    }
</script>
<div id="form">
    <label> First Name:
        <input id="name">
    </label>
    <div>
        <button onclick="onVerify()">Veryfy</button>
    </div>
</div>
<div id="verify">
    <div id="verifyName">
    </div>
    <button onclick="onCommit()">Commit</button>
    <button onclick="onCancel()">Cancel</button>
</div>
<div id="committed">
    Committed! :)
</div>


问:
Xcode 11.5/Catalina not responding on startup
I have recently upgraded both Xcode (to 11.5) and Mac OS to Catalina.  Xcode has been working fine for a few days.  I clicked on a JSON file in my project and Xcode hung (with SBBOD).  I forced quit and rebooted but now Xcode will not load - it starts, but just shows SBBOD again.  On startup, it tries to load my last project, I have tried launching from Finder by clicking on a PlayGround project but same issue!

Any suggestions for how I recover this situation?

答: While the cause is not resolved, I left Xcode running overnight and it is now working.  This issue seems to be with displaying a large JSON file (about 1MB).  Xcode is taking a few hours before it becomes responsive.  I just left it to run.</p>


问:
Django - Make migration command detects changes but on migrating says 'No migrations to apply'
i am new to django developement after making changes to my model i tried to run the command python manage.py makemigrations my_app
it detects changes in my model and shows me the message
todoapp/migrations/0001_initial.py
    - Create model confess
    - Create model UserChoice
    - Create model comment
but on executing  python manage.py migrate my_appcommand i've got this message
No migrations to apply.
i usually do this after making changes in models, i don't know what happened now.
plss help me.

答: Delete all migrations files and __pychache__except__init__.py from your project and app. Also db.sqlite3 database then rerun makemigrations and migrate commands. It should solve your issue.


问:
How do i create a typescript interface for following response data
I need to create a  typescript interface for the following response data only for "hits" key and its nested data as shown in the image. Please somebody help me.

Image Link with response data Structure

答:
For a simple project (with static data structures):

Paste your demo json in http://json2ts.com/  and you will get some typescript interfaces.

There are a lot of other sites that will do this, json-to-typescript, MakeTypes, quicktype.io

It's import to have  good demo data. A lot of null values causes a lot of 'any' types.


问:
Cannot find module '@material-ui/core'
I had a problem with importing "@material-ui/core" to my react/typescript/webpack app. Always when I ran

webpack --config webpack.config.js

it failed with error

Cannot find module '@material-ui/core'

The same error was also underlined in the Visual Studio Code.

My index.tsx looked like this

```<code>import React from "react";
import ReactDOM from 'react-dom';
import { Button } from "@material-ui/core";

function App() {
    return <Button>Hi dudes</Button>
}
ReactDOM.render(<App />, document.getElementById("root"));
</code>```

答: yarn add @material-ui/core or npm i @material-ui/core fixed the issue for me.

Title: Cannot find module '@material-ui/core'

Body:
I had a problem with importing "@material-ui/core" to my react/typescript/webpack app. Always when I ran

webpack --config webpack.config.js

it failed with error

Cannot find module '@material-ui/core'

The same error was also underlined in the Visual Studio Code.

My index.tsx looked like this

import React from "react";
import ReactDOM from 'react-dom';
import { Button } from "@material-ui/core";

function App() {
    return <Button>Hi dudes</Button>
}
ReactDOM.render(<App />, document.getElementById("root"));


问:
Angular 5 FormGroup reset doesn't reset validators
I have a form on my page and when I call FormGroup.reset() it sets the forms class to ng-pristine ng-untouched but FormControl.hasError(...) still returns truthy. What am I doing wrong here?

Template

```<code><form [formGroup]="myForm" (ngSubmit)="submitForm(myForm)">
  <mat-form-field>
    <input matInput formControlName="email" />
    <mat-error *ngIf="email.hasError('required')">
      Email is a required feild
    </mat-error>
  </mat-form-field>
  <mat-form-field>
    <input matInput type="password" formControlName="password" />
    <mat-error *ngIf="password.hasError('required')">
      Password is a required feild
    </mat-error>
  </mat-form-field>
  <button type="submit">Login</button>
</form>
</code>```

Component

```<code>export class MyComponent {
  private myForm: FormGroup;
  private email: FormControl = new FormContorl('', Validators.required);
  private password: FormControl = new FormControl('', Validators.required);

  constructor(
    private formBuilder: FormBuilder
  ) {
    this.myForm = formBuilder.group({
      email: this.email,
      password: this.password
    });
  }

  private submitForm(formData: any): void {
    this.myForm.reset();
  }
}
</code>```

Plunker

https://embed.plnkr.co/Hlivn4/

答:
To anyone whom this may help, I am running Angular 9.1.9 and I didn't want to reset the form/controls just the overall validity of the form so I just ran:

```<code>this.registerForm.setErrors(null);
</code>```

...where registerForm: FormGroup and that reset the form errors, leading to:

```<code>this.registerForm.valid
</code>```

...returning true.

The same can be done for controls:

```<code>this.registerForm.get('email').setErrors(null)
</code>```

As soon as the form is touched, these errors are re-evaluated anyway so if that's not good enough, you may need to have a boolean flag to further pin-down exactly when you want to start showing/hiding error UI.

I did not need to touch the directive in my case.

Body:
I have a form on my page and when I call FormGroup.reset() it sets the forms class to ng-pristine ng-untouched but FormControl.hasError(...) still returns truthy. What am I doing wrong here?

Template

<form [formGroup]="myForm" (ngSubmit)="submitForm(myForm)">
  <mat-form-field>
    <input matInput formControlName="email" />
    <mat-error *ngIf="email.hasError('required')">
      Email is a required feild
    </mat-error>
  </mat-form-field>
  <mat-form-field>
    <input matInput type="password" formControlName="password" />
    <mat-error *ngIf="password.hasError('required')">
      Password is a required feild
    </mat-error>
  </mat-form-field>
  <button type="submit">Login</button>
</form>

Component

export class MyComponent {
  private myForm: FormGroup;
  private email: FormControl = new FormContorl('', Validators.required);
  private password: FormControl = new FormControl('', Validators.required);

  constructor(
    private formBuilder: FormBuilder
  ) {
    this.myForm = formBuilder.group({
      email: this.email,
      password: this.password
    });
  }

  private submitForm(formData: any): void {
    this.myForm.reset();
  }
}

Plunker

https://embed.plnkr.co/Hlivn4/

Body:
To anyone whom this may help, I am running Angular 9.1.9 and I didn't want to reset the form/controls just the overall validity of the form so I just ran:

this.registerForm.setErrors(null);

...where registerForm: FormGroup and that reset the form errors, leading to:

this.registerForm.valid

...returning true.

The same can be done for controls:

this.registerForm.get('email').setErrors(null)

As soon as the form is touched, these errors are re-evaluated anyway so if that's not good enough, you may need to have a boolean flag to further pin-down exactly when you want to start showing/hiding error UI.

I did not need to touch the directive in my case.


问:
Can Haskell programs be represented as Lisp S-expressions?
This would be useful for genetic programming, which usually use a Lisp subset as representation for programs.

I've found something called Liskell (Lisp syntax, Haskell inside) on the web, but the links are broken and I can't find the paper on it...

答: The Liskell paper is at http://clemens.endorphin.org/ILC07-Liskell-draft.pdf and the liskell.org site seems to still be up in general.</p>

ContentLicense: CC BY-SA 3.0


问:
Understanding rust borrowing and dereferencing
I was reading through the Rust documentation and can't quite seem to be able to wrap my head around what is going on. For example, over here I see the following example:

// This function takes ownership of a box and destroys it
fn eat_box_i32(boxed_i32: Box<i32>) {
    println!("Destroying box that contains {}", boxed_i32);
}

// This function borrows an i32
fn borrow_i32(borrowed_i32: &i32) {
    println!("This int is: {}", borrowed_i32);
}

fn main() {
    // Create a boxed i32, and a stacked i32
    let boxed_i32 = Box::new(5_i32);
    let stacked_i32 = 6_i32;

    // Borrow the contents of the box. Ownership is not taken,
    // so the contents can be borrowed again.
    borrow_i32(&boxed_i32);
    borrow_i32(&stacked_i32);

    {
        // Take a reference to the data contained inside the box
        let _ref_to_i32: &i32 = &boxed_i32;

        // Error!
        // Can't destroy `boxed_i32` while the inner value is borrowed later in scope.
        eat_box_i32(boxed_i32);
        // FIXME ^ Comment out this line

        // Attempt to borrow `_ref_to_i32` after inner value is destroyed
        borrow_i32(_ref_to_i32);
        // `_ref_to_i32` goes out of scope and is no longer borrowed.
    }

    // `boxed_i32` can now give up ownership to `eat_box` and be destroyed
    eat_box_i32(boxed_i32);
}

```

Things I believe:

eat_box_i32 takes a pointer to a Box

this line let boxed_i32 = Box::new(5_i32); makes is so that boxed_i32 now contains a pointer because Box is not a primitive

Things I don't understand:

why do we need to call borrow_i32(&boxed_i32); with the ampersand? Isn't boxed_i32 already a pointer?

on this line: let _ref_to_i32: &i32 = &boxed_i32; why is the ampersand required on the right hand side? Isn't boxed_i32 already an address?

how come borrow_i32 can be called with pointer to Box and pointer to i32 ?

答:
Comment on the term "pointers"

You can skip this part if you'd like, I just figured given the questions you asked, this might be a helpful comment:

In Rust, &i32, &mut i32, *const i32, *mut i32, Box<i32>, Rc<i32>, Arc<i32> are all arguably a "pointer to i32" type. However, Rust will not let you convert between them casually, even between those that are laid out identically in memory.

It can be useful to talk about pointers in general sometimes, but as a rule of thumb, if you're trying to figure out why one piece of Rust code compiles, and another doesn't, I'd recommend keeping track of which kind of pointer you're working with.

Things you believe:

eat_box_i32 takes a pointer to a Box

Actually not quite. eat_box_i32 accepts a Box<i32>, and not a pointer to a Box<i32>. It just so happens that Box<i32> in memory is stored as a pointer to an i32.

this line let boxed_i32 = Box::new(5_i32); makes is so that boxed_i32 now contains a pointer because Box is not a primitive

Yes, boxed_i32 is a pointer.

Things you don't understand:

why do we need to call borrow_i32(&boxed_i32); with the ampersand? Isn't boxed_i32 already a pointer?

Yes, boxed_i32 is already a pointer. However, a boxed pointer still indicates ownership. If you passed boxed_i32 instead of &boxed_i32, you would still be passing a pointer, but Rust will consider that variable "consumed", and you would no longer be able to use boxed_i32 after that function call.

on this line: let _ref_to_i32: &i32 = &boxed_i32; why is the ampersand required on the right hand side? Isn't boxed_i32 already an address?

Yes, boxed_i32 is already an address, but the fact that it's an address is kind of meant to be opaque (like a struct with a single private field). The actual type of &boxed_i32 is &Box<i32>.

Though this is weird right? If &boxed_i32 is &Box<i32>, how can you assign it to a variable of type &i32?

This is actually a shorthand -- If a type T implements the Deref<Target=R> trait, it'll automatically convert values of type &T into values of type &R as needed. And it turns out that the Box<T> type implements Deref<Target=T>.

See https://doc.rust-lang.org/std/ops/trait.Deref.html for more info about Deref.

So if you wrote it out explicitly without that automatic conversion, that line would actually look something like:

```<code>let _ref_to_i32: &i32 = Deref::deref(&boxed_i32);
</code>```

how come borrow_i32 can be called with pointer to Box and pointer to i32 ?

The reason is the same as with (2) above.

borrow_i32 accepts &i32 as its parameter. Passing &i32 is obviously ok because the types match exactly. If you try to pass it &Box<i32>, Rust will automatically convert it to &i32 for you, because Box<i32> implements Deref<i32>.

EDIT: Thanks @kmdreko for pointing out that Deref allows the coercion, and not AsRef

Body:
I was reading through the Rust documentation and can't quite seem to be able to wrap my head around what is going on. For example, over here I see the following example:

// This function takes ownership of a box and destroys it
fn eat_box_i32(boxed_i32: Box<i32>) {
    println!("Destroying box that contains {}", boxed_i32);
}

// This function borrows an i32
fn borrow_i32(borrowed_i32: &i32) {
    println!("This int is: {}", borrowed_i32);
}

fn main() {
    // Create a boxed i32, and a stacked i32
    let boxed_i32 = Box::new(5_i32);
    let stacked_i32 = 6_i32;

    // Borrow the contents of the box. Ownership is not taken,
    // so the contents can be borrowed again.
    borrow_i32(&boxed_i32);
    borrow_i32(&stacked_i32);

    {
        // Take a reference to the data contained inside the box
        let _ref_to_i32: &i32 = &boxed_i32;

        // Error!
        // Can't destroy `boxed_i32` while the inner value is borrowed later in scope.
        eat_box_i32(boxed_i32);
        // FIXME ^ Comment out this line

        // Attempt to borrow `_ref_to_i32` after inner value is destroyed
        borrow_i32(_ref_to_i32);
        // `_ref_to_i32` goes out of scope and is no longer borrowed.
    }

    // `boxed_i32` can now give up ownership to `eat_box` and be destroyed
    eat_box_i32(boxed_i32);
}

Things I believe:

eat_box_i32 takes a pointer to a Box

this line let boxed_i32 = Box::new(5_i32); makes is so that boxed_i32 now contains a pointer because Box is not a primitive

Things I don't understand:

why do we need to call borrow_i32(&boxed_i32); with the ampersand? Isn't boxed_i32 already a pointer?

on this line: let _ref_to_i32: &i32 = &boxed_i32; why is the ampersand required on the right hand side? Isn't boxed_i32 already an address?

how come borrow_i32 can be called with pointer to Box and pointer to i32 ?

Body:
Comment on the term "pointers"

You can skip this part if you'd like, I just figured given the questions you asked, this might be a helpful comment:

In Rust, &i32, &mut i32, *const i32, *mut i32, Box<i32>, Rc<i32>, Arc<i32> are all arguably a "pointer to i32" type. However, Rust will not let you convert between them casually, even between those that are laid out identically in memory.

It can be useful to talk about pointers in general sometimes, but as a rule of thumb, if you're trying to figure out why one piece of Rust code compiles, and another doesn't, I'd recommend keeping track of which kind of pointer you're working with.

Things you believe:

eat_box_i32 takes a pointer to a Box

Actually not quite. eat_box_i32 accepts a Box<i32>, and not a pointer to a Box<i32>. It just so happens that Box<i32> in memory is stored as a pointer to an i32.

this line let boxed_i32 = Box::new(5_i32); makes is so that boxed_i32 now contains a pointer because Box is not a primitive

Yes, boxed_i32 is a pointer.

Things you don't understand:

why do we need to call borrow_i32(&boxed_i32); with the ampersand? Isn't boxed_i32 already a pointer?

Yes, boxed_i32 is already a pointer. However, a boxed pointer still indicates ownership. If you passed boxed_i32 instead of &boxed_i32, you would still be passing a pointer, but Rust will consider that variable "consumed", and you would no longer be able to use boxed_i32 after that function call.

on this line: let _ref_to_i32: &i32 = &boxed_i32; why is the ampersand required on the right hand side? Isn't boxed_i32 already an address?

Yes, boxed_i32 is already an address, but the fact that it's an address is kind of meant to be opaque (like a struct with a single private field). The actual type of &boxed_i32 is &Box<i32>.

Though this is weird right? If &boxed_i32 is &Box<i32>, how can you assign it to a variable of type &i32?

This is actually a shorthand -- If a type T implements the Deref<Target=R> trait, it'll automatically convert values of type &T into values of type &R as needed. And it turns out that the Box<T> type implements Deref<Target=T>.

See https://doc.rust-lang.org/std/ops/trait.Deref.html for more info about Deref.

So if you wrote it out explicitly without that automatic conversion, that line would actually look something like:

let _ref_to_i32: &i32 = Deref::deref(&boxed_i32);

how come borrow_i32 can be called with pointer to Box and pointer to i32 ?

The reason is the same as with (2) above.

borrow_i32 accepts &i32 as its parameter. Passing &i32 is obviously ok because the types match exactly. If you try to pass it &Box<i32>, Rust will automatically convert it to &i32 for you, because Box<i32> implements Deref<i32>.

EDIT: Thanks @kmdreko for pointing out that Deref allows the coercion, and not AsRef


问:
Projectiles After Colliding With Enemy Problem How To Fix?
I am trying to make my bullets collide with my enemy and then dis-pear but it just passes throw them for some reason

```<code>    for bullet in bullets[:]:
        if bullet.y + bullet.x < enemys1.hitbox[1] + enemys1.hitbox[3] and bullet.y + bullet.x > enemys1.hitbox[1]:
            if bullet.x - bullet.y > enemys1.hitbox[0] and bullet.x - bullet.y < enemys1.hitbox[0] + enemys1.hitbox[2]:
                enemys1.hit()
                bullets.pop(bullets.index(bullet))

</code>```

this is my projectile class

```<code>
class projectile(object):
   def __init__(self, x, y, dirx, diry, color):
       self.x = x
       self.y = y
       self.dirx = dirx
       self.diry = diry
       self.slash = pygame.image.load("heart.png")
       self.rect  = self.slash.get_rect()
       self.rect.topleft = ( self.x, self.y )
       self.speed = 10
       self.color = color

   def move(self):
       self.x += self.dirx * self.speed
       self.y += self.diry * self.speed

   def draw(self, window):
       self.rect.topleft = (round(self.x), round(self.y))

       window.blit(slash, self.rect)

</code>```

any help is appreciated Thanks!

答:
I recommend to use a pygame.Rect object for the hitbox and colliderect() to find the intersection:

for bullet in bullets[:]:
    hit_rect = pygame.Rect(*enemys1.hitbox)
    if bullet.rect.colliderect(hit_rect):
        enemys1.hit()

```

Body:
I am trying to make my bullets collide with my enemy and then dis-pear but it just passes throw them for some reason

    for bullet in bullets[:]:
        if bullet.y + bullet.x < enemys1.hitbox[1] + enemys1.hitbox[3] and bullet.y + bullet.x > enemys1.hitbox[1]:
            if bullet.x - bullet.y > enemys1.hitbox[0] and bullet.x - bullet.y < enemys1.hitbox[0] + enemys1.hitbox[2]:
                enemys1.hit()
                bullets.pop(bullets.index(bullet))

this is my projectile class

class projectile(object):
   def __init__(self, x, y, dirx, diry, color):
       self.x = x
       self.y = y
       self.dirx = dirx
       self.diry = diry
       self.slash = pygame.image.load("heart.png")
       self.rect  = self.slash.get_rect()
       self.rect.topleft = ( self.x, self.y )
       self.speed = 10
       self.color = color

   def move(self):
       self.x += self.dirx * self.speed
       self.y += self.diry * self.speed

   def draw(self, window):
       self.rect.topleft = (round(self.x), round(self.y))

       window.blit(slash, self.rect)

any help is appreciated Thanks!


问:
How to create random numbers a specific number of times?
How can i create a random number a specific numbers of time?

```<code>public class Feld  {
    public static void main(String[] args) {
        double k = (int)(Math.random()*1000001);
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0;i<n;i++){
            arr[i] = i;
        }
        boolean found = false;
        i=0;
        while (i < arr.length) {
            if (arr[i] == k) {
                found = true;
                break;
            }
            i++;
        }
        if (found) {
            i++;
            System.out.println(i);
        }
        else {
            System.out.println((arr.length + 1));
        }
    }
}
</code>```

My problem is, that if i put k into a loop to create it more than one time i'll get an error at:

```<code>if (arr[i] == k)
</code>```

!!I just found out that i made a mistake explaining my problem. The array should be filled with values from 0-1.000.000 and i am supposed to print out the position of a random generated number for a specific amount of times.

答:
I would write a method that returns an array of random numbers and takes an int argument that defines the length of the array.

One possible solution is this:

```<code>public static int[] createRandomArray(int length) {
    // create an array of the given length
    int[] result = new int[length];
    // and use a single for loop that puts random int values into every index
    for (int i = 0; i < result.length; i++) {
        result[i] = ThreadLocalRandom.current().nextInt();
    }
    // then simply return the result
    return result;
}
</code>```

Try it as follows

```<code>public static void main(String[] args) {
    // super primitive time measurement:
    // take the moment in time before calling the method
    Instant start = Instant.now();
    // then call the method
    int[] array = createRandomArray(1000000);
    // and take the moment in time after the method returned
    Instant end = Instant.now();
    // then calculate the duration
    Duration duration = Duration.between(start, end);
    // and print the duration in milliseconds
    System.out.printf("Array creation took %d milliseconds\n", duration.toMillis());
}
</code>```

The result is the following output on my system:

Array creation took 10 milliseconds
```

Body:
How can i create a random number a specific numbers of time?

public class Feld  {
    public static void main(String[] args) {
        double k = (int)(Math.random()*1000001);
        int n = 1000000;
        int arr[] = new int[n];
        int i = 0;
        for(i = 0;i<n;i++){
            arr[i] = i;
        }
        boolean found = false;
        i=0;
        while (i < arr.length) {
            if (arr[i] == k) {
                found = true;
                break;
            }
            i++;
        }
        if (found) {
            i++;
            System.out.println(i);
        }
        else {
            System.out.println((arr.length + 1));
        }
    }
}

My problem is, that if i put k into a loop to create it more than one time i'll get an error at:

if (arr[i] == k)

!!I just found out that i made a mistake explaining my problem. The array should be filled with values from 0-1.000.000 and i am supposed to print out the position of a random generated number for a specific amount of times.

Body:
I would write a method that returns an array of random numbers and takes an int argument that defines the length of the array.

One possible solution is this:

public static int[] createRandomArray(int length) {
    // create an array of the given length
    int[] result = new int[length];
    // and use a single for loop that puts random int values into every index
    for (int i = 0; i < result.length; i++) {
        result[i] = ThreadLocalRandom.current().nextInt();
    }
    // then simply return the result
    return result;
}

Try it as follows

public static void main(String[] args) {
    // super primitive time measurement:
    // take the moment in time before calling the method
    Instant start = Instant.now();
    // then call the method
    int[] array = createRandomArray(1000000);
    // and take the moment in time after the method returned
    Instant end = Instant.now();
    // then calculate the duration
    Duration duration = Duration.between(start, end);
    // and print the duration in milliseconds
    System.out.printf("Array creation took %d milliseconds\n", duration.toMillis());
}

The result is the following output on my system:

Array creation took 10 milliseconds


问:
CSS Selection inside Web Workers?
I want to extract data from an HTML string in a Web Worker.

I want to clarify that I do not want to manipulate the DOM. I am sending an HTML string to the Web Worker, which then should extract data from the HTML, and then return the extracted data.

In the browser I could do:

```<code>  var html = $("<body><div>...more html...</div></body>");

  var extractedText = $(".selector", html).text();
</code>```

My Question:

What is the equivalent of the above code in a Web Worker environment if given the same HTML string? There's no jQuery, no DOMParser, no querySelector.. in the Web Worker etc. Are there alternatives?

The Why:

I'm doing on the fly scraping of pages in a browser and don't want to block the UI thread because it's pretty heavy work.

I've looked at jsdom, cheerio, etc. but could not figure out how to make them work.

Regarding suggested duplicates:

I have reviewed both of the suggested duplicates and they are ones that I have read before while searching for answers to this question. They address XML parsing and not HTML parsing, and also do not address how to use CSS-selection inside Web Workers.

答:
You can make dom selection inside worker but you will need to create an API that will use post message to change data between main tread and worker (because you can't use DOM directly in worker). The limitation is that you will need to pass strings between, so you can't return Dom Nodes, unless you have some code that will create DOM nodes in worker based on data from main tread.

Because JavaScript is dynamic it should be easy to create dynamic wrapper that will create all those functions for you, and will allow to call querySelelector('.foo') and expose all the Dom APIs. With proxy objects you can even allow to use querySelelector('.foo').innerHTML = 'hello'; in worker with proper code.

There is library that make creating such API easier Comlink from Google. If you don't want to use library you can check this code, this git web terminal that expose isomorphic git functions using RPC like code to worker (It's inspired by Jason's Miller
workerize).

Create worker:
https://github.com/jcubic/git/blob/gh-pages/js/main.js#L116

Worker code
https://github.com/jcubic/git/blob/gh-pages/js/git-worker.js

and quick search give this project that looks promising "Worker DOM", it should give you DOM api in worker (that I'm almost sure use solution I proposed) but I didn't check it and I'm not sure how it works.

With some bit of work you may even have working jQuery inside worker, it would good project to make open source.

Title: CSS Selection inside Web Workers?

Body:
I want to extract data from an HTML string in a Web Worker.

I want to clarify that I do not want to manipulate the DOM. I am sending an HTML string to the Web Worker, which then should extract data from the HTML, and then return the extracted data.

In the browser I could do:

  var html = $("
...more html...
");

  var extractedText = $(".selector", html).text();

My Question:

What is the equivalent of the above code in a Web Worker environment if given the same HTML string? There's no jQuery, no DOMParser, no querySelector.. in the Web Worker etc. Are there alternatives?

The Why:

I'm doing on the fly scraping of pages in a browser and don't want to block the UI thread because it's pretty heavy work.

I've looked at jsdom, cheerio, etc. but could not figure out how to make them work.

Regarding suggested duplicates:

I have reviewed both of the suggested duplicates and they are ones that I have read before while searching for answers to this question. They address XML parsing and not HTML parsing, and also do not address how to use CSS-selection inside Web Workers.


答:
You might be interested in a project I have been working on, husk scheme.

Basically it will let you call into Scheme code (S-expressions) from Haskell, and vice-versa. So you can intermingle that code within your program, and then process the s-expressions as native Haskell data types when you want to do something on the Haskell side.

Anyway, it may be useful to you, or not - have a look and decide for yourself.

Title: Can Haskell programs be represented as Lisp S-expressions?

Body:
This would be useful for genetic programming, which usually use a Lisp subset as representation for programs.

I've found something called Liskell (Lisp syntax, Haskell inside) on the web, but the links are broken and I can't find the paper on it...


问:
Data exists in DB but JPA returning blank, Spring?
I am querying the DB to get the result but I get blank array

The repository class

```<code>@Repository
public interface AppConfigRepository extends CrudRepository<AppConfig, Long> {

@Query("SELECT n FROM AppConfig n WHERE n.appCode = ?1 and n.appVersion = ?2")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
}
</code>```

The table class

```<code>@Entity
@Table(name = "app_config")
@EntityListeners(AuditingEntityListener.class)
public class AppConfig {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "serial")
private long id;
@Column(name = "app_code", nullable = false)
private String appCode;
@Column(name = "app_name", nullable = false)
private String appName;
@Column(name = "api_url", nullable = true)
private String apiUrl;
@Column(name = "db_name", nullable = true)
private String dbName;
@Column(name = "app_version", nullable = false)
private String appVersion;
</code>```

The mapping function

```<code>@RequestMapping(value = "/config", params = { "appCode", "appVersion" }, method = RequestMethod.GET)
public List<AppConfig> getConfig(@RequestParam(value = "appCode", required = true) String appCode,
        @RequestParam(value = "appVersion", required = true) String appVersion) {
    System.out.println(appCode);
    System.out.println(appVersion);
    return configRepository.findByCodeAndVersion(appCode, appCode);
}
</code>```

This is how I am making the URL

```<code>http://localhost:9090/api/v1/config?appCode=MANDL_LIVE&appVersion=12.0
</code>```

In the logs I see

```<code>select appconfig0_.id as id1_0_, appconfig0_.api_url as api_url2_0_, appconfig0_.app_code as app_code3_0_, appconfig0_.app_name as app_name4_0_, appconfig0_.app_version as app_vers5_0_, appconfig0_.db_name as db_name6_0_ from app_config appconfig0_ where appconfig0_.app_code=? and appconfig0_.app_version=?
</code>```

答:
You are calling:

```<code>return configRepository.findByCodeAndVersion(appCode, appCode);
</code>```

Shouldn't it be:

```<code>return configRepository.findByCodeAndVersion(appCode, appVersion);
</code>```

Body:
I am querying the DB to get the result but I get blank array

The repository class

@Repository
public interface AppConfigRepository extends CrudRepository<AppConfig, Long> {

@Query("SELECT n FROM AppConfig n WHERE n.appCode = ?1 and n.appVersion = ?2")
List<AppConfig> findByCodeAndVersion(String appCode, String appVersion);
}

The table class

@Entity
@Table(name = "app_config")
@EntityListeners(AuditingEntityListener.class)
public class AppConfig {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "serial")
private long id;
@Column(name = "app_code", nullable = false)
private String appCode;
@Column(name = "app_name", nullable = false)
private String appName;
@Column(name = "api_url", nullable = true)
private String apiUrl;
@Column(name = "db_name", nullable = true)
private String dbName;
@Column(name = "app_version", nullable = false)
private String appVersion;

The mapping function

@RequestMapping(value = "/config", params = { "appCode", "appVersion" }, method = RequestMethod.GET)
public List<AppConfig> getConfig(@RequestParam(value = "appCode", required = true) String appCode,
        @RequestParam(value = "appVersion", required = true) String appVersion) {
    System.out.println(appCode);
    System.out.println(appVersion);
    return configRepository.findByCodeAndVersion(appCode, appCode);
}

This is how I am making the URL

http://localhost:9090/api/v1/config?appCode=MANDL_LIVE&appVersion=12.0

In the logs I see

select appconfig0_.id as id1_0_, appconfig0_.api_url as api_url2_0_, appconfig0_.app_code as app_code3_0_, appconfig0_.app_name as app_name4_0_, appconfig0_.app_version as app_vers5_0_, appconfig0_.db_name as db_name6_0_ from app_config appconfig0_ where appconfig0_.app_code=? and appconfig0_.app_version=?

Body:
You are calling:

return configRepository.findByCodeAndVersion(appCode, appCode);

Shouldn't it be:

return configRepository.findByCodeAndVersion(appCode, appVersion);


问:
When to use ChangeNotifier?
In the flutter sample explaining how to use the Provider package, there are two models, Catalog and Model.
For the Catalog model, ChangeNotifier is not used, but for the Cart model it's used.

Cart model
Catalog model

Why is ChangeNotifier used for the Cart model and not Catalog model?

My thinking is that the Cart model depends on changes outside (in the catalog model).
The catalog model is hard-coded and hence no need to notify anyone of changes.

Is my thinking correct?

PS: this is my first app and I'm a complete noob when it comes to state management.

答:
Yes you are correct.

The ChangeNotifier as the name suggests stands for notifying the changes. As you can see the function notifyListners() called at catalog and add functions are used to notify the listeners subscribed to the notifier using Consumer widget or using Consumer.of(). So as to when to use ChangeNotifiers ? You can use then whenever there are state changes in a model dependant upon some other view deep in the tree that you cannot get to them directly.

So from this widget tree you can clearly see that MyCatalog and MyCart are totally different from each other in the UI but are dependant logically. i.e. you need to notify the cart widget whenever user changes the MyListItem.

One possible solution for this scenario is that using global variables (sort of) or a variable that is at top of MyCatalog and MyCart in the tree. So that when MyCatalog changes the state the ChangeNotifier at the top of tree would know of the change and notify the MyCart that is listening to the changes.

ChangeNotifiers are used in such scenario where we need to lift the state up as the documentation says here or you could use it when you need the values deep in the tree that you cannot directly give. In case of react we call it props drilling. Giving the state to the child widgets in the tree.

We could acheive this without using providers if I am not wrong. Making MyApp a statefull widget and passing the state to MyCatalog and MyCart widget. so that the renders would know to get the state from. But what if you added another widget that depends on the state deep in the tree. Would you pass the state down ? or Would you use the Provider ? all depends upon you and your application.

Title: When to use ChangeNotifier?


问:
How to read Localizable.strings in the app
I have Localizable.strings files for many languages.

I would like to read the current Localizable.strings line by line in the app to make a translation help.

```<code>        let bpath:String = Bundle.main.path(forResource: "es", ofType: "lproj")! as String

        if let filepath = Bundle.main.path(forResource: bpath + "/Localizable.strings", ofType: nil) {
            do {
                let contents = try String(contentsOfFile: filepath)
                print(contents)
            } catch {
                // contents could not be loaded
                let alert = UIAlertController(title: "Erreur".localized, message: "Fichier \(bpath + "/Localizable.strings") non accessible".localized, preferredStyle: .alert)

                alert.addAction(UIAlertAction.init(title: "Ok".localized, style: .cancel, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
        } else {
            // example.txt not found!
            let alert = UIAlertController(title: "Erreur".localized, message: "Fichier \(bpath + "/Localizable.strings") non trouvé".localized, preferredStyle: .alert)

            alert.addAction(UIAlertAction.init(title: "Ok".localized, style: .cancel, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
</code>```

It don't find the file.

PS : This code works perfectly, but the goal is to read all "keys".

```<code>    let bpath:String = Bundle.main.path(forResource: "es", ofType: "lproj")! as String
    let bundle = Bundle(path: bpath as String)
    let thisWord="Erreur"
    let ourWord=NSLocalizedString(thisWord, bundle: bundle!, comment: "")
</code>```

答:
Use the following to find a path:</p>

```<code>let filepath = Bundle.main.path(forResource: "Localizable",
                                ofType: "strings", inDirectory: "es.lproj")
</code>```

Body:
I have Localizable.strings files for many languages.

I would like to read the current Localizable.strings line by line in the app to make a translation help.

        let bpath:String = Bundle.main.path(forResource: "es", ofType: "lproj")! as String

        if let filepath = Bundle.main.path(forResource: bpath + "/Localizable.strings", ofType: nil) {
            do {
                let contents = try String(contentsOfFile: filepath)
                print(contents)
            } catch {
                // contents could not be loaded
                let alert = UIAlertController(title: "Erreur".localized, message: "Fichier \(bpath + "/Localizable.strings") non accessible".localized, preferredStyle: .alert)

                alert.addAction(UIAlertAction.init(title: "Ok".localized, style: .cancel, handler: nil))
                self.present(alert, animated: true, completion: nil)
            }
        } else {
            // example.txt not found!
            let alert = UIAlertController(title: "Erreur".localized, message: "Fichier \(bpath + "/Localizable.strings") non trouvé".localized, preferredStyle: .alert)

            alert.addAction(UIAlertAction.init(title: "Ok".localized, style: .cancel, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }

It don't find the file.

PS : This code works perfectly, but the goal is to read all "keys".

    let bpath:String = Bundle.main.path(forResource: "es", ofType: "lproj")! as String
    let bundle = Bundle(path: bpath as String)
    let thisWord="Erreur"
    let ourWord=NSLocalizedString(thisWord, bundle: bundle!, comment: "")

Body:
Use the following to find a path:

let filepath = Bundle.main.path(forResource: "Localizable",
                                ofType: "strings", inDirectory: "es.lproj")


问:
Semantic UI centre aligned login box?
I am using the Semantic UI framework for my website. I want to place the login box in the centre of the page.I want only the login box in the page. I don't understand how to centre aligned using Semantic UI 'grid classes'. Please help me how to fit the login box.

My Code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my semantic website</title>
<link rel="stylesheet" href="../css/semantic.min.css">
<link rel="stylesheet" href="../css/style.css">
<script src="../js/jquery-2.1.1.min.js" type="text/javascript" charset="utf-8" async defer>     </script>
<script src="../js/semantic.min.js" type="text/javascript" charset="utf-8" async defer></script>
</head>
<body>
<div class="ui grid">
    <div class="one column row">
        <div class="ui padded grid">
            <div class="three column row">
                <div class="column">
                    <div class="ui segment">
                        <h4 class="ui dividing header">Account Info</h4>
                        <div class="ui form">
                            <div class="field">
                                <label for="username">Username: </label>
                                <div class="ui icon input">
                                    <input type="text" placeholder="Username" name="username" id="username">
                                    <i class="user icon"></i>
                                </div>
                            </div>
                            <div class="field">
                                <label for="password">Password: </label>
                                <div class="ui icon input">
                                    <input type="password" placeholder="Password" name="password" id="password">
                                    <i class="lock icon"></i>
                                </div>
                            </div>
                            <input type="submit" name="submit" class="ui inverted blue button">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
</code>```

答:
This is my implementation, it works well.

JsFiddle link

HTML

TITLE

            SUBTITLE

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ab, alias.

          extra content

```

<p>CSS</p>

<pre class="lang-css prettyprint-override"><code>#v-container {
  background: #ddd;
  height: 100vh;
  width: 100%;
}

.image-margin {
  margin-top: 16px;
  margin-bottom: 16px;
}

.image-border {
  border-radius: 4px !important;
}

.no-background {
  background: transparent !important;
}

</code>```

Title: Semantic UI centre aligned login box?

Body:
I am using the Semantic UI framework for my website. I want to place the login box in the centre of the page.I want only the login box in the page. I don't understand how to centre aligned using Semantic UI 'grid classes'. Please help me how to fit the login box.

My Code:

<!DOCTYPE html>

<meta charset="UTF-8">
<title>my semantic website</title>
<link rel="stylesheet" href="../css/semantic.min.css">
<link rel="stylesheet" href="../css/style.css">

Account Info

                                Username:

                                    <input type="text" placeholder="Username" name="username" id="username">

                                Password:

                                    <input type="password" placeholder="Password" name="password" id="password">

                            <input type="submit" name="submit" class="ui inverted blue button">

Body:
This is my implementation, it works well.

JsFiddle link

HTML

<div id="v-container" class="ui grid middle aligned">
  <div class="row">
    <div class="column" align="middle">

      <div class="ui raised card ">
        <div class="ui small centered image no-background ">
          <img class="image-margin image-border" src="https://semantic-ui.com/images/wireframe/image.png">
        </div>
        <div class="content">
          <div class="ui header">TITLE</div>
          <div class="meta">
            SUBTITLE
          </div>
          <div class="description">
            <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Ab, alias.</p>
          </div>
        </div>
        <div class="extra content">
          extra content
        </div>
      </div>

    </div>
  </div>

CSS

#v-container {
  background: #ddd;
  height: 100vh;
  width: 100%;
}

.image-margin {
  margin-top: 16px;
  margin-bottom: 16px;
}

.image-border {
  border-radius: 4px !important;
}

.no-background {
  background: transparent !important;
}


问:
When to use an object in `setState` instead of using functional `setState`?
I read a lot of articles about using functional setState like that:

```<code>this.setState((state, props) => ({   counter: state.counter + props.increment }));
</code>```

but when do we actually need to use it as an object like that:

```<code>this.setState({quantity: 2})
</code>```

Is there a significant reason why we should use an object in setState in normal cases vs using it as a function?

答:
The norm is to use an object, it's also less code and easier to read. The only reason u want to use a function setState is when u need to access the previous state.

consider the following example

```<code>// you have a switch state

state = {
   checked: false
}

// .. and later in an onChange method

onChange = () => {
   const {checked} = this.state;
   // this is problematic because react works in an async fashion, so it could be that when this function was called checked was false, however it was only executed later when checked was actually true
   this.setState({checked: !checked}

  // on the other hand  this form is safe, even if things were happening async, you are safe because you act on the most updated state
   this.setState(prvState => {...prvState, checked: !prvState.checked})
}

</code>```

Body:
I read a lot of articles about using functional setState like that:

this.setState((state, props) => ({   counter: state.counter + props.increment }));

but when do we actually need to use it as an object like that:

this.setState({quantity: 2})

Is there a significant reason why we should use an object in setState in normal cases vs using it as a function?

Body:
The norm is to use an object, it's also less code and easier to read. The only reason u want to use a function setState is when u need to access the previous state.

consider the following example

// you have a switch state

state = {
   checked: false
}

// .. and later in an onChange method

onChange = () => {
   const {checked} = this.state;
   // this is problematic because react works in an async fashion, so it could be that when this function was called checked was false, however it was only executed later when checked was actually true
   this.setState({checked: !checked}

  // on the other hand  this form is safe, even if things were happening async, you are safe because you act on the most updated state
   this.setState(prvState => {...prvState, checked: !prvState.checked})
}


问:
Animating a CustomUserControl created at runtime
The issue I am having is that when I begin a storyboard, it changes the value in the object as expected, but there is no visible animation. Nothing happens while the storyboard is running, then when it's done, the object will instantly take the final result of the storyboard (using HoldEnd). The duration of the storyboard basically acts like a delay.

I am using a Scrollviewer with a Stackpanel to display a list of
animated custom-user-controls. These items are 28 pixels high, and
contain buttons to expand and collapse sections holding data.

The items are created when an event is received in my MainWindow and
added to the Scrollviewer using scrData.Dispatcher.Invoke(()=>{}).

I suspect the problem could be the thread which owns these controls. Since they're created in the Scrollviewer's dispatcher method, does that mean the UI thread owns them, or the thread which fired the event owns them?

I have used basically the same code to animate things before, so the only real difference is that these controls were created at run-time.

Any help will be appreciated :)

Here is the relevant bits of my code:

MainWindow.cs: (receive data, make item):

```<code>    private void DataPoller_Update(object sender, DataPollerEventArgs e)
    {
        //New Data arrives here
        if (e.message == "results")
        {
            DisplayData(e.data);
        }
    }

    public void DisplayData(List<DataItem> data){
        scrData.Dispatcher.Invoke(() => {
            int i = 0;
            foreach (DataItem item in data) {
                if (IsInCurrentList(item.id)) {
                    Update_ExistingItemInfo(item);
                }
                else {
                    //Add new item to StackPanel
                    CustomControls.data_item newItem = new CustomControls.data_item(item);
                    stkData.Children.Insert(i, newItem);
                }
                i++;
            }
        }
    }
</code>```

From The UserControl's .cs:

```<code>    DataItem data;

    public data_item(DataItem newData)
    {
        InitializeComponent();
        data = newData;
        PopulateDataFields();
        //THESE ROWS SHOULD EXPAND OR COLLAPSE ON btnExpand_Click
        grdMain.RowDefinitions[1].Height = new GridLength(0);
        grdMain.RowDefinitions[2].Height = new GridLength(0);
    }
     private void btnExpand_Click(object sender, RoutedEventArgs e)
     {
         //For some reason, can't find reference to sb_Expand directly.
        btnExpand.Dispatcher.Invoke(()=> {
            if (rowDrilldown.ActualHeight > 0) {
                Storyboard sb = (Storyboard)this.Resources["sb_Collapse"];
                sb.Begin();
                }
            else {
                Storyboard sb = (Storyboard)this.Resources["sb_Expand"];
                sb.Begin();
                }
        });
     }
</code>```

From the UserControl's xaml:

```<code>    <UserControl.Resources>
            <Storyboard x:Key="sb_Expand">
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(RowDefinition.Height)" Storyboard.TargetName="rowDrilldown" BeginTime="0" FillBehavior="HoldEnd">
                    <DiscreteObjectKeyFrame KeyTime="0:0:0">
                        <DiscreteObjectKeyFrame.Value>
                            <GridLength>0</GridLength>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                    <DiscreteObjectKeyFrame KeyTime="0:0:0.25">
                        <DiscreteObjectKeyFrame.Value>
                            <GridLength>400</GridLength>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
            <Storyboard x:Key="sb_Collapse">
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(RowDefinition.Height)" Storyboard.TargetName="rowDrilldown" BeginTime="0" FillBehavior="HoldEnd">
                    <DiscreteObjectKeyFrame KeyTime="0:0:0">
                        <DiscreteObjectKeyFrame.Value>
                            <GridLength>400</GridLength>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                    <DiscreteObjectKeyFrame KeyTime="0:0:0.25">
                        <DiscreteObjectKeyFrame.Value>
                            <GridLength>0</GridLength>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </UserControl.Resources>

        <Border BorderBrush="AliceBlue" BorderThickness="1" CornerRadius="4">
            <Grid x:Name="grdMain">
                <Grid.RowDefinitions>
                    <RowDefinition Height="28"/>
                    <RowDefinition Height="165"/>
                    <RowDefinition x:Name="rowDrilldown" Height="400"/>
                </Grid.RowDefinitions>
                <!--Textboxes and other CustomControls-->
            </Grid>
        </Border>
</code>```

答:
Found an easier way to do it using VisualStateManager:

```<code><Storyboard x:Key="sb_Expand">
            <DoubleAnimationUsingKeyFrames  Storyboard.TargetProperty="Height" Storyboard.TargetName="scrDrilldown" FillBehavior="HoldEnd">
                <EasingDoubleKeyFrame KeyTime="0:0:0" Value="0"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="390"/>
            </DoubleAnimationUsingKeyFrames>
</Storyboard>
</code>```

.

```<code><Grid x:Name="grdMain">
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="grdMain_VSG">
                        <VisualState x:Name="ExpandItem" Storyboard="{StaticResource sb_Expand}"/>
                        <VisualState x:Name="CollapseItem" Storyboard="{StaticResource sb_Collapse}"/>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>
</code>```

//on button click:

```<code>bool tmp = ExtendedVisualStateManager.GoToElementState(this.grdMain as FrameworkElement, "ExpandItem", true);
</code>```

Body:
The issue I am having is that when I begin a storyboard, it changes the value in the object as expected, but there is no visible animation. Nothing happens while the storyboard is running, then when it's done, the object will instantly take the final result of the storyboard (using HoldEnd). The duration of the storyboard basically acts like a delay.

I am using a Scrollviewer with a Stackpanel to display a list of
animated custom-user-controls. These items are 28 pixels high, and
contain buttons to expand and collapse sections holding data.

The items are created when an event is received in my MainWindow and
added to the Scrollviewer using scrData.Dispatcher.Invoke(()=>{}).

I suspect the problem could be the thread which owns these controls. Since they're created in the Scrollviewer's dispatcher method, does that mean the UI thread owns them, or the thread which fired the event owns them?

I have used basically the same code to animate things before, so the only real difference is that these controls were created at run-time.

Any help will be appreciated :)

Here is the relevant bits of my code:

MainWindow.cs: (receive data, make item):

    private void DataPoller_Update(object sender, DataPollerEventArgs e)
    {
        //New Data arrives here
        if (e.message == "results")
        {
            DisplayData(e.data);
        }
    }

    public void DisplayData(List<DataItem> data){
        scrData.Dispatcher.Invoke(() => {
            int i = 0;
            foreach (DataItem item in data) {
                if (IsInCurrentList(item.id)) {
                    Update_ExistingItemInfo(item);
                }
                else {
                    //Add new item to StackPanel
                    CustomControls.data_item newItem = new CustomControls.data_item(item);
                    stkData.Children.Insert(i, newItem);
                }
                i++;
            }
        }
    }

From The UserControl's .cs:

    DataItem data;

    public data_item(DataItem newData)
    {
        InitializeComponent();
        data = newData;
        PopulateDataFields();
        //THESE ROWS SHOULD EXPAND OR COLLAPSE ON btnExpand_Click
        grdMain.RowDefinitions[1].Height = new GridLength(0);
        grdMain.RowDefinitions[2].Height = new GridLength(0);
    }
     private void btnExpand_Click(object sender, RoutedEventArgs e)
     {
         //For some reason, can't find reference to sb_Expand directly.
        btnExpand.Dispatcher.Invoke(()=> {
            if (rowDrilldown.ActualHeight > 0) {
                Storyboard sb = (Storyboard)this.Resources["sb_Collapse"];
                sb.Begin();
                }
            else {
                Storyboard sb = (Storyboard)this.Resources["sb_Expand"];
                sb.Begin();
                }
        });
     }

From the UserControl's xaml:

    <UserControl.Resources>
            <Storyboard x:Key="sb_Expand">
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(RowDefinition.Height)" Storyboard.TargetName="rowDrilldown" BeginTime="0" FillBehavior="HoldEnd">
                    <DiscreteObjectKeyFrame KeyTime="0:0:0">
                        <DiscreteObjectKeyFrame.Value>
                            <GridLength>0</GridLength>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                    <DiscreteObjectKeyFrame KeyTime="0:0:0.25">
                        <DiscreteObjectKeyFrame.Value>
                            <GridLength>400</GridLength>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
            <Storyboard x:Key="sb_Collapse">
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(RowDefinition.Height)" Storyboard.TargetName="rowDrilldown" BeginTime="0" FillBehavior="HoldEnd">
                    <DiscreteObjectKeyFrame KeyTime="0:0:0">
                        <DiscreteObjectKeyFrame.Value>
                            <GridLength>400</GridLength>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                    <DiscreteObjectKeyFrame KeyTime="0:0:0.25">
                        <DiscreteObjectKeyFrame.Value>
                            <GridLength>0</GridLength>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </UserControl.Resources>

        <Border BorderBrush="AliceBlue" BorderThickness="1" CornerRadius="4">
            <Grid x:Name="grdMain">
                <Grid.RowDefinitions>
                    <RowDefinition Height="28"/>
                    <RowDefinition Height="165"/>
                    <RowDefinition x:Name="rowDrilldown" Height="400"/>
                </Grid.RowDefinitions>

            </Grid>
        </Border>

Body:
Found an easier way to do it using VisualStateManager:

<Storyboard x:Key="sb_Expand">
            <DoubleAnimationUsingKeyFrames  Storyboard.TargetProperty="Height" Storyboard.TargetName="scrDrilldown" FillBehavior="HoldEnd">
                <EasingDoubleKeyFrame KeyTime="0:0:0" Value="0"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="390"/>
            </DoubleAnimationUsingKeyFrames>
</Storyboard>

.

<Grid x:Name="grdMain">
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroup x:Name="grdMain_VSG">
                        <VisualState x:Name="ExpandItem" Storyboard="{StaticResource sb_Expand}"/>
                        <VisualState x:Name="CollapseItem" Storyboard="{StaticResource sb_Collapse}"/>
                    </VisualStateGroup>
                </VisualStateManager.VisualStateGroups>

//on button click:

bool tmp = ExtendedVisualStateManager.GoToElementState(this.grdMain as FrameworkElement, "ExpandItem", true);


问:
Artificial generation of cpu load in Java
Is there a simple way to generate a constant CPU load in Java? Like generate CPU load at 60%.</p>

答:
I think that's not even possible, because:

the way the JVM interprets code (provided it interprets code at all) is implementation-dependent

the compiler, and the JVM, may optimize code (in an implementation-dependent manner, of course) so that you may run different bytecodes than the ones in a given .class file.


问:
None is printing
```<code>def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  print(str(pr))

print(lucky_number("Kay"))
print(lucky_number("Cameron"))
</code>```

output

```<code>Hello Kay. Your lucky number is 27
None
Hello Cameron. Your lucky number is 63
None
</code>```

why iam geting none

答:
While every function might not have an explicit return it will have an implicit one, that is None, which incidentally is a normal Python object. Further, functions often return None explicitly.

So calling the function from within the print, without a return Value so None is returned and being printed.

To avoid this issue you should return a desired value from function.

Title: None is printing

Body:
def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  print(str(pr))

print(lucky_number("Kay"))
print(lucky_number("Cameron"))

output

Hello Kay. Your lucky number is 27
None
Hello Cameron. Your lucky number is 63
None

why iam geting none


问:
Laravel 404 error while viewing image saved in public directory of laravel project
I created Laravel project and able to make it work to get json output as well. However image link in json is not working.

https://android.factory2homes.com/
json: https://android.factory2homes.com/index.php/api/products

image link:https://android.factory2homes.com/index.php/public/12142.jpg

i tried creating symlink and copied same image in storage folder as well, but not able to make it work.

答: I resolved issue by savings images to Public_html folder instead of public folder in Laravel app root folder. Public_html is the path that is visible to public, hence other solutions weren't working. </p>


问:
How do I create a column such that its values is count of the number of,1, in that row, which are appearing for the first time in their own column?
How do I do this operation using pandas?

Initial Df:

```<code>    A B C D
0   0 1 0 0
1   0 1 0 0
2   0 0 1 1
3   0 1 0 1
4   1 1 0 0
5   1 1 1 0
</code>```

Final Df:

```<code>    A B C D Param
0   0 1 0 0     1
1   0 1 0 0     0
2   0 0 1 1     2
3   0 1 0 1     0
4   1 1 0 0     1
5   1 1 1 0     0
</code>```

Basically Param is the number of the 1 in that row which is appearing for the first time in its own column.
Example:
index 0 : 1 in the column B is appearing for the first time hence Param1 = 1

index 1 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 2 : 1 in the column C and D is appearing for the first time  in their columns hence Paramm1 = 2

index 3 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 4 : 1 in the column A is appearing for the first time  in the column hence Paramm1 = 1

index 5 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

答:
Assuming these are integers, you can use cumsum() twice to isolate the first occurrence of 1.

```<code>df2 = (df.cumsum() > 0).cumsum() == 1
df['Param'] = df2.sum(axis = 1)
print(df)
</code>```

If df elements are strings, you should first convert them to integers.

```<code>df = df.astype(int)
</code>```

Body:
How do I do this operation using pandas?

Initial Df:

    A B C D
0   0 1 0 0
1   0 1 0 0
2   0 0 1 1
3   0 1 0 1
4   1 1 0 0
5   1 1 1 0

Final Df:

    A B C D Param
0   0 1 0 0     1
1   0 1 0 0     0
2   0 0 1 1     2
3   0 1 0 1     0
4   1 1 0 0     1
5   1 1 1 0     0

Basically Param is the number of the 1 in that row which is appearing for the first time in its own column.
Example:
index 0 : 1 in the column B is appearing for the first time hence Param1 = 1

index 1 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 2 : 1 in the column C and D is appearing for the first time  in their columns hence Paramm1 = 2

index 3 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

index 4 : 1 in the column A is appearing for the first time  in the column hence Paramm1 = 1

index 5 : none of the 1 is appearing for the first time in its own column hence Param1 = 0

Body:
Assuming these are integers, you can use cumsum() twice to isolate the first occurrence of 1.

df2 = (df.cumsum() > 0).cumsum() == 1
df['Param'] = df2.sum(axis = 1)
print(df)

If df elements are strings, you should first convert them to integers.

df = df.astype(int)


问:
AIOHTTP meme command discord.py
I'm making a discord bot and I'm trying to make a random meme command and here's my error and code:</p>

```<code>@client.command(pass_context=True)
async def meme(ctx):
    embed = discord.Embed(title="meme", description="test")

    async with aiohttp.ClientSession() as cs:
        async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
            res = await r.json()
            embed.set_image(res['data']['children'] [random.randint(0, 25)]['data']['url'])
            await client.say(embed=embed)
</code>```

```<code>Ignoring exception in command meme
Traceback (most recent call last):
  File "C:\Users\atill\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 50, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "C:\Users\atill\Downloads\Epic Bot\server.py", line 165, in meme
    embed.set_image(res['data']['children'] [random.randint(0, 25)]['data']['url'])
TypeError: set_image() takes 1 positional argument but 2 were given

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\atill\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
    yield from command.invoke(ctx)
  File "C:\Users\atill\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 374, in invoke
    yield from injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\atill\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 54, in wrapped
    raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_image() takes 1 positional argument but 2 were given

I'm not sure how to make it so it is in an embed aswell
</code>```

答:
<pre class="lang-py prettyprint-override"><code>@client.command(pass_context=True)
async def meme(ctx):
    embed = discord.Embed(title="", description="")

    async with aiohttp.ClientSession() as cs:
        async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
            res = await r.json()
            embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
            await ctx.send(embed=embed)
</code>```

Title: AIOHTTP meme command discord.py

Body:
I'm making a discord bot and I'm trying to make a random meme command and here's my error and code:

@client.command(pass_context=True)
async def meme(ctx):
    embed = discord.Embed(title="meme", description="test")

    async with aiohttp.ClientSession() as cs:
        async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
            res = await r.json()
            embed.set_image(res['data']['children'] [random.randint(0, 25)]['data']['url'])
            await client.say(embed=embed)

Ignoring exception in command meme
Traceback (most recent call last):
  File "C:\Users\atill\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 50, in wrapped
    ret = yield from coro(*args, **kwargs)
  File "C:\Users\atill\Downloads\Epic Bot\server.py", line 165, in meme
    embed.set_image(res['data']['children'] [random.randint(0, 25)]['data']['url'])
TypeError: set_image() takes 1 positional argument but 2 were given

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\atill\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
    yield from command.invoke(ctx)
  File "C:\Users\atill\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 374, in invoke
    yield from injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\atill\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\ext\commands\core.py", line 54, in wrapped
    raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_image() takes 1 positional argument but 2 were given

I'm not sure how to make it so it is in an embed aswell


问:
MySQL Error - ALTER is not valid at this position
I am trying to execute the following query into MySQL Workbench 8.0.15:

```<code>ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
</code>```

I am receiving an error that states:

"ALTER" is not valid at this position for this server version, expecting : CACHE, CHECKSUM, COMMIT, DEALLOCATE, DO, EXECUTE, ...

What could I do to fix this error?

答: I had the same problem, I fix this error by creating a new connection in Mysql Workbench</p>

Body:
I am trying to execute the following query into MySQL Workbench 8.0.15:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

I am receiving an error that states:

"ALTER" is not valid at this position for this server version, expecting : CACHE, CHECKSUM, COMMIT, DEALLOCATE, DO, EXECUTE, ...

What could I do to fix this error?


问:
Highlight words that do not match the given string
What I'd like to do: when the user finishes typing in some text, I want this text to be tested against another string. If they don't match, I want the symbols that failed the test to be highlighted / colored red. So far I was only able to come up with the following code

let string = "The quick brown fox jumps over the lazy dog";

let input = document.querySelector(".js-textarea");

let receivedValue = "";

let checkValue = function() {
  let regex = new RegExp(string,"g");

  receivedValue = input.value;
  if(!regex.test(receivedValue)) {
    input.classList.add("error");
  };
}

input.addEventListener("change",checkValue);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.error {
  border: 1px solid red;
}</code>```

  <textarea class="js-textarea"></textarea>

```

Just to see whether it is actually being tested, I color the border; but how can I get the symbols/words that don't pass the test?

答:
I just used a style red for the entire div, and then wrap matched text with a span with style black.  Also added ^$ to force match whole string for the test, so the whole string has to match for it to ignore it.

You could also use '(.*?)('+string+')(.*?)' and wrap the 1st and 3rd capture groups with error spans.

I'm not sure if this is what you're looking for, but roughly guessing what you are trying to do:

let string = "The quick brown fox jumps over the lazy dog";

let input = document.querySelector(".js-textarea");

let receivedValue = "";

let checkValue = function() {
  let regex1 = new RegExp(string,"g");
  let regex = new RegExp('^'+string+'$',"g");

  receivedValue = input.value;
  if(!regex.test(receivedValue)) {
      document.getElementById('errorbox').innerHTML=receivedValue.replace(regex1,'$&');
//    input.classList.add("error");
  }
}

input.addEventListener("change",checkValue);
checkValue()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.error {
  border: 1px solid red;
}

.matches {
   color: black
}</code>```

  <textarea class="js-textarea">The quick brown fox jumps over the lazy dog. Jack</textarea>

```

Body:
What I'd like to do: when the user finishes typing in some text, I want this text to be tested against another string. If they don't match, I want the symbols that failed the test to be highlighted / colored red. So far I was only able to come up with the following code

let string = "The quick brown fox jumps over the lazy dog";

let input = document.querySelector(".js-textarea");

let receivedValue = "";

let checkValue = function() {
  let regex = new RegExp(string,"g");

  receivedValue = input.value;
  if(!regex.test(receivedValue)) {
    input.classList.add("error");
  };
}

input.addEventListener("change",checkValue);

.error {
  border: 1px solid red;
}

  <textarea class="js-textarea"></textarea>

Just to see whether it is actually being tested, I color the border; but how can I get the symbols/words that don't pass the test?

Body:
I just used a style red for the entire div, and then wrap matched text with a span with style black.  Also added ^$ to force match whole string for the test, so the whole string has to match for it to ignore it.

You could also use '(.*?)('+string+')(.*?)' and wrap the 1st and 3rd capture groups with error spans.

I'm not sure if this is what you're looking for, but roughly guessing what you are trying to do:

let string = "The quick brown fox jumps over the lazy dog";

let input = document.querySelector(".js-textarea");

let receivedValue = "";

let checkValue = function() {
  let regex1 = new RegExp(string,"g");
  let regex = new RegExp('^'+string+'$',"g");

  receivedValue = input.value;
  if(!regex.test(receivedValue)) {
      document.getElementById('errorbox').innerHTML=receivedValue.replace(regex1,'<span class="matches">$&</span>');
//    input.classList.add("error");
  }
}

input.addEventListener("change",checkValue);
checkValue()

.error {
  border: 1px solid red;
}

.matches {
   color: black
}

<div class="textarea-block">
  <textarea class="js-textarea">The quick brown fox jumps over the lazy dog. Jack</textarea>
</div>

<span id="errorbox" style="color:red"></span>


问:
Wildcards and generics error
The code below is throwaway, a failed idea to get an Enumeration to work in the new foreach loop, however I'd like to get it compiling since I keep running into an issue with generics and wild cards.  For whatever reason I cannot see how to fix it.

So, what changes need to be made to make this compile?

```<code>import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Main
{
    private ZipFile zipFile;

    public Set<String> entries()
    {
        final Set<String>                             names;
        final Enumeration<? extends ZipEntry>         enumeration;
        final IterableEnumeration<? extends ZipEntry> iteratable;

        names = new HashSet<String>();

        // zipFile.entries() returns "Enumeration<? extends ZipEntry>"
        enumeration = zipFile.entries();

        // this line won't compile
        iteratable  = new IterableEnumeration<? extends ZipEntry>(enumeration);

        for(final ZipEntry entry : iteratable)
        {
            if(!(entry.isDirectory()))
            {
                names.add(entry.getName());
            }
        }

        return (names);
    }
}

class IterableEnumeration<T>
    implements Iterable<T>
{
    private final Enumeration<T> enumeration;

    public IterableEnumeration(final Enumeration<T> e)
    {
        enumeration = e;
    }

    public Iterator<T> iterator()
    {
        final EnumerationIterator<T> iterator;

        // yeah cannot do this since an Iterable is supposed to work multiple times on the same object and Enumeration is descructive...
        iterator = new EnumerationIterator<T>(enumeration);

        return (iterator);
    }
}

class EnumerationIterator<T>
    implements Iterator<T>
{
    private final Enumeration<T> enumeration;

    public EnumerationIterator(final Enumeration<T> e)
    {
        enumeration = e;
    }

    public boolean hasNext()
    {
        return (enumeration.hasMoreElements());
    }

    public T next()
    {
        return (enumeration.nextElement());
    }

    public void remove()
    {
        throw new UnsupportedOperationException("Cannt remove via an Enumeration");
    }
}
</code>```

The error is:

```<code>Main.java:26: unexpected type
found   : ? extends java.util.zip.ZipEntry
required: class or interface without bounds
        iteratable  = new IterableEnumeration<? extends ZipEntry>(enumeration);
                                             ^
1 error
</code>```

答:
You cannot specify a wildcard when constructing a parameterized type. This is the correct syntax:

```<code>iteratable  = new IterableEnumeration<ZipEntry>(enumeration);
</code>```

As you noted, there's difficulty in implementing Iterable with an Enumeration because Enumeration is one-time use, while code can rely on Iterable to create as many fresh Iterator objects as it wishes. You could safely use this in enhanced for-loops, but it would be unsafe to pass such an Iterable to any other method.

Oscar is right, the above change is not sufficient. I overlooked the fact that the underlying enumeration is "? extends ZipEntry". In addition, make the following changes:

```<code>class IterableEnumeration<T>
  implements Iterable<T>
{

  private final Enumeration<? extends T> enumeration;

  public IterableEnumeration(final Enumeration<? extends T> e)
  {
    enumeration = e;
  }

  ...
</code>```

and

```<code>class EnumerationIterator<T>
  implements Iterator<T>
{

  private final Enumeration<? extends T> enumeration;

  public EnumerationIterator(final Enumeration<? extends T> e)
  {
    enumeration = e;
  }

  ...
</code>```

These changes basically mean, "IterableEnumeration<T> can collaborate with an Enumeration of any sub-type of T."

OwnerDisplayName: TofuBeer

ContentLicense: CC BY-SA 2.5

Title: Wildcards and generics error

Body:
The code below is throwaway, a failed idea to get an Enumeration to work in the new foreach loop, however I'd like to get it compiling since I keep running into an issue with generics and wild cards.  For whatever reason I cannot see how to fix it.

So, what changes need to be made to make this compile?

import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Main
{
    private ZipFile zipFile;

    public Set<String> entries()
    {
        final Set<String>                             names;
        final Enumeration<? extends ZipEntry>         enumeration;
        final IterableEnumeration<? extends ZipEntry> iteratable;

        names = new HashSet<String>();

        // zipFile.entries() returns "Enumeration<? extends ZipEntry>"
        enumeration = zipFile.entries();

        // this line won't compile
        iteratable  = new IterableEnumeration<? extends ZipEntry>(enumeration);

        for(final ZipEntry entry : iteratable)
        {
            if(!(entry.isDirectory()))
            {
                names.add(entry.getName());
            }
        }

        return (names);
    }
}

class IterableEnumeration<T>
    implements Iterable<T>
{
    private final Enumeration<T> enumeration;

    public IterableEnumeration(final Enumeration<T> e)
    {
        enumeration = e;
    }

    public Iterator<T> iterator()
    {
        final EnumerationIterator<T> iterator;

        // yeah cannot do this since an Iterable is supposed to work multiple times on the same object and Enumeration is descructive...
        iterator = new EnumerationIterator<T>(enumeration);

        return (iterator);
    }
}

class EnumerationIterator<T>
    implements Iterator<T>
{
    private final Enumeration<T> enumeration;

    public EnumerationIterator(final Enumeration<T> e)
    {
        enumeration = e;
    }

    public boolean hasNext()
    {
        return (enumeration.hasMoreElements());
    }

    public T next()
    {
        return (enumeration.nextElement());
    }

    public void remove()
    {
        throw new UnsupportedOperationException("Cannt remove via an Enumeration");
    }
}

The error is:

Main.java:26: unexpected type
found   : ? extends java.util.zip.ZipEntry
required: class or interface without bounds
        iteratable  = new IterableEnumeration<? extends ZipEntry>(enumeration);
                                             ^
1 error

LastEditorDisplayName: Oscar Reyes

Body:
You cannot specify a wildcard when constructing a parameterized type. This is the correct syntax:

iteratable  = new IterableEnumeration<ZipEntry>(enumeration);

As you noted, there's difficulty in implementing Iterable with an Enumeration because Enumeration is one-time use, while code can rely on Iterable to create as many fresh Iterator objects as it wishes. You could safely use this in enhanced for-loops, but it would be unsafe to pass such an Iterable to any other method.

Oscar is right, the above change is not sufficient. I overlooked the fact that the underlying enumeration is "? extends ZipEntry". In addition, make the following changes:

class IterableEnumeration<T>
  implements Iterable<T>
{

  private final Enumeration<? extends T> enumeration;

  public IterableEnumeration(final Enumeration<? extends T> e)
  {
    enumeration = e;
  }

  ...

and

class EnumerationIterator<T>
  implements Iterator<T>
{

  private final Enumeration<? extends T> enumeration;

  public EnumerationIterator(final Enumeration<? extends T> e)
  {
    enumeration = e;
  }

  ...

These changes basically mean, "IterableEnumeration<T> can collaborate with an Enumeration of any sub-type of T."

OwnerDisplayName: erickson

LastEditorDisplayName: erickson


答:
Because you haven't return anything.
If code is like this:

```<code>def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  print(str(pr))
  return "OK"

print(lucky_number("Kay"))
print(lucky_number("Cameron"))
</code>```

Output:

```<code>Hello Kay. Your lucky number is 27
OK
Hello Cameron. Your lucky number is 63
OK
</code>```

Calling the function in print(), prints the output of the function, in this case OK. But the string that you wanted to print is printed by the function itself, not because of the print that is calling the function.

So code like this:

```<code>def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  print(str(pr))

lucky_number("Kay")
lucky_number("Cameron")
</code>```

Output:

```<code>Hello Kay. Your lucky number is 27
Hello Cameron. Your lucky number is 63
</code>```

Title: None is printing

Body:
Because you haven't return anything.
If code is like this:

def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  print(str(pr))
  return "OK"

print(lucky_number("Kay"))
print(lucky_number("Cameron"))

Output:

Hello Kay. Your lucky number is 27
OK
Hello Cameron. Your lucky number is 63
OK

Calling the function in print(), prints the output of the function, in this case OK. But the string that you wanted to print is printed by the function itself, not because of the print that is calling the function.

So code like this:

def lucky_number(name):
  number = int(len(name) * 9)
  pr = "Hello " + name + ". Your lucky number is " + str(number)
  print(str(pr))

lucky_number("Kay")
lucky_number("Cameron")

Output:

Hello Kay. Your lucky number is 27
Hello Cameron. Your lucky number is 63


答:
here you are printing the output:

```<code>print(str(pr))
</code>```

and here you are printing none:

```<code>print(lucky_number("Kay"))
</code>```

why are you printing in calling method?
just call it simply, not printing.

or instead of print(str(pr)) use return str(pr) and print the output while calling the method.

Title: None is printing

Body:
here you are printing the output:

print(str(pr))

and here you are printing none:

print(lucky_number("Kay"))

why are you printing in calling method?
just call it simply, not printing.

or instead of print(str(pr)) use return str(pr) and print the output while calling the method.