问:
Very simple array, loop, and logical comparison issue
Very simple question: I'm trying to compare values in an array and I'm completely stumped as to why my comparison logic is failing. Somehow, during the course of my loop, 6 is being evaluated as > 524. Any ideas as to what I'm doing wrong? I'm totally stumped. Here's the code, and thanks!

```<code>function highAndLow(numbers){

    var compArr = numbers.split(" ");

    var highNum = compArr[0]
    var lowNum = compArr[0];

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] > highNum) {
          highNum = compArr[i]
          console.log(highNum)
        }
      }

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] < lowNum) {
          lowNum = compArr[i]
        }
      }

      return highNum + " " + lowNum
}

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")
</code>```

Again, I'm not sure how, but the result I'm getting in the console is 6 for the highNum (incorrect) and -214 for the lowNum (which is correct). Am I missing something obvious?

答:
The elements of compArr are strings, so they're being compared lexicographically, not numerically. You should make an array of numbers:

```<code>var compArr = numbers.split(" ").map(Number);
</code>```

function highAndLow(numbers){

    var compArr = numbers.split(" ").map(Number);

    var highNum = compArr[0]
    var lowNum = compArr[0];

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] > highNum) {
          highNum = compArr[i]
          console.log(highNum)
        }
      }

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] < lowNum) {
          lowNum = compArr[i]
        }
      }

      return highNum + " " + lowNum
}

console.log(highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"));```

Body:
Very simple question: I'm trying to compare values in an array and I'm completely stumped as to why my comparison logic is failing. Somehow, during the course of my loop, 6 is being evaluated as > 524. Any ideas as to what I'm doing wrong? I'm totally stumped. Here's the code, and thanks!

function highAndLow(numbers){

    var compArr = numbers.split(" ");

    var highNum = compArr[0]
    var lowNum = compArr[0];

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] > highNum) {
          highNum = compArr[i]
          console.log(highNum)
        }
      }

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] < lowNum) {
          lowNum = compArr[i]
        }
      }

      return highNum + " " + lowNum
}

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")

Again, I'm not sure how, but the result I'm getting in the console is 6 for the highNum (incorrect) and -214 for the lowNum (which is correct). Am I missing something obvious?

Body:
The elements of compArr are strings, so they're being compared lexicographically, not numerically. You should make an array of numbers:

var compArr = numbers.split(" ").map(Number);

function highAndLow(numbers){

    var compArr = numbers.split(" ").map(Number);

    var highNum = compArr[0]
    var lowNum = compArr[0];

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] > highNum) {
          highNum = compArr[i]
          console.log(highNum)
        }
      }

      for (i = 1; i < compArr.length; i++) {
        if (compArr[i] < lowNum) {
          lowNum = compArr[i]
        }
      }

      return highNum + " " + lowNum
}

console.log(highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"));


来源: stackexchange

问:
Can't instantiate class even included
I'm very new to PHP, and I can't solve an issue even I read a lot of tutorials and SO posts.
I've a custom class (user), and I'd like to instantiate it in php code, but even I include it, I get this error.

Fatal error: Class 'User' not found in D:\wamp64\www\MyFirstPhp\formPhp.php on line 17

Please help me find out what I do wrong.

Here is my user class:

```<code>  <?php
/**
 * Created by IntelliJ IDEA.
 * User: molnard
 * Date: 2017. 06. 06.
 * Time: 15:36
 */

namespace infopro;

class User
{
    private $username;
    private $userage;
    private $sex;

    public function __construct($username, $userage, $sex)
    {
        if (!is_null($username)) $this->username = $username;
        if (!is_null($userage)) $this->userage = $this->userage;
        if (!is_null($sex)) $this->sex = $sex;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return mixed
     */
    public function getUserage()
    {
        return $this->userage;
    }

    /**
     * @param mixed $userage
     */
    public function setUserage($userage)
    {
        $this->userage = $userage;
    }

    /**
     * @return mixed
     */
    public function getSex()
    {
        return $this->sex;
    }

    /**
     * @param mixed $sex
     */
    public function setSex($sex)
    {
        $this->sex = $sex;
    }
}
?>
</code>```

And here is my form.php class where I'd like to instantiate user class.

```<code>    <!Doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form php</title>
</head>
<body>
<?php
include("User.php");

$name = $_POST["name"];
$age = $_POST["age"];
$sex = $_POST["sex"];
echo "New user<br>name: " . $name . "<br>" .
    "age: " . $age . "<br>" . "sex: " . $sex."<br>";

$newuser = new User($name, $age, $sex);
$newAge = $newuser->getAge();
echo $newAge;
?>
</body>
</html>
</code>```

答:
The exception already told you, whats wrong with your code. There's no such User class. If you use namespaces, and your currently in another namespace (or no namespace), you have to use fully qualified names. Means: namespace + classname.

In your case, you have to prefix your class name with the namespace infopro, which leads to \infopro\User

```<code>$user = new \infopro\User(...);
</code>```

If you don't want to use always the fqn and you are in a diffrent namespace, you could also import the classname into the local scope of the file with use.

```<code>use \infopro\User;

// somewhere later ...
$user = new User(...);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can't instantiate class even included

Body:
I'm very new to PHP, and I can't solve an issue even I read a lot of tutorials and SO posts.
I've a custom class (user), and I'd like to instantiate it in php code, but even I include it, I get this error.

Fatal error: Class 'User' not found in D:\wamp64\www\MyFirstPhp\formPhp.php on line 17

Please help me find out what I do wrong.

Here is my user class:

  <?php
/**
 * Created by IntelliJ IDEA.
 * User: molnard
 * Date: 2017. 06. 06.
 * Time: 15:36
 */

namespace infopro;

class User
{
    private $username;
    private $userage;
    private $sex;

    public function __construct($username, $userage, $sex)
    {
        if (!is_null($username)) $this->username = $username;
        if (!is_null($userage)) $this->userage = $this->userage;
        if (!is_null($sex)) $this->sex = $sex;
    }

    /**
     * @return mixed
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param mixed $username
     */
    public function setUsername($username)
    {
        $this->username = $username;
    }

    /**
     * @return mixed
     */
    public function getUserage()
    {
        return $this->userage;
    }

    /**
     * @param mixed $userage
     */
    public function setUserage($userage)
    {
        $this->userage = $userage;
    }

    /**
     * @return mixed
     */
    public function getSex()
    {
        return $this->sex;
    }

    /**
     * @param mixed $sex
     */
    public function setSex($sex)
    {
        $this->sex = $sex;
    }
}
?>

And here is my form.php class where I'd like to instantiate user class.

    <!Doctype html>

    <meta charset="UTF-8">
    <title>Form php</title>

<?php
include("User.php");

$name = $_POST["name"];
$age = $_POST["age"];
$sex = $_POST["sex"];
echo "New user
name: " . $name . "
" .
    "age: " . $age . "
" . "sex: " . $sex."
";

$newuser = new User($name, $age, $sex);
$newAge = $newuser->getAge();
echo $newAge;
?>

Body:
The exception already told you, whats wrong with your code. There's no such User class. If you use namespaces, and your currently in another namespace (or no namespace), you have to use fully qualified names. Means: namespace + classname.

In your case, you have to prefix your class name with the namespace infopro, which leads to \infopro\User

$user = new \infopro\User(...);

If you don't want to use always the fqn and you are in a diffrent namespace, you could also import the classname into the local scope of the file with use.

use \infopro\User;

// somewhere later ...
$user = new User(...);


问:
simple way to identify the user is having the account in Gmail?
Do any one say which is the simple way to identify the user is having the account in Gmail ?</p>

答:
Use the built-in PHP function stripos which will return False if the email address string does not contain "gmail" (all gmail email accounts, which do not use mail forwarding, contain the "gmail" string).

```<code>if (stripos($user_email_address, "gmail"))
{
    echo "We have a gmail user!";
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Use the built-in PHP function stripos which will return False if the email address string does not contain "gmail" (all gmail email accounts, which do not use mail forwarding, contain the "gmail" string).

if (stripos($user_email_address, "gmail"))
{
    echo "We have a gmail user!";
}


问:
PHPUnit: How to assert that a class extends another class?
In my PHPUnit test, I would like to assert that the class that I am testing extends another class. How can I do this with PHPUnit?</p>

答:
Or also you should use this assert like this:</p>

```<code>    $this->assertSame(
        'Symfony\Component\Form\AbstractType',
        get_parent_class('AppBundle\Form\CarType'),
        'The form does not extend the AbstractType class'
        );
</code>```

Body:
Or also you should use this assert like this:

    $this->assertSame(
        'Symfony\Component\Form\AbstractType',
        get_parent_class('AppBundle\Form\CarType'),
        'The form does not extend the AbstractType class'
        );


问:
Validate multicolumn property Firebase Database Rules
I have a multicolumn index property filter_active in this structure.

```<code>"books": {
   "435085rfddsfiou4r80": {
        "name": "Harry Potter 1"
   }
}

"review": {
   "540398fsdo9043": {
        "filter_active": "true|435085rfddsfiou4r80|false"
        "active": true,
        "archived": false,
        "book_id": "435085rfddsfiou4r80"
        "review": "good book"
   }
}
</code>```

Now I want to use the security rules to validate the filter_active property. I need to check if the book exists in the books node. Also the book id in the filter must be equal to the book_id in the review object.

There is no such thing as a split method in the Firebase Database Rules. In addition, I tried to create a dynamic regex but I believe this is not possible.

Is there anyway I can fix this problem?

答:
If the unwanted text in filter_active is always a small number of known words or characters, they can be eliminated by repeated use of replace().  For example, to eliminate true, false, and |:

```<code>newData.child('filter_active').val().replace('true','')
    .replace('false','').replace('|','')
</code>```

You can then check for the existence of a book with the resulting key:

```<code>root.child('books').child(newData.child('filter_active').val()
        .replace('true','').replace('false','').replace('|','')).exists()
</code>```

Body:
I have a multicolumn index property filter_active in this structure.

"books": {
   "435085rfddsfiou4r80": {
        "name": "Harry Potter 1"
   }
}

"review": {
   "540398fsdo9043": {
        "filter_active": "true|435085rfddsfiou4r80|false"
        "active": true,
        "archived": false,
        "book_id": "435085rfddsfiou4r80"
        "review": "good book"
   }
}

Now I want to use the security rules to validate the filter_active property. I need to check if the book exists in the books node. Also the book id in the filter must be equal to the book_id in the review object.

There is no such thing as a split method in the Firebase Database Rules. In addition, I tried to create a dynamic regex but I believe this is not possible.

Is there anyway I can fix this problem?

Body:
If the unwanted text in filter_active is always a small number of known words or characters, they can be eliminated by repeated use of replace().  For example, to eliminate true, false, and |:

newData.child('filter_active').val().replace('true','')
    .replace('false','').replace('|','')

You can then check for the existence of a book with the resulting key:

root.child('books').child(newData.child('filter_active').val()
        .replace('true','').replace('false','').replace('|','')).exists()


问:
'_comp' cannot be used as a function error
I am getting "'_comp' cannot be used as a function" error in the stl_algobase.h header file. Here is my code and the part of the header file that is supposed to have the error.
code:

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

using namespace std;

void subsqr(int a[10][10]){
    //int s[][10];
    for(int i =1;i<5;i++){
        for(int j = 1;j<5;j++){
            if(a[i][j] == 1){
                a[i][j] = min(a[i][j-1], a[i-1][j],a[i-1][j-1]) + 1;
            }
        }
    }
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
            cout<<a[i][j]<<"\t";
        }
        cout<<endl;
    }
}

int main(){
    int a[10][10] = {{0,1,1,0,1}, {1,1,0,1,0}, {1,1,1,0}, {1,1,1,1,0}, {1,1,1,1,1}, {0,0,0,0,0}};

    subsqr(a);
    return 0;
}
</code>```

stl_algobase.h:

```<code> template<typename _Tp, typename _Compare>
    inline const _Tp&
    min(const _Tp& __a, const _Tp& __b, _Compare __comp)
    {
      //return __comp(__b, __a) ? __b : __a;
      if (__comp(__b, __a))
            return __b;
      return __a;
    }
</code>```

The compiler says that the error is in the line

```<code>if (__comp(__b, __a))
</code>```

答:
It may not be the problem but the header of your min function specifies it needs 3 parameters : 2 of type __Tp and one of type _Compare but in your program, you call it with 3 type __TP :

```<code>a[i][j] = min(a[i][j-1], a[i-1][j],a[i-1][j-1]) + 1; // the third parameter is an int, not a function !
</code>```

EDIT : If you want to find out the min of three numbers, consider this post, with ints and float it is not needed to specify a comp function.
For a quick fix, replace the line I highlighted with this one :

```<code>std::min({a[i][j-1], a[i-1][j], a[i-1][j-1]});
</code>```

Body:
I am getting "'_comp' cannot be used as a function" error in the stl_algobase.h header file. Here is my code and the part of the header file that is supposed to have the error.
code:

#include<iostream>
#include<algorithm>

using namespace std;

void subsqr(int a[10][10]){
    //int s[][10];
    for(int i =1;i<5;i++){
        for(int j = 1;j<5;j++){
            if(a[i][j] == 1){
                a[i][j] = min(a[i][j-1], a[i-1][j],a[i-1][j-1]) + 1;
            }
        }
    }
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
            cout<<a[i][j]<<"\t";
        }
        cout<<endl;
    }
}

int main(){
    int a[10][10] = {{0,1,1,0,1}, {1,1,0,1,0}, {1,1,1,0}, {1,1,1,1,0}, {1,1,1,1,1}, {0,0,0,0,0}};

    subsqr(a);
    return 0;
}

stl_algobase.h:

 template<typename _Tp, typename _Compare>
    inline const _Tp&
    min(const _Tp& __a, const _Tp& __b, _Compare __comp)
    {
      //return __comp(__b, __a) ? __b : __a;
      if (__comp(__b, __a))
            return __b;
      return __a;
    }

The compiler says that the error is in the line

if (__comp(__b, __a))

Body:
It may not be the problem but the header of your min function specifies it needs 3 parameters : 2 of type __Tp and one of type _Compare but in your program, you call it with 3 type __TP :

a[i][j] = min(a[i][j-1], a[i-1][j],a[i-1][j-1]) + 1; // the third parameter is an int, not a function !

EDIT : If you want to find out the min of three numbers, consider this post, with ints and float it is not needed to specify a comp function.
For a quick fix, replace the line I highlighted with this one :

std::min({a[i][j-1], a[i-1][j], a[i-1][j-1]});


问:
Improving the Performance of this Stored Procedure in MySQL
I am attempting to optimize this Stored Procedure. Currently, this iteration when done from the very top of the chain, can take about 2.4-2.7 seconds. I would love to get this down to below 1 second if possible.

I have done research on what I can do to optimize this and most of MySQL's own tips do not work. You cannot LOCK tables or use the LOAD DATA statements inside Stored Procedures. When running tests, it appears that the INSERT INTO SELECT statements are taking the most time inside this query.

When I ran one CALL, I got 2.6 seconds with around 13 INSERT INTO statements firing off. At least 3 took 0.43-0.45 seconds to complete. All other statements took very little time to complete.

Here is my current settings inside my 'my.cnf' file:

```<code>default-storage-engine = MyISAM
key_buffer_size = 256M
innodb_buffer_pool_size = 3G
innodb_buffer_pool_load_at_startup = ON
innodb_sort_buffer_size = 16M
innodb_flush_method = O_DIRECT
read_buffer_size = 4M
thread_stack = 256K
bulk_insert_buffer_size = 64MB
</code>```

Here is my Stored Procedure:

```<code>BEGIN
    DECLARE lastLayer INT;
    DECLARE lastInsertCount INT;
    DECLARE tempTableRowCount INT;
    DROP TABLE IF EXISTS `temp`;
    DROP TABLE IF EXISTS `pendingBusiness`;

    CREATE TABLE `temp`
    (
        `layer` INT(5),
        `title_c` VARCHAR(255),
        `name` VARCHAR(255),
        `rep_first_name` VARCHAR(255),
        `rep_last_name` VARCHAR(255),
        `id_c` CHAR(36),
        `contact_status_reps_c` VARCHAR(255),
        `phone_mobile` VARCHAR(255),
        `contract_type_c` VARCHAR(255),
        `email_address` VARCHAR(255)
    );

    CREATE TABLE `pendingBusiness`
    (
        `layer` INT(5),
        `title_c` VARCHAR(255),
        `name` VARCHAR(255),
        `rep_first_name` VARCHAR(255),
        `rep_last_name` VARCHAR(255),
        `id_c` CHAR(36),
        `contact_status_reps_c` VARCHAR(255),
        `investor_first_name` VARCHAR(255),
        `investor_last_name` VARCHAR(255),
        `product_detail` VARCHAR(255),
        `paperwork_status_c` VARCHAR(255),
        `next_step` VARCHAR(255),
        `outstanding_requirements_c` VARCHAR(255),
        `funding_status_c` VARCHAR(255),
        `funding_next_step_c` VARCHAR(255),
        `fulfillment_status_c` VARCHAR(255),
        `fulfillment_next_step_c` VARCHAR(255),
        `amount` VARCHAR(255),
        `stage` VARCHAR(255),
        `date_entered` DATETIME,
        `case_manager` VARCHAR(255),
        `lost_sale_date_c` DATETIME,
        `compensation_run_c` DATETIME,
        `product_id` CHAR(36),
        `rep_state` VARCHAR(255),
        `investor_state` VARCHAR(255)
    );

    INSERT INTO `temp`(`layer`, `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `phone_mobile`,`contract_type_c`,`email_address`)
    SELECT 0,
    wn_writing_number_cstm.title_c,
    wn_writing_number.`name`,
    preps_contracted_reps.first_name,
    preps_contracted_reps.last_name,
    wn_writing_number_cstm.id_c,
    preps_contracted_reps_cstm.contact_status_reps_c,
    preps_contracted_reps.phone_mobile,
    preps_contracted_reps_cstm.contract_type_c,
    email_addresses.email_address
FROM wn_writing_number LEFT OUTER JOIN wn_writing_number_cac_customize_agent_comp_1_c ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing946b_number_ida = wn_writing_number.id
     LEFT OUTER JOIN cac_customize_agent_comp ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing3148nt_comp_idb = cac_customize_agent_comp.id
     LEFT OUTER JOIN cac_customize_agent_comp_cstm ON cac_customize_agent_comp.id = cac_customize_agent_comp_cstm.id_c
     LEFT OUTER JOIN aos_products_cac_customize_agent_comp_1_c ON cac_customize_agent_comp_cstm.id_c = aos_products_cac_customize_agent_comp_1_c.aos_produca2b8nt_comp_idb
     LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
     LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
     LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
     LEFT OUTER JOIN email_addr_bean_rel ON email_addr_bean_rel.bean_id = preps_contracted_reps_cstm.id_c
     LEFT OUTER JOIN email_addresses ON email_addr_bean_rel.email_address_id = email_addresses.id
     LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
    WHERE wn_writing_number_cstm.wn_writing_number_id_c = passId AND wn_writing_number.deleted = '0' AND preps_contracted_reps.deleted = '0' AND wn_writing_number.deleted = '0' AND email_addr_bean_rel.deleted = '0'
    GROUP BY wn_writing_number.`name`;

    INSERT INTO `pendingBusiness`(`title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `investor_first_name`, `investor_last_name`, `product_detail`, `paperwork_status_c`, `next_step`, `outstanding_requirements_c`, `funding_status_c`, `funding_next_step_c`, `fulfillment_status_c`, `fulfillment_next_step_c`, `amount`, `stage`, `date_entered`, `case_manager`, `lost_sale_date_c`, `compensation_run_c`, `product_id`, `rep_state`, `investor_state`)
    SELECT
    wn_writing_number_cstm.title_c,
    wn_writing_number.`name`,
    preps_contracted_reps.first_name,
    preps_contracted_reps.last_name,
    wn_writing_number_cstm.id_c,
    preps_contracted_reps_cstm.contact_status_reps_c,
    contacts.first_name,
    contacts.last_name,
    aos_products.`name`,
    opportunities_cstm.paperwork_status_c,
    opportunities.next_step,
    opportunities_cstm.outstanding_requirements_c,
    opportunities_cstm.funding_status_c,
    opportunities_cstm.funding_next_step_c,
    opportunities_cstm.fulfillment_status_c,
    opportunities_cstm.fulfillment_next_step_c,
    opportunities.amount,
    opportunities_cstm.stage_c,
    opportunities.date_entered,
    CONCAT(users.first_name, " ", users.last_name) AS case_manager,
    opportunities_cstm.lost_sale_date_c,
    opportunities_cstm.compensation_run_c,
    aos_products.id,
    preps_contracted_reps.primary_address_state,
    opportunities_cstm.state_of_residence_c
FROM wn_writing_number
     LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
     LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
     LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
     LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
     LEFT OUTER JOIN opportunities_cstm ON opportunities_cstm.wn_writing_number_id_c = wn_writing_number.id
     LEFT OUTER JOIN contacts ON opportunities_cstm.contact_id_c = contacts.id
     LEFT OUTER JOIN opportunities ON opportunities_cstm.id_c = opportunities.id
     LEFT OUTER JOIN aos_products ON opportunities_cstm.aos_products_id_c = aos_products.id
     LEFT OUTER JOIN users ON opportunities_cstm.user_id_c = users.id
WHERE wn_writing_number.id = passId AND opportunities.deleted = '0' AND opportunities.date_entered >= DATE_SUB(NOW(),INTERVAL 1.5 YEAR)
GROUP BY opportunities_cstm.id_c;

    SET lastLayer := 0;
    SET lastInsertCount := 1;

    LayerLoop: WHILE lastInsertCount > 0 DO
      INSERT INTO `temp`(`layer`, `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `phone_mobile`,`contract_type_c`,`email_address`)
      SELECT lastLayer + 1,
        wn_writing_number_cstm.title_c,
        wn_writing_number.`name`,
        preps_contracted_reps.first_name,
        preps_contracted_reps.last_name,
        wn_writing_number_cstm.id_c,
        preps_contracted_reps_cstm.contact_status_reps_c,
        preps_contracted_reps.phone_mobile,
        preps_contracted_reps_cstm.contract_type_c,
        email_addresses.email_address
    FROM wn_writing_number LEFT OUTER JOIN wn_writing_number_cac_customize_agent_comp_1_c ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing946b_number_ida = wn_writing_number.id
         LEFT OUTER JOIN cac_customize_agent_comp ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing3148nt_comp_idb = cac_customize_agent_comp.id
         LEFT OUTER JOIN cac_customize_agent_comp_cstm ON cac_customize_agent_comp.id = cac_customize_agent_comp_cstm.id_c
         LEFT OUTER JOIN aos_products_cac_customize_agent_comp_1_c ON cac_customize_agent_comp_cstm.id_c = aos_products_cac_customize_agent_comp_1_c.aos_produca2b8nt_comp_idb
         LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
         LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
         LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
         LEFT OUTER JOIN email_addr_bean_rel ON email_addr_bean_rel.bean_id = preps_contracted_reps_cstm.id_c
         LEFT OUTER JOIN email_addresses ON email_addr_bean_rel.email_address_id = email_addresses.id
         LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
      WHERE wn_writing_number_cstm.wn_writing_number_id_c IN (SELECT id_c FROM `temp` WHERE layer = lastLayer) AND wn_writing_number.deleted = '0' AND preps_contracted_reps.deleted = '0' AND wn_writing_number.deleted = '0' AND email_addr_bean_rel.deleted = '0'
      GROUP BY wn_writing_number.`name`;

      SET lastInsertCount := ROW_COUNT();

      INSERT INTO `pendingBusiness`(`layer`, `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `investor_first_name`, `investor_last_name`, `product_detail`, `paperwork_status_c`, `next_step`, `outstanding_requirements_c`, `funding_status_c`, `funding_next_step_c`, `fulfillment_status_c`, `fulfillment_next_step_c`, `amount`, `stage`, `date_entered`, `case_manager`, `lost_sale_date_c`, `compensation_run_c`, `product_id`, `rep_state`, `investor_state`)
      SELECT lastLayer + 1,
        wn_writing_number_cstm.title_c,
        wn_writing_number.`name`,
        preps_contracted_reps.first_name,
        preps_contracted_reps.last_name,
        wn_writing_number_cstm.id_c,
        preps_contracted_reps_cstm.contact_status_reps_c,
        contacts.first_name,
        contacts.last_name,
        aos_products.`name`,
        opportunities_cstm.paperwork_status_c,
        opportunities.next_step,
        opportunities_cstm.outstanding_requirements_c,
        opportunities_cstm.funding_status_c,
        opportunities_cstm.funding_next_step_c,
        opportunities_cstm.fulfillment_status_c,
        opportunities_cstm.fulfillment_next_step_c,
        opportunities.amount,
        opportunities_cstm.stage_c,
        opportunities.date_entered,
        CONCAT(users.first_name, " ", users.last_name) AS case_manager,
        opportunities_cstm.lost_sale_date_c,
        opportunities_cstm.compensation_run_c,
        aos_products.id,
        preps_contracted_reps.primary_address_state,
        opportunities_cstm.state_of_residence_c
    FROM wn_writing_number
         LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
         LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
         LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
         LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
         LEFT OUTER JOIN opportunities_cstm ON opportunities_cstm.wn_writing_number_id_c = wn_writing_number.id
         LEFT OUTER JOIN contacts ON opportunities_cstm.contact_id_c = contacts.id
         LEFT OUTER JOIN opportunities ON opportunities_cstm.id_c = opportunities.id
         LEFT OUTER JOIN aos_products ON opportunities_cstm.aos_products_id_c = aos_products.id
         LEFT OUTER JOIN users ON opportunities_cstm.user_id_c = users.id
      WHERE opportunities.deleted = '0' AND wn_writing_number_cstm.wn_writing_number_id_c IN (SELECT id_c FROM `temp` WHERE layer = lastLayer) AND opportunities.date_entered >= DATE_SUB(NOW(),INTERVAL 1.5 YEAR)
      GROUP BY opportunities_cstm.id_c;

      SET lastLayer := lastLayer + 1;
    END WHILE LayerLoop;

    SELECT `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `investor_first_name`, `investor_last_name`, `product_detail`, `paperwork_status_c`, `next_step`, `outstanding_requirements_c`, `funding_status_c`, `funding_next_step_c`, `fulfillment_status_c`, `fulfillment_next_step_c`, `amount`, `stage`, `date_entered`, `case_manager`, `lost_sale_date_c`, `compensation_run_c`, `product_id`, `rep_state`, `investor_state`
    FROM `pendingBusiness`
    ORDER BY rep_first_name ASC;

    DROP TABLE IF EXISTS `pendingBusiness`;
END
</code>```

答:
FWIW, your query is functionally identical to the following. However, the following has the advantage of being easier to read. That said, your GROUP BY clause will return (potentially) indeterminate results for all but name.

```<code>SELECT 0
     , k.title_c
     , a.name
     , g.first_name
     , g.last_name
     , k.id_c
     , h.contact_status_reps_c
     , g.phone_mobile
     , h.contract_type_c
     , j.email_address
  FROM wn_writing_number a
  JOIN wn_writing_number_cac_customize_agent_comp_1_c b
    ON b.wn_writing946b_number_ida = a.id
  JOIN cac_customize_agent_comp c
    ON c.id = b.wn_writing3148nt_comp_idb
  LEFT
  JOIN cac_customize_agent_comp_cstm d
    ON d.id_c = c.id
  LEFT
  JOIN aos_products_cac_customize_agent_comp_1_c e
    ON e.aos_produca2b8nt_comp_idb = d.id_c
  LEFT
  JOIN preps_contracted_reps_wn_writing_number_1_c f
    ON f.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = a.id
  JOIN preps_contracted_reps g
    ON g.id = f.preps_cont9effed_reps_ida
  LEFT
  JOIN preps_contracted_reps_cstm h
    ON h.id_c = g.id
  JOIN email_addr_bean_rel i
    ON i.bean_id = h.id_c
  LEFT
  JOIN email_addresses j
    ON j.id = i.email_address_id
  JOIN wn_writing_number_cstm k
    ON k.id_c = a.id
 WHERE k.wn_writing_number_id_c = passId
   AND a.deleted = 0
   AND g.deleted = 0
   AND i.deleted = 0
 GROUP
    BY a.name;
</code>```

Body:
I am attempting to optimize this Stored Procedure. Currently, this iteration when done from the very top of the chain, can take about 2.4-2.7 seconds. I would love to get this down to below 1 second if possible.

I have done research on what I can do to optimize this and most of MySQL's own tips do not work. You cannot LOCK tables or use the LOAD DATA statements inside Stored Procedures. When running tests, it appears that the INSERT INTO SELECT statements are taking the most time inside this query.

When I ran one CALL, I got 2.6 seconds with around 13 INSERT INTO statements firing off. At least 3 took 0.43-0.45 seconds to complete. All other statements took very little time to complete.

Here is my current settings inside my 'my.cnf' file:

default-storage-engine = MyISAM
key_buffer_size = 256M
innodb_buffer_pool_size = 3G
innodb_buffer_pool_load_at_startup = ON
innodb_sort_buffer_size = 16M
innodb_flush_method = O_DIRECT
read_buffer_size = 4M
thread_stack = 256K
bulk_insert_buffer_size = 64MB

Here is my Stored Procedure:

BEGIN
    DECLARE lastLayer INT;
    DECLARE lastInsertCount INT;
    DECLARE tempTableRowCount INT;
    DROP TABLE IF EXISTS `temp`;
    DROP TABLE IF EXISTS `pendingBusiness`;

    CREATE TABLE `temp`
    (
        `layer` INT(5),
        `title_c` VARCHAR(255),
        `name` VARCHAR(255),
        `rep_first_name` VARCHAR(255),
        `rep_last_name` VARCHAR(255),
        `id_c` CHAR(36),
        `contact_status_reps_c` VARCHAR(255),
        `phone_mobile` VARCHAR(255),
        `contract_type_c` VARCHAR(255),
        `email_address` VARCHAR(255)
    );

    CREATE TABLE `pendingBusiness`
    (
        `layer` INT(5),
        `title_c` VARCHAR(255),
        `name` VARCHAR(255),
        `rep_first_name` VARCHAR(255),
        `rep_last_name` VARCHAR(255),
        `id_c` CHAR(36),
        `contact_status_reps_c` VARCHAR(255),
        `investor_first_name` VARCHAR(255),
        `investor_last_name` VARCHAR(255),
        `product_detail` VARCHAR(255),
        `paperwork_status_c` VARCHAR(255),
        `next_step` VARCHAR(255),
        `outstanding_requirements_c` VARCHAR(255),
        `funding_status_c` VARCHAR(255),
        `funding_next_step_c` VARCHAR(255),
        `fulfillment_status_c` VARCHAR(255),
        `fulfillment_next_step_c` VARCHAR(255),
        `amount` VARCHAR(255),
        `stage` VARCHAR(255),
        `date_entered` DATETIME,
        `case_manager` VARCHAR(255),
        `lost_sale_date_c` DATETIME,
        `compensation_run_c` DATETIME,
        `product_id` CHAR(36),
        `rep_state` VARCHAR(255),
        `investor_state` VARCHAR(255)
    );

    INSERT INTO `temp`(`layer`, `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `phone_mobile`,`contract_type_c`,`email_address`)
    SELECT 0,
    wn_writing_number_cstm.title_c,
    wn_writing_number.`name`,
    preps_contracted_reps.first_name,
    preps_contracted_reps.last_name,
    wn_writing_number_cstm.id_c,
    preps_contracted_reps_cstm.contact_status_reps_c,
    preps_contracted_reps.phone_mobile,
    preps_contracted_reps_cstm.contract_type_c,
    email_addresses.email_address
FROM wn_writing_number LEFT OUTER JOIN wn_writing_number_cac_customize_agent_comp_1_c ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing946b_number_ida = wn_writing_number.id
     LEFT OUTER JOIN cac_customize_agent_comp ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing3148nt_comp_idb = cac_customize_agent_comp.id
     LEFT OUTER JOIN cac_customize_agent_comp_cstm ON cac_customize_agent_comp.id = cac_customize_agent_comp_cstm.id_c
     LEFT OUTER JOIN aos_products_cac_customize_agent_comp_1_c ON cac_customize_agent_comp_cstm.id_c = aos_products_cac_customize_agent_comp_1_c.aos_produca2b8nt_comp_idb
     LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
     LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
     LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
     LEFT OUTER JOIN email_addr_bean_rel ON email_addr_bean_rel.bean_id = preps_contracted_reps_cstm.id_c
     LEFT OUTER JOIN email_addresses ON email_addr_bean_rel.email_address_id = email_addresses.id
     LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
    WHERE wn_writing_number_cstm.wn_writing_number_id_c = passId AND wn_writing_number.deleted = '0' AND preps_contracted_reps.deleted = '0' AND wn_writing_number.deleted = '0' AND email_addr_bean_rel.deleted = '0'
    GROUP BY wn_writing_number.`name`;

    INSERT INTO `pendingBusiness`(`title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `investor_first_name`, `investor_last_name`, `product_detail`, `paperwork_status_c`, `next_step`, `outstanding_requirements_c`, `funding_status_c`, `funding_next_step_c`, `fulfillment_status_c`, `fulfillment_next_step_c`, `amount`, `stage`, `date_entered`, `case_manager`, `lost_sale_date_c`, `compensation_run_c`, `product_id`, `rep_state`, `investor_state`)
    SELECT
    wn_writing_number_cstm.title_c,
    wn_writing_number.`name`,
    preps_contracted_reps.first_name,
    preps_contracted_reps.last_name,
    wn_writing_number_cstm.id_c,
    preps_contracted_reps_cstm.contact_status_reps_c,
    contacts.first_name,
    contacts.last_name,
    aos_products.`name`,
    opportunities_cstm.paperwork_status_c,
    opportunities.next_step,
    opportunities_cstm.outstanding_requirements_c,
    opportunities_cstm.funding_status_c,
    opportunities_cstm.funding_next_step_c,
    opportunities_cstm.fulfillment_status_c,
    opportunities_cstm.fulfillment_next_step_c,
    opportunities.amount,
    opportunities_cstm.stage_c,
    opportunities.date_entered,
    CONCAT(users.first_name, " ", users.last_name) AS case_manager,
    opportunities_cstm.lost_sale_date_c,
    opportunities_cstm.compensation_run_c,
    aos_products.id,
    preps_contracted_reps.primary_address_state,
    opportunities_cstm.state_of_residence_c
FROM wn_writing_number
     LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
     LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
     LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
     LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
     LEFT OUTER JOIN opportunities_cstm ON opportunities_cstm.wn_writing_number_id_c = wn_writing_number.id
     LEFT OUTER JOIN contacts ON opportunities_cstm.contact_id_c = contacts.id
     LEFT OUTER JOIN opportunities ON opportunities_cstm.id_c = opportunities.id
     LEFT OUTER JOIN aos_products ON opportunities_cstm.aos_products_id_c = aos_products.id
     LEFT OUTER JOIN users ON opportunities_cstm.user_id_c = users.id
WHERE wn_writing_number.id = passId AND opportunities.deleted = '0' AND opportunities.date_entered >= DATE_SUB(NOW(),INTERVAL 1.5 YEAR)
GROUP BY opportunities_cstm.id_c;

    SET lastLayer := 0;
    SET lastInsertCount := 1;

    LayerLoop: WHILE lastInsertCount > 0 DO
      INSERT INTO `temp`(`layer`, `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `phone_mobile`,`contract_type_c`,`email_address`)
      SELECT lastLayer + 1,
        wn_writing_number_cstm.title_c,
        wn_writing_number.`name`,
        preps_contracted_reps.first_name,
        preps_contracted_reps.last_name,
        wn_writing_number_cstm.id_c,
        preps_contracted_reps_cstm.contact_status_reps_c,
        preps_contracted_reps.phone_mobile,
        preps_contracted_reps_cstm.contract_type_c,
        email_addresses.email_address
    FROM wn_writing_number LEFT OUTER JOIN wn_writing_number_cac_customize_agent_comp_1_c ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing946b_number_ida = wn_writing_number.id
         LEFT OUTER JOIN cac_customize_agent_comp ON wn_writing_number_cac_customize_agent_comp_1_c.wn_writing3148nt_comp_idb = cac_customize_agent_comp.id
         LEFT OUTER JOIN cac_customize_agent_comp_cstm ON cac_customize_agent_comp.id = cac_customize_agent_comp_cstm.id_c
         LEFT OUTER JOIN aos_products_cac_customize_agent_comp_1_c ON cac_customize_agent_comp_cstm.id_c = aos_products_cac_customize_agent_comp_1_c.aos_produca2b8nt_comp_idb
         LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
         LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
         LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
         LEFT OUTER JOIN email_addr_bean_rel ON email_addr_bean_rel.bean_id = preps_contracted_reps_cstm.id_c
         LEFT OUTER JOIN email_addresses ON email_addr_bean_rel.email_address_id = email_addresses.id
         LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
      WHERE wn_writing_number_cstm.wn_writing_number_id_c IN (SELECT id_c FROM `temp` WHERE layer = lastLayer) AND wn_writing_number.deleted = '0' AND preps_contracted_reps.deleted = '0' AND wn_writing_number.deleted = '0' AND email_addr_bean_rel.deleted = '0'
      GROUP BY wn_writing_number.`name`;

      SET lastInsertCount := ROW_COUNT();

      INSERT INTO `pendingBusiness`(`layer`, `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `investor_first_name`, `investor_last_name`, `product_detail`, `paperwork_status_c`, `next_step`, `outstanding_requirements_c`, `funding_status_c`, `funding_next_step_c`, `fulfillment_status_c`, `fulfillment_next_step_c`, `amount`, `stage`, `date_entered`, `case_manager`, `lost_sale_date_c`, `compensation_run_c`, `product_id`, `rep_state`, `investor_state`)
      SELECT lastLayer + 1,
        wn_writing_number_cstm.title_c,
        wn_writing_number.`name`,
        preps_contracted_reps.first_name,
        preps_contracted_reps.last_name,
        wn_writing_number_cstm.id_c,
        preps_contracted_reps_cstm.contact_status_reps_c,
        contacts.first_name,
        contacts.last_name,
        aos_products.`name`,
        opportunities_cstm.paperwork_status_c,
        opportunities.next_step,
        opportunities_cstm.outstanding_requirements_c,
        opportunities_cstm.funding_status_c,
        opportunities_cstm.funding_next_step_c,
        opportunities_cstm.fulfillment_status_c,
        opportunities_cstm.fulfillment_next_step_c,
        opportunities.amount,
        opportunities_cstm.stage_c,
        opportunities.date_entered,
        CONCAT(users.first_name, " ", users.last_name) AS case_manager,
        opportunities_cstm.lost_sale_date_c,
        opportunities_cstm.compensation_run_c,
        aos_products.id,
        preps_contracted_reps.primary_address_state,
        opportunities_cstm.state_of_residence_c
    FROM wn_writing_number
         LEFT OUTER JOIN preps_contracted_reps_wn_writing_number_1_c ON preps_contracted_reps_wn_writing_number_1_c.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = wn_writing_number.id
         LEFT OUTER JOIN preps_contracted_reps ON preps_contracted_reps_wn_writing_number_1_c.preps_cont9effed_reps_ida = preps_contracted_reps.id
         LEFT OUTER JOIN preps_contracted_reps_cstm ON preps_contracted_reps.id = preps_contracted_reps_cstm.id_c
         LEFT OUTER JOIN wn_writing_number_cstm ON wn_writing_number_cstm.id_c = wn_writing_number.id
         LEFT OUTER JOIN opportunities_cstm ON opportunities_cstm.wn_writing_number_id_c = wn_writing_number.id
         LEFT OUTER JOIN contacts ON opportunities_cstm.contact_id_c = contacts.id
         LEFT OUTER JOIN opportunities ON opportunities_cstm.id_c = opportunities.id
         LEFT OUTER JOIN aos_products ON opportunities_cstm.aos_products_id_c = aos_products.id
         LEFT OUTER JOIN users ON opportunities_cstm.user_id_c = users.id
      WHERE opportunities.deleted = '0' AND wn_writing_number_cstm.wn_writing_number_id_c IN (SELECT id_c FROM `temp` WHERE layer = lastLayer) AND opportunities.date_entered >= DATE_SUB(NOW(),INTERVAL 1.5 YEAR)
      GROUP BY opportunities_cstm.id_c;

      SET lastLayer := lastLayer + 1;
    END WHILE LayerLoop;

    SELECT `title_c`, `name`, `rep_first_name`, `rep_last_name`, `id_c`, `contact_status_reps_c`, `investor_first_name`, `investor_last_name`, `product_detail`, `paperwork_status_c`, `next_step`, `outstanding_requirements_c`, `funding_status_c`, `funding_next_step_c`, `fulfillment_status_c`, `fulfillment_next_step_c`, `amount`, `stage`, `date_entered`, `case_manager`, `lost_sale_date_c`, `compensation_run_c`, `product_id`, `rep_state`, `investor_state`
    FROM `pendingBusiness`
    ORDER BY rep_first_name ASC;

    DROP TABLE IF EXISTS `pendingBusiness`;
END

Body:
FWIW, your query is functionally identical to the following. However, the following has the advantage of being easier to read. That said, your GROUP BY clause will return (potentially) indeterminate results for all but name.

SELECT 0
     , k.title_c
     , a.name
     , g.first_name
     , g.last_name
     , k.id_c
     , h.contact_status_reps_c
     , g.phone_mobile
     , h.contract_type_c
     , j.email_address
  FROM wn_writing_number a
  JOIN wn_writing_number_cac_customize_agent_comp_1_c b
    ON b.wn_writing946b_number_ida = a.id
  JOIN cac_customize_agent_comp c
    ON c.id = b.wn_writing3148nt_comp_idb
  LEFT
  JOIN cac_customize_agent_comp_cstm d
    ON d.id_c = c.id
  LEFT
  JOIN aos_products_cac_customize_agent_comp_1_c e
    ON e.aos_produca2b8nt_comp_idb = d.id_c
  LEFT
  JOIN preps_contracted_reps_wn_writing_number_1_c f
    ON f.preps_contracted_reps_wn_writing_number_1wn_writing_number_idb = a.id
  JOIN preps_contracted_reps g
    ON g.id = f.preps_cont9effed_reps_ida
  LEFT
  JOIN preps_contracted_reps_cstm h
    ON h.id_c = g.id
  JOIN email_addr_bean_rel i
    ON i.bean_id = h.id_c
  LEFT
  JOIN email_addresses j
    ON j.id = i.email_address_id
  JOIN wn_writing_number_cstm k
    ON k.id_c = a.id
 WHERE k.wn_writing_number_id_c = passId
   AND a.deleted = 0
   AND g.deleted = 0
   AND i.deleted = 0
 GROUP
    BY a.name;


问:
Understanding migrations in Realm - Swift
I'm trying to understand migrations, can someone describe situations where migrations are required?

For instance let's pretend for a moment that an app has been released and the following Realm objects were used but now version 2 needs to be released and a new Realm object was added to this new version, do I need a migration?

Version 1

```<code>import Foundation
import RealmSwift

class Item:Object{
    dynamic var productName:String = ""
    dynamic var createdAt = NSDate()
}

import Foundation
import RealmSwift

class ItemList: Object {
    dynamic var listName = ""
    dynamic var createdAt = NSDate()
    let items = List<Item>()
}
</code>```

Version 2

Version 2 needs a new object.

```<code>import Foundation
import RealmSwift

class Item:Object{
    dynamic var productName:String = ""
    dynamic var createdAt = NSDate()
}

import Foundation
import RealmSwift

class ItemList: Object {
    dynamic var listName = ""
    dynamic var createdAt = NSDate()
    let items = List<Item>()
}

// New object for version 2
import Foundation
import RealmSwift

class NewObjec:Object{
    dynamic var someString:String = ""
    dynamic var createdAt = NSDate()
}
</code>```

Do I need to create a migration if existing objects didn't change but an extra object was added?

In general, can someone describe the situations where migrations are needed?

Thanks a lot

答:
No, you should update the schema version because the Realm schema has been updated, but you don't have to add a migration block.
You could consider Realm as a real database, so in this case it's like your adding a new "column".

In this realm doc section you can find the following block:

```<code>// Set the block which will be called automatically when opening a Realm with
// a schema version lower than the one set above
migrationBlock: { migration, oldSchemaVersion in
  // We haven’t migrated anything yet, so oldSchemaVersion == 0
  if (oldSchemaVersion < 1) {
    // Nothing to do!
    // Realm will automatically detect new properties and removed properties
    // And will update the schema on disk automatically
  }
})
</code>```

You can omit the migration block, updating the Realm version if you're just adding/removing properties:

```<code>Realm.Configuration(schemaVersion: 2)
</code>```

As you can see, they say you have to update schema version, then it will automatically update the realm schema adding new (or removed) properties.

In case you're gonna make "special" changes, you have to fill the migration block with you're logic.
Take a look at this:

Version 1:

```<code>class Person: Object {
    dynamic var firstName = ""
    dynamic var lastName = ""
    dynamic var age = 0
}
</code>```

Version 2:

```<code>class Person: Object {
    dynamic var fullName = ""
    dynamic var age = 0
}
</code>```

In this case, you're not just adding fullName and removing firstName, lastName, but you're combining them, so it is necessary a custom logic.

```<code>migrationBlock: { migration, oldSchemaVersion in
  if (oldSchemaVersion < 1) {
    // The enumerateObjects(ofType:_:) method iterates
    // over every Person object stored in the Realm file
    migration.enumerateObjects(ofType: Person.className()) { oldObject, newObject in
      // combine name fields into a single field
      let firstName = oldObject!["firstName"] as! String
      let lastName = oldObject!["lastName"] as! String
      newObject!["fullName"] = "\(firstName) \(lastName)"
    }
  }
})
</code>```

In conclusion, you need to update schema version every time you update your Models, but you don't need to write a migration block if you're just adding/removing properties.

Edit: Thanks to Dávid Pásztor for suggestions

Body:
I'm trying to understand migrations, can someone describe situations where migrations are required?

For instance let's pretend for a moment that an app has been released and the following Realm objects were used but now version 2 needs to be released and a new Realm object was added to this new version, do I need a migration?

Version 1

import Foundation
import RealmSwift

class Item:Object{
    dynamic var productName:String = ""
    dynamic var createdAt = NSDate()
}

import Foundation
import RealmSwift

class ItemList: Object {
    dynamic var listName = ""
    dynamic var createdAt = NSDate()
    let items = List<Item>()
}

Version 2

Version 2 needs a new object.

import Foundation
import RealmSwift

class Item:Object{
    dynamic var productName:String = ""
    dynamic var createdAt = NSDate()
}

import Foundation
import RealmSwift

class ItemList: Object {
    dynamic var listName = ""
    dynamic var createdAt = NSDate()
    let items = List<Item>()
}

// New object for version 2
import Foundation
import RealmSwift

class NewObjec:Object{
    dynamic var someString:String = ""
    dynamic var createdAt = NSDate()
}

Do I need to create a migration if existing objects didn't change but an extra object was added?

In general, can someone describe the situations where migrations are needed?

Thanks a lot

Body:
No, you should update the schema version because the Realm schema has been updated, but you don't have to add a migration block.
You could consider Realm as a real database, so in this case it's like your adding a new "column".

In this realm doc section you can find the following block:

// Set the block which will be called automatically when opening a Realm with
// a schema version lower than the one set above
migrationBlock: { migration, oldSchemaVersion in
  // We haven’t migrated anything yet, so oldSchemaVersion == 0
  if (oldSchemaVersion < 1) {
    // Nothing to do!
    // Realm will automatically detect new properties and removed properties
    // And will update the schema on disk automatically
  }
})

You can omit the migration block, updating the Realm version if you're just adding/removing properties:

Realm.Configuration(schemaVersion: 2)

As you can see, they say you have to update schema version, then it will automatically update the realm schema adding new (or removed) properties.

In case you're gonna make "special" changes, you have to fill the migration block with you're logic.
Take a look at this:

Version 1:

class Person: Object {
    dynamic var firstName = ""
    dynamic var lastName = ""
    dynamic var age = 0
}

Version 2:

class Person: Object {
    dynamic var fullName = ""
    dynamic var age = 0
}

In this case, you're not just adding fullName and removing firstName, lastName, but you're combining them, so it is necessary a custom logic.

migrationBlock: { migration, oldSchemaVersion in
  if (oldSchemaVersion < 1) {
    // The enumerateObjects(ofType:_:) method iterates
    // over every Person object stored in the Realm file
    migration.enumerateObjects(ofType: Person.className()) { oldObject, newObject in
      // combine name fields into a single field
      let firstName = oldObject!["firstName"] as! String
      let lastName = oldObject!["lastName"] as! String
      newObject!["fullName"] = "\(firstName) \(lastName)"
    }
  }
})

In conclusion, you need to update schema version every time you update your Models, but you don't need to write a migration block if you're just adding/removing properties.

Edit: Thanks to Dávid Pásztor for suggestions


问:
Microsoft Graph and PHP - get data
I simply want to download the data from the Microsoft graph API.

However, all it tells me at Microsoft's graph documentation is to go the the url (i.e. get https://graph.microsoft.com/v1.0/users).  However, this requires an authorization token.  I have tried doing it using ajax, but it doesn't seem to work.  I find the documentation awful and total lacking in information.

```<code>var url = 'https://graph.microsoft.com/v1.0/users';
var token = '';
$.ajax({
    method: 'GET',
    url: url,
    dataType: 'json',
    headers: {"Authorization": "Bearer " + token}
})
.done(function( data ) {
    if (data.ok) {
        if (data.count > 0) {
            console.log(data);
        }
    } else {
        alert(data.error);
    }
})
.fail(function() {
    console.log('fail');
});
</code>```

How could I go about doing this?

答:
Microsoft Graph uses Oauth 2.0, which is a complex authentication completed by the target user of your application, where you send them to Microsoft with a series of parameters including your own (not the target user's) application key, and they sign in and then Microsoft sends them back with the "access_token" value you need to put in the Authorization: Bearer header for all subsequent requests.

They have a run down on this process, including registering for the application key, here: https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_user

They also have example code here: https://developer.microsoft.com/en-us/graph/quick-start (there is a node.js version, but I am not sure if you can accomplish this authorization piece in simple frontend javascript)

And this is the single most useful way to figure out how API Requests in Graph actually work (but it won't help you with the Oauth stuff): https://developer.microsoft.com/en-us/graph/graph-explorer

Title: Microsoft Graph and PHP - get data

Body:
I simply want to download the data from the Microsoft graph API.

However, all it tells me at Microsoft's graph documentation is to go the the url (i.e. get https://graph.microsoft.com/v1.0/users).  However, this requires an authorization token.  I have tried doing it using ajax, but it doesn't seem to work.  I find the documentation awful and total lacking in information.

var url = 'https://graph.microsoft.com/v1.0/users';
var token = '';
$.ajax({
    method: 'GET',
    url: url,
    dataType: 'json',
    headers: {"Authorization": "Bearer " + token}
})
.done(function( data ) {
    if (data.ok) {
        if (data.count > 0) {
            console.log(data);
        }
    } else {
        alert(data.error);
    }
})
.fail(function() {
    console.log('fail');
});

How could I go about doing this?


问:
C++ Qt editor question
I have the case when I have to manually close the persistent editor for the QTableWidget.

By default, closing the editor this doesn't result in saving the changes to the QTableWidgetItem (it simply discards them).

I wish to save these changes along with the closePersistentEditor call - how should it be done?

I tried emitting cellChanged before the closePersistentEditor call - it didn't help

答:
Looks like you can write something like this</p>

```<code>void MyTableWidget::commitAndClosePersistentEditor(const QTableWidgetItem* item)
{
    if (!item)
        return;

    QModelIndex index = indexFromItem(item);
    QWidget* editor = indexWidget(index);
    commitData(editor);
    closePresistentEditor(item);
}
</code>```

Title: C++ Qt editor question

Body:
Looks like you can write something like this

void MyTableWidget::commitAndClosePersistentEditor(const QTableWidgetItem* item)
{
    if (!item)
        return;

    QModelIndex index = indexFromItem(item);
    QWidget* editor = indexWidget(index);
    commitData(editor);
    closePresistentEditor(item);
}


问:
Print numbers in specific range without using any loop or conditions (Java)
Maybe first idea come to mind to solve this kind of problems is recursive function but also it will be a challenge to write recursive function without any condition.

I tried this approach to print numbers from 10 to 60:

```<code>public static void printNumbers(int n){
       int divisonByZero = 1 / (61 - n);
       System.out.println(n);
       printNumbers(n+1);
}
public static void main(String[] args) {
       printNumbers(10);
}
</code>```

But it will crash when it reach number 61 without exception handling

also even with try catch the Arithmetic Exception it's still not a preferable solution because it's handling an exception (runtime error).

I think main problem when using recursive functions is the stop condition.

As well I read that there is a way in C++ by creating a class with a static variable counter and initialize it then increment the counter variable and print it in the constructor after that instantiating number of objects of class counter will print these numbers.

Any suggested solutions to solve this challenge would be appreciated.

答:
You can do something like this: (Idea taken from this answer)</p>

```<code>public class Application {

    public static void main(String[] args) {
        Print40Numbers();
        Print10Numbers();

    }

    private static int currentNumber = 10;

    private static void Print1Number() { System.out.println(currentNumber++); }
    private static void Print2Numbers() { Print1Number(); Print1Number(); }
    private static void Print5Numbers() { Print2Numbers(); Print2Numbers(); Print1Number(); }
    private static void Print10Numbers() { Print5Numbers();Print5Numbers();}
    private static void Print20Numbers() { Print10Numbers();Print10Numbers();}
    private static void Print40Numbers() { Print20Numbers();Print20Numbers();}

}
</code>```

Body:
Maybe first idea come to mind to solve this kind of problems is recursive function but also it will be a challenge to write recursive function without any condition.

I tried this approach to print numbers from 10 to 60:

public static void printNumbers(int n){
       int divisonByZero = 1 / (61 - n);
       System.out.println(n);
       printNumbers(n+1);
}
public static void main(String[] args) {
       printNumbers(10);
}

But it will crash when it reach number 61 without exception handling

also even with try catch the Arithmetic Exception it's still not a preferable solution because it's handling an exception (runtime error).

I think main problem when using recursive functions is the stop condition.

As well I read that there is a way in C++ by creating a class with a static variable counter and initialize it then increment the counter variable and print it in the constructor after that instantiating number of objects of class counter will print these numbers.

Any suggested solutions to solve this challenge would be appreciated.

Body:
You can do something like this: (Idea taken from this answer)

public class Application {

    public static void main(String[] args) {
        Print40Numbers();
        Print10Numbers();

    }

    private static int currentNumber = 10;

    private static void Print1Number() { System.out.println(currentNumber++); }
    private static void Print2Numbers() { Print1Number(); Print1Number(); }
    private static void Print5Numbers() { Print2Numbers(); Print2Numbers(); Print1Number(); }
    private static void Print10Numbers() { Print5Numbers();Print5Numbers();}
    private static void Print20Numbers() { Print10Numbers();Print10Numbers();}
    private static void Print40Numbers() { Print20Numbers();Print20Numbers();}

}


问:
I m new to Matlab and currently working of weapon detection in images but i m getting false positives here.What should i do?
How can i caluclate the F1 score using matlab .This code is giving positive  results in negative samples also .I think thats because of dynamic background of images in datset. Should i change the dataset for better accuracy or change the approach .Please Help

Thanks

DataSet : http://kt.agh.edu.pl/~matiolanski/KnivesImagesDatabase/KnivesImagesDatabase.rar

CODE:`

```<code>TrainingSet = imageSet('Trainingset','recursive');

testSet= imageSet('TestSet','recursive');

img=read(TrainingSet(1),1);
[hog_4x4, vis4x4] = extractHOGFeatures(img,'CellSize',[4 4]);
cellSize = [4 4];
hogFeatureSize = length(hog_4x4);

trainingFeatures= [];
trainingLabels   = [];

x=  TrainingSet(1).Count;
y=  TrainingSet(2).Count;
for digit = 1:numel(TrainingSet)-1

    numImages = TrainingSet(digit).Count;
    for i = 1:numImages-1

    img = rgb2gray(read(TrainingSet(digit), i));

    %Apply pre-processing steps

    features(i,:) = extractHOGFeatures(img, 'CellSize', cellSize);

end

%labels = repmat(TrainingSet(digit).Description, numImages, 1);

trainingFeatures = [trainingFeatures; features];
%trainingLabels = [trainingLabels;   labels  ];

end
negativeSize = size(trainingFeatures,1);
trainingLabels = zeros(size(trainingFeatures,1),1);

for digit = 2:2

    numImages= TrainingSet(digit).Count;
    for i = 1:numImages-1

        img = rgb2gray(read(TrainingSet(digit), (i)));

        features1(i,:) = extractHOGFeatures(img, 'CellSize', cellSize);

    end

    %labels = repmat(TrainingSet(digit).Description, numImages, 1);

    trainingFeatures = [trainingFeatures; features1];
    %trainingLabels  = [trainingLabels;   labels  ];

end

 positiveLabels = ones(size(trainingFeatures,1) - negativeSize,1);
trainingLabels = [trainingLabels ; positiveLabels];

classifier = fitcsvm(trainingFeatures, trainingLabels);
classOrder =classifier.ClassNames;

img=read(testSet(1),1);

img = rgb2gray(img);
[testFeatures, testLabels] = extractHOGFeatures(img, 'CellSize', cellSize);

%Make class predictions using the test features.
predictedLabels = predict(classifier, testFeatures);
if(predictedLabels==1)

    warndlg('Object Detected','!! Warning !!');

else

     warndlg('Object Not Detected','!! Warning !!');

end
</code>```

答: I strongly recommend using Faster-rcnn for the problem. It is one of the state-of-the art Convolutional Neural Network architectures used extensively for object detection task. Here is a matlab implementation of the same.    </p>

Body:
How can i caluclate the F1 score using matlab .This code is giving positive  results in negative samples also .I think thats because of dynamic background of images in datset. Should i change the dataset for better accuracy or change the approach .Please Help

Thanks

DataSet : http://kt.agh.edu.pl/~matiolanski/KnivesImagesDatabase/KnivesImagesDatabase.rar

CODE:`

TrainingSet = imageSet('Trainingset','recursive');

testSet= imageSet('TestSet','recursive');

img=read(TrainingSet(1),1);
[hog_4x4, vis4x4] = extractHOGFeatures(img,'CellSize',[4 4]);
cellSize = [4 4];
hogFeatureSize = length(hog_4x4);

trainingFeatures= [];
trainingLabels   = [];

x=  TrainingSet(1).Count;
y=  TrainingSet(2).Count;
for digit = 1:numel(TrainingSet)-1

    numImages = TrainingSet(digit).Count;
    for i = 1:numImages-1

    img = rgb2gray(read(TrainingSet(digit), i));

    %Apply pre-processing steps

    features(i,:) = extractHOGFeatures(img, 'CellSize', cellSize);

end

%labels = repmat(TrainingSet(digit).Description, numImages, 1);

trainingFeatures = [trainingFeatures; features];
%trainingLabels = [trainingLabels;   labels  ];

end
negativeSize = size(trainingFeatures,1);
trainingLabels = zeros(size(trainingFeatures,1),1);

for digit = 2:2

    numImages= TrainingSet(digit).Count;
    for i = 1:numImages-1

        img = rgb2gray(read(TrainingSet(digit), (i)));

        features1(i,:) = extractHOGFeatures(img, 'CellSize', cellSize);

    end

    %labels = repmat(TrainingSet(digit).Description, numImages, 1);

    trainingFeatures = [trainingFeatures; features1];
    %trainingLabels  = [trainingLabels;   labels  ];

end

 positiveLabels = ones(size(trainingFeatures,1) - negativeSize,1);
trainingLabels = [trainingLabels ; positiveLabels];

classifier = fitcsvm(trainingFeatures, trainingLabels);
classOrder =classifier.ClassNames;

img=read(testSet(1),1);

img = rgb2gray(img);
[testFeatures, testLabels] = extractHOGFeatures(img, 'CellSize', cellSize);

%Make class predictions using the test features.
predictedLabels = predict(classifier, testFeatures);
if(predictedLabels==1)

    warndlg('Object Detected','!! Warning !!');

else

     warndlg('Object Not Detected','!! Warning !!');

end


问:
How does does WebSphere cluster handle requests from same session when target server instance is unresponsive?
It is my understanding that WebSphere clusters can be configured such that requests from the same session always go to the same instance in the cluster.

I see the following article:

https://www.ibm.com/support/knowledgecenter/SSAW57_7.0.0/com.ibm.websphere.nd.doc/info/ae/ae/cprs_plan_cluster.html

If this is true, what happens if the instance goes down while the session is still active.  Is the user logged out and asked to start the session again or the session is transferred to another instance?

答:
Clusters can be configured to replicate (share) their session data.

Frontend HTTP proxies (like IHS + the WAS plugin, or any manually confiured HTTP proxy) can be taught how to maintain affinity with a backend server.  In the event the frontend server cannot maintain affinity, it will use its own logic to try another server in the cluster.

Whether or not that other server can continue with the session, and how up to date it is, is part of the configuration of the HTTP session component in WAS.


问:
Python Selenium verify record is deleted
I have this code in python and selenium to find the deleted records and verify that the record is deleted.

```<code>def find_deleted_device(self, mac, serialno):
    index = 0
    loopNext = True
    matched = False
    while loopNext:
        index = 0
        if not element_locator.find_elements_by_css(driver_obj, self.no_device):
            record = element_locator.find_elements_by_css(driver_obj, self.devices_record)
            macaarray = element_locator.find_elements_by_css(driver_obj, self.device_record_mac_address)
            serialnum = element_locator.find_elements_by_css(driver_obj, self.device_record_serial_number)

            for facility_mac, serialnumber in zip(macaarray, serialnum):
                if facility_mac.text == mac and serialnumber.text == serialno:
                    loopNext = False
                    matched = True
                    break
                elif index == len(record) - 1:
                    if index >= 19:
                        next_page = element_locator.find_element_by_css(driver_obj, self.nextpageselector)
                        if next_page.is_enabled():
                            next_page.click()
                        else:
                            loopNext = False
                    index = index + 1
                else:
                    loopNext = False
        else:
            print('No matching macaddress and serial number, No device message appears')
            assert True
            loopNext = False

    if matched:
        print "The mac and serial number matched, should have been deleted"
        assert False
    else:
        print('No matching macaddress and serial number found')
        assert True
sleep(2)
</code>```

But the problem is there are two scenarios:
1) If only one record exists and we delete that then I get a message "No Records exist"
2) second scenario is a few records exists and I can loop through and verify that the record is deleted.

In case of scenario 1, it works fine.
In case of scenario 2 , it passes but with an error something like  "1496424768.39". How do I escape this error.

答:
I fixed my issue using the following alternative approach.

```<code>#This method is used to search deleted group
    def find_deleted_device_with_paging(self, mac, serialno):

        page_num = element_locator.find_element_by_css(driver_obj, ".test-grid-pagination-summary")
        if page_num.text < 1:
            print('No matching macaddress and serial number found')
            assert True

        else:
            index = 0
            loopNext = True
            matched = False
            print "The mac and serial number matched, should have been deleted"
            while loopNext:
                index = 0
                record = element_locator.find_elements_by_css(driver_obj, self.devices_record)
                macaarray = element_locator.find_elements_by_css(driver_obj, self.device_record_mac_address)
                serialnum = element_locator.find_elements_by_css(driver_obj, self.device_record_serial_number)

                for facility_mac, serialnumber in zip(macaarray, serialnum):
                    if facility_mac.text == mac and serialnumber.text == serialno:
                        loopNext = False
                        matched = True
                        break
                    elif index == len(record) - 1:
                        if index >= 19:
                            next_page = element_locator.find_element_by_css(driver_obj, self.nextpageselector)
                            if next_page.is_enabled():
                                next_page.click()
                            else:
                                loopNext = False
                        index = index + 1
                    else:
                        loopNext = False

            if matched:
                print "The mac and serial number matched, should have been deleted"
                assert False
            else:
                print('No matching macaddress and serial number found')
                assert True
</code>```

So, Instead of verifying the message ,I am comparing the number of records that exist on that page for pagination purpose. This fixed my code.

Body:
I have this code in python and selenium to find the deleted records and verify that the record is deleted.

def find_deleted_device(self, mac, serialno):
    index = 0
    loopNext = True
    matched = False
    while loopNext:
        index = 0
        if not element_locator.find_elements_by_css(driver_obj, self.no_device):
            record = element_locator.find_elements_by_css(driver_obj, self.devices_record)
            macaarray = element_locator.find_elements_by_css(driver_obj, self.device_record_mac_address)
            serialnum = element_locator.find_elements_by_css(driver_obj, self.device_record_serial_number)

            for facility_mac, serialnumber in zip(macaarray, serialnum):
                if facility_mac.text == mac and serialnumber.text == serialno:
                    loopNext = False
                    matched = True
                    break
                elif index == len(record) - 1:
                    if index >= 19:
                        next_page = element_locator.find_element_by_css(driver_obj, self.nextpageselector)
                        if next_page.is_enabled():
                            next_page.click()
                        else:
                            loopNext = False
                    index = index + 1
                else:
                    loopNext = False
        else:
            print('No matching macaddress and serial number, No device message appears')
            assert True
            loopNext = False

    if matched:
        print "The mac and serial number matched, should have been deleted"
        assert False
    else:
        print('No matching macaddress and serial number found')
        assert True
sleep(2)

But the problem is there are two scenarios:
1) If only one record exists and we delete that then I get a message "No Records exist"
2) second scenario is a few records exists and I can loop through and verify that the record is deleted.

In case of scenario 1, it works fine.
In case of scenario 2 , it passes but with an error something like  "1496424768.39". How do I escape this error.

Body:
I fixed my issue using the following alternative approach.

#This method is used to search deleted group
    def find_deleted_device_with_paging(self, mac, serialno):

        page_num = element_locator.find_element_by_css(driver_obj, ".test-grid-pagination-summary")
        if page_num.text < 1:
            print('No matching macaddress and serial number found')
            assert True

        else:
            index = 0
            loopNext = True
            matched = False
            print "The mac and serial number matched, should have been deleted"
            while loopNext:
                index = 0
                record = element_locator.find_elements_by_css(driver_obj, self.devices_record)
                macaarray = element_locator.find_elements_by_css(driver_obj, self.device_record_mac_address)
                serialnum = element_locator.find_elements_by_css(driver_obj, self.device_record_serial_number)

                for facility_mac, serialnumber in zip(macaarray, serialnum):
                    if facility_mac.text == mac and serialnumber.text == serialno:
                        loopNext = False
                        matched = True
                        break
                    elif index == len(record) - 1:
                        if index >= 19:
                            next_page = element_locator.find_element_by_css(driver_obj, self.nextpageselector)
                            if next_page.is_enabled():
                                next_page.click()
                            else:
                                loopNext = False
                        index = index + 1
                    else:
                        loopNext = False

            if matched:
                print "The mac and serial number matched, should have been deleted"
                assert False
            else:
                print('No matching macaddress and serial number found')
                assert True

So, Instead of verifying the message ,I am comparing the number of records that exist on that page for pagination purpose. This fixed my code.


问:
Is this Promise chain guaranteed to execute in this order?

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

let p = sleep(50);

p.then(() => console.log('a')).then(() => console.log('c'));
p.then(() => console.log('b')).then(() => console.log('d'));```

Is this guaranteed to print "a, b, c, d" in that order?

As far as I can tell, "a" has to fire before "c" and "b" has to fire before "d", but beyond that, can the JS interpreter decide to execute the remainder in a different order?

答:
As far as I can tell, "a" has to fire before "c" and "b" has to fire before "d"

Yes, that much for certan.

beyond that, can the JS interpreter decide to execute the remainder in a different order?

Depends on whom you ask, but no there are more guarantees that make the output more predictable:

the Promise/A+ specification also demands that "all respective callbacks must execute in the order of their originating calls to then." So in your example, that means "a" has to fire before "b", because the callback was chained first to p.

the ECMAScript specification defines a job queue for promise callbacks, nailing down the order (imo unnecessarily). It conforms to Promises/A+ in that the "a" and "b" callbacks are queued in the order they were set up when the promise fulfills. It also means that after "a" returns and fulfills the promise, it will schedule "c", and after "b" returns and fulfills the promise, it will schedule "d", so their order is determined as well (for synchronous callbacks).

In general, don't rely on any scheduling algorithm, if you require a certain order then make it explicit.

Body:
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

let p = sleep(50);

p.then(() => console.log('a')).then(() => console.log('c'));
p.then(() => console.log('b')).then(() => console.log('d'));

Is this guaranteed to print "a, b, c, d" in that order?

As far as I can tell, "a" has to fire before "c" and "b" has to fire before "d", but beyond that, can the JS interpreter decide to execute the remainder in a different order?


问:
What is the process to reassign a variable to point to another in C#?
At the moment I have the following inside a for loop:

```<code>NewArray.Add(RawDataArray[i].Value);
</code>```

During the course of processing RawDataArray a number of additional arrays will be created, for example NewArray1,NewArray2 etc

At one point I will need NewArray to point to NewArray1 so that the .Add method adds the data to NewArray1 and at another point, I need to point NewArray to another NewArrayX

How do I do this in C#?

Edit

In order to try and clarify here is a relevant section:

```<code>    List<object> NewArray = new List<object>();

            for (int i = 1; i <= RawDataArray.Count; i++)
            {
                if (RawDataArray[i].TypeCode == 5005)
                {
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5016)
                {
                    //RawDataArray[i] should be added to NewArray1
                    >> Create NewArray1 and "change" NewArray so that it points to NewArray1 <<
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5017)
                {
                    //RawDataArray[i] should be added to NewArray2
                    >> Create NewArray2 and "change" NewArray so that it points to NewArray2 <<
                    NewArray.Add(RawDataArray[i].Value);
                }
            }
</code>```

Additional edit

I guess a little more information is required so you can see the full picture. I have a raw data stream, in this case simulated by RawDataArray (OK terminology of 'array' not correct, accepted!!).

```<code>    struct TypedValue
        {
            private readonly int typeCode;
            private readonly object value;

            public TypedValue(int typeCode, object value)
            {
                this.typeCode = typeCode;
                this.value = value;
            }

            public int TypeCode { get { return typeCode; } }
            public object Value { get { return value; } }

        }

        static readonly IList<TypedValue> RawDataArray = new ReadOnlyCollection<TypedValue>
        (new[] {
            new TypedValue(5005,@"String Value 1"),
            new TypedValue(5005,@"String Value 2"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 3"),
            new TypedValue(5005,@"String Value 4"),
            new TypedValue(5005,@"String Value 5"),
            new TypedValue(5005,@"String Value 6"),
            new TypedValue(5005,@"String Value 7"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 8"),
            new TypedValue(5005,@"String Value 9"),
            new TypedValue(5005,@"String Value 10"),
            new TypedValue(5005,@"String Value 11"),
            new TypedValue(5005,@"String Value 12"),
            new TypedValue(5005,@"String Value 13"),
            new TypedValue(5005,@"String Value 14"),
            new TypedValue(5005,@"String Value 15"),
            new TypedValue(5005,@"String Value 16"),
            new TypedValue(5005,@"String Value 17"),
            new TypedValue(5005,@"String Value 18"),
            new TypedValue(5005,@"String Value 19"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 20"),
            new TypedValue(5005,@"String Value 21"),
            new TypedValue(5005,@"String Value 22"),
            new TypedValue(5005,@"String Value 23"),
            new TypedValue(5005,@"String Value 24"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5005,@"String Value 25"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 26"),
            new TypedValue(5005,@"String Value 27"),
            new TypedValue(5005,@"String Value 28"),
            new TypedValue(5005,@"String Value 29"),
            new TypedValue(5005,@"String Value 30"),
            new TypedValue(5017,@"-1"),
        });
</code>```

The confusing part is that typeCode of 5016 and 5017 form the start and end respectively of a block of data.  That is to say the data between these typeCodes needs to go in to a temporary array (or something) which is then inserted in to NewArray.

So, in pseudo code, I have this working thought:

1) for (int i = 1; i <= RawDataArray.Count; i++)

2) if i.typeCode = 5005 then add i.value to NewArray

3) if i.typeCode = 5016 then create a temporary array and make NewArray point to it so that calls to the Add method now adds to the temporary array.

4) if i.typeCode = 5017 then add temporary array to NewArray and the point NewArray variable to NewArray.

```<code>        List<object> NewArray = new List<object>();

            for (int i = 1; i <= RawDataArray.Count; i++)
            {
                if (RawDataArray[i].TypeCode == 5005)
                {
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5016)
                {
                    //RawDataArray[i] should be added to temporary array
                    //Create temporary array and "change" NewArray so that it points to temporary array
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5017)
                {
                    //temporary array should be added to NewArray
                    //Add temporary array to NewArray and re-assign NewArray Variable to reference NewArray so that calls to .Add method add to NewArray
                }
            }
</code>```

The idea is this.  As the RawDataArray is iterated through, if it encounters a typeCode of 5005 it adds the value to NewArray.  If the typeCode is 5016 it starts a temporary array and re-assigns the NewArray variable to point to the temporary array. When it next encounters a 5005 typeCode the NewArray variable is pointing to the temporary array so that the add method adds the value to the temporary array.

When the 5017 typeCode is found we know that the temporary array is complete and needs to be added to NewArray and so the process completes. Since the NewArray Variable now points to NewArray and not the temporary array, any subsequent .Add calls will add to NewArray (so typeCode of 5005 outside the 5016 and 5017 data block is added to NewArray.

This image may also help: http://i.xomf.com/myhln.png

I find an image is perhaps sometimes better.

答:
After your clarification on your question I elected to re-answer (as editing is for clarification of existing answers, not for a completely different answer)

This is what you need to do:

```<code>var results = new List<List<TypedValue>>();
var tempList = new List<TypedValue>();
foreach (var value in RawDataArray)
{
    if (value.TypeCode == 5016)
        tempList = new List<TypedValue>();

    tempList.Add(value);

    if (value.TypeCode == 5017)
        results.Add(tempList);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
At the moment I have the following inside a for loop:

NewArray.Add(RawDataArray[i].Value);

During the course of processing RawDataArray a number of additional arrays will be created, for example NewArray1,NewArray2 etc

At one point I will need NewArray to point to NewArray1 so that the .Add method adds the data to NewArray1 and at another point, I need to point NewArray to another NewArrayX

How do I do this in C#?

Edit

In order to try and clarify here is a relevant section:

    List<object> NewArray = new List<object>();

            for (int i = 1; i <= RawDataArray.Count; i++)
            {
                if (RawDataArray[i].TypeCode == 5005)
                {
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5016)
                {
                    //RawDataArray[i] should be added to NewArray1
                    >> Create NewArray1 and "change" NewArray so that it points to NewArray1 <<
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5017)
                {
                    //RawDataArray[i] should be added to NewArray2
                    >> Create NewArray2 and "change" NewArray so that it points to NewArray2 <<
                    NewArray.Add(RawDataArray[i].Value);
                }
            }

Additional edit

I guess a little more information is required so you can see the full picture. I have a raw data stream, in this case simulated by RawDataArray (OK terminology of 'array' not correct, accepted!!).

    struct TypedValue
        {
            private readonly int typeCode;
            private readonly object value;

            public TypedValue(int typeCode, object value)
            {
                this.typeCode = typeCode;
                this.value = value;
            }

            public int TypeCode { get { return typeCode; } }
            public object Value { get { return value; } }

        }

        static readonly IList<TypedValue> RawDataArray = new ReadOnlyCollection<TypedValue>
        (new[] {
            new TypedValue(5005,@"String Value 1"),
            new TypedValue(5005,@"String Value 2"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 3"),
            new TypedValue(5005,@"String Value 4"),
            new TypedValue(5005,@"String Value 5"),
            new TypedValue(5005,@"String Value 6"),
            new TypedValue(5005,@"String Value 7"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 8"),
            new TypedValue(5005,@"String Value 9"),
            new TypedValue(5005,@"String Value 10"),
            new TypedValue(5005,@"String Value 11"),
            new TypedValue(5005,@"String Value 12"),
            new TypedValue(5005,@"String Value 13"),
            new TypedValue(5005,@"String Value 14"),
            new TypedValue(5005,@"String Value 15"),
            new TypedValue(5005,@"String Value 16"),
            new TypedValue(5005,@"String Value 17"),
            new TypedValue(5005,@"String Value 18"),
            new TypedValue(5005,@"String Value 19"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 20"),
            new TypedValue(5005,@"String Value 21"),
            new TypedValue(5005,@"String Value 22"),
            new TypedValue(5005,@"String Value 23"),
            new TypedValue(5005,@"String Value 24"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5005,@"String Value 25"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 26"),
            new TypedValue(5005,@"String Value 27"),
            new TypedValue(5005,@"String Value 28"),
            new TypedValue(5005,@"String Value 29"),
            new TypedValue(5005,@"String Value 30"),
            new TypedValue(5017,@"-1"),
        });

The confusing part is that typeCode of 5016 and 5017 form the start and end respectively of a block of data.  That is to say the data between these typeCodes needs to go in to a temporary array (or something) which is then inserted in to NewArray.

So, in pseudo code, I have this working thought:

1) for (int i = 1; i <= RawDataArray.Count; i++)

2) if i.typeCode = 5005 then add i.value to NewArray

3) if i.typeCode = 5016 then create a temporary array and make NewArray point to it so that calls to the Add method now adds to the temporary array.

4) if i.typeCode = 5017 then add temporary array to NewArray and the point NewArray variable to NewArray.

        List<object> NewArray = new List<object>();

            for (int i = 1; i <= RawDataArray.Count; i++)
            {
                if (RawDataArray[i].TypeCode == 5005)
                {
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5016)
                {
                    //RawDataArray[i] should be added to temporary array
                    //Create temporary array and "change" NewArray so that it points to temporary array
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5017)
                {
                    //temporary array should be added to NewArray
                    //Add temporary array to NewArray and re-assign NewArray Variable to reference NewArray so that calls to .Add method add to NewArray
                }
            }

The idea is this.  As the RawDataArray is iterated through, if it encounters a typeCode of 5005 it adds the value to NewArray.  If the typeCode is 5016 it starts a temporary array and re-assigns the NewArray variable to point to the temporary array. When it next encounters a 5005 typeCode the NewArray variable is pointing to the temporary array so that the add method adds the value to the temporary array.

When the 5017 typeCode is found we know that the temporary array is complete and needs to be added to NewArray and so the process completes. Since the NewArray Variable now points to NewArray and not the temporary array, any subsequent .Add calls will add to NewArray (so typeCode of 5005 outside the 5016 and 5017 data block is added to NewArray.

This image may also help: http://i.xomf.com/myhln.png

I find an image is perhaps sometimes better.

Body:
After your clarification on your question I elected to re-answer (as editing is for clarification of existing answers, not for a completely different answer)

This is what you need to do:

var results = new List<List<TypedValue>>();
var tempList = new List<TypedValue>();
foreach (var value in RawDataArray)
{
    if (value.TypeCode == 5016)
        tempList = new List<TypedValue>();

    tempList.Add(value);

    if (value.TypeCode == 5017)
        results.Add(tempList);
}


问:
C# Error Handling for System.Xml in a Console App
I've inherited a C# console app and I'm not well-versed in writing error handling.  After several months of this app running nightly without any issue, it just started throwing the following error, daily, for the last 3 days:

```<code> Unhandled Exception: System.Xml.XmlException: An error occurred while parsing EntityName. Line 5, position 338.
    at System.Xml.XmlTextReaderImpl.Throw(Exception e)
    at System.Xml.XmlTextReaderImpl.HandleEntityReference(Boolean isInAttributeValue, EntityExpandType expandType, Int32& charRefEndPos)
    at System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos, Int32& outOrChars)
    at System.Xml.XmlTextReaderImpl.FinishPartialValue()
    at System.Xml.XmlTextReaderImpl.get_Value()
    at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
    at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
    at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
    at System.Xml.Linq.XDocument.Load(String uri, LoadOptions options)
    at System.Xml.Linq.XDocument.Load(String uri)
    at Data.Service.AssignmentService.<HandleMarkupActivityStep>d__10.MoveNext() in C:\Users\default\Source\Workspaces\Data\Data - Transfer\Data.Service\AssignmentService.cs:line 381
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Vital4Data.Service.AssignmentService.<ProcessSingleHtmlSource>d__17.MoveNext() in C:\Users\default\Source\Workspaces\Data\Data - Transfer\Data.Service\AssignmentService.cs:line 948
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
    at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
    at System.Threading.ThreadPoolWorkQueue.Dispatch()
    at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
 Status changed to Failed
 Job failed due to exit code -532462766
</code>```

Until I can have someone dig into the app to solve the issue, I just need the app to ignore this error, and continue without failing, for now.  How would I go about adding error handling to the code to accomplish this?  Is this a candidate for a try/catch block?  Or is a try/catch block what caught and threw this in the first place?  I'd appreciate any guidance so I can simply tell the program to ignore the error and continue executing.

答:
Console apps are often used on scheduled jobs.
As ColinM said, You should implement a try-catch, but I'd also recomend to log your trace for further analysis.</p>

Body:
I've inherited a C# console app and I'm not well-versed in writing error handling.  After several months of this app running nightly without any issue, it just started throwing the following error, daily, for the last 3 days:

 Unhandled Exception: System.Xml.XmlException: An error occurred while parsing EntityName. Line 5, position 338.
    at System.Xml.XmlTextReaderImpl.Throw(Exception e)
    at System.Xml.XmlTextReaderImpl.HandleEntityReference(Boolean isInAttributeValue, EntityExpandType expandType, Int32& charRefEndPos)
    at System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos, Int32& outOrChars)
    at System.Xml.XmlTextReaderImpl.FinishPartialValue()
    at System.Xml.XmlTextReaderImpl.get_Value()
    at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
    at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
    at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
    at System.Xml.Linq.XDocument.Load(String uri, LoadOptions options)
    at System.Xml.Linq.XDocument.Load(String uri)
    at Data.Service.AssignmentService.<HandleMarkupActivityStep>d__10.MoveNext() in C:\Users\default\Source\Workspaces\Data\Data - Transfer\Data.Service\AssignmentService.cs:line 381
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Vital4Data.Service.AssignmentService.<ProcessSingleHtmlSource>d__17.MoveNext() in C:\Users\default\Source\Workspaces\Data\Data - Transfer\Data.Service\AssignmentService.cs:line 948
 --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
    at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
    at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
    at System.Threading.ThreadPoolWorkQueue.Dispatch()
    at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
 Status changed to Failed
 Job failed due to exit code -532462766

Until I can have someone dig into the app to solve the issue, I just need the app to ignore this error, and continue without failing, for now.  How would I go about adding error handling to the code to accomplish this?  Is this a candidate for a try/catch block?  Or is a try/catch block what caught and threw this in the first place?  I'd appreciate any guidance so I can simply tell the program to ignore the error and continue executing.