问:
Final fields Vs. Volatile
From the java docs of final field semantics:

Final field in JDK14

They are guaranteeing to see the final field as set in constructor, please find the code below:

```<code>class FinalFieldExample {
    final int x;
    int y;
    static FinalFieldExample f;

    public FinalFieldExample() {
        x = 3;
        y = 4;
    }

    static void writer() {
        f = new FinalFieldExample();
    }

    static void reader() {
        if (f != null) {
            int i = f.x;  // guaranteed to see 3
            int j = f.y;  // could see 0
        }
    }
}
</code>```

Now here I am confused about volatile vs final .

To my understanding final filed is used make sure you can not change the variable in application and volatile guarantees to maintain the order and avoid happen before relationship.

So my question is how come they guarantee the visibility and ordering using final variable instead of volatile ? Please help.

答:
So my question is how come they guarantee the visibility and ordering using final variable

Because they defined it that way, and it's now the job of the VM to adhere to this definition.

Of course, the follow-up question is: Why did they define it that way?

It's because of a weird "feature" of the Java memory model. Consider this example

```<code>class Foo {
    int x;
    volatile int y;
    Foo() {
        x = 3;
        y = 4;
    }

    static final Foo INSTANCE;
    static {
       INSTANCE= new Foo();
    }
}
</code>```

The static intitializer will be compiled into this (simplified pseudocode):

```<code>   Foo tmp = allocate(Foo.class)
   Foo.INSTANCE = tmp
   tmp.x = 3
   tmp.y = 4
</code>```

As you can see, the instance is made public before the constructor is executed, volatile doesn't change anything here.

This behavior is unexpected for most developer and can lead to very hard-to-debug bugs. Thus, to reduce the extend of this issue a bit, the specification was adjusted to require final fields to be initialized before the instance is made public.

Example from above, with x declared final.

```<code>   Foo tmp = allocate(Foo.class)
   tmp.x = 3
   Foo.INSTANCE = tmp
   tmp.y = 4
</code>```

Title: Final fields Vs. Volatile

Body:
From the java docs of final field semantics:

Final field in JDK14

They are guaranteeing to see the final field as set in constructor, please find the code below:

class FinalFieldExample {
    final int x;
    int y;
    static FinalFieldExample f;

    public FinalFieldExample() {
        x = 3;
        y = 4;
    }

    static void writer() {
        f = new FinalFieldExample();
    }

    static void reader() {
        if (f != null) {
            int i = f.x;  // guaranteed to see 3
            int j = f.y;  // could see 0
        }
    }
}

Now here I am confused about volatile vs final .

To my understanding final filed is used make sure you can not change the variable in application and volatile guarantees to maintain the order and avoid happen before relationship.

So my question is how come they guarantee the visibility and ordering using final variable instead of volatile ? Please help.

Body:
So my question is how come they guarantee the visibility and ordering using final variable

Because they defined it that way, and it's now the job of the VM to adhere to this definition.

Of course, the follow-up question is: Why did they define it that way?

It's because of a weird "feature" of the Java memory model. Consider this example

class Foo {
    int x;
    volatile int y;
    Foo() {
        x = 3;
        y = 4;
    }

    static final Foo INSTANCE;
    static {
       INSTANCE= new Foo();
    }
}

The static intitializer will be compiled into this (simplified pseudocode):

   Foo tmp = allocate(Foo.class)
   Foo.INSTANCE = tmp
   tmp.x = 3
   tmp.y = 4

As you can see, the instance is made public before the constructor is executed, volatile doesn't change anything here.

This behavior is unexpected for most developer and can lead to very hard-to-debug bugs. Thus, to reduce the extend of this issue a bit, the specification was adjusted to require final fields to be initialized before the instance is made public.

Example from above, with x declared final.

   Foo tmp = allocate(Foo.class)
   tmp.x = 3
   Foo.INSTANCE = tmp
   tmp.y = 4


来源: stackexchange

问:
model.show is not working correctly not getting the id into the controller laravel
so my route is this

```<code>Route::resource('/rentals', 'RentalsController',);
</code>```

and my model is this

```<code>
namespace App;

use Illuminate\Database\Eloquent\Model;

class rentals extends Model
{
    public function avaliablities() {
        return $this->hasMany('\App\avaliablities');
    }
    public function reviews() {
        return $this->hasMany('\App\reviews');
    }
    public function reservations() {
        return $this->hasMany('\App\reservations');
    }
}
</code>```

and the part of the controller in function is this

```<code>    public function show(rentals $rentals)
    {
        dd($rentals);
        $rental = \App\Rentals::with('reviews')->find($rental->id);

        dd($rental);
        return view('detail', compact('rentals'));
    }

</code>```

but when i do the dump and die $rentals there is nothing in it but it also gives no error. (edit it does say it is an int and is an id)

so i am stuck at this and have no idee to fix it probaly something with my routes but i tried the get but that just broke everything when i did

```<code>Route::get('/rentals/{id}','RentalsController@show', );
</code>```

and i am totaly out of idee's

and in previous projects where i used laravel this did work. and as shown here i get the data of the id again from the database so you can go to the page via a link and it doesn't break and also gets updated

and checked if i didn't make a custom id by accedent in the seeder but it looked fine

答:
the problem i had i wil give noman the probs for the right answer this is correct

```<code>Route::get('/Rentals/{rentals}','RentalsController@show', );
</code>```

but what happands with the resource for some reason it got rid of the s while making the routes

look at the picture i added

and i don't think there is anyway to fix this in the code without maby a lot of work

so if you use the cmd to make all the links and want to use the resources don't make it plural (so multiple) but make it one rental

and that should fix the resources

ContentLicense: CC BY-SA 4.0

Body:
so my route is this

Route::resource('/rentals', 'RentalsController',);

and my model is this

namespace App;

use Illuminate\Database\Eloquent\Model;

class rentals extends Model
{
    public function avaliablities() {
        return $this->hasMany('\App\avaliablities');
    }
    public function reviews() {
        return $this->hasMany('\App\reviews');
    }
    public function reservations() {
        return $this->hasMany('\App\reservations');
    }
}

and the part of the controller in function is this

    public function show(rentals $rentals)
    {
        dd($rentals);
        $rental = \App\Rentals::with('reviews')->find($rental->id);

        dd($rental);
        return view('detail', compact('rentals'));
    }

but when i do the dump and die $rentals there is nothing in it but it also gives no error. (edit it does say it is an int and is an id)

so i am stuck at this and have no idee to fix it probaly something with my routes but i tried the get but that just broke everything when i did

Route::get('/rentals/{id}','RentalsController@show', );

and i am totaly out of idee's

and in previous projects where i used laravel this did work. and as shown here i get the data of the id again from the database so you can go to the page via a link and it doesn't break and also gets updated

and checked if i didn't make a custom id by accedent in the seeder but it looked fine

Body:
the problem i had i wil give noman the probs for the right answer this is correct

Route::get('/Rentals/{rentals}','RentalsController@show', );

but what happands with the resource for some reason it got rid of the s while making the routes

look at the picture i added

and i don't think there is anyway to fix this in the code without maby a lot of work

so if you use the cmd to make all the links and want to use the resources don't make it plural (so multiple) but make it one rental

and that should fix the resources


问:
Webview tag not working in Electron, even if tag enabled
So I have been trying to make a simple electron app that uses a <webview> tag, but it's not working at all for me. I already had a little google around and found out that the webview tag needs to be enabled when creating the window.

I used electron-forge to create the boilerplate code. This is the function in index.js that creates the window with webviewTag enabled:

```<code>// Create the browser window.
mainWindow = new BrowserWindow({
    width: 1280,
    height: 800,
    webPreferences: {
        webviewTag: true
    }
});
</code>```

This is the code I have in index.html that is supposed to just show a webpage:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <web-view src="https://github.com" style="display:block; width:700px; height:480px"></web-view>
  </body>
</html>
</code>```

When I have a look through the dev-tools the webview is definetly there and has the dimensions that I set. So it isn't just a case that the webview is just not visible.

Another weird thing is that when I start the app it opens the dev-tools (not surprising as it is in the code), but the page has also a dark background color. Once I close the dev-tools the page becomes white for some reason.

I have some screenshots of this here:

dev-tools open

dev-tools closed

Thanks for reading and thanks in advance for taking the time to help me :)

答: tag should be <webview ... instead of <web-view ...

Body:
So I have been trying to make a simple electron app that uses a <webview> tag, but it's not working at all for me. I already had a little google around and found out that the webview tag needs to be enabled when creating the window.

I used electron-forge to create the boilerplate code. This is the function in index.js that creates the window with webviewTag enabled:

// Create the browser window.
mainWindow = new BrowserWindow({
    width: 1280,
    height: 800,
    webPreferences: {
        webviewTag: true
    }
});

This is the code I have in index.html that is supposed to just show a webpage:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

    <web-view src="https://github.com" style="display:block; width:700px; height:480px"></web-view>

When I have a look through the dev-tools the webview is definetly there and has the dimensions that I set. So it isn't just a case that the webview is just not visible.

Another weird thing is that when I start the app it opens the dev-tools (not surprising as it is in the code), but the page has also a dark background color. Once I close the dev-tools the page becomes white for some reason.

I have some screenshots of this here:

dev-tools open

dev-tools closed

Thanks for reading and thanks in advance for taking the time to help me :)


问:
Function to filter tibble with argument having same name as a column
A petty problem with an obvious solution to rename the parameter of the function. Yet I am interested whether there is a way how I can achieve the following where column name and argument name are the same?

library(dplyr)
d <- data.frame(x = 1:3)

f <- function(x) {
  list(
          ## returns all b/c always true
          d %>% filter(x == x),

          ## does not work either
          ## any way to tell dplyr to use the parameter x
          d %>% filter(.data$x == x)
       )
}
f(1)
```

答:
One option could be:</p>

```<code>f <- function(x) {
 d %>%
  filter(x == !!x)
}
</code>```

Body:
One option could be:

f <- function(x) {
 d %>%
  filter(x == !!x)
}


问:
Return non-nullable type
I'm sure, my code gets not null value for return:

    fun getBitmap(id: Int): Bitmap{
        if (!(id in bitmapStorage))
            bitmapStorage.put(id, BitmapFactory.decodeResource(resources, id))
        return bitmapStorage.get(id)
    }
```

What's the right way to return Bitmap type instead of Bitmap??

!!, as Bitmap or something else?

答:
You can use !! operator or API of MutableMap - getOrPut, it'll return non-null type

```<code>fun getBitmap(id: Int): Bitmap{
    return bitmapStorage.getOrPut(id) {BitmapFactory.decodeResource(resources, id)}
}
</code>```

Note that the operation is not guaranteed to be atomic if the map is being modified concurrently.

Title: Return non-nullable type

Body:
I'm sure, my code gets not null value for return:

    fun getBitmap(id: Int): Bitmap{
        if (!(id in bitmapStorage))
            bitmapStorage.put(id, BitmapFactory.decodeResource(resources, id))
        return bitmapStorage.get(id)
    }

What's the right way to return Bitmap type instead of Bitmap??

!!, as Bitmap or something else?

Body:
You can use !! operator or API of MutableMap - getOrPut, it'll return non-null type

fun getBitmap(id: Int): Bitmap{
    return bitmapStorage.getOrPut(id) {BitmapFactory.decodeResource(resources, id)}
}

Note that the operation is not guaranteed to be atomic if the map is being modified concurrently.


问:
Sharepoint Online Edit but not publish permissions
We are trying to create a group for our Intranet that would allow people to create news posts, but not publish them. Users who have the default Edit permission, are able to publish. Which settings do I need to add to allow people to add drafts, but not publish?</p>

答:
You could enable content approval for the site page library. Go to library settings-> Versioning settings-> enable content approval for the library:

Usually, when an item is in Pending status, only the item originator and the people who have permissions to manage lists and libraries can see it. After its status changes from Pending to Approved, it becomes visible to anyone who has permission to view the list or library.

Read this article for more:

https://support.microsoft.com/en-us/office/require-approval-of-items-in-a-site-list-or-library-cd0761c4-8c3f-4ea2-9435-13c28aa23d08


问:
ORACLE APEX: Try to insert LOGIN PAGE custom email to a table
I try to create a different action when user presses the LOGIN button.
I can't insert values from the LOGIN form.

I Try with this code:

```<code>INSERT INTO DEBTOR_EMAIL VALUES (V':P9999_USERNAME', V':P9999_EMAIL');
</code>```

And I get an error:

ORA-06550: line 1, column 30: ORA-00936: missing expression

Could some please help how to reference form input fields?

答:
Remove v and single quotes:

```<code>INSERT INTO DEBTOR_EMAIL VALUES (:P9999_USERNAME, :P9999_EMAIL);
</code>```

Body:
I try to create a different action when user presses the LOGIN button.
I can't insert values from the LOGIN form.

I Try with this code:

INSERT INTO DEBTOR_EMAIL VALUES (V':P9999_USERNAME', V':P9999_EMAIL');

And I get an error:

ORA-06550: line 1, column 30: ORA-00936: missing expression

Could some please help how to reference form input fields?

Body:
Remove v and single quotes:

INSERT INTO DEBTOR_EMAIL VALUES (:P9999_USERNAME, :P9999_EMAIL);


问:
Php query to mysql database not giving desired results
So I have a database table with months, the number value for the months and years. eg. June, 6, 2020.

I have a select drop-down that dynamically populates based on the data from the table.

The idea is, if the current month is June, the select dropdown should only be populated with the months of June to December.

The issue I am having, which I don't undestand, is that on the page when I run the query, the drop down is only being populated with May to September. Whereas if I run the same query directly on the table in the database, I get the desired results.

The query below:

```<code>    $yvalue = $_POST['years']; //assume this to be "2020";
    $curyear = date('Y');
    $curmonth = date('n'); // Lets also assume this to be "5";

    if ($yvalue==$curyear) {

    $query = "SELECT calmonthsID, months, value, years from calmonths WHERE years=? AND value>=? ORDER BY calmonthsID ASC";
    $stmt = $connQlife->prepare($query);
    $stmt->bind_param('ss', $yvalue, $curmonth);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($calmonthsID, $months, $value, $years);

    }else{
    $query = "SELECT calmonthsID, months, value, years from calmonths WHERE years=? ORDER BY calmonthsID ASC";
    $stmt = $connQlife->prepare($query);
    $stmt->bind_param('s', $yvalue);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($calmonthsID, $months, $value, $years);
    }

    echo "<option>- Select Month -</option>";

    while($stmt->fetch()) {
        echo '<option value='.$value.'>'.$months.'</option>';
    } $stmt->close();
</code>```

When the above query runs on the page, the drop down is populated with months May to September. Omitting October to December.

When I assumed $curmonth = date('n'); to be 10 I get the drop down populated with months February to December. Omitting January.

Again When I assumed $curmonth = date('n'); to be 11 I get the drop down populated with months February to December. Omitting January and October.

And when I assumed 12, January, October  and November were missing.

But running all these queries directly in the database gave the desired results. So I am puzzled as to what is wrong or what is happening when running the queries in Php.

This is the database data:

```<code>calmonthsID  months      value     years
1            January      1        2020
2            Febuary      2        2020
3            March        3        2020
4            April        4        2020
5            May          5        2020
6            June         6        2020
7            July         7        2020
8            August       8        2020
9            September    9        2020
10           October      10       2020
11           November     11       2020
12           December     12       2020
13           January      1        2021
....
</code>```

答:
It looks like you've defined the value column in your database as varchar instead of int. It needs to be int, otherwise MySQL will do a string comparison for the >= test in your query instead of a numeric comparison.

A string comparison does a character-by-character comparison of the two values, with the result that, for example 5 is seen as greater than 10 because it actually compares the 5 with the 1 first.

It's important that you assign the correct data type to your columns - if you want something to be treated as a number and be able to do maths on it, then you must declare it as a numeric field.

You can see the difference in the results with the two different data types here: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=def28599d8180932de25342ea6647782

Body:
So I have a database table with months, the number value for the months and years. eg. June, 6, 2020.

I have a select drop-down that dynamically populates based on the data from the table.

The idea is, if the current month is June, the select dropdown should only be populated with the months of June to December.

The issue I am having, which I don't undestand, is that on the page when I run the query, the drop down is only being populated with May to September. Whereas if I run the same query directly on the table in the database, I get the desired results.

The query below:

    $yvalue = $_POST['years']; //assume this to be "2020";
    $curyear = date('Y');
    $curmonth = date('n'); // Lets also assume this to be "5";

    if ($yvalue==$curyear) {

    $query = "SELECT calmonthsID, months, value, years from calmonths WHERE years=? AND value>=? ORDER BY calmonthsID ASC";
    $stmt = $connQlife->prepare($query);
    $stmt->bind_param('ss', $yvalue, $curmonth);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($calmonthsID, $months, $value, $years);

    }else{
    $query = "SELECT calmonthsID, months, value, years from calmonths WHERE years=? ORDER BY calmonthsID ASC";
    $stmt = $connQlife->prepare($query);
    $stmt->bind_param('s', $yvalue);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($calmonthsID, $months, $value, $years);
    }

    echo "<option>- Select Month -</option>";

    while($stmt->fetch()) {
        echo '<option value='.$value.'>'.$months.'</option>';
    } $stmt->close();

When the above query runs on the page, the drop down is populated with months May to September. Omitting October to December.

When I assumed $curmonth = date('n'); to be 10 I get the drop down populated with months February to December. Omitting January.

Again When I assumed $curmonth = date('n'); to be 11 I get the drop down populated with months February to December. Omitting January and October.

And when I assumed 12, January, October  and November were missing.

But running all these queries directly in the database gave the desired results. So I am puzzled as to what is wrong or what is happening when running the queries in Php.

This is the database data:

calmonthsID  months      value     years
1            January      1        2020
2            Febuary      2        2020
3            March        3        2020
4            April        4        2020
5            May          5        2020
6            June         6        2020
7            July         7        2020
8            August       8        2020
9            September    9        2020
10           October      10       2020
11           November     11       2020
12           December     12       2020
13           January      1        2021
....


问:
Button that moves box with text - JavaScript Jquery
I have to make this first button called "натисни" make box "кутийка с текст" move to right by 10px when i click the button. Any suggestions ?

Here is the code.

http://jsfiddle.net/08y7rqf5/

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", () => {
  banner.toggleClass("alt")
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

кутийка с текст

            <input type="button" class="btn btn-info float-right" value="Натисни">

```

答:
give the div an ID - I use move

Add CSS #move { position:relative}  - you cannot move unless it is position absolute or relative

Add the script -(but do not have onclick or similar)

$(function() {
  $('[value="Натисни"]').on("click",function() {
    const div = $(this).prev(); // or $("#move")
    let pos = Math.round(div.position().left)
    div.css({"left":(pos+10)+"px"}); // or $("#move").css(....)
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

#move { position:relative}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  </script>

кутийка с текст

            <input type="button" class="btn btn-info float-right" value="Натисни">

```

Body:
I have to make this first button called "натисни" make box "кутийка с текст" move to right by 10px when i click the button. Any suggestions ?

Here is the code.

http://jsfiddle.net/08y7rqf5/

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", () => {
  banner.toggleClass("alt")
})

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

кутийка с текст

            <input type="button" class="btn btn-info float-right" value="Натисни">

Body:
give the div an ID - I use move

Add CSS #move { position:relative}  - you cannot move unless it is position absolute or relative

Add the script -(but do not have onclick or similar)

$(function() {
  $('[value="Натисни"]').on("click",function() {
    const div = $(this).prev(); // or $("#move")
    let pos = Math.round(div.position().left)
    div.css({"left":(pos+10)+"px"}); // or $("#move").css(....)
  })
})

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

#move { position:relative}

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

  </script>
</head>
<body>
  <!-- задача 1 -->
  <div class="container my-5">
    <div class="row">
      <div class="col-12">
        <ul class="list-group">
          <li class="list-group-item">
            <div id="move" class="d-inline-block border p-2 bg-primary text-white" data-margin="10">кутийка с текст</div>
            <input type="button" class="btn btn-info float-right" value="Натисни">
          </li>
        </ul>
      </div>
    </div>
  </div>


问:
Can someone explain the parameter void(*pfn)(void*)?
I've come across this piece of code

```<code>inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)
</code>```

I don't understand this part

```<code>void(*pfn)(void*)
</code>```

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

答:
It is a function pointer. The name pfn is a clue. Specifically it is a pointer to a function that takes a "void pointer" and returns nothing. A "void pointer" is a fake type that can be cast to some other kind of pointer. </p>

<p>Most C++ books cover both void pointers and function pointers in some detail. Probably more detail than necessary, since you can write perfectly good C++ code without ever using either. If your books are somehow all super modern and don't cover them, look for a C reference. </p>

ContentLicense: CC BY-SA 3.0

Body:
I've come across this piece of code

inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false)

I don't understand this part

void(*pfn)(void*)

Can someone tell me what it means/is?

This is btw not listed in books for beginners so if you want to mention to read books, it's not there.

Afaik, void is datatype of a function meaning it will not return anything, however that part there...void is used on a pointer?

Body:
It is a function pointer. The name pfn is a clue. Specifically it is a pointer to a function that takes a "void pointer" and returns nothing. A "void pointer" is a fake type that can be cast to some other kind of pointer.

Most C++ books cover both void pointers and function pointers in some detail. Probably more detail than necessary, since you can write perfectly good C++ code without ever using either. If your books are somehow all super modern and don't cover them, look for a C reference.


问:
Locate the Keys with same values in JSON
I have below json

```<code>[{
    "workType": "NDB To Nice",
    "priority": 5
},
{
    "workType": "PDAD",
    "priority": 0
}, {
    "workType": "PPACA",
    "priority": 0
}, {
    "workType": "Retrigger",
    "priority": "5"
}, {
    "workType": "Special Intake Request Intake",
    "priority": "7"
}]
</code>```

I need to call out all the "worktype" which have same "priority" , iff the priority is NOT EQUAL TO 0.

Means for above example i should get keys = ["NDB To Nice","Retrigger"] since they both have priority 5.

I have tried below code

```<code>  function(array, k) {
  return array.reduce(function(acc, cur) {
    (acc[cur[k]] = acc[cur[k]] || []).push(cur);
    return acc;
  }, {});
};
</code>```

But i am not able to achieve the output.

答:
const array = [{ "workType": "NDB To Nice", "priority": 5 }, { "workType": "PDAD", "priority": 0 }, { "workType": "PPACA", "priority": 0 }, { "workType": "Retrigger", "priority": "5" }, { "workType": "Special Intake Request Intake", "priority": "7" }];
const output = array.filter(a => a.priority > 0 && array.filter(a2=> a.priority == a2.priority).length > 1).map(a => a.workType);
console.log(output)```

Body:
I have below json

[{
    "workType": "NDB To Nice",
    "priority": 5
},
{
    "workType": "PDAD",
    "priority": 0
}, {
    "workType": "PPACA",
    "priority": 0
}, {
    "workType": "Retrigger",
    "priority": "5"
}, {
    "workType": "Special Intake Request Intake",
    "priority": "7"
}]

I need to call out all the "worktype" which have same "priority" , iff the priority is NOT EQUAL TO 0.

Means for above example i should get keys = ["NDB To Nice","Retrigger"] since they both have priority 5.

I have tried below code

  function(array, k) {
  return array.reduce(function(acc, cur) {
    (acc[cur[k]] = acc[cur[k]] || []).push(cur);
    return acc;
  }, {});
};

But i am not able to achieve the output.


问:
Bokeh: Hovertool stacks on old instances after callback triggered
I've got a program that displays stock market info for a google. I can adjust it with a DateRangeSlider to increase the dates that we're looking at. I also have a hovertool set on the chart to display the various aspects of the data for each respective day.

The issue I'm having is on callback. Instead of the hover data being refreshed with each call, it retains memory of previous calls and just stacks the previous hover info on top of the new.

Here's my code for running in Jupyter:

```<code>from pandas_datareader import data
from pandas import Timedelta
from datetime import datetime, date
from bokeh.plotting import figure, show
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, HoverTool, NumeralTickFormatter, DatetimeTickFormatter, TextInput, DateRangeSlider
from bokeh.io import output_notebook, curdoc

output_notebook()

def inc_dec(c, o):
"""Determines if the financial day with and Increase or Decrease"""
    if c > o:
        return "Increase"
    elif c == 0:
        return "Equal"
    else:
        return "Decrease"

def get_sources(start = date(2016, 3, 1), end = date(2016, 3, 10), company = "GOOG"):
"""Gets all my dataframes for each glyph below"""

    #Gather data for df's
    df = data.DataReader(company, data_source="yahoo", start=start, end=end)
    df["Status"] = [inc_dec(c, o) for c, o in zip(df.Close, df.Open)]
    df["Mid"] = (df.Open + df.Close) / 2
    df["Height"] = abs(df.Open - df.Close)
    df["Width"] = 12*60*60*1000
    df["Segment, Left"] = df.index - Timedelta(hours=2)
    df["Segment, Right"] = df.index + Timedelta(hours=2)

    #my df is complete. Split them
    inc_df = df[df.Status == "Increase"]
    dec_df = df[df.Status == "Decrease"]

    #inc_s = ColumnDataSource(inc_df)
    #dec_s = ColumnDataSource(dec_df)
    #tot_s = ColumnDataSource(df)
    #Dictionary of dataframes, Increasing, Decreasing, and Total
    dfs = {"I": inc_df, "D": dec_df, "T": df}

    return dfs

def fin(doc):
"""Initialize the graphs and make an application"""

    #Get df's and convert to CDS
    dfs = get_sources()
    inc_s = ColumnDataSource(dfs["I"])
    dec_s = ColumnDataSource(dfs["D"])
    tot_s = ColumnDataSource(dfs["T"])

    hover = HoverTool(names=["inc","dec"],
                    tooltips = [("Date", "@Date{%m/%d/%Y}"),
                        ("High", "@High{$0.00}"),
                        ("Low","@Low{$0.00}"),
                        ("Open","@Open{$0.00}"),
                        ("Close","@Close{$0.00}"),
                        ("Volume", "@Volume{0,0}")],
                    formatters = {"@Date" : "datetime"})

    #Formatting the plot, p
    p = figure(x_axis_type="datetime", width=1000, height=300, sizing_mode="scale_width", tools="crosshair,pan,wheel_zoom,box_zoom,reset")
    #p.title.text = "{}: Finacial Data".format(company)       #Change this with company later
    p.title.text = "GOOG: Financial Data"
    p.title.align = "center"
    p.xaxis.axis_label="Date"
    p.yaxis.axis_label="Price"
    p.yaxis.formatter = NumeralTickFormatter(format="$0,0.00")
    p.grid.grid_line_alpha = 0.3

    #Add glyphs
    p.segment(x0='Date', y0='High', x1='Date', y1='Low', source=tot_s) #vertical
    p.segment(x0='Segment, Left', y0='High', x1='Segment, Right', y1='High', source=tot_s) #high
    p.segment(x0='Segment, Left', y0='Low', x1='Segment, Right', y1='Low', source=tot_s) #low
    p.rect(x="Date", y="Mid", width="Width", height="Height", name="inc",
        fill_color="#00FFFF", line_color="black", source=inc_s)
    p.rect(x="Date", y="Mid", width="Width", height="Height", name="dec",
        fill_color="#B22222", line_color="black", source=dec_s)

    p.add_tools(hover)

    #the callbacks
    def cb_date(attr, new, old):
    """Callback for the DateRangeSlider"""

        if not isinstance(new[0], int):
            return None
        else:
            #Get new dates, pass them to get_sources to get df's, add new CDS's
            start = date.fromtimestamp(new[0]/1000)
            end = date.fromtimestamp(new[1]/1000)
            dfs = get_sources(start=start, end=end)
            inc_s.stream(dfs["I"])
            dec_s.stream(dfs["D"])
            tot_s.stream(dfs["T"])

    #def cb_com(attr, new, old):
        #Changes the company name, do later

    #add widgets
    slider = DateRangeSlider(start=date(2016, 1, 1),
                                     end=date(2016, 5, 1),
                                     value=(date(2016, 3, 1), date(2016, 3, 10)),
                                     step=1,
                                     title="Change Dates:")

    slider.on_change('value', cb_date)

    doc.add_root(column(slider,p))

show(fin)
</code>```

Let me know what how I can go forward with this. I'm pretty lost.

答: I cannot run your code without some test data, but it seems to me that the issue is with the calls to the stream function. Streaming data does not remove the old data, even if the X coordinate is the same (data sources don't know and don't care about coordinates). If you want to replace the data for some particular date, you should use patch. If you want to replace the whole data, you should just assign the new value to the data attribute of a data source.

Body:
I've got a program that displays stock market info for a google. I can adjust it with a DateRangeSlider to increase the dates that we're looking at. I also have a hovertool set on the chart to display the various aspects of the data for each respective day.

The issue I'm having is on callback. Instead of the hover data being refreshed with each call, it retains memory of previous calls and just stacks the previous hover info on top of the new.

Here's my code for running in Jupyter:

from pandas_datareader import data
from pandas import Timedelta
from datetime import datetime, date
from bokeh.plotting import figure, show
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, HoverTool, NumeralTickFormatter, DatetimeTickFormatter, TextInput, DateRangeSlider
from bokeh.io import output_notebook, curdoc

output_notebook()

def inc_dec(c, o):
"""Determines if the financial day with and Increase or Decrease"""
    if c > o:
        return "Increase"
    elif c == 0:
        return "Equal"
    else:
        return "Decrease"

def get_sources(start = date(2016, 3, 1), end = date(2016, 3, 10), company = "GOOG"):
"""Gets all my dataframes for each glyph below"""

    #Gather data for df's
    df = data.DataReader(company, data_source="yahoo", start=start, end=end)
    df["Status"] = [inc_dec(c, o) for c, o in zip(df.Close, df.Open)]
    df["Mid"] = (df.Open + df.Close) / 2
    df["Height"] = abs(df.Open - df.Close)
    df["Width"] = 12*60*60*1000
    df["Segment, Left"] = df.index - Timedelta(hours=2)
    df["Segment, Right"] = df.index + Timedelta(hours=2)

    #my df is complete. Split them
    inc_df = df[df.Status == "Increase"]
    dec_df = df[df.Status == "Decrease"]

    #inc_s = ColumnDataSource(inc_df)
    #dec_s = ColumnDataSource(dec_df)
    #tot_s = ColumnDataSource(df)
    #Dictionary of dataframes, Increasing, Decreasing, and Total
    dfs = {"I": inc_df, "D": dec_df, "T": df}

    return dfs

def fin(doc):
"""Initialize the graphs and make an application"""

    #Get df's and convert to CDS
    dfs = get_sources()
    inc_s = ColumnDataSource(dfs["I"])
    dec_s = ColumnDataSource(dfs["D"])
    tot_s = ColumnDataSource(dfs["T"])

    hover = HoverTool(names=["inc","dec"],
                    tooltips = [("Date", "@Date{%m/%d/%Y}"),
                        ("High", "@High{$0.00}"),
                        ("Low","@Low{$0.00}"),
                        ("Open","@Open{$0.00}"),
                        ("Close","@Close{$0.00}"),
                        ("Volume", "@Volume{0,0}")],
                    formatters = {"@Date" : "datetime"})

    #Formatting the plot, p
    p = figure(x_axis_type="datetime", width=1000, height=300, sizing_mode="scale_width", tools="crosshair,pan,wheel_zoom,box_zoom,reset")
    #p.title.text = "{}: Finacial Data".format(company)       #Change this with company later
    p.title.text = "GOOG: Financial Data"
    p.title.align = "center"
    p.xaxis.axis_label="Date"
    p.yaxis.axis_label="Price"
    p.yaxis.formatter = NumeralTickFormatter(format="$0,0.00")
    p.grid.grid_line_alpha = 0.3

    #Add glyphs
    p.segment(x0='Date', y0='High', x1='Date', y1='Low', source=tot_s) #vertical
    p.segment(x0='Segment, Left', y0='High', x1='Segment, Right', y1='High', source=tot_s) #high
    p.segment(x0='Segment, Left', y0='Low', x1='Segment, Right', y1='Low', source=tot_s) #low
    p.rect(x="Date", y="Mid", width="Width", height="Height", name="inc",
        fill_color="#00FFFF", line_color="black", source=inc_s)
    p.rect(x="Date", y="Mid", width="Width", height="Height", name="dec",
        fill_color="#B22222", line_color="black", source=dec_s)

    p.add_tools(hover)

    #the callbacks
    def cb_date(attr, new, old):
    """Callback for the DateRangeSlider"""

        if not isinstance(new[0], int):
            return None
        else:
            #Get new dates, pass them to get_sources to get df's, add new CDS's
            start = date.fromtimestamp(new[0]/1000)
            end = date.fromtimestamp(new[1]/1000)
            dfs = get_sources(start=start, end=end)
            inc_s.stream(dfs["I"])
            dec_s.stream(dfs["D"])
            tot_s.stream(dfs["T"])

    #def cb_com(attr, new, old):
        #Changes the company name, do later

    #add widgets
    slider = DateRangeSlider(start=date(2016, 1, 1),
                                     end=date(2016, 5, 1),
                                     value=(date(2016, 3, 1), date(2016, 3, 10)),
                                     step=1,
                                     title="Change Dates:")

    slider.on_change('value', cb_date)

    doc.add_root(column(slider,p))

show(fin)

Let me know what how I can go forward with this. I'm pretty lost.


问:
django.urls.exceptions.NoReverseMatch: Reverse for 'new_entry' with arguments '(1,)' not found. 1 pattern(s) tried: ['new_entry/$']
I am currently working on a tutorial in the "Python Crash course" Book.

The tutorial is about creating a "Learning Log" Webapp with Django. The idea of the app is to allow users to: 1. create "Topics" they have learned about 2. add "Entries" to those Topics, describing details they have learned specific to those topics

I am currently stuck at editing an existing Entry form and receive an Error, when I run
http://127.0.0.1:8000/topics/2/

forms.py file

```<code>    from django import forms
    from .models import Topic,Entry
    class Topicform(forms.ModelForm):
         class Meta:
         model = Topic
         fields =['text']
         labels = {'text' :''}
    class Entryform(forms.ModelForm):
        class Meta:
        model = Entry
        fields =['text']
        labels = {'text' :''}
        widgets = {'text' : forms.Textarea(attrs={'cols':80})}
</code>```

urls.py file

```<code>    from django.conf.urls import url
    from . import views
    app_name='learning_logs'
    urlpatterns=[
      #Home page
    url(r'^$',views.index,name='index'),
      #Show all topics page
    url(r'^topics/$',views.topics,name='topics'),
      #Detail page for a single topic
    url(r'^topics/(?P<topic_id>\d+)/$',views.topic,name='topic'),
      #Page for adding a new topic
    url(r'^new_topic/$',views.new_topic,name='new_topic'),
      #Page for adding a new entry
    url(r'^new_entry/$',views.new_entry,name='new_entry'),
      #Page for editing an entry
    url(r'^edit_entry/(?P<entry_id>\d+)/$',views.edit_entry,name='edit_entry'),
</code>```

]

views.py file

```<code>    from django.http import HttpResponseRedirect
    from django.urls import reverse
    from django.shortcuts import render
    from .models import Topic,Entry
    from .forms import Topicform, Entryform
    --snip--
    def edit_entry(request,entry_id):
        entry = Entry.objects.get(id=entry_id)
        topic=entry.topic

        if request.method != 'POST':
        # No data submitted; create a blank form
           form = Entryform(instance = entry)
        else:
        # Post data submitted;process data
           form = Entryform(request.POST,instance=entry)
           if form.is_valid():
                form.save()
        return HttpResponseRedirect(reverse('learning_logs:topics',args=[topic.id]))

   context={'entry':entry,'topic':topic,'form':form}
   return render(request,'learning_logs/edit_entry.html',context)
</code>```

edit_entry.html file

```<code>    {% extends "learning_logs/base.html" %}

    {% block content %}

    <p><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p>

    <p>Edit Entry:</p>
    <form action= "{%url 'learning_logs:edit_entry' entry.id %}" method = 'post'>
        {%csrf_token %}
        {{form.as_p}}
    <button name="submit">save changes</button>
    </form>

   {% endblock content %}
</code>```

topic.html file

```<code>    {% extends "learning_logs/base.html" %}

    {% block content %}
    <p> Topic: {{topic}} </p>
    <p> Entries:</p>
    <p>
       <a href="{% url 'learning_logs:new_entry' topic.id %}">Add new entry</a>
    </p>
    <ul>
         {%for entry in entries%}
       <li>
         <p> {{entry.date_added|date:'M d,Y H:i'}} </p>
         <p> {{entry.text|linebreaks}} </p>
         <p>
            <a href="{% url 'learning_logs:edit_entry' entry.id %}">edit entry</a>
         </p>
      </li>
  {%empty%}
      <li>
         There are no entries for this topic yet.
      </li>
 {% endfor %}
 </ul>
{% endblock content %}
</code>```

答:
Adding to Biplove's answer,
In your views.py file, Your topics path doesn't take any parameters. May have been a silly typo due to the way you named your urls

So, if you want to return to the list of topics after editing, you should change

```<code>return HttpResponseRedirect(reverse('learning_logs:topics',args=[topic.id]))
</code>```

To

```<code>return HttpResponseRedirect(reverse('learning_logs:topics')
</code>```

But if you want to return to the topic you just edited, you should do this then...

```<code>return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id]))
</code>```

Body:
I am currently working on a tutorial in the "Python Crash course" Book.

The tutorial is about creating a "Learning Log" Webapp with Django. The idea of the app is to allow users to: 1. create "Topics" they have learned about 2. add "Entries" to those Topics, describing details they have learned specific to those topics

I am currently stuck at editing an existing Entry form and receive an Error, when I run
http://127.0.0.1:8000/topics/2/

forms.py file

    from django import forms
    from .models import Topic,Entry
    class Topicform(forms.ModelForm):
         class Meta:
         model = Topic
         fields =['text']
         labels = {'text' :''}
    class Entryform(forms.ModelForm):
        class Meta:
        model = Entry
        fields =['text']
        labels = {'text' :''}
        widgets = {'text' : forms.Textarea(attrs={'cols':80})}

urls.py file

    from django.conf.urls import url
    from . import views
    app_name='learning_logs'
    urlpatterns=[
      #Home page
    url(r'^$',views.index,name='index'),
      #Show all topics page
    url(r'^topics/$',views.topics,name='topics'),
      #Detail page for a single topic
    url(r'^topics/(?P<topic_id>\d+)/$',views.topic,name='topic'),
      #Page for adding a new topic
    url(r'^new_topic/$',views.new_topic,name='new_topic'),
      #Page for adding a new entry
    url(r'^new_entry/$',views.new_entry,name='new_entry'),
      #Page for editing an entry
    url(r'^edit_entry/(?P<entry_id>\d+)/$',views.edit_entry,name='edit_entry'),

]

views.py file

    from django.http import HttpResponseRedirect
    from django.urls import reverse
    from django.shortcuts import render
    from .models import Topic,Entry
    from .forms import Topicform, Entryform
    --snip--
    def edit_entry(request,entry_id):
        entry = Entry.objects.get(id=entry_id)
        topic=entry.topic

        if request.method != 'POST':
        # No data submitted; create a blank form
           form = Entryform(instance = entry)
        else:
        # Post data submitted;process data
           form = Entryform(request.POST,instance=entry)
           if form.is_valid():
                form.save()
        return HttpResponseRedirect(reverse('learning_logs:topics',args=[topic.id]))

   context={'entry':entry,'topic':topic,'form':form}
   return render(request,'learning_logs/edit_entry.html',context)

edit_entry.html file

    {% extends "learning_logs/base.html" %}

    {% block content %}

{{ topic }}

Edit Entry:

    <form action= "{%url 'learning_logs:edit_entry' entry.id %}" method = 'post'>
        {%csrf_token %}
        {{form.as_p}}
    <button name="submit">save changes</button>
    </form>

   {% endblock content %}

topic.html file

    {% extends "learning_logs/base.html" %}

    {% block content %}

 Topic: {{topic}}

 Entries:

       Add new entry

         {%for entry in entries%}

 {{entry.date_added|date:'M d,Y H:i'}}

 {{entry.text|linebreaks}}

            edit entry

  {%empty%}

         There are no entries for this topic yet.

 {% endfor %}

{% endblock content %}

Body:
Adding to Biplove's answer,
In your views.py file, Your topics path doesn't take any parameters. May have been a silly typo due to the way you named your urls

So, if you want to return to the list of topics after editing, you should change

return HttpResponseRedirect(reverse('learning_logs:topics',args=[topic.id]))

To

return HttpResponseRedirect(reverse('learning_logs:topics')

But if you want to return to the topic you just edited, you should do this then...

return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id]))


问:
How do i use a complex type derived from an abstract complex type using php and Soap
I recently started working with SOAP but and finding it hard to understand the use of abstract complex types.

I am trying to place a request to a wsdl yet I keep getting the error. 'The specified type is abstract: name="HomeAffairsIDVRequestedBase".

My php is as follows :

```<code>$result = $this->soap->__soapCall('PlaceRequest',array('PlaceRequest'=>
                                               array('request' =>
                                                   array(
                                                            'type'=> 'tns:HomeAffairsIDVStandardRequest',
                                                            "IsBatchSearch"=>false,
                                                            "ParentRequestId"=>0,
                                                            "Reference"=>'test',
                                                            "Requester"=>'axxess',
                                                            "SessionId"=>'true',
                                                            "IdNumber"=>$this->idNumber
                                                            ))));
</code>```

and the targeted wsdl section is as follows

```<code><s:element name="PlaceRequest">
    <s:complexType>
        <s:sequence>
            <s:element minOccurs="0" maxOccurs="1" name="request" type="tns:HomeAffairsIDVRequestBase"/>
        </s:sequence>
    </s:complexType>
</s:element>
<s:complexType name="HomeAffairsIDVRequestBase" abstract="true">
    <s:sequence>
        <s:element minOccurs="1" maxOccurs="1" name="IsBatchSearch" type="s:boolean"/>
        <s:element minOccurs="1" maxOccurs="1" name="ParentRequestId" nillable="true" type="s:int"/>
        <s:element minOccurs="0" maxOccurs="1" name="Reference" type="s:string"/>
        <s:element minOccurs="0" maxOccurs="1" name="Requester" type="s:string"/>
        <s:element minOccurs="1" maxOccurs="1" name="SessionId" nillable="true" type="s1:guid"/>
    </s:sequence>
</s:complexType>
<s:complexType name="HomeAffairsIDVRequest" abstract="true">
    <s:complexContent mixed="false">
        <s:extension base="tns:HomeAffairsIDVRequestBase">
            <s:sequence>
                <s:element minOccurs="0" maxOccurs="1" name="IdNumber" type="s:string"/>
            </s:sequence>
        </s:extension>
    </s:complexContent>
</s:complexType>
<s:complexType name="HomeAffairsIDVStandardRequest">
    <s:complexContent mixed="false">
        <s:extension base="tns:HomeAffairsIDVRequest"/>
    </s:complexContent>
</s:complexType>
<s:complexType name="HomeAffairsIDVAdvancedRequest">
    <s:complexContent mixed="false">
        <s:extension base="tns:HomeAffairsIDVRequest"/>
    </s:complexContent>
</s:complexType>
</code>```

Note: I can not edit the wsdl.

答:
You can read complex type definitions from the wsdl as php class definitions. Each complex type is a php value object. Abstract complex types are abstract value object, which can be inherited from.

As we have the complex types defined, we can build our php classes.

```<code>abstract class HomeAffairsIDVRequestBase
{
    protected bool $IsBatchSearch;
    protected int $ParentRequestId;
    protected ?string $Reference;
    protected ?string $Requester;
    protected string $SessionId;

    public function getIsBatchSearch(): bool
    {
        return $this->IsBatchSearch;
    }

    public function setIsBatchSearch(bool $isBatchSearch): self
    {
        $this->isBatchSearch = $isBatchSearch;
        return $this;
    }

    public function getParentRequestId(): int
    {
        return $this->ParentRequestId;
    }

    public function setParentRequestId(int $parentRequestId): self
    {
        $this->ParentRequestId = $parentRequestId;
        return $this;
    }

    public function getReference(): ?string
    {
        return $this->Reference;
    }

    public function setReference(string $reference): self
    {
        $this->Reference = $reference;
        return $this;
    }

    public function getRequester(): ?string
    {
        return $this->Requester;
    }

    public function setRequester(string $requester): self
    {
        $this->Requester = $requester;
        return $this;
    }

    public function getSessionId(): string
    {
        return $this->SessionId;
    }

    public function setSessionId(string $sessionId): self
    {
        $this->SessionId = $sessionId;
        return $this;
    }
}
</code>```

This is our first abstract complex type definition HomeAffairsIDVRequestBase as an abstract php class. As you can see the abstract class has all the properties, which are defined in the wsdl file for this complex type. Beside that we have getter and setter methods for a better handling of the class properties.

When we look at the definition for HomeAffairsIDVStandardRequest we can see, that it inherits from HomeAffairsIDVRequest. This in mind we have to write to more php classes.

```<code>abstract class HomeAffairsIDVRequest extends HomeAffairsIDVRequestBase
{
    protected ?string $IdNumber;

    public function getIdNumber(): ?string
    {
        return $this->IdNumber;
    }

    public function setIdNumber(?string $idNumber): self
    {
        $this->IdNumber = $idNumber;
        return $this;
    }
}

class HomeAffairsIDVStandardRequest extends HomeAffairsIDVRequest
{

}
</code>```

Since one of the complex types HomeAffairsIDVStandardRequest and HomeAffairsIDVAdvancedRequest is not abstract, wie can use this classes for the request. Keep in mind, that abstract php classes can not be initialized directly. Same goes for abstract complex types in the wsdl.

Now we need the request element as a class. This is our parent element in our soap request. The PlaceRequest element just has one property called request. Since this element is a inheritation of HomeAffairsIDVRequestBase and this definition is abstract, wie have to use a type attribute later in the request.

```<code>class PlaceRequest
{
    protected HomeAffairsIDVRequestBase $request;

    public function getRequest(): HomeAffairsIDVRequestBase
    {
        return $this->request;
    }

    public function setRequest(HomeAffairsIDVRequestBase $request): self
    {
        $this->request = $request;
        return $this;
    }
}
</code>```

Until now we have our data structure as PHP value objects. That 's all we need so far. Now let us have a look on a possible request.

```<code>try {
    $wsdl = 'https://path.to.your.wsdl.file.com?wsdl';
    $client = new SoapClient($wsdl, [
        'exceptions' => true,
        'trace' => true,
    ]);

    // initialize our value object
    $standard = (new HomeAffairsIDVStandardRequest())
        ->setIsBatchSearch(false)
        ->setParentRequestId(0)
        ->setReference('test')
        ->setRequester('requester')
        ->setSessionId('true')
        ->setIdNumber($idNumber);

    // initialize our request element
    $request = (new PlaceRequest())
        ->setRequest($standard);

    $response = $client->placeRequest($request);
} catch (SoapFault $fault) {
    // error handling like var_dump($fault)
}
</code>```

Since I don 't see the whole wsdl content, I can not say, how the request XML should look like. It can happen, that the above shown ends up in a soap fault. In this case try the following example.

Change the type hint in the PlaceRequest class.

```<code>class PlaceRequest
{
    protected SoapVar $request;

    public function getRequest(): SoapVar
    {
        return $this->request;
    }

    public function setRequest(SoapVar $request): self
    {
        $this->request = $request;
        return $this;
    }
}
</code>```

After that create a new SoapVar instance with the $standard instance.

```<code>// we 've already defined the $standard object above (sets an type attribute for the request node)
$standard = new SoapVar($standard, SOAP_ENC_OBJECT, 'HomeAffairsIDVStandardRequest', 'http://your.namespace.tld/namespace', 'request', 'http://your.namespace.tld/namespace');

// initialise the request element and set the soap var parameter
$request = (new PlaceRequest())
    ->setRequest($standard);

// send it via soap client
$client->PlaceRequest($request);
</code>```

As an additional information you should always look at the send xml and the received xml to have a better overview on error handling. We 've set the trace option when initializing the soap client. This enables us to see, what the last request and the last response were.

```<code>...
} catch (SoapFault $fault) {
    if ($client) {
        // get last request
        var_dump($client->__getLastRequest());

        // get last response
        var_dump($client->__getLastResponse());
    }
}
</code>```

Body:
I recently started working with SOAP but and finding it hard to understand the use of abstract complex types.

I am trying to place a request to a wsdl yet I keep getting the error. 'The specified type is abstract: name="HomeAffairsIDVRequestedBase".

My php is as follows :

$result = $this->soap->__soapCall('PlaceRequest',array('PlaceRequest'=>
                                               array('request' =>
                                                   array(
                                                            'type'=> 'tns:HomeAffairsIDVStandardRequest',
                                                            "IsBatchSearch"=>false,
                                                            "ParentRequestId"=>0,
                                                            "Reference"=>'test',
                                                            "Requester"=>'axxess',
                                                            "SessionId"=>'true',
                                                            "IdNumber"=>$this->idNumber
                                                            ))));

and the targeted wsdl section is as follows

<s:element name="PlaceRequest">
    <s:complexType>
        <s:sequence>
            <s:element minOccurs="0" maxOccurs="1" name="request" type="tns:HomeAffairsIDVRequestBase"/>
        </s:sequence>
    </s:complexType>
</s:element>
<s:complexType name="HomeAffairsIDVRequestBase" abstract="true">
    <s:sequence>
        <s:element minOccurs="1" maxOccurs="1" name="IsBatchSearch" type="s:boolean"/>
        <s:element minOccurs="1" maxOccurs="1" name="ParentRequestId" nillable="true" type="s:int"/>
        <s:element minOccurs="0" maxOccurs="1" name="Reference" type="s:string"/>
        <s:element minOccurs="0" maxOccurs="1" name="Requester" type="s:string"/>
        <s:element minOccurs="1" maxOccurs="1" name="SessionId" nillable="true" type="s1:guid"/>
    </s:sequence>
</s:complexType>
<s:complexType name="HomeAffairsIDVRequest" abstract="true">
    <s:complexContent mixed="false">
        <s:extension base="tns:HomeAffairsIDVRequestBase">
            <s:sequence>
                <s:element minOccurs="0" maxOccurs="1" name="IdNumber" type="s:string"/>
            </s:sequence>
        </s:extension>
    </s:complexContent>
</s:complexType>
<s:complexType name="HomeAffairsIDVStandardRequest">
    <s:complexContent mixed="false">
        <s:extension base="tns:HomeAffairsIDVRequest"/>
    </s:complexContent>
</s:complexType>
<s:complexType name="HomeAffairsIDVAdvancedRequest">
    <s:complexContent mixed="false">
        <s:extension base="tns:HomeAffairsIDVRequest"/>
    </s:complexContent>
</s:complexType>

Note: I can not edit the wsdl.

Body:
You can read complex type definitions from the wsdl as php class definitions. Each complex type is a php value object. Abstract complex types are abstract value object, which can be inherited from.

As we have the complex types defined, we can build our php classes.

abstract class HomeAffairsIDVRequestBase
{
    protected bool $IsBatchSearch;
    protected int $ParentRequestId;
    protected ?string $Reference;
    protected ?string $Requester;
    protected string $SessionId;

    public function getIsBatchSearch(): bool
    {
        return $this->IsBatchSearch;
    }

    public function setIsBatchSearch(bool $isBatchSearch): self
    {
        $this->isBatchSearch = $isBatchSearch;
        return $this;
    }

    public function getParentRequestId(): int
    {
        return $this->ParentRequestId;
    }

    public function setParentRequestId(int $parentRequestId): self
    {
        $this->ParentRequestId = $parentRequestId;
        return $this;
    }

    public function getReference(): ?string
    {
        return $this->Reference;
    }

    public function setReference(string $reference): self
    {
        $this->Reference = $reference;
        return $this;
    }

    public function getRequester(): ?string
    {
        return $this->Requester;
    }

    public function setRequester(string $requester): self
    {
        $this->Requester = $requester;
        return $this;
    }

    public function getSessionId(): string
    {
        return $this->SessionId;
    }

    public function setSessionId(string $sessionId): self
    {
        $this->SessionId = $sessionId;
        return $this;
    }
}

This is our first abstract complex type definition HomeAffairsIDVRequestBase as an abstract php class. As you can see the abstract class has all the properties, which are defined in the wsdl file for this complex type. Beside that we have getter and setter methods for a better handling of the class properties.

When we look at the definition for HomeAffairsIDVStandardRequest we can see, that it inherits from HomeAffairsIDVRequest. This in mind we have to write to more php classes.

abstract class HomeAffairsIDVRequest extends HomeAffairsIDVRequestBase
{
    protected ?string $IdNumber;

    public function getIdNumber(): ?string
    {
        return $this->IdNumber;
    }

    public function setIdNumber(?string $idNumber): self
    {
        $this->IdNumber = $idNumber;
        return $this;
    }
}

class HomeAffairsIDVStandardRequest extends HomeAffairsIDVRequest
{

}

Since one of the complex types HomeAffairsIDVStandardRequest and HomeAffairsIDVAdvancedRequest is not abstract, wie can use this classes for the request. Keep in mind, that abstract php classes can not be initialized directly. Same goes for abstract complex types in the wsdl.

Now we need the request element as a class. This is our parent element in our soap request. The PlaceRequest element just has one property called request. Since this element is a inheritation of HomeAffairsIDVRequestBase and this definition is abstract, wie have to use a type attribute later in the request.

class PlaceRequest
{
    protected HomeAffairsIDVRequestBase $request;

    public function getRequest(): HomeAffairsIDVRequestBase
    {
        return $this->request;
    }

    public function setRequest(HomeAffairsIDVRequestBase $request): self
    {
        $this->request = $request;
        return $this;
    }
}

Until now we have our data structure as PHP value objects. That 's all we need so far. Now let us have a look on a possible request.

try {
    $wsdl = 'https://path.to.your.wsdl.file.com?wsdl';
    $client = new SoapClient($wsdl, [
        'exceptions' => true,
        'trace' => true,
    ]);

    // initialize our value object
    $standard = (new HomeAffairsIDVStandardRequest())
        ->setIsBatchSearch(false)
        ->setParentRequestId(0)
        ->setReference('test')
        ->setRequester('requester')
        ->setSessionId('true')
        ->setIdNumber($idNumber);

    // initialize our request element
    $request = (new PlaceRequest())
        ->setRequest($standard);

    $response = $client->placeRequest($request);
} catch (SoapFault $fault) {
    // error handling like var_dump($fault)
}

Since I don 't see the whole wsdl content, I can not say, how the request XML should look like. It can happen, that the above shown ends up in a soap fault. In this case try the following example.

Change the type hint in the PlaceRequest class.

class PlaceRequest
{
    protected SoapVar $request;

    public function getRequest(): SoapVar
    {
        return $this->request;
    }

    public function setRequest(SoapVar $request): self
    {
        $this->request = $request;
        return $this;
    }
}

After that create a new SoapVar instance with the $standard instance.

// we 've already defined the $standard object above (sets an type attribute for the request node)
$standard = new SoapVar($standard, SOAP_ENC_OBJECT, 'HomeAffairsIDVStandardRequest', 'http://your.namespace.tld/namespace', 'request', 'http://your.namespace.tld/namespace');

// initialise the request element and set the soap var parameter
$request = (new PlaceRequest())
    ->setRequest($standard);

// send it via soap client
$client->PlaceRequest($request);

As an additional information you should always look at the send xml and the received xml to have a better overview on error handling. We 've set the trace option when initializing the soap client. This enables us to see, what the last request and the last response were.

...
} catch (SoapFault $fault) {
    if ($client) {
        // get last request
        var_dump($client->__getLastRequest());

        // get last response
        var_dump($client->__getLastResponse());
    }
}


问:
Simple loop optimized by clang, how?
From CppCon 2014: Mike Acton "Data-Oriented Design and C++", he shows this simple loop

```<code>int Foo::Bar(int count)
{
    int value = 0;
    for (int i=0;i<count;i++)
    {
        if ( m_NeedParentUpdate )
        {
            value++;
        }
    }
    return (value);
}
</code>```

Being optimized by clang as such

I don't understand what is happening here. Why is this code bad, and why is it optimized as such by clang, why does this work?

About the loop, he also says "I'm sure you can optimize this in your head". I don't get it. How do I optimize this?

答:
The reason it is considered bad is that you'll have to read the member variable m_NeedParentUpdate on every iteration. If this were a large for loop and you're trying to read a bunch of other member variables as well, then reading this m_NeedParentUpdate might take space in your cache, potentially reducing the effective cache usage. This would result in a performance penalty.

The specifics of performance penalty would depend on the data layout of the class running this code and what other member variables are accessed inside the for loop.

The way we can optimize this is to move the boolean check outside as we really need to do it only once.

```<code>int Foo::Bar(int count)
{
    int value = 0;
    if ( m_NeedParentUpdate )
    {
        for (int i=0;i<count;i++)
        {

            value++;
        }
    }
    return (value);
}
</code>```

Title: Simple loop optimized by clang, how?

Body:
From CppCon 2014: Mike Acton "Data-Oriented Design and C++", he shows this simple loop

int Foo::Bar(int count)
{
    int value = 0;
    for (int i=0;i<count;i++)
    {
        if ( m_NeedParentUpdate )
        {
            value++;
        }
    }
    return (value);
}

Being optimized by clang as such

I don't understand what is happening here. Why is this code bad, and why is it optimized as such by clang, why does this work?

About the loop, he also says "I'm sure you can optimize this in your head". I don't get it. How do I optimize this?

Body:
The reason it is considered bad is that you'll have to read the member variable m_NeedParentUpdate on every iteration. If this were a large for loop and you're trying to read a bunch of other member variables as well, then reading this m_NeedParentUpdate might take space in your cache, potentially reducing the effective cache usage. This would result in a performance penalty.

The specifics of performance penalty would depend on the data layout of the class running this code and what other member variables are accessed inside the for loop.

The way we can optimize this is to move the boolean check outside as we really need to do it only once.

int Foo::Bar(int count)
{
    int value = 0;
    if ( m_NeedParentUpdate )
    {
        for (int i=0;i<count;i++)
        {

            value++;
        }
    }
    return (value);
}


问:
Debugger shows null value despite having value in Firebase Database
I was trying to send a value through intent, but my app was getting crashed. So, I try to check the value in the debugger and it is showing null. Here is the image.

As you can see that it shows userId = "null" and profilephotoURl ="null". Why is this happening?

And here is the image of the Database.

Here is the Code

ProfileInfo.class

```<code>public class ProfileInfo {

String userName, profilePhotoUrl, phoneNumber, userId;

public ProfileInfo() {}

public ProfileInfo(String userName, String profilePhotoUrl, String phoneNumber, String userId) {
    this.userName = userName;
    this.profilePhotoUrl = profilePhotoUrl;
    this.phoneNumber = phoneNumber;
    this.userId = userId;
}

public ProfileInfo(String userName, String phoneNumber) {
    this.userName = userName;
    this.phoneNumber = phoneNumber;
}

public String getUserId() {
    return userId;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public String getUserName() {
    return userName;
}

public String getProfilePhotoUrl() {
    return profilePhotoUrl;
}
</code>```

UserAdapter.class

```<code>public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {

    private ArrayList<ProfileInfo> minfo;
    public static final String USER_ID = "userid";
    Context context;

    public UsersAdapter(Context context, ArrayList<ProfileInfo> minfo) {
        this.context = context;
        this.minfo = minfo;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_item, parent, false);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(lp);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        final ProfileInfo profileInfo = minfo.get(position);
        holder.username.setText(profileInfo.getUserName());
        holder.phoneNumber.setText(profileInfo.getPhoneNumber());
        holder.id.setText(profileInfo.getUserId());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MessageLayout.class);
                intent.putExtra(USER_ID, profileInfo.getUserId());
                Log.d("UserID:", profileInfo.getUserId());
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return minfo.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        TextView username;
        TextView phoneNumber, id;
        CircleImageView profileImage;
        RelativeLayout relativeLayout;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            username = itemView.findViewById(R.id.user);
            phoneNumber = itemView.findViewById(R.id.phone);
            id = itemView.findViewById(R.id.id);
            profileImage = itemView.findViewById(R.id.circleProfileImage);
            relativeLayout = itemView.findViewById(R.id.relativeLayout);

        }
    }
}
</code>```

MessageLayout.class

```<code>public class MessageLayout extends AppCompatActivity {

    FirebaseUser currentUser;
    DatabaseReference db, chatDb;
    EditText message;
    ImageButton sendMessage;
    TextView username;
    CircleImageView profileImage;
    String recieverId, messageText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_layout);

        message = findViewById(R.id.editTextMessage);
        sendMessage = findViewById(R.id.sendMessage);
        username = findViewById(R.id.displayUsername);
        profileImage = findViewById(R.id.circledp);
        currentUser = FirebaseAuth.getInstance().getCurrentUser();

        Intent intent = getIntent();
        recieverId = intent.getStringExtra(UsersAdapter.USER_ID);

        db = FirebaseDatabase.getInstance().getReference().child("UserInfo").child(recieverId);
        chatDb = FirebaseDatabase.getInstance().getReference().child("Chats");
        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                ProfileInfo info = dataSnapshot.getValue(ProfileInfo.class);

                username.setText(info.getUserName());
                Glide.with(MessageLayout.this).load(info.getProfilePhotoUrl()).into(profileImage);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }
</code>```

答:
The problem is in your constructor. It seems like your datasnapshot is being cast using your ProfileInfo(String userName, String phoneNumber) constructor.

Here's what you can do: Ensure that there are only two constructors in your model class: The regular no-argument constructor and then your full-blown constructor. Something like this:

```<code>public ProfileInfo() {}

public ProfileInfo(String userName, String profilePhotoUrl, String phoneNumber, String userId) {
    this.userName = userName;
    this.profilePhotoUrl = profilePhotoUrl;
    this.phoneNumber = phoneNumber;
    this.userId = userId;
}
</code>```

Then, run your code and try again.

Body:
I was trying to send a value through intent, but my app was getting crashed. So, I try to check the value in the debugger and it is showing null. Here is the image.

As you can see that it shows userId = "null" and profilephotoURl ="null". Why is this happening?

And here is the image of the Database.

Here is the Code

ProfileInfo.class

public class ProfileInfo {

String userName, profilePhotoUrl, phoneNumber, userId;

public ProfileInfo() {}

public ProfileInfo(String userName, String profilePhotoUrl, String phoneNumber, String userId) {
    this.userName = userName;
    this.profilePhotoUrl = profilePhotoUrl;
    this.phoneNumber = phoneNumber;
    this.userId = userId;
}

public ProfileInfo(String userName, String phoneNumber) {
    this.userName = userName;
    this.phoneNumber = phoneNumber;
}

public String getUserId() {
    return userId;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public String getUserName() {
    return userName;
}

public String getProfilePhotoUrl() {
    return profilePhotoUrl;
}

UserAdapter.class

public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {

    private ArrayList<ProfileInfo> minfo;
    public static final String USER_ID = "userid";
    Context context;

    public UsersAdapter(Context context, ArrayList<ProfileInfo> minfo) {
        this.context = context;
        this.minfo = minfo;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_item, parent, false);
        RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(lp);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        final ProfileInfo profileInfo = minfo.get(position);
        holder.username.setText(profileInfo.getUserName());
        holder.phoneNumber.setText(profileInfo.getPhoneNumber());
        holder.id.setText(profileInfo.getUserId());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MessageLayout.class);
                intent.putExtra(USER_ID, profileInfo.getUserId());
                Log.d("UserID:", profileInfo.getUserId());
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return minfo.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        TextView username;
        TextView phoneNumber, id;
        CircleImageView profileImage;
        RelativeLayout relativeLayout;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            username = itemView.findViewById(R.id.user);
            phoneNumber = itemView.findViewById(R.id.phone);
            id = itemView.findViewById(R.id.id);
            profileImage = itemView.findViewById(R.id.circleProfileImage);
            relativeLayout = itemView.findViewById(R.id.relativeLayout);

        }
    }
}

MessageLayout.class

public class MessageLayout extends AppCompatActivity {

    FirebaseUser currentUser;
    DatabaseReference db, chatDb;
    EditText message;
    ImageButton sendMessage;
    TextView username;
    CircleImageView profileImage;
    String recieverId, messageText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_layout);

        message = findViewById(R.id.editTextMessage);
        sendMessage = findViewById(R.id.sendMessage);
        username = findViewById(R.id.displayUsername);
        profileImage = findViewById(R.id.circledp);
        currentUser = FirebaseAuth.getInstance().getCurrentUser();

        Intent intent = getIntent();
        recieverId = intent.getStringExtra(UsersAdapter.USER_ID);

        db = FirebaseDatabase.getInstance().getReference().child("UserInfo").child(recieverId);
        chatDb = FirebaseDatabase.getInstance().getReference().child("Chats");
        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                ProfileInfo info = dataSnapshot.getValue(ProfileInfo.class);

                username.setText(info.getUserName());
                Glide.with(MessageLayout.this).load(info.getProfilePhotoUrl()).into(profileImage);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

Body:
The problem is in your constructor. It seems like your datasnapshot is being cast using your ProfileInfo(String userName, String phoneNumber) constructor.

Here's what you can do: Ensure that there are only two constructors in your model class: The regular no-argument constructor and then your full-blown constructor. Something like this:

public ProfileInfo() {}

public ProfileInfo(String userName, String profilePhotoUrl, String phoneNumber, String userId) {
    this.userName = userName;
    this.profilePhotoUrl = profilePhotoUrl;
    this.phoneNumber = phoneNumber;
    this.userId = userId;
}

Then, run your code and try again.


问:
Using enums as status returned status indicators in C#
Just wondering what the general consensus was about returning enums from methods indicating the status. The notion of returning codes (ints) is pretty innate in oldschool systems programming (C) but I am wondering if the methodology for indicating the status has changed.

thanks

Edit: I am aware that enums are basically int values. I'm inquiring about the sheer practice of having methods start throwing around status codes (be them enums or ints) to indicate statuses altogether. It seems like a good practice but I was wondering if there is any negative feelings about the idea.

I would always choose an enum over an int return for a status code.

答: if All you want is a status returned then an enum is a much better way to go vs just an int for a number of reasons, it forces consistency on what means what so you don't have to remember what return code 1 means, making your code much more maintainable. </p>

OwnerDisplayName: Chance

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chance

OwnerDisplayName: Bob The Janitor


问:
Complex jquery selector that looks for a token in a string.split
I have an html table where one of the columns contains s with comma-delimited data.  I want to come up with a jQuery selector that returns all of the rows (
s are preferable, but the s will work for now) where one of the comma-delimited tokens  in a span tag matches a supplied string.

I started with something like the following:

```<code>$('td.col_8 span:contains("duck")')
</code>```

which will get me all spans in a particular column containing the word 'duck'.  However, it could also match fox, mallard-duck. Since 'duck' is not a unique token in that span, I wouldn't want that included in the match.

Is there a way to narrow my result set so I'm only including results where there's an exact match to a particular token in a column-delimited list?

(I'm using jQuery 1.2.3)

答:
This is where the beauty of jQuery expressions come in.

You can add your own custom selector. I'm going to call it tag in this case

```<code>jQuery.expr[":"].tag = function(elem, index, match, nodeList) {
    var tags = $(elem).text().replace(/(?:\ +)?,(?:\ +)?/g, ",").split(",");
    return tags.indexOf(match[3]) > -1;
}
</code>```

This will check each previously matched element against this selector. Fist it flattens the , seperations (so something like "firstTag ,    onotherer, badly   , spaced, tag" will work). jQuery already takes care of parsing the selector and passes it in as match. match[3] is what you're interested in. With the following usage match[3] will be 'duck'

```<code>$('td.col_8 span:tag("duck")')
</code>```

the return line will return true of false based on the tag being in the list.

Body:
I have an html table where one of the columns contains s with comma-delimited data.  I want to come up with a jQuery selector that returns all of the rows (
s are preferable, but the s will work for now) where one of the comma-delimited tokens  in a span tag matches a supplied string.

I started with something like the following:

$('td.col_8 span:contains("duck")')

which will get me all spans in a particular column containing the word 'duck'.  However, it could also match fox, mallard-duck. Since 'duck' is not a unique token in that span, I wouldn't want that included in the match.

Is there a way to narrow my result set so I'm only including results where there's an exact match to a particular token in a column-delimited list?

(I'm using jQuery 1.2.3)

Body:
This is where the beauty of jQuery expressions come in.

You can add your own custom selector. I'm going to call it tag in this case

jQuery.expr[":"].tag = function(elem, index, match, nodeList) {
    var tags = $(elem).text().replace(/(?:\ +)?,(?:\ +)?/g, ",").split(",");
    return tags.indexOf(match[3]) > -1;
}

This will check each previously matched element against this selector. Fist it flattens the , seperations (so something like "firstTag ,    onotherer, badly   , spaced, tag" will work). jQuery already takes care of parsing the selector and passes it in as match. match[3] is what you're interested in. With the following usage match[3] will be 'duck'

$('td.col_8 span:tag("duck")')

the return line will return true of false based on the tag being in the list.


问:
How can I detect if a file is binary (non-text) in Python?
How can I tell if a file is binary (non-text) in Python?

I am searching through a large set of files in Python, and keep getting matches in binary files. This makes the output look incredibly messy.

I know I could use grep -I, but I am doing more with the data than what grep allows for.

In the past, I would have just searched for characters greater than 0x7f, but utf8 and the like, make that impossible on modern systems. Ideally, the solution would be fast.

答:
```<code>from binaryornot.check import is_binary
is_binary('filename')
</code>```

Documentation

Body:
from binaryornot.check import is_binary
is_binary('filename')

Documentation


问:
In a .NET console app, is it possible to have a line of text stay visible in the console all the time?
I was thinking of adding a simple bandwidth monitor to a console application and I was wondering if it would be possible to keep a line in the console window visible at all times. I could set something up manually to pass new console output into a method that would get the contents of the console, clear the console, add the bandwidth data on the first row, then rewrite each line of previous information back to the console, etc.. but that seems like a really hacky way to go about it, and I'd be limited to the amount of rows visible at once in the console window (no scrolling).

Any idea?  Any built in functionality for this?   Example:

```<code>STATS: Downloaded: 2599b, Uploaded: 754b  <- this always stays at the top
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
</code>```

答: As Reed Copsey said, you could easily replicate a fake console application with a WinForm (just a simple form with some formatted text in a RichTextBox).  You could do exactly what you want with little hassle and hardly the amount of work involved and get the expected result.

Body:
I was thinking of adding a simple bandwidth monitor to a console application and I was wondering if it would be possible to keep a line in the console window visible at all times. I could set something up manually to pass new console output into a method that would get the contents of the console, clear the console, add the bandwidth data on the first row, then rewrite each line of previous information back to the console, etc.. but that seems like a really hacky way to go about it, and I'd be limited to the amount of rows visible at once in the console window (no scrolling).

Any idea?  Any built in functionality for this?   Example:

STATS: Downloaded: 2599b, Uploaded: 754b  <- this always stays at the top
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text
constantly changing text


问:
Ifelse statement in R: One value cannot equal another
I have a dataframe with two columns: df$user and df$type. The users are a list of different user names and the type category has two values: 'high_user' and 'small_user'

I want to create some code so that one user cannot be both types. For example if the user is high_user he cannot also be a small_user.

```<code>head(df$user)

[1] RompnStomp       Vladiman         Celticdreamer54  Crimea is Russia shrek1978third   annietattooface

head(df$type)

"high_user" "high_user" "small_user" "high_user" "high_user" "small_user"

</code>```

Any help would be greatly appreciated.

答:
One way would be to assign the first value of User to all the values of it's type.

```<code>df$new_type <- df$type[match(df$User, unique(df$User))]
df

#  User       type   new_type
#1    a  high_user  high_user
#2    b  high_user  high_user
#3    a small_user  high_user
#4    c small_user small_user
#5    c  high_user small_user
</code>```

This can also be done using grouped operations.

```<code>library(dplyr)
df %>% group_by(User) %>% mutate(new_type = first(type))
</code>```

data

```<code>df <- data.frame(User = c('a', 'b', 'a', 'c', 'c'),
      type = c('high_user', 'high_user', 'small_user', 'small_user', 'high_user'))
</code>```

Body:
I have a dataframe with two columns: df$user and df$type. The users are a list of different user names and the type category has two values: 'high_user' and 'small_user'

I want to create some code so that one user cannot be both types. For example if the user is high_user he cannot also be a small_user.

head(df$user)

[1] RompnStomp       Vladiman         Celticdreamer54  Crimea is Russia shrek1978third   annietattooface

head(df$type)

"high_user" "high_user" "small_user" "high_user" "high_user" "small_user"

Any help would be greatly appreciated.

Body:
One way would be to assign the first value of User to all the values of it's type.

df$new_type <- df$type[match(df$User, unique(df$User))]
df

#  User       type   new_type
#1    a  high_user  high_user
#2    b  high_user  high_user
#3    a small_user  high_user
#4    c small_user small_user
#5    c  high_user small_user

This can also be done using grouped operations.

library(dplyr)
df %>% group_by(User) %>% mutate(new_type = first(type))

data

df <- data.frame(User = c('a', 'b', 'a', 'c', 'c'),
      type = c('high_user', 'high_user', 'small_user', 'small_user', 'high_user'))


问:
The image contain error with imagick
```<code><?php

header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');

// If 0 is provided as a width or height parameter,
// aspect ratio is maintained
$image->thumbnailImage(100, 0);

echo $image;

?>
</code>```

is giving error The image “http://localhost/test/into.php” cannot be displayed because it contains errors.Solve this please?

答:
Please read details in commented lines</p>

```<code><?php

//drawing stuff that creates $image

ob_get_clean(); //this statement is what mine was lacking before I could get it to work properly
header("Content-type: image/png");
echo $image;
</code>```

Title: The image contain error with imagick

Body:
<?php

header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');

// If 0 is provided as a width or height parameter,
// aspect ratio is maintained
$image->thumbnailImage(100, 0);

echo $image;

?>

is giving error The image “http://localhost/test/into.php” cannot be displayed because it contains errors.Solve this please?

Body:
Please read details in commented lines

<?php

//drawing stuff that creates $image

ob_get_clean(); //this statement is what mine was lacking before I could get it to work properly
header("Content-type: image/png");
echo $image;


问:
Visual Studio Code doesnt stop at breakpoints on debugging
Am studying C# and using Visual Studio Code. Problem that I currently have is that new installations of VSCode and C# doesnt stop on breakpoint when debugging. Even on fresh "helloWorld"-app it doesnt stop to breakpoint as in the old laptop it works.

OperatingSystem: Win10

VSCode-versions on both:1.44.2

C# SDK on new: 3.1.201

C# SDK on the old: 3.0.100 (have this also tried on the new laptop)

C# for VisualStudio Code (Omnisharp):1.21.18 on both old and the new one

...would really like to use VSCode as its more lightweight that VisualStudio Community that doesnt seem to have this "symptom".

答: Seems that I had 32bit SDK on the old laptop and this new one needed 64bit. When installed 64bit it started to work.</p>


问:
Reach router navigate updates URL but not component
I'm trying to get Reach Router to navigate programmatically from one of my components. The URL is updated as expected however the route is not rendered and if I look at the React developer tools I can see the original component is listed as being displayed.

If I refresh the page once at the new URL then it renders correctly.

How can I get it to render the new route?

A simplified example is shown below and I'm using @reach/router@1.2.1 (it may also be salient that I'm using Redux).

```<code>import React from 'react';

import { navigate } from '@reach/router';

const ExampleComponent = props => {
  navigate('/a/different/url');

  return <div />;
};

export default ExampleComponent;
</code>```

答:
Could it be that you use @reach/router in combination with redux-first-history? Because I had the same issue and could solve it with the following configuration of my historyContext:

```<code>import { globalHistory } from "@reach/router";
// other imports

const historyContext = createReduxHistoryContext({
   // your options...
   reachGlobalHistory: globalHistory // <-- this option is the important one that fixed my issue
}
</code>```

More on this in the README of redux-first-history

Body:
I'm trying to get Reach Router to navigate programmatically from one of my components. The URL is updated as expected however the route is not rendered and if I look at the React developer tools I can see the original component is listed as being displayed.

If I refresh the page once at the new URL then it renders correctly.

How can I get it to render the new route?

A simplified example is shown below and I'm using @reach/router@1.2.1 (it may also be salient that I'm using Redux).

import React from 'react';

import { navigate } from '@reach/router';

const ExampleComponent = props => {
  navigate('/a/different/url');

  return
;
};

export default ExampleComponent;

Body:
Could it be that you use @reach/router in combination with redux-first-history? Because I had the same issue and could solve it with the following configuration of my historyContext:

import { globalHistory } from "@reach/router";
// other imports

const historyContext = createReduxHistoryContext({
   // your options...
   reachGlobalHistory: globalHistory // <-- this option is the important one that fixed my issue
}

More on this in the README of redux-first-history