问:
Refresh or update the button action
```<code>-(IBAction)button:(id)sender
{
    button = [UIButton buttonWithType:UIBarButtonSystemItemRefresh];
    NSLog(@"Value of txtfrequency in button fuinction :%@",txtfrequency.text);
    int z = [txtfrequency.text  intValue];
    NSLog(@"Value of z is :%d",z);
    int y = 10;
    //create a new dynamic button
    for (int j=0; j<z; j++)
    {
        CGRect frame = CGRectMake(20, y , 50, 30);
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTag:j];
        button.frame = frame;
        CGRect frame1 = CGRectMake(100, y , 50, 30);

    textFieldRounded = [[UITextField alloc] initWithFrame:frame1];
    textFieldRounded.borderStyle =UIButtonTypeInfoDark;   //UITextBorderStyleNone;
    textFieldRounded.textColor = [UIColor blackColor]; //text color
    textFieldRounded.font = [UIFont systemFontOfSize:17.0];  //font size
    textFieldRounded.backgroundColor = [UIColor whiteColor]; //background color
    textFieldRounded.autocorrectionType = UITextAutocorrectionTypeNo;   // no auto correction support

    textFieldRounded.keyboardType = UIKeyboardTypeDefault;  // type of the keyboard
    textFieldRounded.returnKeyType = UIReturnKeyDone;  // type of the return key
    textFieldRounded.clearButtonMode = UITextFieldViewModeWhileEditing; // has a clear 'x' button to the right
    textFieldRounded.delegate = self;
    [textFieldRounded setTag:j];

    //[[scroll viewWithTag:j] removeFromSuperview];
    [button reloadInputViews];
    [textFieldRounded removeFromSuperview];

    //[scroll

    [scroll addSubview:button];
    scroll.contentSize= CGSizeMake(100, 1400);
    [scroll addSubview:textFieldRounded];
    y= y+50;

}
}
</code>```

Hii..

Above code generates no of buttons dynamically whenever user give input for buttons. But there is problem in this event.. e.g. User have given the input to generate 4 buttons ..then on view we get 4 buttons but now if user wantto have only 2 buttons then there is still 4 buttons on view. I am not able to refersh or update the action of button.

Anyone know how can I do this.

Please help me.

Thanks alot.

答:
You will have to remember the current number of buttons. Let us say you store it in numberOfButtons.

You can clean up the existing text fields like this,

```<code>- (IBAction)button:(id)sender
{
    button = [UIButton buttonWithType:UIBarButtonSystemItemRefresh];
    int y = 10;

    for ( int i = 40; i < numberOfButtons+40; i++ ) {
        [[scroll viewWithTag:i] removeFromSuperview];
    }
    numberOfButtons = [txtfrequency.text intValue]; // Make `numberOfButtons` an ivar.

    for ( int i = 40; i < numberOfButtons+40; i++ ) {
        [..] // Add a button here.
    }
}
</code>```

The problem with using fast enumeration is that you will be modifying the array which will raise an error.

Title: Refresh or update the button action

Body:
-(IBAction)button:(id)sender
{
    button = [UIButton buttonWithType:UIBarButtonSystemItemRefresh];
    NSLog(@"Value of txtfrequency in button fuinction :%@",txtfrequency.text);
    int z = [txtfrequency.text  intValue];
    NSLog(@"Value of z is :%d",z);
    int y = 10;
    //create a new dynamic button
    for (int j=0; j<z; j++)
    {
        CGRect frame = CGRectMake(20, y , 50, 30);
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTag:j];
        button.frame = frame;
        CGRect frame1 = CGRectMake(100, y , 50, 30);

    textFieldRounded = [[UITextField alloc] initWithFrame:frame1];
    textFieldRounded.borderStyle =UIButtonTypeInfoDark;   //UITextBorderStyleNone;
    textFieldRounded.textColor = [UIColor blackColor]; //text color
    textFieldRounded.font = [UIFont systemFontOfSize:17.0];  //font size
    textFieldRounded.backgroundColor = [UIColor whiteColor]; //background color
    textFieldRounded.autocorrectionType = UITextAutocorrectionTypeNo;   // no auto correction support

    textFieldRounded.keyboardType = UIKeyboardTypeDefault;  // type of the keyboard
    textFieldRounded.returnKeyType = UIReturnKeyDone;  // type of the return key
    textFieldRounded.clearButtonMode = UITextFieldViewModeWhileEditing; // has a clear 'x' button to the right
    textFieldRounded.delegate = self;
    [textFieldRounded setTag:j];

    //[[scroll viewWithTag:j] removeFromSuperview];
    [button reloadInputViews];
    [textFieldRounded removeFromSuperview];

    //[scroll

    [scroll addSubview:button];
    scroll.contentSize= CGSizeMake(100, 1400);
    [scroll addSubview:textFieldRounded];
    y= y+50;

}
}

Hii..

Above code generates no of buttons dynamically whenever user give input for buttons. But there is problem in this event.. e.g. User have given the input to generate 4 buttons ..then on view we get 4 buttons but now if user wantto have only 2 buttons then there is still 4 buttons on view. I am not able to refersh or update the action of button.

Anyone know how can I do this.

Please help me.

Thanks alot.

Body:
You will have to remember the current number of buttons. Let us say you store it in numberOfButtons.

You can clean up the existing text fields like this,

- (IBAction)button:(id)sender
{
    button = [UIButton buttonWithType:UIBarButtonSystemItemRefresh];
    int y = 10;

    for ( int i = 40; i < numberOfButtons+40; i++ ) {
        [[scroll viewWithTag:i] removeFromSuperview];
    }
    numberOfButtons = [txtfrequency.text intValue]; // Make `numberOfButtons` an ivar.

    for ( int i = 40; i < numberOfButtons+40; i++ ) {
        [..] // Add a button here.
    }
}

The problem with using fast enumeration is that you will be modifying the array which will raise an error.


来源: stackexchange

问:
Yii2 dataprovider not loading GET parameters
I am trying to setup pagination for Yii2 listView. I am sending 'page' parameter in GET request, but 0 gets always loaded into dataprovider->pagination->page property. When debugging I can see the GET page parameter set correctly, also when trying to set pageSize as 'per-page' GET parameter it works and loads correctly.

My controller code:

```<code>$searchModel = new WinerySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize = $this->pageSize;

if (\Yii::$app->request->isAjax) {

$displayedItems = $dataProvider->pagination->pageSize * ($dataProvider->pagination->page) + $dataProvider->count;
</code>```

0 is always returned by $dataProvider->pagination->page

Ajax request code:

```<code>var pageNumber = 1;
$.ajax({
        method: 'GET',
        url: url+"?page="+pageNumber,
        success: function(data, textStatus, request){
</code>```

答:
Insert

```<code><?php var_dump($dataProvider->pagination->page); ?>
<?php var_dump($dataProvider->pagination); ?>
</code>```

at the bottom of one of your grids or lists on the index page. The var_dump always returns a value one less than the page number if you refresh the page manually. I used a pageSize of 1. I noticed also that it can remain dormant ie. on its current value even with page changes via the pagination buttons and not via a refresh.

Consider perhaps this code:

```<code>public function getPage($recalculate = false)
{
    if ($this->_page === null || $recalculate) {
        $page = (int) $this->getQueryParam($this->pageParam, 1) - 1;
        $this->setPage($page, true);
    }

    return $this->_page;
}
</code>```

Or perhaps considering reworking this code:

```<code>$dataProvider->pagination = [
        'pageSize'=>$pageSize,
        'page'=>$pageNumber-1,
];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to setup pagination for Yii2 listView. I am sending 'page' parameter in GET request, but 0 gets always loaded into dataprovider->pagination->page property. When debugging I can see the GET page parameter set correctly, also when trying to set pageSize as 'per-page' GET parameter it works and loads correctly.

My controller code:

$searchModel = new WinerySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize = $this->pageSize;

if (\Yii::$app->request->isAjax) {

$displayedItems = $dataProvider->pagination->pageSize * ($dataProvider->pagination->page) + $dataProvider->count;

0 is always returned by $dataProvider->pagination->page

Ajax request code:

var pageNumber = 1;
$.ajax({
        method: 'GET',
        url: url+"?page="+pageNumber,
        success: function(data, textStatus, request){

Body:
Insert

<?php var_dump($dataProvider->pagination->page); ?>
<?php var_dump($dataProvider->pagination); ?>

at the bottom of one of your grids or lists on the index page. The var_dump always returns a value one less than the page number if you refresh the page manually. I used a pageSize of 1. I noticed also that it can remain dormant ie. on its current value even with page changes via the pagination buttons and not via a refresh.

Consider perhaps this code:

public function getPage($recalculate = false)
{
    if ($this->_page === null || $recalculate) {
        $page = (int) $this->getQueryParam($this->pageParam, 1) - 1;
        $this->setPage($page, true);
    }

    return $this->_page;
}

Or perhaps considering reworking this code:

$dataProvider->pagination = [
        'pageSize'=>$pageSize,
        'page'=>$pageNumber-1,
];


问:
How to show the row or line number in powershell format-table
I'd like the data presented by format-table to include the line or row number of the items.
How can I achieve this?

some-command | ft

```<code>Line    Something       Else
----    ---------       ----
0       Item1           Property1
1       Item2           Property2
</code>```

答:
You coiuld loop through the data and prepend an extra property Line to the output using a counter variable.

Something like this:

```<code># demo data
$data = [PsCustomObject]@{'Something' = 'Item1'; 'Else' = 'Property1'},
        [PsCustomObject]@{'Something' = 'Item2'; 'Else' = 'Property2'},
        [PsCustomObject]@{'Something' = 'Item3'; 'Else' = 'Property3'}

$count = 0
$data | ForEach-Object {
    $_ |  Select-Object @{Name = 'Line'; Expression = {$count}}, *
    $count++
} | Format-Table -AutoSize
</code>```

Output:

```
Line Something Else
---- --------- ----
   0 Item1     Property1
   1 Item2     Property2
   2 Item3     Property3
```

Body:
I'd like the data presented by format-table to include the line or row number of the items.
How can I achieve this?

some-command | ft

Line    Something       Else
----    ---------       ----
0       Item1           Property1
1       Item2           Property2

Body:
You coiuld loop through the data and prepend an extra property Line to the output using a counter variable.

Something like this:

# demo data
$data = [PsCustomObject]@{'Something' = 'Item1'; 'Else' = 'Property1'},
        [PsCustomObject]@{'Something' = 'Item2'; 'Else' = 'Property2'},
        [PsCustomObject]@{'Something' = 'Item3'; 'Else' = 'Property3'}

$count = 0
$data | ForEach-Object {
    $_ |  Select-Object @{Name = 'Line'; Expression = {$count}}, *
    $count++
} | Format-Table -AutoSize

Output:

Line Something Else
---- --------- ----
   0 Item1     Property1
   1 Item2     Property2
   2 Item3     Property3


问:
how to use pivot table in python pandas for below input?
Input:(status_df)

ID         status

1        matched

 2        not matched

 3        matched

 4        matched

 5        unknown

 6        not matched

 7        not matched

 8        matched

 9        unknown

10        unknown

after pivot(i want count for values in separate column and grand total at last row )

count of status

status      Total

matched              4

not matched      3

unknown              3

Grand Total    10

答:
Use Series.value_counts for counter, then add new value by Series.loc:

```<code>s = status_df['status'].value_counts()
s.loc['Grand Total'] = s.sum()
print (s)
matched         4
unknown         3
not matched     3
Grand Total    10
Name: status, dtype: int64
</code>```

Then convert to 2 columns DataFrame and create MultiIndex by MultiIndex.from_product:

```<code>df = s.rename_axis('status').reset_index(name='Total')
df.columns = pd.MultiIndex.from_product([['count of status'], df.columns])
print (df)
   count of status
           status Total
0         matched     4
1         unknown     3
2     not matched     3
3     Grand Total    10
</code>```

Body:
Use Series.value_counts for counter, then add new value by Series.loc:

s = status_df['status'].value_counts()
s.loc['Grand Total'] = s.sum()
print (s)
matched         4
unknown         3
not matched     3
Grand Total    10
Name: status, dtype: int64

Then convert to 2 columns DataFrame and create MultiIndex by MultiIndex.from_product:

df = s.rename_axis('status').reset_index(name='Total')
df.columns = pd.MultiIndex.from_product([['count of status'], df.columns])
print (df)
   count of status
           status Total
0         matched     4
1         unknown     3
2     not matched     3
3     Grand Total    10


问:
How to make countdown start every eight hours?
I wonder how to make countdown start every 8 hours? for example
the puzzle starts at 10 pm next is 6 am, and next 2 pm.

I have javascript like this

```

and how to make that countDown date every 8 hours? like 10 pm, 6 am and 2 pm? Thank you.

答:
How about wrapping it in a function that takes in a date (in ms, in this case) (countdown(date)) and then calling the function with 8+ hours once the timer is up:

```<code>    // Set the date we're counting down to
    var countDownDate = new Date("May 31, 2020 22:00:00").getTime();

function countdown(date) {
    // Update the count down every 1 second
    var x = setInterval(function() {

    // Get today's date and time
    var now = new Date().getTime();

    // Find the distance between now and the count down date
    var distance = date - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = days + "d " + hours + "h "
    + minutes + "m " + seconds + "s ";

    // If the count down is over, write some text and start new countdown
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
        let newDate = date + (8 * 3600 * 1000);
        countdown(newDate);
    }
    }, 1000);
}

countdown(countDownDate);
</code>```

DEMO using initial countdown set to 3 seconds from now.

Code Explanation:

take in the initial date - can be set to anything.

Countdown until the initial date is reached.

Start a new 8-hour timer.

Example case starting date = "May 31, 2020 19:37:35".

First countdown will countdown 5 hours (from now to 19:37:35).

Second countdown will countdown 8 hours (from 19:37:35 until
03:37:35).

Third countdown will countdown 8 hours (from 3:37:35 to 11:37:35).

Body:
I wonder how to make countdown start every 8 hours? for example
the puzzle starts at 10 pm next is 6 am, and next 2 pm.

I have javascript like this

and how to make that countDown date every 8 hours? like 10 pm, 6 am and 2 pm? Thank you.

Body:
How about wrapping it in a function that takes in a date (in ms, in this case) (countdown(date)) and then calling the function with 8+ hours once the timer is up:

    // Set the date we're counting down to
    var countDownDate = new Date("May 31, 2020 22:00:00").getTime();

function countdown(date) {
    // Update the count down every 1 second
    var x = setInterval(function() {

    // Get today's date and time
    var now = new Date().getTime();

    // Find the distance between now and the count down date
    var distance = date - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("demo").innerHTML = days + "d " + hours + "h "
    + minutes + "m " + seconds + "s ";

    // If the count down is over, write some text and start new countdown
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
        let newDate = date + (8 * 3600 * 1000);
        countdown(newDate);
    }
    }, 1000);
}

countdown(countDownDate);

DEMO using initial countdown set to 3 seconds from now.

Code Explanation:

take in the initial date - can be set to anything.

Countdown until the initial date is reached.

Start a new 8-hour timer.

Example case starting date = "May 31, 2020 19:37:35".

First countdown will countdown 5 hours (from now to 19:37:35).

Second countdown will countdown 8 hours (from 19:37:35 until
03:37:35).

Third countdown will countdown 8 hours (from 3:37:35 to 11:37:35).


问:
can any one suggest a good math function in javascript to round integer?
i have to round the value from 2.3456789 to 2.345 .

After . there must be three number only remaining should be removed

答:
Use Math.round().

This will round to 3 decimal places.

```<code>var result=Math.round(2.3456789*1000)/1000  //returns 2.345
</code>```

In fact, the formula to round any number to x decimal points is:

1) Multiple the original number by 10^x (10 to the power of x).

2) Apply Math.round() to the result.

3) Divide result by 10^x.

ContentLicense: CC BY-SA 3.0

Body:
Use Math.round().

This will round to 3 decimal places.

var result=Math.round(2.3456789*1000)/1000  //returns 2.345

In fact, the formula to round any number to x decimal points is:

1) Multiple the original number by 10^x (10 to the power of x).

2) Apply Math.round() to the result.

3) Divide result by 10^x.


问:
update dart sdk for flutter
I would like to use dart SDK >= 2.2.0 with flutter. But my current version used BY Flutter is 2.1.2

```<code>flutter --version
Flutter 1.2.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 8661d8aecd (2 months ago) • 2019-02-14 19:19:53 -0800
Engine • revision 3757390fa4
Tools • Dart 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)
</code>```

I tried to install the 2.2.0 version independently and I succeed :

```<code>dart --version
Dart VM version: 2.2.0 (Tue Feb 26 15:04:32 2019 +0100) on "macos_x64"
</code>```

However, Flutter doesn't use this version as you can see above. I tried to replace files of the dart-sdk used by flutter (flutter/bin/cache/dart-sdk) by the version that I installed independently, but when I try to run Flutter after that I have a snapshot problem so I have put back the original dart-sdk folder in the flutter directory.

Do you have any ideas how can I update it?

PS: I downloaded flutter very recently (10 days ago) from here: https://flutter.dev/docs/get-started/install/macos

答:
If using windows, you can use chocolatey to upgrade sdk by using command.

```<code>choco upgrade dart-sdk
</code>```

If you want the latest pre-release version:

```<code>choco upgrade dart-sdk --pre
</code>```

Title: update dart sdk for flutter

Body:
I would like to use dart SDK >= 2.2.0 with flutter. But my current version used BY Flutter is 2.1.2

flutter --version
Flutter 1.2.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 8661d8aecd (2 months ago) • 2019-02-14 19:19:53 -0800
Engine • revision 3757390fa4
Tools • Dart 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)

I tried to install the 2.2.0 version independently and I succeed :

dart --version
Dart VM version: 2.2.0 (Tue Feb 26 15:04:32 2019 +0100) on "macos_x64"

However, Flutter doesn't use this version as you can see above. I tried to replace files of the dart-sdk used by flutter (flutter/bin/cache/dart-sdk) by the version that I installed independently, but when I try to run Flutter after that I have a snapshot problem so I have put back the original dart-sdk folder in the flutter directory.

Do you have any ideas how can I update it?

PS: I downloaded flutter very recently (10 days ago) from here: https://flutter.dev/docs/get-started/install/macos

Body:
If using windows, you can use chocolatey to upgrade sdk by using command.

choco upgrade dart-sdk

If you want the latest pre-release version:

choco upgrade dart-sdk --pre


问:
How can I remove a specific item from an array in JavaScript?
How do I remove a specific value from an array? Something like:

array.remove(value);
```

Constraints: I have to use core JavaScript. Frameworks are not allowed.

答:
An immutable way of removing an element from an array using the ES6 spread operator.

Let's say you want to remove 4.

```<code>let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]
</code>```

Body:
How do I remove a specific value from an array? Something like:

array.remove(value);

Constraints: I have to use core JavaScript. Frameworks are not allowed.

Body:
An immutable way of removing an element from an array using the ES6 spread operator.

Let's say you want to remove 4.

let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]


问:
Paginating a List in React
Probably a silly question but can't seem to figure it out on my own. Let's say I have a long list of items displayed on the page. I simply want to paginate it into pages of e.g. 5 items per page. To avoid reinventing the wheel, looked up a couple of libraries and react-js-pagination seems to do what I need. But for the life of me I can't figure it out.
What I have tried per the simplified example below:

Put <Pagination /> and my list in the same div.

Gave my list items a class of page-item per the API docs.

No luck. I added a parent of
 and/or put my items in
 tags. Even gave the parent
 a class of "pagination". Nothing. The only difference I am able to achieve is all items appearing in the same line like you see in the screenshot. Anything you figure out I am missing is appreciated.

```<code>import 'react-toastify/dist/ReactToastify.css';
import Pagination from "react-js-pagination";
import 'bootstrap/dist/css/bootstrap.css';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            activePage: 1
        }
    }

    handlePageChange(pageNumber) {
        this.setState({activePage: pageNumber});
    }

    render() {
        return (
            <div>
                <ul className="pagination">
                    <li className="page-item">1</li>
                    <li className="page-item">2</li>
                    <li className="page-item">3</li>
                    <li className="page-item">4</li>
                    <li className="page-item">5</li>
                    <li className="page-item">6</li>
                    <li className="page-item">7</li>
                    <li className="page-item">8</li>
                    <li className="page-item">9</li>
                    <li className="page-item">10</li>
                    <li className="page-item">11</li>
                </ul>
                <Pagination
                    activePage={this.state.activePage}
                    itemsCountPerPage={2}
                    totalItemsCount={11}
                    pageRangeDisplayed={5}
                    onChange={this.handlePageChange.bind(this)}
                    itemClass="page-item"
                    linkClass="page-link"
                />
            </div>
        );
    }
}

export default App;
</code>```

Result so far:

答:
You are missing the pagination logic.  Its not so trivial, here is a simple example (not related to react-js-pagination):

```<code>function Pagination({ pageSize, children }) {
  const [currentPage, setCurrentPage] = useState(0);

  const totalChildren = React.Children.count(children);
  const totalPages = Math.ceil(totalChildren / pageSize);

  const childrenArray = _.chunk(React.Children.toArray(children), pageSize);

  return (
    <>
      {childrenArray[currentPage]}
      <Radio.Group defaultValue={0} size={totalPages}>
        {generateNButtons(totalPages, setCurrentPage)}
      </Radio.Group>
    </>
  );
}
</code>```

Title: Paginating a List in React

Body:
Probably a silly question but can't seem to figure it out on my own. Let's say I have a long list of items displayed on the page. I simply want to paginate it into pages of e.g. 5 items per page. To avoid reinventing the wheel, looked up a couple of libraries and react-js-pagination seems to do what I need. But for the life of me I can't figure it out.
What I have tried per the simplified example below:

Put <Pagination /> and my list in the same div.

Gave my list items a class of page-item per the API docs.

No luck. I added a parent of
 and/or put my items in
 tags. Even gave the parent
 a class of "pagination". Nothing. The only difference I am able to achieve is all items appearing in the same line like you see in the screenshot. Anything you figure out I am missing is appreciated.

import 'react-toastify/dist/ReactToastify.css';
import Pagination from "react-js-pagination";
import 'bootstrap/dist/css/bootstrap.css';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            activePage: 1
        }
    }

    handlePageChange(pageNumber) {
        this.setState({activePage: pageNumber});
    }

    render() {
        return (

1

2

3

4

5

6

7

8

9

10

11

                <Pagination
                    activePage={this.state.activePage}
                    itemsCountPerPage={2}
                    totalItemsCount={11}
                    pageRangeDisplayed={5}
                    onChange={this.handlePageChange.bind(this)}
                    itemClass="page-item"
                    linkClass="page-link"
                />

        );
    }
}

export default App;

Result so far:

Body:
You are missing the pagination logic.  Its not so trivial, here is a simple example (not related to react-js-pagination):

function Pagination({ pageSize, children }) {
  const [currentPage, setCurrentPage] = useState(0);

  const totalChildren = React.Children.count(children);
  const totalPages = Math.ceil(totalChildren / pageSize);

  const childrenArray = _.chunk(React.Children.toArray(children), pageSize);

  return (
    <>
      {childrenArray[currentPage]}
      <Radio.Group defaultValue={0} size={totalPages}>
        {generateNButtons(totalPages, setCurrentPage)}
      </Radio.Group>
    </>
  );
}


问:
Add class name to an exact element
There are 7 links in one div and 7 divs in another. Example https://jsfiddle.net/tania_poltava/2oqtr9v1/
I want, when the first link is hovered to influent on first img, adding class; and with other links.

im triing to do this - getting the number of hovered link, then looking for the div with classname with such number, and try to add new class.

```<code><div class="links">
    <a href="#" class="services__link--1">button1</a>
    <a href="#" class="services__link--2">button2</a>
    <a href="#" class="services__link--3">button3</a>
    <a href="#" class="services__link--4">button4</a>
    <a href="#" class="services__link--5">button5</a>
    <a href="#" class="services__link--6">button6</a>
    <a href="#" class="services__link--7">button7</a>
</div>
<div class="rounds">
    <div class="services__round--1"></div>
    <div class="services__round--2"></div>
    <div class="services__round--3"></div>
    <div class="services__round--4"></div>
    <div class="services__round--5"></div>
    <div class="services__round--6"></div>
    <div class="services__round--7"></div>
</div>

.rounds div {
  background: grey;
  width:40px;
  height: 40px;
  border-radius: 50%;
}
.services__round--active {
  background: green;
}

jQuery(function ($) {
$(document).ready(function() {
 var link = $(".links a");
 var linkClass = $(link).attr('class');
 var linkNumb = linkClass.replace(/[^0-9]/g,'');
 var roundClass = "services__round--" + linkNumb;
 $(link).hover(function(){
 var round = $(roundClass).addClass('services__round--active');
        // check
console.log(linkNumb);
console.log(linkClass);
console.log(roundClass);

})

})
})
</code>```

答:
EDITED: Answer for your code is;

https://jsfiddle.net/g3wjc6tz/

```<code>jQuery(function($) {
  $(document).ready(function() {
    var link = $(".links a");
    $(link).hover(function() {
      // check
      $('.services__round--active').removeClass('services__round--active')
      var linkClass = $(this).attr('class');
      var linkNumb = linkClass.replace(/[^0-9]/g, '');
      var roundClass = "services__round--" + linkNumb;
      var round = $('.' + roundClass).addClass('services__round--active');
      console.log(linkNumb);
      console.log(linkClass);
      console.log(roundClass);

    })

  })
})
</code>```

Not the best but more simple and proper way to do it: https://jsfiddle.net/g3wjc6tz/1/

Title: Add class name to an exact element

Body:
There are 7 links in one div and 7 divs in another. Example https://jsfiddle.net/tania_poltava/2oqtr9v1/
I want, when the first link is hovered to influent on first img, adding class; and with other links.

im triing to do this - getting the number of hovered link, then looking for the div with classname with such number, and try to add new class.

    button1
    button2
    button3
    button4
    button5
    button6
    button7

.rounds div {
  background: grey;
  width:40px;
  height: 40px;
  border-radius: 50%;
}
.services__round--active {
  background: green;
}

jQuery(function ($) {
$(document).ready(function() {
 var link = $(".links a");
 var linkClass = $(link).attr('class');
 var linkNumb = linkClass.replace(/[^0-9]/g,'');
 var roundClass = "services__round--" + linkNumb;
 $(link).hover(function(){
 var round = $(roundClass).addClass('services__round--active');
        // check
console.log(linkNumb);
console.log(linkClass);
console.log(roundClass);

})

})
})

Body:
EDITED: Answer for your code is;

https://jsfiddle.net/g3wjc6tz/

jQuery(function($) {
  $(document).ready(function() {
    var link = $(".links a");
    $(link).hover(function() {
      // check
      $('.services__round--active').removeClass('services__round--active')
      var linkClass = $(this).attr('class');
      var linkNumb = linkClass.replace(/[^0-9]/g, '');
      var roundClass = "services__round--" + linkNumb;
      var round = $('.' + roundClass).addClass('services__round--active');
      console.log(linkNumb);
      console.log(linkClass);
      console.log(roundClass);

    })

  })
})

Not the best but more simple and proper way to do it: https://jsfiddle.net/g3wjc6tz/1/


问:
["'<built-in function id>' is not a valid UUID."]
I am trying to patch an existing but i get an unknown problem .Does anybody know why?

Models.py

```<code>class Article(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(UserProfile,on_delete=models.CASCADE, related_name='articles')
    caption = models.CharField(max_length=250)
</code>```

Views.py

```<code>class ArticleView(CreateAPIView):
  serializer_class = ArticleCreateSerializer
  permission_classes = (IsAuthenticated,)

  def patch(self, request, *args, **kwargs):
        article = get_object_or_404(Article, pk=id)
        serializer = ArticleCreateSerializer(data=request.data, partial=True)
        if serializer.is_valid():
            article = serializer.save()
            return Response(ArticleCreateSerializer(article).data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

Error:

```<code>["'<built-in function id>' is not a valid UUID."]
</code>```

答:
article = get_object_or_404(Article, pk=id)

id here is built-in python function

```<code>article = get_object_or_404(Article, pk=kwargs.get('id'))
</code>```

will be right.

Body:
I am trying to patch an existing but i get an unknown problem .Does anybody know why?

Models.py

class Article(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(UserProfile,on_delete=models.CASCADE, related_name='articles')
    caption = models.CharField(max_length=250)

Views.py

class ArticleView(CreateAPIView):
  serializer_class = ArticleCreateSerializer
  permission_classes = (IsAuthenticated,)

  def patch(self, request, *args, **kwargs):
        article = get_object_or_404(Article, pk=id)
        serializer = ArticleCreateSerializer(data=request.data, partial=True)
        if serializer.is_valid():
            article = serializer.save()
            return Response(ArticleCreateSerializer(article).data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Error:

["'<built-in function id>' is not a valid UUID."]

Body:
article = get_object_or_404(Article, pk=id)

id here is built-in python function

article = get_object_or_404(Article, pk=kwargs.get('id'))

will be right.


问:
Search and Search All in COBOL
I want to know the result when we try to search an item in COBOL using SEARCH or SEARCH ALL and this item appears multiple times in the table.
Will any of the two will find all the occurrences ?</p>

答:
Neither will, but with the search you can set the initial starting index and do a second search to find subsequent entries.

Search

The Search verb does a linear search through the table. Table entries can be in any sequence.

If there are multiple entries the first after the starting index will be found.

You can use the Set index to verb to set the starting position.

Search All

The Search All does a binary search of the Table. The table must be in Key Sequence.
If there are multiple match's, any one could be found. For large tables, the Search All will be faster option.

Title: Search and Search All in COBOL


问:
How do I make 2 lists correspond to each other?
I have 2 lists here:

```<code>list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]
</code>```

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

```<code>if happy > sad:
    print ("you are happy")
</code>```

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.

答:
You can use a dictionary in python. A simple way to represent a key-value pair.
Ex: did = {'jack': 4098, 'sape': 4139}
click on it for better understandinghow to use dictionary

Body:
I have 2 lists here:

list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]

I want to make it so that the numbers are assigned to the emotions? (happy is equal to 2, sad is equal to 5, etc). Ideally, I want to make it so you can compare items from list1, for example:

if happy > sad:
    print ("you are happy")

I want to make this code as efficient as possible, so I do not want to separately assign each variable from list1 a number.


问:
How does the python -m prefix in command work?
I am very new to Python programming. I can use pip install without any trouble. I've seen a lot of posts in online which prefix pip install with python -m. When I use python -m before the pip command nothing seems to happen. Please explain.

答:
If you run python -h, the -m flag is described as:

```<code>-m mod : run library module as a script (terminates option list)
</code>```

In this case, when you run python -m pip Python runs the pip module as a script (i.e. it executes the code inside it). If you have added pip to your PATH you can then just run pip directly without the need to invoke it via python.

python -m pip install <some module> and pip install <some module> should perform identically. If you have multiple versions of Python installed on your system, using pip might install a module for the wrong version of Python. You can check the version using pip -V which will output something like

```<code>pip 18.1 from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip (python 3.7)
</code>```

here the python version is python3.7.

If the version of the pip command doesn't match with the version of Python used to execute a program when the program is executed it will not run. You can check your Python version with python -V, which will output something like

```<code>Python 2.7.16
</code>```

If the pip version doesn't match your Python version you can either update your path's pip, or you can use python -m pip. To select the correct version (i.e. if python runs Python 2 and you want to use Python 3) just execute python3 -m pip or python3.7 -m pip.

Body:
If you run python -h, the -m flag is described as:

-m mod : run library module as a script (terminates option list)

In this case, when you run python -m pip Python runs the pip module as a script (i.e. it executes the code inside it). If you have added pip to your PATH you can then just run pip directly without the need to invoke it via python.

python -m pip install <some module> and pip install <some module> should perform identically. If you have multiple versions of Python installed on your system, using pip might install a module for the wrong version of Python. You can check the version using pip -V which will output something like

pip 18.1 from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip (python 3.7)

here the python version is python3.7.

If the version of the pip command doesn't match with the version of Python used to execute a program when the program is executed it will not run. You can check your Python version with python -V, which will output something like

Python 2.7.16

If the pip version doesn't match your Python version you can either update your path's pip, or you can use python -m pip. To select the correct version (i.e. if python runs Python 2 and you want to use Python 3) just execute python3 -m pip or python3.7 -m pip.


问:
TypedArray.getText() on android.R.attr.text returns null
I am trying to implement a custom textview which uses StaticLayout. To get 'android:text' attribute of the view, I implemented like this in initializing field:

```<code>@SupressLint("ResourceType")
class ExampleTextView(context: Context, attrs: AttributeSet?, defStyleAttr: Int): View(...) {
    private var mText: String

    init {
        val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
            ...
            android.R.attr.text,
            ...
        ))

        mText = styledAttributes.getText(1)
        ...

        styledAttributes.recycle()
    }
    ...
}
</code>```

Then in layout xml:

```<code><com.example.package.ExampleTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is an example text" />
</code>```

I obviously set 'android:text' in the custom textview. But when I try to get attribute from TypedArray, it returns null. Another try with styledAttributes.getString(1) also does return null.

Stack Trace:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.package, PID: 19154
    android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class com.example.package.ExampleTextView
    Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class com.example.package.ExampleTextView
    Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:647)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at com.example.package.adapter.elementsAdapter.onCreateViewHolder(PatchNoteElementsAdapter.kt:54)
        at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:7078)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6235)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at com.google.android.material.appbar.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:148)
        at com.google.android.material.appbar.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:43)
        at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1996)
        at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:918)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
E/AndroidRuntime:     at com.android.internal.policy.DecorView.onLayout(DecorView.java:765)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2806)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2333)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1473)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7215)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1004)
        at android.view.Choreographer.doCallbacks(Choreographer.java:816)
        at android.view.Choreographer.doFrame(Choreographer.java:751)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:990)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:280)
        at android.app.ActivityThread.main(ActivityThread.java:6706)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: kotlin.KotlinNullPointerException
        at com.example.package.ExampleTextView.<init>(ExampleTextView.kt:66)
        at com.example.package.ExampleTextView.<init>(ExampleTextView.kt:22)
            ... 67 more
</code>```

Is there anything that I missed?

答:
SHORT ANSWER: Sort your attribute IDs in ascending order.

I found an answer. It is because the order of IntArray which is being passed as paramter on context.obtainStyledAttributes().

When I defined styledAttributes, I wrote like this:

```<code>val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
    android.R.attr.fontFamily,
    android.R.attr.text,
    android.R.attr.textSize,
    android.R.attr.textColor,
    android.R.attr.textAlignment,
    android.R.attr.lineSpacingExtra
))
</code>```

According to above, the styledAttributes didn't get ordered. We can know it when we check a value of constant through android studio documentation (Ctrl+Q). Which is equal to this:

```<code>val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
    16843692,
    16843087,
    16842901,
    16842904,
    16843697,
    16843287
))
</code>```

Although I didn't metioned in the question, I also got null when I tried to get value of textSize and lineSpacingExtra.

Why? Because when obtainStyledAttributes called with unordered list, the attribute value will be null whatever you do; getText(), getString(), getDimension(), getFont(), getResourceId(), etc... if the next value of attribute constant is smaller than before one.

That's the reason that I got null when I tried to get value of attribute constant 16843087, 16842901, 16843287 which is smaller than before ones; 16843692, 16843087, 16843697.

In addition, according to Android Developer Reference, they are obviously saying that array of attribute constants must be sorted in ascending order. https://developer.android.com/reference/android/content/res/Resources.Theme#obtainStyledAttributes(android.util.AttributeSet,%20int[],%20int,%20int)

attrs | int: The desired attributes in the style. These attribute IDs must be sorted in ascending order. This value cannot be null.

So, to get attribute values correctly, I should did like this:

```<code>val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
    android.R.attr.textSize,
    android.R.attr.textColor,
    android.R.attr.text,
    android.R.attr.lineSpacingExtra,
    android.R.attr.fontFamily,
    android.R.attr.textAlignment
))
</code>```

which is sorted in ascending order very well. Hope this helped for future readers.

Body:
I am trying to implement a custom textview which uses StaticLayout. To get 'android:text' attribute of the view, I implemented like this in initializing field:

@SupressLint("ResourceType")
class ExampleTextView(context: Context, attrs: AttributeSet?, defStyleAttr: Int): View(...) {
    private var mText: String

    init {
        val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
            ...
            android.R.attr.text,
            ...
        ))

        mText = styledAttributes.getText(1)
        ...

        styledAttributes.recycle()
    }
    ...
}

Then in layout xml:

<com.example.package.ExampleTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is an example text" />

I obviously set 'android:text' in the custom textview. But when I try to get attribute from TypedArray, it returns null. Another try with styledAttributes.getString(1) also does return null.

Stack Trace:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.package, PID: 19154
    android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class com.example.package.ExampleTextView
    Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class com.example.package.ExampleTextView
    Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:647)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at com.example.package.adapter.elementsAdapter.onCreateViewHolder(PatchNoteElementsAdapter.kt:54)
        at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:7078)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6235)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at com.google.android.material.appbar.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:148)
        at com.google.android.material.appbar.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:43)
        at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1996)
        at androidx.coordinatorlayout.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:918)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
E/AndroidRuntime:     at com.android.internal.policy.DecorView.onLayout(DecorView.java:765)
        at android.view.View.layout(View.java:20691)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2806)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2333)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1473)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7215)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1004)
        at android.view.Choreographer.doCallbacks(Choreographer.java:816)
        at android.view.Choreographer.doFrame(Choreographer.java:751)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:990)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:280)
        at android.app.ActivityThread.main(ActivityThread.java:6706)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: kotlin.KotlinNullPointerException
        at com.example.package.ExampleTextView.<init>(ExampleTextView.kt:66)
        at com.example.package.ExampleTextView.<init>(ExampleTextView.kt:22)
            ... 67 more

Is there anything that I missed?

Body:
SHORT ANSWER: Sort your attribute IDs in ascending order.

I found an answer. It is because the order of IntArray which is being passed as paramter on context.obtainStyledAttributes().

When I defined styledAttributes, I wrote like this:

val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
    android.R.attr.fontFamily,
    android.R.attr.text,
    android.R.attr.textSize,
    android.R.attr.textColor,
    android.R.attr.textAlignment,
    android.R.attr.lineSpacingExtra
))

According to above, the styledAttributes didn't get ordered. We can know it when we check a value of constant through android studio documentation (Ctrl+Q). Which is equal to this:

val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
    16843692,
    16843087,
    16842901,
    16842904,
    16843697,
    16843287
))

Although I didn't metioned in the question, I also got null when I tried to get value of textSize and lineSpacingExtra.

Why? Because when obtainStyledAttributes called with unordered list, the attribute value will be null whatever you do; getText(), getString(), getDimension(), getFont(), getResourceId(), etc... if the next value of attribute constant is smaller than before one.

That's the reason that I got null when I tried to get value of attribute constant 16843087, 16842901, 16843287 which is smaller than before ones; 16843692, 16843087, 16843697.

In addition, according to Android Developer Reference, they are obviously saying that array of attribute constants must be sorted in ascending order. https://developer.android.com/reference/android/content/res/Resources.Theme#obtainStyledAttributes(android.util.AttributeSet,%20int[],%20int,%20int)

attrs | int: The desired attributes in the style. These attribute IDs must be sorted in ascending order. This value cannot be null.

So, to get attribute values correctly, I should did like this:

val styledAttributes = context.obtainStyledAttributes(attrs, intArrayOf(
    android.R.attr.textSize,
    android.R.attr.textColor,
    android.R.attr.text,
    android.R.attr.lineSpacingExtra,
    android.R.attr.fontFamily,
    android.R.attr.textAlignment
))

which is sorted in ascending order very well. Hope this helped for future readers.


问:
league/csv problem reading file with ISO-8859-1 encoding
```<code>$data = file_get_contents($path);
$data = mb_convert_encoding($data, 'UTF-8', mb_detect_encoding($data, 'UTF-8, ISO-8859-1', true));

$csv = Reader::createFromString($data);
$csv->setDelimiter(';');
$csv->setHeaderOffset(0);

$test = $csv->getContent();

return (new Statement)->process($csv);
</code>```

When I debug and look at $test, all characters are displayed correctly (no lÃ¸nn etc).

When I loop through the TabularDataReader object returned from this line:

```<code>return (new Statement)->process($csv);
</code>```

the headers are displaying incorrectly e.g "Bil lÃ¸nn" (should be "Bil lønn").

Do I have to set encoding on the Statement object as well? I looked through the class, but couldn't find any functions related to encoding.

答:
I've had the same issue with league/csv and ISO-8859-1 encoding. Try this workaround:

$data = file_get_contents($path);

if (!mb_check_encoding($data, 'UTF-8')) {
    $data = mb_convert_encoding($data, 'UTF-8');
}

$csv = Reader::createFromString($data);
$csv->setDelimiter(';');
$csv->setHeaderOffset(0);

$test = $csv->getContent();

return (new Statement)->process($csv);
```

Body:
$data = file_get_contents($path);
$data = mb_convert_encoding($data, 'UTF-8', mb_detect_encoding($data, 'UTF-8, ISO-8859-1', true));

$csv = Reader::createFromString($data);
$csv->setDelimiter(';');
$csv->setHeaderOffset(0);

$test = $csv->getContent();

return (new Statement)->process($csv);

When I debug and look at $test, all characters are displayed correctly (no lÃ¸nn etc).

When I loop through the TabularDataReader object returned from this line:

return (new Statement)->process($csv);

the headers are displaying incorrectly e.g "Bil lÃ¸nn" (should be "Bil lønn").

Do I have to set encoding on the Statement object as well? I looked through the class, but couldn't find any functions related to encoding.


问:
Table usage in the webpage in asp.net(C#)
```<code>  int numcells = 2;

          foreach (System.IO.FileInfo fi in fileQuery)
          {
              Label1.Text = fileList.Count().ToString();

                  TableRow r = new TableRow();
                  for (int i = 0; i < numcells; i++)
                  {
                      if (i.Equals("0"))
                      {

                          TableCell c = new TableCell();
                          c.Controls.Add(new LiteralControl(fi.Name.ToString()));
                          r.Cells.Add(c);

                      }
                      if (i.Equals("1"))
                      {

                          TableCell c = new TableCell();
                          c.Controls.Add(new LiteralControl(Server.MapPath(strheadlinesid).ToString() + fi.Name.ToString()));
                          r.Cells.Add(c);
                      }
                      Table1.Rows.Add(r);

              }
</code>```

I tried with the above code to print file name and and its path in the table.

But for some reason it's not printing the table.

Is there any wrong in the syntax.

       Please let me know the wrong in the code  if anyone finds it.

答:
i.Equals("0") and i.Equals("1") is incorrect and should be i.Equals(0) and i.Equals(1)

This will sort out your problem, Equals is used to determine if the specified object is equal to the current object, and in this case it is not because "1" is a string and 1 is an integer.

have a look here for more info on equals

Body:
  int numcells = 2;

          foreach (System.IO.FileInfo fi in fileQuery)
          {
              Label1.Text = fileList.Count().ToString();

                  TableRow r = new TableRow();
                  for (int i = 0; i < numcells; i++)
                  {
                      if (i.Equals("0"))
                      {

                          TableCell c = new TableCell();
                          c.Controls.Add(new LiteralControl(fi.Name.ToString()));
                          r.Cells.Add(c);

                      }
                      if (i.Equals("1"))
                      {

                          TableCell c = new TableCell();
                          c.Controls.Add(new LiteralControl(Server.MapPath(strheadlinesid).ToString() + fi.Name.ToString()));
                          r.Cells.Add(c);
                      }
                      Table1.Rows.Add(r);

              }

I tried with the above code to print file name and and its path in the table.

But for some reason it's not printing the table.

Is there any wrong in the syntax.

       Please let me know the wrong in the code  if anyone finds it.


问:
How do I linear search two arrays in c++?
I have two arrays of data type double - called array1[10] and array2[8]. I am required to search for array2 inside array1 at each element using a linear search function. The function declaration is

```<code>string linSearch (double array1[10], double array2[8]);
</code>```

If array2 is found inside array1 then I need to print out the index of where it is found in array1. If its not found I need the output to be "NA". This output must be a delimited-comma- string.
eg.

```<code>//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}

//after the linear search completes, the output must be the index in which //array2 is found in array1. if its not found, then it must be NA:

2,NA,5,6,0,NA,NA,7
</code>```

So far I have the code that follows. Its my first time working with arrays and I am still having difficulties grasping the concept- like once I define the function how do I even call it in the main program?! anyway..the function definition I have (excluding the main program) is:

```<code>string linSearch (double array1[10], double array2[8])
{
    int index1 = 0;
    int index2 =0;
    int position =-1;
    bool found = false;
    while (index1<10 && !found && index2<8)
    {
        if array1[index1] == array2[index2])
        {
            found = true;
            position = index1;
        }
        index1++;
        index2++;
    }

    return position;

}
</code>```

I am EXTREMELY confused about searching for one array in the other and how to output the delimited list as well as how to connect it to my main program. Any help would be GREATLY appreciated. Thanks!

答:
You are not searching one array inside the other. You are searching for elements from one array in a second array. If you are using a linear search and if you do not want to sort the array, you need 2 nested loops to do that. One for each element in the second array, and one to find that element in the first array.

Keep things simple and start with finding the position of a single element in one array. Because you are comparing doubles, you should not compare them with ==. Next you just need a function that calls the first for each element in the second array:

```<code>#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

void index_to_string(const std::vector<double>& v,double e,std::ostream& out){
    auto it = std::find_if(v.begin(),
                           v.end(),
                           [e](const double& x) {
                               return std::abs(e-x) < 1e-8;
                           }
                        );
    if (it == v.end()) {
        out << "NA";
    } else {
        out << (it - v.begin());
    }
}

void all_indices_to_string(const std::vector<double>& v1,const std::vector<double>& v2,std::ostream& out){
    if (v1.size() == 0 || v2.size()==0) return;
    index_to_string(v1,v2[0],out);
    for (size_t i=1;i<v2.size();++i){
        out << ",";
        index_to_string(v1,v2[i],out);
    }
}

int main() {
    double array1[] ={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4};
    double array2[] ={6,45,2,7,1.1,5,4,8.8};
    all_indices_to_string(
        std::vector<double>(std::begin(array1),std::end(array1)),
        std::vector<double>(std::begin(array2),std::end(array2)),
        std::cout
    );
}
</code>```

Output:

```<code>2,NA,5,3,0,NA,NA,7
</code>```

Body:
I have two arrays of data type double - called array1[10] and array2[8]. I am required to search for array2 inside array1 at each element using a linear search function. The function declaration is

string linSearch (double array1[10], double array2[8]);

If array2 is found inside array1 then I need to print out the index of where it is found in array1. If its not found I need the output to be "NA". This output must be a delimited-comma- string.
eg.

//given the two arrays:
array1={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4}
array2={6,45,2,7,1.1,5,4,8.8}

//after the linear search completes, the output must be the index in which //array2 is found in array1. if its not found, then it must be NA:

2,NA,5,6,0,NA,NA,7

So far I have the code that follows. Its my first time working with arrays and I am still having difficulties grasping the concept- like once I define the function how do I even call it in the main program?! anyway..the function definition I have (excluding the main program) is:

string linSearch (double array1[10], double array2[8])
{
    int index1 = 0;
    int index2 =0;
    int position =-1;
    bool found = false;
    while (index1<10 && !found && index2<8)
    {
        if array1[index1] == array2[index2])
        {
            found = true;
            position = index1;
        }
        index1++;
        index2++;
    }

    return position;

}

I am EXTREMELY confused about searching for one array in the other and how to output the delimited list as well as how to connect it to my main program. Any help would be GREATLY appreciated. Thanks!

Body:
You are not searching one array inside the other. You are searching for elements from one array in a second array. If you are using a linear search and if you do not want to sort the array, you need 2 nested loops to do that. One for each element in the second array, and one to find that element in the first array.

Keep things simple and start with finding the position of a single element in one array. Because you are comparing doubles, you should not compare them with ==. Next you just need a function that calls the first for each element in the second array:

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

void index_to_string(const std::vector<double>& v,double e,std::ostream& out){
    auto it = std::find_if(v.begin(),
                           v.end(),
                           [e](const double& x) {
                               return std::abs(e-x) < 1e-8;
                           }
                        );
    if (it == v.end()) {
        out << "NA";
    } else {
        out << (it - v.begin());
    }
}

void all_indices_to_string(const std::vector<double>& v1,const std::vector<double>& v2,std::ostream& out){
    if (v1.size() == 0 || v2.size()==0) return;
    index_to_string(v1,v2[0],out);
    for (size_t i=1;i<v2.size();++i){
        out << ",";
        index_to_string(v1,v2[i],out);
    }
}

int main() {
    double array1[] ={1.1,1.2,6,7,3.5,2,7,8.8,9,23.4};
    double array2[] ={6,45,2,7,1.1,5,4,8.8};
    all_indices_to_string(
        std::vector<double>(std::begin(array1),std::end(array1)),
        std::vector<double>(std::begin(array2),std::end(array2)),
        std::cout
    );
}

Output:

2,NA,5,3,0,NA,NA,7


问:
HighCharts - Make the pie chart 100% of the div
How can I make a pie chart fill 100% of the divit is contained in? The div has a width of 198px and it's height is 152px.

Additionally I would like to have a linear-gradient effect inside each pie slice, can you advise on how to do that?

答:
my solutions; (for legend position margin-top error..)</p>

```<code>chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie',
                    height:'100%' // added...
                },

plotOptions: {
        pie: {
            size:'100%',
             height: '100%',
            dataLabels: {
                enabled: false
            }
        }
    }
</code>```

Body:
my solutions; (for legend position margin-top error..)

chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie',
                    height:'100%' // added...
                },

plotOptions: {
        pie: {
            size:'100%',
             height: '100%',
            dataLabels: {
                enabled: false
            }
        }
    }


问:
Python - Convert a roman numeral to an integer
I've tried the following Python 3 code that transform from Roman to Integer.

The code is working fine at a glance. But there are certain problem happened when I input X, V or related to X and V value.

For example: when I try V the code is not working but for IV showing correct value.

My code:

```<code>class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
if message <= ("MMMCMXCIX"):
   print (ob1.romanToInt(message))
else:
    print ("Try again")
</code>```

I've set the condition which is, if the input roman number is equal or less than MMMCMXCIX, it will print the roman number; else it will print Try again.

The problem is when I input X, V or related to X and V value the output is showing Try again

Please help me to understand where I went wrong.

答:
In the end its just an addition of numbers, you just need to figure if they need to be interpreted positive or negativ:

```<code>roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}

def roman2Dec(inp):
    inpNum = [roman[x] for x in inp]
    return sum([-x if i < len(inpNum)-1 and x < inpNum[i+1] else x for i, x in enumerate(inpNum)])

for nums in [('IX', 9), ('XL', 40), ('LXI', 61), ('MMMCMXCIX', 3999)]:
    result = roman2Dec(nums[0])
    print result == nums[1]
</code>```

Output:

```<code>True
True
True
True
</code>```

Body:
I've tried the following Python 3 code that transform from Roman to Integer.

The code is working fine at a glance. But there are certain problem happened when I input X, V or related to X and V value.

For example: when I try V the code is not working but for IV showing correct value.

My code:

class Solution(object):
   def romanToInt(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
if message <= ("MMMCMXCIX"):
   print (ob1.romanToInt(message))
else:
    print ("Try again")

I've set the condition which is, if the input roman number is equal or less than MMMCMXCIX, it will print the roman number; else it will print Try again.

The problem is when I input X, V or related to X and V value the output is showing Try again

Please help me to understand where I went wrong.

Body:
In the end its just an addition of numbers, you just need to figure if they need to be interpreted positive or negativ:

roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}

def roman2Dec(inp):
    inpNum = [roman[x] for x in inp]
    return sum([-x if i < len(inpNum)-1 and x < inpNum[i+1] else x for i, x in enumerate(inpNum)])

for nums in [('IX', 9), ('XL', 40), ('LXI', 61), ('MMMCMXCIX', 3999)]:
    result = roman2Dec(nums[0])
    print result == nums[1]

Output:

True
True
True
True


问:
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres" while connecting to postgress from Spring Boot
This is the command prompt where I have created container and database
application.yml

```<code>app:
  datasource:
    jdbc-url: jdbc:postgresql://localhost:5432/postgresDB
    username: postgres
    password: password
    pool-size: 30
</code>```

I am new to docker. I have created one container in docker and in that container I have created Postgres DB but while connecting to the database I am getting the following error:

Stacktrace:

```<code>org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:525) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:146) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:197) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:211) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.Driver.makeConnection(Driver.java:459) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.Driver.connect(Driver.java:261) ~[postgresql-42.2.12.jar:42.2.12]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-3.4.5.jar:na]
    at org.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:56) [flyway-core-6.4.1.jar:na]
    at org.flywaydb.core.internal.jdbc.JdbcConnectionFactory.<init>(JdbcConnectionFactory.java:80) [flyway-core-6.4.1.jar:na]
    at org.flywaydb.core.Flyway.execute(Flyway.java:456) [flyway-core-6.4.1.jar:na]
    at org.flywaydb.core.Flyway.migrate(Flyway.java:159) [flyway-core-6.4.1.jar:na]
    at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:65) [spring-boot-autoconfigure-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:895) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at com.freecodecamp.freecodecamp.FreecodecampApplication.main(FreecodecampApplication.java:10) ~[classes/:na]

2020-05-31 15:40:31.124  WARN 18004 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.exception.FlywaySqlException:
Unable to obtain connection from database: FATAL: password authentication failed for user "postgres"
</code>```

答:
As you can see in the tracktrace,

```<code>org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"
</code>```

your application cannot login to your DB because your credentials are not right. Are you sure about username: postgres and password: password?

Can you try using a DBMS to connect to your DB using those credentials?

Body:
This is the command prompt where I have created container and database
application.yml

app:
  datasource:
    jdbc-url: jdbc:postgresql://localhost:5432/postgresDB
    username: postgres
    password: password
    pool-size: 30

I am new to docker. I have created one container in docker and in that container I have created Postgres DB but while connecting to the database I am getting the following error:

Stacktrace:

org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"
    at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:525) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:146) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:197) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:211) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.Driver.makeConnection(Driver.java:459) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.Driver.connect(Driver.java:261) ~[postgresql-42.2.12.jar:42.2.12]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-3.4.5.jar:na]
    at org.flywaydb.core.internal.jdbc.JdbcUtils.openConnection(JdbcUtils.java:56) [flyway-core-6.4.1.jar:na]
    at org.flywaydb.core.internal.jdbc.JdbcConnectionFactory.<init>(JdbcConnectionFactory.java:80) [flyway-core-6.4.1.jar:na]
    at org.flywaydb.core.Flyway.execute(Flyway.java:456) [flyway-core-6.4.1.jar:na]
    at org.flywaydb.core.Flyway.migrate(Flyway.java:159) [flyway-core-6.4.1.jar:na]
    at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:65) [spring-boot-autoconfigure-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) [spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:895) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at com.freecodecamp.freecodecamp.FreecodecampApplication.main(FreecodecampApplication.java:10) ~[classes/:na]

2020-05-31 15:40:31.124  WARN 18004 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.exception.FlywaySqlException:
Unable to obtain connection from database: FATAL: password authentication failed for user "postgres"

Body:
As you can see in the tracktrace,

org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"

your application cannot login to your DB because your credentials are not right. Are you sure about username: postgres and password: password?

Can you try using a DBMS to connect to your DB using those credentials?


问:
How to persist the list which we made dynamically from dataFrame in scala spark
```<code> def getAnimalName(dataFrame: DataFrame): List[String] = {
    dataFrame.select("animal").
      filter(col("animal").isNotNull && col("animal").notEqual("")).
      rdd.map(r => r.getString(0)).distinct().collect.toList
  }
</code>```

I am basicaly Calling this function 2 times For getting the list for different purposes . I just want to know is there a way to retain the list in memory and we dont have to call the same function again and again to generate the list and only have to generate the list only one time in scala spark.

答:
You would have to persist or cache at this point

```<code>dataFrame.select("animal").
      filter(col("animal").isNotNull && col("animal").notEqual("")).
      rdd.map(r => r.getString(0)).distinct().persist
</code>```

and then call the function as follow

```<code>def getAnimalName(dataFrame: DataFrame): List[String] = {
    dataFrame.collect.toList
  }
</code>```

as many times as you need it without repeat the process.
I hope it helps.

Body:
 def getAnimalName(dataFrame: DataFrame): List[String] = {
    dataFrame.select("animal").
      filter(col("animal").isNotNull && col("animal").notEqual("")).
      rdd.map(r => r.getString(0)).distinct().collect.toList
  }

I am basicaly Calling this function 2 times For getting the list for different purposes . I just want to know is there a way to retain the list in memory and we dont have to call the same function again and again to generate the list and only have to generate the list only one time in scala spark.

Body:
You would have to persist or cache at this point

dataFrame.select("animal").
      filter(col("animal").isNotNull && col("animal").notEqual("")).
      rdd.map(r => r.getString(0)).distinct().persist

and then call the function as follow

def getAnimalName(dataFrame: DataFrame): List[String] = {
    dataFrame.collect.toList
  }

as many times as you need it without repeat the process.
I hope it helps.


问:
Liftweb and memory in hosting? Tune up liftweb?
I want to deploy web application developed using liftweb framework, I looked for good hosting and decided to use webfaction.com, they have pretty good features, but have very strict in memory.

If web application is just catalog, that don't have some heavy stuff in server side, and only getting all from Mysql and rendering pages,
how much memory I need?

How to tune up liftweb applications?

I have already see some links from David Pollak about tuning up, but links was broken, can any body give working link?

What is best choice to test web application for memory?

And does any one have experienced webfaction, because as I chatted tech support I must install apache tomcat from sources, can you give some advise how to do it in a best way?

Thanks for attention.

答: I'm using Lift with Tomcat and MySQL on VPS box, and as I can see after some months my application usually requires about 80Mb of RAM. Under testing load (50 visitors simultaneously) RAM usage was about 130-150Mb (CPU utilization was about 10-20%, but I have no heavy SQL queries). This is for 32-bit host system, under 64-bit host RAM usage will be increased.</p>


问:
CVXOPT seemingly provides non-optimal result for this simple quadratic program
I am trying to solve a simple quadratic program using CVXOPT and am troubled by the fact that I can guess a feasible solution better than the optimum provided by the solver. The optimisation is of the form:

I will provide the definitions of P,q,G,h,A, and b at the end. When I import and run:

```<code>from cvxopt import matrix, spmatrix, solvers
# Code that creates matrices goes here
sol = solvers.qp(P, q, G, h, A, b)
</code>```

the result is:

```<code>   pcost       dcost       gap    pres   dres
 0:  0.0000e+00 -5.5000e+00  6e+00  6e-17  4e+00
 1:  0.0000e+00 -5.5000e-02  6e-02  1e-16  4e-02
 2:  0.0000e+00 -5.5000e-04  6e-04  3e-16  4e-04
 3:  0.0000e+00 -5.5000e-06  6e-06  1e-16  4e-06
 4:  0.0000e+00 -5.5000e-08  6e-08  1e-16  4e-08
Optimal solution found.

Objective = 0.0
</code>```

However I can define a different solution guessed_solution that is feasible and further minimises the objective:

```<code>guessed_solution = matrix([0.5,0.5,0.0,0.0,0.0,0.0,0.5,0.5,0.0,0.0,1.0])

# Check Ax = b; want to see zeroes
print(A * guessed_solution - b)
>>>
[ 0.00e+00]
[ 0.00e+00]
[ 2.78e-17]

# Check Gx <= h; want to see non-positive entries
print(G * guessed_solution - h)
>>>
[-5.00e-01]
[-5.00e-01]
[ 0.00e+00]
[ 0.00e+00]
[ 0.00e+00]
[ 0.00e+00]
[-5.00e-01]
[-5.00e-01]
[-1.00e+00]
[-1.00e+00]
[ 0.00e+00]
[ 0.00e+00]
[ 0.00e+00]
[-1.00e+00]

# Check objective
print(guessed_solution.T * P * guessed_solution + q.T * guessed_solution)
>>>[-6.67e-01]
</code>```

This results in an objective that is -2/3, clearly less than 0. I presume that the 2.78e-17 error in the Ax=b test is not relevant.

Any help on resolving this would be appreciated! And below is the definition of relevant matrices in code (biggest matrix is 11 by 11).

```<code>P = matrix([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0],[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0/3.0, 0.0, 2.0/3.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0/3.0, 2.0/3.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0],[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0/3.0, 0.0, -2.0/3.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0/3.0, -2.0/3.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]).T
q = matrix([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])

A = matrix([[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],[1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],[0.0, 1.0, 1.0/3.0, 2.0/3.0, 0.0, -1.0, -1.0/3.0, -2.0/3.0, 0.0, 0.0, 0.0]]).T
b = matrix([1.0, 1.0, 0.0])

G = spmatrix([-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0], [0,1,2,3,4,5,6,7,8,9,10,11,12,13], [0,1,2,3,4,5,6,7,8,9,10,8,9,10])
h = matrix([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0])
</code>```

答:
Your quadratic form is not valid in regards to the assumptions.

It needs to be PSD (and symmetric).

Making it symmetric:

```<code>P = (P + P.T) / 2
</code>```

will lead to cvxopt showing an error, which is due to P being indefinite:

```<code>import numpy as np

np_matrix = np.array(P)
print(np.linalg.eigvalsh(np_matrix))

#[-8.16496581e-01 -7.45355992e-01 -5.77350269e-01 -2.40008780e-16 -6.33511351e-17 -4.59089160e-17 -3.94415555e-22  5.54077304e-17  5.77350269e-01  7.45355992e-01  8.16496581e-01]
</code>```

You got a solver designed for convex-optimization problems (if and only if P is PSD) feeded by some non-convex optimization problem. This won't work (in general).

Body:
I am trying to solve a simple quadratic program using CVXOPT and am troubled by the fact that I can guess a feasible solution better than the optimum provided by the solver. The optimisation is of the form:

I will provide the definitions of P,q,G,h,A, and b at the end. When I import and run:

from cvxopt import matrix, spmatrix, solvers
# Code that creates matrices goes here
sol = solvers.qp(P, q, G, h, A, b)

the result is:

   pcost       dcost       gap    pres   dres
 0:  0.0000e+00 -5.5000e+00  6e+00  6e-17  4e+00
 1:  0.0000e+00 -5.5000e-02  6e-02  1e-16  4e-02
 2:  0.0000e+00 -5.5000e-04  6e-04  3e-16  4e-04
 3:  0.0000e+00 -5.5000e-06  6e-06  1e-16  4e-06
 4:  0.0000e+00 -5.5000e-08  6e-08  1e-16  4e-08
Optimal solution found.

Objective = 0.0

However I can define a different solution guessed_solution that is feasible and further minimises the objective:

guessed_solution = matrix([0.5,0.5,0.0,0.0,0.0,0.0,0.5,0.5,0.0,0.0,1.0])

# Check Ax = b; want to see zeroes
print(A * guessed_solution - b)
>>>
[ 0.00e+00]
[ 0.00e+00]
[ 2.78e-17]

# Check Gx <= h; want to see non-positive entries
print(G * guessed_solution - h)
>>>
[-5.00e-01]
[-5.00e-01]
[ 0.00e+00]
[ 0.00e+00]
[ 0.00e+00]
[ 0.00e+00]
[-5.00e-01]
[-5.00e-01]
[-1.00e+00]
[-1.00e+00]
[ 0.00e+00]
[ 0.00e+00]
[ 0.00e+00]
[-1.00e+00]

# Check objective
print(guessed_solution.T * P * guessed_solution + q.T * guessed_solution)
>>>[-6.67e-01]

This results in an objective that is -2/3, clearly less than 0. I presume that the 2.78e-17 error in the Ax=b test is not relevant.

Any help on resolving this would be appreciated! And below is the definition of relevant matrices in code (biggest matrix is 11 by 11).

P = matrix([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0],[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0/3.0, 0.0, 2.0/3.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0/3.0, 2.0/3.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0],[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0/3.0, 0.0, -2.0/3.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0/3.0, -2.0/3.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]).T
q = matrix([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])

A = matrix([[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],[1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],[0.0, 1.0, 1.0/3.0, 2.0/3.0, 0.0, -1.0, -1.0/3.0, -2.0/3.0, 0.0, 0.0, 0.0]]).T
b = matrix([1.0, 1.0, 0.0])

G = spmatrix([-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0], [0,1,2,3,4,5,6,7,8,9,10,11,12,13], [0,1,2,3,4,5,6,7,8,9,10,8,9,10])
h = matrix([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0])

Body:
Your quadratic form is not valid in regards to the assumptions.

It needs to be PSD (and symmetric).

Making it symmetric:

P = (P + P.T) / 2

will lead to cvxopt showing an error, which is due to P being indefinite:

import numpy as np

np_matrix = np.array(P)
print(np.linalg.eigvalsh(np_matrix))

#[-8.16496581e-01 -7.45355992e-01 -5.77350269e-01 -2.40008780e-16 -6.33511351e-17 -4.59089160e-17 -3.94415555e-22  5.54077304e-17  5.77350269e-01  7.45355992e-01  8.16496581e-01]

You got a solver designed for convex-optimization problems (if and only if P is PSD) feeded by some non-convex optimization problem. This won't work (in general).