Form field not show on Ajax Callback even the callback is called

Question: I have a form with one shown field of type select with ajax callback to show another form field dynamically of type select and with ajax callback again,
the problem is second field ajax callback should show a third field dynamically but nothing is shown.
here is my code
public function buildForm(array $form, FormStateInterface $form_state) {
    $controller = new Place_AdsController();
    $terms = $controller->content();

    $form['#attached']['library'][] = 'Place_Ads/general';
    $form['level1value'] = array(
        '#type' => 'hidden',
    );
    $form['level1'] = array(
        '#type' => 'select',
        '#description' => 'Please select level one term',
        '#options' => $terms,
        '#attributes' => array(
            'class' => array(
                'mycategory'
            ),
        ),
        '#ajax' => array(
            // Function to call when event on form element triggered.
            'callback' => '::level1SelectedCallback',
            // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
            'wrapper' => 'ajax-wrapper2',
            'effect' => 'fade',
            // Javascript event to trigger Ajax. Currently for: 'onchange'.
            'event' => 'change',
            'progress' => array(
                // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                'type' => 'throbber',
                // Message to show along progress graphic. Default: 'Please wait...'.
                'message' => NULL,
            ),
        ),
    );
    $form['ajax_wrapper2'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'ajax-wrapper2'],
    ];
    $form['ajax_wrapper3'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'ajax-wrapper3'],
    ];

    if ($form_state->getValue('level1') != false) {
        $form['ajax_wrapper2']['level2'] = array(
            '#type' => 'select',
            '#description' => 'Please select level two term',
            //'#options' => '',
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
            '#ajax' => array(
                // Function to call when event on form element triggered.
                'callback' => '::level2SelectedCallback',
                // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
                'wrapper' => 'ajax-wrapper3',
                'effect' => 'fade',
                // Javascript event to trigger Ajax. Currently for: 'onchange'.
                'event' => 'change',
                'progress' => array(
                    // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                    'type' => 'throbber',
                    // Message to show along progress graphic. Default: 'Please wait...'.
                    'message' => NULL,
                ),
            ),
        );
    }
    if ($form_state->getValue('level2') != false) {
        //$form['ajax_wrapper3'][0]['#suffix'] = '
';
        $form['ajax_wrapper3']['level3'] = array(
            '#type' => 'select',
            '#description' => 'Please select level three term',
            //'#options' => '',
            '#attributes' => array(
                'class' => array(
                    'mycategory'
                ),
            ),
            '#ajax' => array(
                // Function to call when event on form element triggered.
                'callback' => '::level3SelectedCallback',
                // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
                'wrapper' => 'ajax-wrapper4',
                'effect' => 'fade',
                // Javascript event to trigger Ajax. Currently for: 'onchange'.
                'event' => 'change',
                'progress' => array(
                    // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
                    'type' => 'throbber',
                    // Message to show along progress graphic. Default: 'Please wait...'.
                    'message' => NULL,
                ),
            ),
        );
    }

    return $form;
}

public function level1SelectedCallback(array &$form, FormStateInterface $form_state) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();
    $controller = new Place_AdsController();
    $terms = array();
    if ($form_state->getValue('level1') != false) {
        $val = $form_state->getValue('level1');
        $terms = $controller->getTerms($val);

    }

    $form['ajax_wrapper2']['level2']['#options'] = $terms;
    $ajax_response->addCommand(new HtmlCommand('#ajax-wrapper2', $form['ajax_wrapper2']['level2']));
    // We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username.
    $ajax_response->addCommand(new InvokeCommand('#ajax-wrapper2', 'change'));
    $ajax_response->addCommand(new InvokeCommand('#level2', 'change'));

    return $ajax_response;
}

public function level2SelectedCallback(array &$form, FormStateInterface $form_state) {

    $ajax_response = new AjaxResponse();
    $controller = new Place_AdsController();
    $terms = array();
    if ($form_state->getValue('level2') != false) {
        $val = $form_state->getValue('level2');
        $terms = $controller->getTerms($val);

    }

    $form['ajax_wrapper3']['level3']['#options'] = $terms;
    $ajax_response->addCommand(new HtmlCommand('#ajax-wrapper3', $form['ajax_wrapper3']['level3']));
    // We can still invoke the change command on #edit-user-name so it triggers Ajax on that element to validate username.
    $ajax_response->addCommand(new InvokeCommand('#ajax-wrapper3', 'change'));
    $ajax_response->addCommand(new InvokeCommand('#level3', 'change'));

    return $ajax_response;

}

public function level3SelectedCallbackold(array &$form, FormStateInterface $form_state) {
    return null;
}

Comment: any errors showing?
Comment: No error showing
Answer: Changing the option list in an ajax callback like this
$form['ajax_wrapper2']['level2']['#options'] = $terms;

does not work, because the formbuilder does not know about this and will not recognize the new options. You have to move this code to buildForm().
Otherwise you will see a select element, but when you choose an option, nothing will happen or an error occurs that you have chosen the wrong option.
Comment: this piece of code is working fine and the select "#level2" is shown successfully with its ajax callback being fired, however the problem is in the 3rd level "#level3" select not shown even with empty options.
So the question why its working with level2 but never with level3?
Comment: sorry, can't debug the whole code, but this was the most obvious problem, i explain this a bit more, see the edit


PHP: Convert Google Sheets result object to simple array

Question: I've google sheet with this data:

I'm pulling it from google drive with simple code:
   $ranges = [
    'Price_1'
   ];
   $params = array(
    'ranges' => $ranges
   );

   $response = $service->spreadsheets_values->batchGet($spreadsheetId, $params);

The response is a complicated object:
object(Google_Service_Sheets_BatchGetValuesResponse)#58 (8) { ["collection_key":protected]=> string(11) "valueRanges" ["spreadsheetId"]=> string(44) "1BQpKLuvlaVeGqIqoGUOynF9IZ5C3zK6gagZiRJO1UEU" ["valueRangesType":protected]=> string(32) "Google_Service_Sheets_ValueRange" ["valueRangesDataType":protected]=> string(5) "array" ["internal_gapi_mappings":protected]=> array(0) { } ["modelData":protected]=> array(0) { } ["processed":protected]=> array(0) { } ["valueRanges"]=> array(1) { [0]=> object(Google_Service_Sheets_ValueRange)#67 (7) { ["collection_key":protected]=> string(6) "values" ["majorDimension"]=> string(4) "ROWS" ["range"]=> string(14) "Price_1!E2:E74" ["values"]=> array(65) { [0]=> array(1) { [0]=> string(2) "28" } [1]=> array(1) { [0]=> string(2) "14" } [2]=> array(1) { [0]=> string(1) "0" } [3]=> array(0) { } [4]=> array(1) { [0]=> string(2) "55" } [5]=> array(1) { [0]=> string(2) "28" } [6]=> array(1) { [0]=> string(1) "0" } [7]=> array(0) { } [8]=> array(0) { } [9]=> array(0) { } [10]=> array(0) { } [11]=> array(0) { } [12]=> array(0) { } [13]=> array(0) { } [14]=> array(0) { } [15]=> array(0) { } [16]=> array(0) { } [17]=> array(0) { } [18]=> array(0) { } [19]=> array(0) { } [20]=> array(1) { [0]=> string(2) "59" } [21]=> array(1) { [0]=> string(2) "49" } [22]=> array(0) { } [23]=> array(1) { [0]=> string(2) "38" } [24]=> array(1) { [0]=> string(2) "38" } [25]=> array(0) { } [26]=> array(1) { [0]=> string(2) "37" } [27]=> array(1) { [0]=> string(2) "25" } [28]=> array(1) { [0]=> string(1) "0" } [29]=> array(0) { } [30]=> array(1) { [0]=> string(2) "79" } [31]=> array(1) { [0]=> string(2) "99" } [32]=> array(0) { } [33]=> array(1) { [0]=> string(2) "75" } [34]=> array(1) { [0]=> string(2) "99" } [35]=> array(0) { } [36]=> array(1) { [0]=> string(2) "79" } [37]=> array(1) { [0]=> string(2) "99" } [38]=> array(0) { } [39]=> array(1) { [0]=> string(3) "160" } [40]=> array(1) { [0]=> string(3) "190" } [41]=> array(0) { } [42]=> array(0) { } [43]=> array(0) { } [44]=> array(0) { } [45]=> array(0) { } [46]=> array(0) { } [47]=> array(0) { } [48]=> array(0) { } [49]=> array(0) { } [50]=> array(0) { } [51]=> array(0) { } [52]=> array(1) { [0]=> string(2) "33" } [53]=> array(0) { } [54]=> array(1) { [0]=> string(2) "59" } [55]=> array(1) { [0]=> string(2) "34" } [56]=> array(1) { [0]=> string(1) "0" } [57]=> array(0) { } [58]=> array(1) { [0]=> string(2) "29" } [59]=> array(1) { [0]=> string(2) "14" } [60]=> array(1) { [0]=> string(1) "0" } [61]=> array(0) { } [62]=> array(1) { [0]=> string(2) "37" } [63]=> array(1) { [0]=> string(2) "25" } [64]=> array(1) { [0]=> string(1) "0" } } ["internal_gapi_mappings":protected]=> array(0) { } ["modelData":protected]=> array(0) { } ["processed":protected]=> array(0) { } } } }

and var_dump($response->getValueRanges()[0]['values']); gives this result:
array(74) { [0]=> array(5) { [0]=> string(2) "ID" [1]=> string(10) "Ticket for" [2]=> string(9) "Excursion" [3]=> string(8) "Duration" [4]=> string(14) "Price (Brutto)" } [1]=> array(5) { [0]=> string(3) "01A" [1]=> string(13) "adult ( 12+ )" [2]=> string(9) "Catamaran" [3]=> string(2) "2h" [4]=> string(2) "28" } [2]=> array(5) { [0]=> string(3) "01B" [1]=> string(18) "child ( age 5-11 )" [2]=> string(9) "Catamaran" [3]=> string(2) "2h" [4]=> string(2) "14" } [3]=> array(5) { [0]=> string(3) "01C" [1]=> string(18) "toodler ( age 0-4)" [2]=> string(9) "Catamaran" [3]=> string(2) "2h" [4]=> string(1) "0" } [4]=> array(0) { } [5]=> array(5) { [0]=> string(3) "02A" [1]=> string(13) "adult, age 8+" [2]=> string(17) "Luxurt yacht trip" [3]=> string(2) "3h" [4]=> string(2) "55" } [6]=> array(5) { [0]=> string(3) "02B" [1]=> string(14) "child, age 3-7" [2]=> string(17) "Luxurt yacht trip" [3]=> string(2) "3h" [4]=> string(2) "28" } [7]=> array(5) { [0]=> string(3) "02C" [1]=> string(16) "toodler, age 0-2" [2]=> string(17) "Luxurt yacht trip" [3]=> string(2) "3h" [4]=> string(1) "0" } [8]=> array(0) { } [9]=> array(3) { [0]=> string(3) "03A" [1]=> string(0) "" [2]=> string(8) "Sailboat" } [10]=> array(3) { [0]=> string(3) "03B" [1]=> string(0) "" [2]=> string(8) "Sailboat" } [11]=> array(3) { [0]=> string(3) "03C" [1]=> string(0) "" [2]=> string(8) "Sailboat" } [12]=> array(0) { } [13]=> array(3) { [0]=> string(3) "04A" [1]=> string(0) "" [2]=> string(9) "Submarine" } [14]=> array(3) { [0]=> string(3) "04B" [1]=> string(0) "" [2]=> string(9) "Submarine" } [15]=> array(3) { [0]=> string(3) "04C" [1]=> string(0) "" [2]=> string(9) "Submarine" } [16]=> array(0) { } [17]=> array(3) { [0]=> string(3) "05A" [1]=> string(0) "" [2]=> string(13) "JetSki safari" } [18]=> array(3) { [0]=> string(3) "05B" [1]=> string(0) "" [2]=> string(13) "JetSki safari" } [19]=> array(3) { [0]=> string(3) "05C" [1]=> string(0) "" [2]=> string(13) "JetSki safari" } [20]=> array(0) { } [21]=> array(5) { [0]=> string(3) "06A" [1]=> string(9) "fisherman" [2]=> string(7) "Fishing" [3]=> string(2) "4h" [4]=> string(2) "59" } [22]=> array(5) { [0]=> string(3) "06B" [1]=> string(9) "spectator" [2]=> string(7) "Fishing" [3]=> string(2) "4h" [4]=> string(2) "49" } [23]=> array(0) { } [24]=> array(5) { [0]=> string(3) "07A" [1]=> string(5) "adult" [2]=> string(12) "Parascending" [3]=> string(5) "30min" [4]=> string(2) "38" } [25]=> array(5) { [0]=> string(3) "07B" [1]=> string(13) "child, age 6+" [2]=> string(12) "Parascending" [3]=> string(5) "30min" [4]=> string(2) "38" } [26]=> array(0) { } [27]=> array(5) { [0]=> string(3) "08A" [1]=> string(14) "adult, age 12+" [2]=> string(9) "Siam Park" [3]=> string(0) "" [4]=> string(2) "37" } [28]=> array(5) { [0]=> string(3) "08B" [1]=> string(15) "child, age 3-11" [2]=> string(9) "Siam Park" [3]=> string(0) "" [4]=> string(2) "25" } [29]=> array(5) { [0]=> string(3) "08C" [1]=> string(16) "toodler, age 0-1" [2]=> string(9) "Siam Park" [3]=> string(0) "" [4]=> string(1) "0" } [30]=> array(0) { } [31]=> array(5) { [0]=> string(3) "09A" [1]=> string(17) "flight from 800m." [2]=> string(18) "Paragliding tandem" [3]=> string(5) "15min" [4]=> string(2) "79" } [32]=> array(5) { [0]=> string(3) "09B" [1]=> string(18) "flight from 1000m." [2]=> string(18) "Paragliding tandem" [3]=> string(5) "25min" [4]=> string(2) "99" } [33]=> array(0) { } [34]=> array(5) { [0]=> string(3) "10A" [1]=> string(21) "Single (for 1 person)" [2]=> string(27) "Quad safari Forest explorer" [3]=> string(2) "3h" [4]=> string(2) "75" } [35]=> array(5) { [0]=> string(3) "10B" [1]=> string(22) "Double (for 2 persons)" [2]=> string(27) "Quad safari Forest explorer" [3]=> string(2) "3h" [4]=> string(2) "99" } [36]=> array(0) { } [37]=> array(5) { [0]=> string(3) "11A" [1]=> string(21) "Single (for 1 person)" [2]=> string(24) "Quad Safari - Teide tour" [3]=> string(2) "4h" [4]=> string(2) "79" } [38]=> array(5) { [0]=> string(3) "11B" [1]=> string(22) "Double (for 2 persons)" [2]=> string(24) "Quad Safari - Teide tour" [3]=> string(2) "4h" [4]=> string(2) "99" } [39]=> array(0) { } [40]=> array(5) { [0]=> string(3) "12A" [1]=> string(21) "Single (for 1 person)" [2]=> string(15) "Buggy adventure" [3]=> string(2) "3h" [4]=> string(3) "160" } [41]=> array(5) { [0]=> string(3) "12B" [1]=> string(22) "Double (for 2 persons)" [2]=> string(15) "Buggy adventure" [3]=> string(2) "3h" [4]=> string(3) "190" } [42]=> array(0) { } [43]=> array(3) { [0]=> string(3) "13A" [1]=> string(0) "" [2]=> string(8) "Trekking" } [44]=> array(3) { [0]=> string(3) "13B" [1]=> string(0) "" [2]=> string(8) "Trekking" } [45]=> array(3) { [0]=> string(3) "13C" [1]=> string(0) "" [2]=> string(8) "Trekking" } [46]=> array(0) { } [47]=> array(3) { [0]=> string(3) "14A" [1]=> string(0) "" [2]=> string(7) "Karting" } [48]=> array(3) { [0]=> string(3) "14B" [1]=> string(0) "" [2]=> string(7) "Karting" } [49]=> array(3) { [0]=> string(3) "14C" [1]=> string(0) "" [2]=> string(7) "Karting" } [50]=> array(0) { } [51]=> array(3) { [0]=> string(3) "15A" [1]=> string(0) "" [2]=> string(11) "Jungle park" } [52]=> array(3) { [0]=> string(3) "15B" [1]=> string(0) "" [2]=> string(11) "Jungle park" } [53]=> array(5) { [0]=> string(3) "15C" [1]=> string(0) "" [2]=> string(11) "Jungle park" [3]=> string(0) "" [4]=> string(2) "33" } [54]=> array(0) { } [55]=> array(5) { [0]=> string(3) "16A" [1]=> string(14) "adult, age 12+" [2]=> string(16) "La Gomera island" [3]=> string(12) "7:40 - 18:00" [4]=> string(2) "59" } [56]=> array(5) { [0]=> string(3) "16B" [1]=> string(15) "child, age 2-11" [2]=> string(16) "La Gomera island" [3]=> string(12) "7:40 - 18:00" [4]=> string(2) "34" } [57]=> array(5) { [0]=> string(3) "16C" [1]=> string(16) "toodler, age 0-1" [2]=> string(16) "La Gomera island" [3]=> string(12) "7:40 - 18:00" [4]=> string(1) "0" } [58]=> array(0) { } [59]=> array(5) { [0]=> string(3) "17A" [1]=> string(14) "adult, age 12+" [2]=> string(31) "Santa Cruz/ La Laguna/ Taganana" [3]=> string(1) "?" [4]=> string(2) "29" } [60]=> array(5) { [0]=> string(3) "17B" [1]=> string(15) "child, age 2-11" [2]=> string(31) "Santa Cruz/ La Laguna/ Taganana" [3]=> string(1) "?" [4]=> string(2) "14" } [61]=> array(5) { [0]=> string(3) "17C" [1]=> string(16) "toodler, age 0-1" [2]=> string(31) "Santa Cruz/ La Laguna/ Taganana" [3]=> string(1) "?" [4]=> string(1) "0" } [62]=> array(0) { } [63]=> array(5) { [0]=> string(3) "18A" [1]=> string(14) "adult, age 12+" [2]=> string(11) "Loro parque" [3]=> string(12) "8:30 - 18:45" [4]=> string(2) "37" } [64]=> array(5) { [0]=> string(3) "18B" [1]=> string(15) "child, age 6-11" [2]=> string(11) "Loro parque" [3]=> string(0) "" [4]=> string(2) "25" } [65]=> array(5) { [0]=> string(3) "18C" [1]=> string(16) "toodler, age 0-1" [2]=> string(11) "Loro parque" [3]=> string(0) "" [4]=> string(1) "0" } [66]=> array(0) { } [67]=> array(3) { [0]=> string(3) "19A" [1]=> string(0) "" [2]=> string(9) "Antologia" } [68]=> array(3) { [0]=> string(3) "19B" [1]=> string(0) "" [2]=> string(9) "Antologia" } [69]=> array(3) { [0]=> string(3) "19C" [1]=> string(0) "" [2]=> string(9) "Antologia" } [70]=> array(0) { } [71]=> array(3) { [0]=> string(3) "20A" [1]=> string(0) "" [2]=> string(13) "Medieval show" } [72]=> array(3) { [0]=> string(3) "20B" [1]=> string(0) "" [2]=> string(13) "Medieval show" } [73]=> array(3) { [0]=> string(3) "20C" [1]=> string(0) "" [2]=> string(13) "Medieval show" } }

And:
for($i = 1; $i < 5; $i++) {
    print_r ($response->getValueRanges()[0]['values'][$i]);
}

Gives: Array ( [0] => 01A [1] => adult ( 12+ ) [2] => Catamaran [3] => 2h [4] => 28 ) Array ( [0] => 01B [1] => child ( age 5-11 ) [2] => Catamaran [3] => 2h [4] => 14 ) Array ( [0] => 01C [1] => toodler ( age 0-4) [2] => Catamaran [3] => 2h [4] => 0 ) Array ( )
In result I need a simple array, which will hold a key[row id], the ID from from ID row and price from last row, somethig like this: $result[$i] = unique_id=1, ID=01A, price=28
How it could be achieved?
Comment: A lot better - now extract the "values" field - notice it contain 2 dimension array - each element is array of size 5 (representing row)
Comment: Try `var_dump(response["valueRanges"]);` first and share how the data is formated
Comment: If I done this right, the `var_dump($response["A1:C75"]);` returns NULL
Comment: I meant actually the string "valueRanges" - look at the object or search for example use of google sheets
Comment: understood, it's an array. I'm updating the question, cause the string is too long for the comment
Comment: You need to check your ranges. In the response you getting only column E (price) - in your var_dump see the prices at key "values"
Comment: I hope, now it's right. There was a specific range in the `   $ranges = [
 'Price_1'
   ];`
Comment: Just updated with results :)
Answer: So after getting the data for google sheet with:
$arr = $response->getValueRanges()[0]['values'];

You can use this simple for loop to get the data as you need:
// notice start from 1 to avoid the headers
for($i = 1; $i < count($arr); $i++) {
    $res[$i] = array("unique_id" => $i, "ID" => $arr[$i][0], "price" => $arr[$i][4]);
}

Now $res will contain you structure.


Compactness - Norm on $\Bbb R^n$

Question: I am trying to prove the question below by Heine-Borel, $K_1$ and $K_2$ are subsets of $\Bbb R^n$.
Let $K_1 $and $K_2$ be two compact sets and A = $\{\lvert x_1 - x_2\lvert: x_1 \in K_1,x_2 \in K_2\}.$ Show that $A$ is compact.
Proof:
I am proving by Heine-Borel, therefore two steps.
First Step: show that A is bounded
For any $x_1 \in K$ and $x_2 \in K$, we know that $\lvert x_1 - x_2\lvert \leq  \lvert x_1\lvert + \lvert x_2\lvert$, as $\lvert x_1\lvert $ and $\lvert x_2\lvert $ are bounded the sum is bounded, so we are done proving that $\lvert x_1 - x_2\lvert$ is bounded.
Second Step: show that $A$ is closed
I am not sure how to do the second step.
Answer: Take a sequence $(a_n)_{n\in\Bbb N}$ of points of $A$ which converges to some $a\in\Bbb R$; you want to prove that $a\in A$. Each $a_n$ can be writen as $|x_n-y_n|$ with $x_n\in K_1$ and $y_n\in K_2$. The sequence $(x_n)_{n\in\Bbb N}$ has a subsequence $(x_{n_k})_{k\in\Bbb N}$ which converges to some $x\in K_1$, since $K_1$ is compact. And the sequence $(y_{n_k})_{k\in\Bbb N}$ has some subsequence $(y_{m_l})_{l\in\Bbb N}$ which converges to some $y\in K_2$. But then\begin{align}a&=\lim_{l\to\infty}a_{n_l}\\&=\lim_{l\to\infty}\left|x_{n_l}-y_{n_l}\right|\\&=\left|\lim_{l\to\infty}(x_{n_l}-y_{n_l})\right|\\&=|x-y|\\&\in A.\end{align}
Comment: Very clear answer, I am not sure how I did not get that before.
Comment: I'm glad I could help.
Answer: The product of two compact subspaces is a compact. Therefore $K_1 \times K_2$ is a compact subspace of $\mathbb R^n \times \mathbb R^n$.
Then the application $(x,y) \mapsto \Vert x-y \Vert$ is continuous from $\mathbb R^n \times \mathbb R^n$ to $\mathbb R$.
As the image under a continuous map of a compact is compact, $A$ is compact.
Comment: I accepted the other answer because I do not know enough about continuity to understand/evaluate your answer.
Comment: @Beaba No problem at all. The answer from José is indeed more directly linked to Heine-Borel theorem.

Compactness - Norm on $\Bbb R^n$


Does this integral relation follow from Stokes' theorem?

Question: In Landau and Lifhsitz's Electrodynamics of continuous media there is an integral relation for the curl of magnetisation (just after equation 27.8) in the form
$\int\limits_{V}\mathbf{r}\times\left(\nabla\times\mathbf{M}\right)dV=-\oint\limits_{\partial V}\mathbf{r}\times(\mathbf{M}\times\mathbf{dS})-\int\limits_V(\mathbf{M}\times\nabla)\times\mathbf{r}\,dV$,
where $\mathbf{r}$ is the position vector and $\mathbf{M}$ is the magnetisation. The integral goes over the volume $V$, or its boundary $\partial V$.
I am having trouble proving this - does the relation follow from Stokes' theorem? Any suggestions would be much appreciated.
Comment: Aren't the first and third integrals in what you wrote exactly the same (aside from a missing small-space before the "d")? If so, this certainly looks odd, if not wrong.
Comment: @JohnHughes my apologies, and thank you for pointing out my mistake - I wrote the terms in the wrong order. I now edited the post to correct the mistake.
Answer: Bring the rightmost integral to the left side; pull both under the same integral sign. Now the thing in the left integral looks like a derivative of a product, so you have
$$
\int_V d(thing) = \int_{\partial V} thing
$$
which looks like Stokes' to me.
Of course, this requires that $d(r \times (M \times dS))$ is indeed the thing under the (newly combined) left integral, and I don't know what magnetization is, nor any of its properties, nor do I know how to do integrals with $dS$ and $dV$ in them reliably -- I really only "get" the differential-forms version of Stokes' Theorem -- but this seems to be pretty clearly the way to go.
Comment: Thank you for your reply. Apologies for not elaborating on what magnetisation is; $\mathbf{M}$ and $\mathbf{r}$ are both vectors in 3D, $dV$ is the volume element (i. e. $dxdydz$ in Carthesian coordinates, likewise $dS$ is the surface element).


Compute some expectations involving beta and gamma distributions

Question: a) Let $X \sim {\text {Beta}}(a,b)$, with density $f(x) = \frac{x^{a-1}(1-x)^{b-1}} {B (a,b)}$. Find the expectation of $X \ln X$ and $\frac{1}{X+1}.$
b) Let $Y \sim {\text {Gamma}}(\alpha,\beta)$, with density $g(y) = {\frac {\beta ^{\alpha }}{\Gamma (\alpha )}}y^{\alpha \,-\,1}e^{-\beta y}$. Find the expectation of $Y \ln Y$ and $\frac{1}{Y+1}.$
c) Assume $X,Y$ are independent. Find $\Bbb E [\frac{1}{XY+1}]$ and $\Bbb E [\frac{1}{Y-XY+1}]$.
I reduced my previous question to the above much simpler questions. Any help with this question will help the previous question as well. Any help with any of above expectation calculations will be very much appreciated.
Comment: Can you please write the expressions of their pdf ... at least for Gamma (if same as wiki then put wiki link)... and also conditions on $a,b$ etc.
Comment: Conditions on parameters do seem important. If either X or Y concentrates probability near 0, then you need to investigate whether expectations of 1/X and 1/Y exist.
Comment: Thanks. I amended the question.
Comment: $E(1/(X+1))$ can be done by expanding $1/(X+1)$.
Comment: This question contains a more general solution to $E(1/(X+1))$ https://stats.stackexchange.com/questions/277864/a-bound-based-on-jensens-inequality
Comment: To avoid confusion, the previous comment refers to the solution to $E(\frac{1}{Y+1})$, not $E(\frac{1}{X+1})$.
Comment: As presented, this issue has no connection with statistics. I have erased the corresponding tag.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
$\ds{\Large\left.a\right)}$
\begin{align}
&\bbox[13px,#ffd]{\int_{0}^{1}{x^{a - 1}\pars{1 - x}^{b - 1} \over \mrm{B}\pars{a,b}}\,x\ln\pars{x}\,\dd x} =
\left.{1 \over \mrm{B}\pars{a,b}}\,\partiald{}{\nu}
\int_{0}^{1}x^{a + \nu}\pars{1 - x}^{b - 1}\,\dd x\,\right\vert_{\ \nu\ =\ 0}
\\[5mm] = &\
\left.{1 \over \mrm{B}\pars{a,b}}\,\partiald{\mrm{B}\pars{a + \nu + 1,b}}{\nu}
\,\right\vert_{\ \nu\ =\ 0} =
\left.{1 \over \mrm{B}\pars{a,b}}\,\partiald{}{\nu}
{\Gamma\pars{a + \nu + 1}\Gamma\pars{b} \over \Gamma\pars{a + \nu + 1 + b}}
\,\right\vert_{\ \nu\ =\ 0}
\\[5mm] = &\
{\Gamma\pars{b} \over
\Gamma\pars{a}\Gamma\pars{b}/\Gamma\pars{a + b}}
\bracks{\Gamma\pars{1 + a}\,{H_{a} - H_{a + b} \over \Gamma\pars{1 + a + b}}}
\\[5mm] = &\
{\Gamma\pars{a + b} \over
\Gamma\pars{a}}\bracks{%
a\,\Gamma\pars{a}\,{H_{a} - H_{a + b} \over \pars{a + b}\Gamma\pars{a + b}}} =
\bbx{{a \over a + b}\pars{H_{a} - H_{a + b}}}
\end{align}

\begin{align}
&\bbox[13px,#ffd]{\int_{0}^{1}{x^{a - 1}\pars{1 - x}^{b - 1} \over \mrm{B}\pars{a,b}}
\,{1 \over x + 1}\,\dd x} =
{1 \over \mrm{B}\pars{a,b}}\int_{0}^{1}x^{a - 1}\pars{1 - x}^{b - 1}
\bracks{1 - \pars{-1}x}^{\,-1}\,\dd x
\\[5mm] = &\
{1 \over \mrm{B}\pars{a,b}}\bracks{%
\mrm{B}\pars{a,b}\,\mbox{}_{2}\mrm{F}_{1}\pars{1,a;a + b;-1}} =
\bbx{\mbox{}_{2}\mrm{F}_{1}\pars{1,a;a + b;-1}}\label{1}\tag{1}
\end{align}

\eqref{1} is evaluated as an 'Euler Type' expression for the Hypergeometric Function: It's given in
  this link.

$\ds{\Large\left.b\right)}$
\begin{align}
&\bbox[13px,#ffd]{\int_{0}^{\infty}{\beta^{\alpha} \over \Gamma\pars{\alpha}}
\,y^{\alpha - 1}\expo{-\beta y}y\ln\pars{y}\,\dd y} =
{\beta^{\alpha} \over \Gamma\pars{\alpha}}
\left.\partiald{}{\nu}\int_{0}^{\infty}y^{\alpha + \nu}\expo{-\beta y}\,\dd y
\,\right\vert_{\ \nu\ =\ 0}
\\[5mm] = &\
{\beta^{\alpha} \over \Gamma\pars{\alpha}}
\partiald{}{\nu}\bracks{{1 \over \beta^{\alpha + \nu + 1}}
\int_{0}^{\infty}y^{\alpha + \nu}\expo{-y}\,\dd y}_{\ \nu\ =\ 0} =
{\beta^{\alpha} \over \Gamma\pars{\alpha}}
\partiald{}{\nu}\bracks{{\Gamma\pars{\alpha + \nu + 1} \over
\beta^{\alpha + \nu + 1}}}_{\ \nu\ =\ 0}
\\[5mm] = &\
{\beta^{\alpha} \over \Gamma\pars{\alpha}}\braces{%
-\beta^\pars{-1 - \alpha}\,\Gamma\pars{1 + \alpha}\bracks{\ln\pars{\beta} - H_{\alpha} + \gamma}} =
\bbx{{\alpha \over \beta}\bracks{H_{\alpha} - \gamma - \ln\pars{\beta}}}
\end{align}
Answer: Have you tried a computer algebra system?
Part (a): For $X \sim \text{Beta}(a,b)$ with pdf $f(x)$:

Then here is the output generated by mathStatica / Mathematica to the first problem:

... where HarmonicNumber[n] denotes the $n^\text{th}$ harmonic number $H_n=\sum _{i=1}^n \frac{1}{i}$, and

where Hypergeometric2F1Regularized[a,b,c,z] denotes ${_2}F{_1}(a,b;c;z) / \Gamma(c)$, and Expect is a mathStatica function (of which I am one of the authors).

Part (b): For $Y \sim \text{Gamma}(\alpha,\beta)$ with pdf $g(y)$:

... you seek:

... where EulerGamma is Euler's constant (approx 0.577), and:

where ExpInteralE[$\alpha$, $\beta$ ] is the exponential integral function $\int _1^{\infty} \frac{1}{t^\alpha} e^{-\beta t} dt$

Part (c): Find $\Bbb E [\frac{1}{XY+1}]$ and $\Bbb E [\frac{1}{Y-XY+1}]$.
These two questions are essentially the same. To see this, note that if $X \sim \text{Beta}(a,b)$, then $(1-X) \sim \text{Beta}(b,a)$, and that $\Bbb E [\frac{1}{Y-XY+1}] = \Bbb E [\frac{1}{(1-X)Y+1}]$ which is thus also of form  $\Bbb E [\frac{1}{XY+1}]$ (just with the $X$ parameters swapped). So we only need to solve the first part.
Given independence, the joint pdf of $(X,Y)$, say $h(x,y) = f(x) g(y)$:

Then $\Bbb E [\frac{1}{XY+1}]$ is:

While this expression looks rather cumbersome, it appears to be correct, and works fine for non-integer parameter values. For instance, when ${a = 2.2, b = 3.3, \alpha = 4.1, \beta = 5.2}$, the above expression returns a value of 0.780101 for the expectation (which is consistent with Monte Carlo simulation).


Block visibility role section is missing

Question: I am doing development in drupal 8. All of a sudden, I see that block visibility role section is missing.

How can I bring the block visibility role section back?
Comment: I'm voting to close this question because it's about an [issue in a third-party module, already reported in the project issue queue](https://www.drupal.org/project/rules/issues/3160347).
Comment: Does it happen on all blocks? Where do the options in the screenshot come from? Is it a module? Does it happen when you're not using that module?
Answer: There is a bug in Rules 8.x-3.0-alpha6 that hides the core block visibility conditions. Please upgrade to Rules 8.x-3.x-dev. See https://www.drupal.org/project/rules/issues/3160347


Subroutine in a SQL Server stored procedure

Question: Can anyone share me a light on how to create a subroutine in a stored procedure in SQL Server?
I have a procedures in Oracle that will call a subroutine within the same procedures for 50 times in different lines in the procedure. Now I want to recreate the same procedure in SQL Server. Could you share me some light on how to do this?
Comment: There isn't such a thing as a subroutine in SQL Server. But a stored procedure can call another stored procedure.
Answer: If your subroutine is performing data modifications (CRUD) or need to use temporary tables(#teporary_table) it needs to be stored procedure. In other cases, you can use create a function. You can choose from different types of functions depending on their complexity and return values:

scalar function - returns one value
inline table-valued - it's like view with parameters (you cannot declare table variables for example, its one SELECT statement) and returns rowset
multi-statement table-valued - returns rowset but you can have more complex logic

Also, in SQL Server there is SQL CLR and you can create functions or procedures (or as called them "subroutines") in .net code.
Answer: In SQL Server you have stored procedures and table and scalar functions. Another feature that is convenient are common table expressions.
Functions you can use directly in SQL statements (SELECT, INSERT, UPDATE, JOIN), so they seamless to reuse.
Table function:
SELECT *
FROM myFunction(@UserID) as f
    INNER JOIN users AS u ON f.UserID = u.ID

Scalar function you can put in SELECT part of query.
SELECT u.ID, myFunction(u.ID)
FROM users as u

Common table expressions are nice for readability:
;WITH MyCTP AS
(
    // complex SQL
)
SELECT *
FROM myTable INNER JOIN MyCTP ON...

You can have multiple CTEs before SELECT statement, but you can only use them in the statment above which they were declared.
Stored procedures
They are a bit of pain in the a$$, because you need to capture result into variables in order to use them in the calling stored procedure.
 DECLARE @Input INT
 DECLARE @Result INT

 EXEC myStoredProcedure @Input, @Result OUT

If procedure outputs table, it gets even more complicated. You need to use cursor to capture result.
Answer: A trick:
create proc MyProc @MySub varchar(20) = ''
as
if @MySub = 'MySub' goto MySub

print 'MyProc'
exec MyProc MySub
return

MySub:
print 'MySub'
return

Comment: [What is the problem with GOTO?](https://stackoverflow.com/questions/3517726/what-is-wrong-with-using-goto). Not only is this bad code in any language and doesn't really answer the question, there are *good* answers already


css - always define standard rule 'keyframe' when defining keyframe Error

Question: Estou recebendo erro no código abaixo que diz

css -  always define standard rule 'keyframe' when defining keyframe   Error

Ele é executado normalmente no Chrome, mas não está funcionando no IE 11
@-webkit-keyframes fadeIn {
  0% {
    opacity: 0;
    top: 100px;
  }
  75% {
    opacity: 0.5;
    top: 0px;
  }
  100% {
    opacity: 1;
  }
}

Answer: Seu problema é que vc está declarando a animação apenas para o vendor prefix -webkit- que o Chrome entende mais o IE não.
Animação funcionando no IE11

Para corrigis basta vc adicionar o mesmo CSS porém sem o prefixo @keyframes fadeIn {}
Veja que vai funcionar ai agora sem erro, esse é o código referente a imagem acima

.box {
    width: 100px;
    height: 100px;
    background-color: red;
    animation: fadeIn 1s linear infinite;
}
@-webkit-keyframes fadeIn {
  0% {
    opacity: 0;
    top: 100px;
  }
  75% {
    opacity: 0.5;
    top: 0px;
  }
  100% {
    opacity: 1;
  }
}
@keyframes fadeIn {
  0% {
    opacity: 0;
    top: 100px;
  }
  75% {
    opacity: 0.5;
    top: 0px;
  }
  100% {
    opacity: 1;
  }
}

Dica
Nessa pergunta tem detalhes que vão te interessar É necessário adicionar prefixos em algumas propriedades do CSS?
Comment: Verdade. Super importante abordar outros navegadores para mitigar possíveis falhas de compatibilidade  ;)
Comment: Correto.
Basta remover a definição do motor webkit que funcionou.

Thank You!
Comment: @RafaelPatriciodaCruz na verdade se vc quiser garantir que os browsers mais antigos vão reconhecer a propriedade seria interessante manter os dois `@-webkit-keyframes fadeIn { } ` e `@-webkit-keyframes fadeIn { }` e se vc quiser ir além ainda pode se resguardar para o FireFox antigo usando `@-moz-keyframes fadeIn { }` (moz = mozilla)


Basic calculations with Order Statistics

Question: I've come across the following problem, and I am tempted to delve into order statistics to solve this. I would greatly appreciate any help!
Suppose you draw 6 independent samples from a continuous distribution. What is the approximate probability that the population median of the distribution lies between the smallest and largest observations?
Comment: What is the probability that a sample of 6 data points are all below the population median? Do you see the next steps?
Comment: RIght. What's the chance that 5 are below it and 1 is above?
Comment: Foxah - You found the probability that all 6 data points will be below the population median. So you also know the probability that all 6 data points will be above the population median. There is only one other pertinent possibility - that the sample range contains the median.
Comment: The analysis posted in reply to a similar question at https://stats.stackexchange.com/questions/122001 provides a full answer.  Another analysis at https://stats.stackexchange.com/questions/45124/ also answers this question.
Comment: @Foxah my hint was an attempt to get you to spot you were just doing binomial calculations (so giving a shortcut to computing all such quantile questions)
Comment: If the maximum is less than the median, then all points in the sample have to be less than the median. So (.5^6) = .015625
Comment: @Glen_b --> So, it should be 1-.5^6 = .9844?
Comment: As so many do, you're using the word "sample" incorrectly. You draw a sample, ONE sample, of six independent observations. They're not samples; they're observations.
Comment: @Glen_b - thanks for that! I actually started to head down that path after your hint. But I'm still kinda stuck, and not entirely convinced by the solution below. Will bang head against the wall a bit more.
Answer: The probability that the population median does not lie between the largest and smallest observatrions is the probability that either all of them are larger than the median or all of them are smaller. This is
$$
\left( \frac 1 2 \right)^6 + \left( \frac 1 2 \right)^6.
$$


how to rewrite field in view

Question: I have following Html code, I want to rewrite two field .1st is  [field_poster_hover_image] and 2nd is [field_team_image] .This is my HTML Code.

and I have written code like this but its not working

Comment: Where have u written the above html code ?
Answer: You don't want to use [field_team_image] in the src ,just put the [field_team_image] you can get the image and print $data in views custom php field to get the another image to get the url.
Comment: ok ,it's working but what about image of data-log ?
Comment: what you want to do with that image?please explain.
Comment: yes I want [field_poster_hover_image] image in the place of data-logo="images/girls-12s.png"
Comment: Better you print the $data in views php field (to add php field in views you have to install this module if it is drupal 6, https://drupal.org/project/views_customfield )and get the url of the images dynamically.
Comment: How can I print data ?
Comment: I am using Custom text and write my html code here.
Answer: You can use hook_views_pre_render(&$view) to rewrite the code .
 function hook_views_pre_render(&$view) {

      switch ($view->name) {
        case 'YOUR_VIEW_NAME':
          foreach($view->result as $key => $value) {
          $value->field_some_element[0]['rendered']['#markup'] = '
Your custom markup should be placed here
';
    }
        break;
      }

Comment: @Nikunj Jagad have u tried hook_views_pre_render() ?
Comment: I used  https://drupal.org/project/image_url_formatter  to  display image.Its working
Answer: Using the Image URL Formatter module it is possible to display image. Here is a quote about it (from the module's project page):

... adds a url formatter for image field. Then you can output image url directly.
I had created a content type, and added an image field instance to it. Later on I used views to export the data of this content type. And I wanted to output the data, so I could import it into another Drupal 7 site with the Feeds module. What I needed is the url of the image field, but I could not export the image url directly. That is why I created this small module.
Answer: You can alter the HTML output at the row level from inside the Views UI:

Add the fields to your view. Settings:
Create a label - unchecked
Exclude from display - checked
Otherwise configure each field depending on what kind of output you want. For example, with an image field you might select as your formatter "Image" (to display the rendered image tag) or "Download link" (to display the download path to the file). The latter would be most appropriate in this case.
Add a new field Global: Custom text. Add the mark-up below, only replace [field_myfield1] and [field_myfield2] with the actual tokens for each field, which can be found by expanding Replacement patterns.

//

//
:) Bonus: If using the node title as the text in your alt attribute, in the above HTML you can replace "project 1" with the [title] token.

how to rewrite field in view


How to send mail after selecting text from select list using rules?

Question: In my content I have a select list text field. I have four options for that. While clicking only particular one in select list and giving click save. Then I want to generate mail to users.For example: I have select list fields like born, dead, live, none... while user selects born and goes to click save. I want to send a mail for administrator.
Comment: I don't think there is a way to do it "while user selects born and goes to click save". You can do it after the user has selected born and has clicked save.
Comment: Is your field named category and are you using taxonomy terms? OR did you just copy paste this example from somewhere?
Comment: What do you want the e-mail to say? Does it depend on what they selected?
Comment: So you just want the e-mail to say New litter was born, if they select new litter? and if they select something else, don't send anything?
Answer: (UPDATED)
go to /admin/config/workflow/rules/reaction/add
1) Name: Give the rule whatever name you want.
2) React on even: (Under Node) Select After Saving New Content
Restrict by type: select Cage Card Info
Now you're taken to a new page
3) Under Conditions, click on Add Condition.
4) In the drop down, select TEXT COMPARISON
5) Click on the Blue Link that says (DATA SELECTORS)
6) Look for your field, if you named it "warnings", then look for node:field-warnings
then highlight it, copy and paste it under Data Selector*
7) Under Matching Text put New litter
Then click SAVE
8) Under Actions, click add action
scroll all the way down, under system, select mail
9) Under TO, put [site:mail] OR email@example.com (if you don't have access to your websites e-mail inbox)
Then fill out the subject and message fields, click save.
You're done, now go and test it.
Side Note 1:
I figured why the e-mail was not being set. I was trying email@example.com instead of putting email@example.com as the websites admin e-mail in <code>/admin/config/system/site-information</code>

"under Configuration/Site Information under "Site Details" you MUST
  insert an email address from your domain, and then the email works."

Side Note 2: seems like e-mails get sent after running cron. So you wont see the e-mail until cron runs. See Mail is sending after a cron run
Comment: Comments have been removed. Please don't use them for extended discussion; that is not the purpose of comments on Stack Exchange sites.


Use of ACF and PACF

Question: I am new to time series analysis, I have come across ACF and PACF while working on time series data set.
There is a confusion, in some links/texts ACF and PACF is plotted without taking difference i.e. time series is non-stationary and they just mention that depending upon shape of ACF and PACF we can decide if we need to make time series stationary or not?
There are links/texts which mention that in order to decide AR or MA or ARMA model, plot ACF and PACF after taking difference of series.
Does this mean that ACF and PACF can be plotted for both non-stationary and stationary series? but purpose is different.
For non-stationary time series, PACF and ACF plots can be used to visualize if time series is stationary or not
For stationary time series PACF and ACF plots can be used to determine the model and its order.
Is my understanding correct?
Comment: There's a similar question/answer [here](https://stats.stackexchange.com/q/422556/119085). ACF/PACF can be useful both before and after differencing.
Answer: Generally speaking, ACF and PACF help you to find out which ARIMA type best suits your data (eg ARIMA(2,1,1)). The time series has to be stationary when checking ACF and PACF. https://towardsdatascience.com/identifying-ar-and-ma-terms-using-acf-and-pacf-plots-in-time-series-forecasting-ccb9fd073db8 maybe here you can find some further clarifications.
It is important to point out that many times there isn't a clear answer by just looking at ACFs and PACFs, so you can use tools implemented in almost all statistical softwares to find out which ARIMA type best suits your data.
Comment: But when i plot ACF and PACF on stationary data it looks stationary and all values are within 95% CLs

Use of ACF and PACF


Nonparametric repeated measures test to test for significant differences?

Question: Some weeks ago, I used 5 different microphones to record the same sound. The idea was to compare what differences existed between these recordings. To do that I wanted to use some sort of test to check for significant differences in the audio features that I am interested (amplitude, fundamental frequency, etc.).
All the audio features from the recorded audios do not follow a normal distribution. For this reason, I should use nonparametric tests. Furthermore, since all the microphones recorded the same sound I should use some sort of repeated measures test. However, I am not sure what test I should use. I have only used repeated ANOVA before, but according to my knowledge that would not be correct for this case, as it is a parametric test.
Could you recommend me some non parametric test for repeated measures in order to control for differences? (it would be great that it was also implemented in R).
Answer: Friedman test maybe?
<code>(microphones<-matrix(c(1:10,2:11,3:12,4:13,5:14), nrow=10)) # 5 microphones, 10 features
      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    2    3    4    5
 [2,]    2    3    4    5    6
 [3,]    3    4    5    6    7
 [4,]    4    5    6    7    8
 [5,]    5    6    7    8    9
 [6,]    6    7    8    9   10
 [7,]    7    8    9   10   11
 [8,]    8    9   10   11   12
 [9,]    9   10   11   12   13
[10,]   10   11   12   13   14

friedman.test(microphones)

    Friedman rank sum test

data:  microphones
Friedman chi-squared = 40, df = 4, p-value = 4.328e-08
</code>


Problemas com roteamento usando o asp.net core

Question: Ao tentar rotear uma aplicação core 2.0, não consigo chegar na controller.
public class GetClientController : Controller
    {
        LoadClient loadClient = new LoadClient();

        [HttpGet]
        public IEnumerable<Cliente> GetCliente(double cpf)
        {
            return loadClient.GetCliente().AsEnumerable().ToList();
        }
    }

Na controller acima, o RoutePrefix não rola, tentei esses dois namespace e não rolou:
using System.Net.Http;
using System.Web.Http;

Na minha model fiz isso
[Route("api/getcliente/{cpf}")]
        public List<Cliente> GetCliente(Int64 cpf)
        {
            List<Cliente> cliente = new List<Cliente>();

            cliente.Add(new Cliente(123456, "firstname.lastname@example.com", "986754007", "CB", "EML"));
            cliente.Add(new Cliente(908734, "firstname.lastname@example.com", "988877731", "CB", "SMS"));
            cliente.Add(new Cliente(674300, "firstname.lastname@example.com", "965241131", "PF", "EML"));
            cliente.Add(new Cliente(101654, "email@example.com", "987450101", "EX", "EML"));
            cliente.Add(new Cliente(501274, "firstname.lastname@example.com", "986754144", "PA", "SMS"));

            var lista = cliente
                .Where(cp => cp.Cpf == cpf).ToList();

            return lista;
        }

quando eu testo no postman, não me dá erro, mas não obtenho a lista passada. Esse é o postman:

EDIT1
Fiz essa edição e removi da model e mesmo assim não entra no método
public class GetClientController : Controller
    {
        LoadClient loadClient = new LoadClient();

        [HttpGet]
        [Route("api/getcliente/{cpf}")]
        public IEnumerable<Cliente> GetCliente(Int64 cpf)
        {
            return loadClient.GetCliente(cpf).AsEnumerable().ToList();
        }
    }

EDIT2

EDIT3
Meu Startap.cs
public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }

EDIT4
Fiz essa alteração e mesmo assim não rolou
[Route("api/[controller]")]
    public class GetClientController : Controller
    {
        LoadClient loadClient = new LoadClient();

        [HttpGet("getcliente/{cpf}")]
        public IEnumerable<Cliente> GetCliente(Int64 cpf)
        {
            return loadClient.GetCliente(cpf).AsEnumerable().ToList();
        }
    }

Comment: Se colocou o roteamento na model? o roteamento é na classe do Controller!
Comment: Não sei o que você fez, só sei que na sua pergunta a rota está no lugar errado tem que ser no controller ! e também a rota está com problemas!
Comment: Faz o seguinte no lugar de cpf coloque `id`(`[Route("api/getcliente/{id}")]`) e no paramentro `int id`(`public IEnumerable GetCliente(int cpf)`) também...
Comment: Tente remover o "api" do Route que está em cima do seu método.
Comment: Se seu método GetCliente espera um parâmetro, você tem que passar um parâmetro pra ele, do contrário, não irá achar nada mesmo. Observe que no seu postman, o método que chamou é getclient e não getcliente.
Comment: Como você fez esse projeto? Como a gente observou tem bastante problemas o seu código e isso pode fazer com que não funcione corretamente !!!
Comment: Procure por routes.MapRoute dentro da classe Startup.cs e coloque o código aqui, por favor.
Comment: Será necessário algum atributo de classe na  **Rota**? Tentei o **RoutePrefix** e não consegui.
Comment: @perozzo, o .Net Core não tem isso
Comment: Ah não? Eu uso .Net Core 2.0 e meu projeto tem isso.
Comment: @VirgilioNovic, esse projeto é só um mock para testar um outro serviço. Ele não é só isso mesmo e para testes. Precisei fazê-lo às pressas e não funfou.
Comment: @perozzo, printei o meu projeto e veja que não tenho essa pasta
Comment: É um arquivo e não uma pasta. Presta atenção. Tá na tua frente o arquivo e tu não viu.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/79057/discussion-between-perozzo-and-pnet).
Comment: Tu leu o que eu comentei? Vamos denovo: Procure por routes.MapRoute dentro da classe Startup.cs e coloque o código aqui, por favor.
Comment: @perozzo, editei o post e postei o startup
Comment: Aí está o problema. Seu arquivo Startup.cs está bem distante do que deveria estar.
Comment: Entendi, falta o MapRoute, certo? Estou procurando um exemplo em como configurar esse cara
Comment: Quando criou o projeto do zero ele já não veio com o MapRoute pronto pra vc?
Comment: Veja também o *ASP Net Core 2 Razor Pages*, que simplifica tudo isto.
Answer: No Aspnet Core não existe mais o annotation RoutePrefix, agora tanto para o annotation da Classe quando da Action se usa o Route, como vc fez.
Porém quando vc cria a rota [Route("api/getcliente/{cpf}")], vc está dizendo que a propriedade cpf será recebida de alguma maneira.
Somado a isso, vc usa um [HttpGet], então vc quer passar o cpf pela própria url.
Sabendo disso, o print do postman mostra que vc não está informando a url corretamente.
Ela deveria ser: http://localhost:55730/api/getclient/31865881384
Se mesmo assim a Action não receber o cpf, é porque vc não deixou explícito no parâmetro que ele deverá ser recebido via url.
Para isso faça a seguinte alteração:
public class GetClientController : Controller
{
    LoadClient loadClient = new LoadClient();

    [HttpGet]
    [Route("api/getcliente/{cpf}")]
    public IEnumerable<Cliente> GetCliente([FromRoute]double cpf)
    {
        return loadClient.GetCliente().AsEnumerable().ToList();
    }
}

Comment: Eu tenho dois métodos sobrecarregados, 1 com parâmetro e outro sem, razão de naquele momento em que capturei o print do postman, estava passando o GetAll(Sem parâmentros), foi mal não ter explicitado isso.
Comment: Fiz as alterações devidas e continua me retornando um statuscode 404(page not found)
Comment: Na verdade me confundi, o correto é FromRoute e não FromQuery. Com FromQuery vc precisaria chamar a url assim: api/getcliente?cpf=12345678
Comment: Olhando bem, a minha controller tem um ToList() para apenas um elemento. Isso pode dar pau? Porque troquei para FromRoute e mesmo assim não rolou
Comment: Fiz outra alteração(Edit4) e não rolou
Answer: Resolvi. No Startup eu fiz:
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddRouting();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMvc();
        }

e na controller chamei
[Route("api/[controller]")]
    public class GetClientController : Controller
    {
        LoadClient loadClient = new LoadClient();

        [HttpGet("{cpf}")]
        public IEnumerable<Cliente> GetCliente(Int64 cpf)
        {
            return loadClient.GetCliente(cpf).AsEnumerable().ToList();
        }
    }

Com isso resolvi o problema. Obrigado a todos.


Show Snackbar above to showModalBottomSheet Flutter

Question: I have showModalBottomSheet to get OTP code, If the user enter wrong code, I want to show snackBar. So, I used this method,
showModalBottomSheet(
        isScrollControlled: true,
        isDismissible: false,
        context: context,
        builder: (context) {
          return SafeArea(
            child: Stack(
              alignment: Alignment.topCenter,
              clipBehavior: Clip.none,
              children: [
                Column(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 30, vertical: 0),
                      child: Column(children: [
                        Padding(
                          padding:
                              const EdgeInsets.symmetric(horizontal: 50),
                          child: TextField(
                            controller: codeController,
                            keyboardType: TextInputType.number,
                          ),
                        ),
                        const SizedBox(
                          height: 5,
                        ),
                        Padding(
                          padding:
                              const EdgeInsets.symmetric(horizontal: 50),
                          child: CustomButton(
                              onTap: () async {
                                if (codeController.text.length == 6) {
                                  try {
                                    PhoneAuthCredential credential =
                                        PhoneAuthProvider.credential(
                                            verificationId: verificationId,
                                            smsCode:
                                                codeController.text.trim());
                                    await _auth
                                        .signInWithCredential(credential);
                                    Navigator.of(context)
                                        .pushNamedAndRemoveUntil(
                                            '/home',
                                            (Route<dynamic> route) =>
                                                false);
                                  } catch (e) {
                                  // ----------------------------------------------
                                  //this snackbar
                                     showSnackBar(
                                           context,
                                           "Invalid verification code",
                                          "Please enter correct verification code");
                                    }
                                  }
                              },
                              text: "Continue",
                              height: 50),
                        )
                      ]),
                    )
                  ],
                )
              ],
            ),
          );
        });

The snackBar showing under the showModalBottomSheet, So I want to show the snackBar above to showModalBottomSheet without hiding showModalBottomSheet.
Answer: You can use another Scaffold to get new  ScaffoldMessenger from showModalBottomSheet instead of top level.
showModalBottomSheet(
    isScrollControlled: true,
    isDismissible: false,
    context: context,
    builder: (context) {
      return SafeArea(
        child: Scaffold( //here another scaffold
          body: Stack(
            alignment: Alignment.topCenter,
            clipBehavior: Clip.none,
            children: [
              Column(
                children: [
                  Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 30, vertical: 0),
                    child: Column(
                      children: [
                        ElevatedButton(
                          onPressed: () {
                            const SnackBar snackBar = SnackBar(
                                content: Text(
                                    "Hey, I am above BottomSheet"));
                            ScaffoldMessenger.of(context)
                                .showSnackBar(snackBar);
                          },
                          child: Text("show SnackBar"),
                        )
                      ],
                    ),
                  )
                ],
              )
            ],
          ),
        ),
      );
    });

Comment: Hey, @Yeasin, i'm facing the same problem as the one showed in this question. Your aswer worked for me as well, but with one downside... Using scaffold makes my bottom sheet take the whole screens' height... is there anything I can do to prevent scaffold from taking all available height and use only enough to show the content ? Thank you.
Comment: Glad to help, you can find more about [`Scaffold`](https://api.flutter.dev/flutter/material/Scaffold-class.html) widget,


Statement from Proposition 0.18 of Hatcher

Question: On page $16$ of Hatcher's, following proof is given:
but I can't see the induced deformation retract's existence.
My attempt is to use "passing to the quotient", but somehow at the end I can't guarantee the final step of my argument:
$\require{AMScd}$
\begin{CD}
{X_0\sqcup (X_1 \times I)} @>{\text{fix }X_0,\, D = D_2\circ D_1}>> X_0\sqcup (X_1 \times I)\\
@VVV @VVV\\
{X_0\sqcup_{F} (X_1 \times I)} @>{\exists ?}>> {X_0\sqcup_{F} (X_1 \times I)}
\end{CD}
Where $D_1$ is the deformation retraction mentioned in the picture onto $X_1\times\{0\} \cup A\times I$, and $D_2$ deforms $X_1\times\{0\} \cup A\times I$ onto $X_1\times \{0\}$ in the natural way.
To apply passing to the quotient argument, I must show (necessarily, but not enough) that whenever $\pi((a,t)) = \pi((a',t'))$ for $a,a
 \in A$,we have $D((a,t)) = D((a',t'))$. Now condition using $\pi$ is equivalent to $F(a,t) = F(a',t')$. Condition using $D$ is equivalent to $f(a) = f(a')$. But we only have $f_t(a) = f_{t'}(a')$. How to resolve this?
In general, I just can't see how to induce the deformation retraction, so if this is not the way to go, that fact constitutes an answer too.
Answer: $\require{AMScd}$I don't quite buy your diagrams because you forget you must in fact have a map $(X_0\sqcup_F(X_1\times I))\times I\to X_0\sqcup_F(X\times I)$ to speak of a deformation retraction.
Let $G:X_1\times I\times I\to X_1\times I$ be the deformation retraction onto $X_1\times\{0\}\cup A\times I$.
Luckily, $-\times I$ is cocontinuous ($I$ is LCH) which is a miracle that makes a lot of stuff in topology work. Thus $(X_0\sqcup_F(X_1\times I))\times I$ is the pushout: $$\begin{CD}A\times I\times I@>>>X_1\times I\times I\\@VF\times1VV@VVV\\X_0\times I@>>>(X_0\sqcup_F(X_1\times I))\times I\end{CD}$$To get a map into $X_0\sqcup_F(X_1\times I)$ again we specifiy the following components; the projection $X_0\times I\to X_0\to X_0\sqcup_F(X_1\times I)$ and $X_1\times I\times I\overset{G}{\to}X_1\times I\to X_0\sqcup_F(X_1\times I)$. As $G$ is identity on $A\times I$ this truly, by pushout properties, induces something $H:(X_0\sqcup_F(X_1\times I))\times I\to X_0\sqcup_F(X_1\times I)$ which is necessarily (using uniqueness of components for pushouts) equal to the identity at time zero and, at time $1$ the image of $H$ is contained in the images of $X_0,X_1\times\{0\}$ and $A\times I$, but $A\times I$'s image is wholly contained in $X_0$ and $X_1\times\{0\}$'s image wholly contained in $X_0\sqcup_fX_1$; we see $H$ at time $1$ has image contained in $X_0\sqcup_f X_1\hookrightarrow X_0\sqcup_F(X_1\times I)$. Moreover, $H$ restricted to this subspace, at any time, yields - as $G$ is identity on $X_1\times\{0\}$ - the identity on both the $X_0$ and $X_1$ components i.e. $H$ is the identity on this subspace, as required.


Launching help page in Help Viewer in 10.6

Question: I launch help file in 10.4 and 10.5 using AHGotoPage which work great.
When I try launching in 10.6 I get error "hVURLHandlerErrorDomain error 1003" but no idea why.
Note: The error is only on Release version not in Debug.
I even tried with AHLookupAnchor, even this gives the error. Am I missing some thing in solution? Is there any other solution I can try? is there any specific change in help file launching in 10.6?
thanks for all help.
Answer: I have replaced the call AHGotoPage to [[NSWorkspace sharedWorkspace] openURLs: so that I can lauch help file which is working great.


Pros and Cons of Keep-Alive from Web Server Side

Question: Keep-Alive connection feature in HTTP protocol is meant to reduce TCP connection hits to web server. It should be able to improve web server performance. However, I found that some web servers deliberately disable KeepAlive feature from server side.
In my understanding, some reverse proxy, i.e. HAProxy, disables HTTP keep-alive in order to reduce memory usage which is more critical than CPU usage in some situation.
Is there any other reason why Web server disables Keep-Alive?
Answer: Actually, Keep-Alive is meant to improve HTTP performance, not server performance (though for SSL connections it does reduce the cost on the server of re-negotiating the encryption).  The big win is in the number of round trips the browser has to make to get the content.  With Keep-Alive the browser gets to eliminate a full round trip for every request after the first, usually cutting full page load times in half.
Keep-Alive increase server load which is why some shared hosting providers disable it.  Each open connection consumes memory as well as a file descriptor (linux) and in extreme cases (some Apache configs) it may have a 1:1 mapping from connections to processes.
Comment: How is this different from web-sockets. Do web'sockers also increase server load?


How do i get TypeScript source files to show up in node inspector?

Question: I'm working a node express app using typescript 2.3.
I compile using tsc
I would like to be able to debug my TypeScript code using node-inspector (now bundled with node 6.3+)
I have sourceMaps turned on in my tsConfig.json
{
  "compilerOptions": {
    "target": "es6",
    "lib": ["es2017"],
    "module": "commonjs",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noResolve": false,
    "noEmitOnError": false,
    "noImplicitAny": true,
    "declaration": true,
    "sourceMap": true,
    "inlineSources": true,
    "outDir": "dist/",
    "moduleResolution": "node",
    "skipLibCheck": true
  },
  "include": [
    "src/**/*.ts",
    "test/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

I also see the following when connected through the WebUI for fish.controller.js
exports.FishController = FishController;
//# sourceMappingURL=fish.controller.js.map
});

The problem is that i do NOT see the actual TypeScript source or map files in the node-inspector window.
I've ensured they exist:
$ ls -l

-rw-r--r--  1 xxx  staff    945 Sep 19 14:32 fish.controller.d.ts
-rw-r--r--  1 xxx  staff   5318 Sep 19 14:32 fish.controller.js
-rw-r--r--  1 xxx  staff   8528 Sep 19 14:32 fish.controller.js.map

How do i include the TS Files and set breakpoints?
Comment: You can read on how sourcemaps work for debugging here: http://www.andrewconnell.com/blog/debugging-node-js-projects-with-typescript-and-vs-code-digging-into-sourcemaps
Comment: Not directly related, but i was able to get the webstorm debugger to work by configuring a Chromium Remote session, and then providing a "mapRoot": "dist/" option in tsconfig.json
Answer: Can you try to set sourceMap: false and instead add

 "inlineSources": true,
 "inlineSourceMap": true

to your compilerOptions of tsconfig.json?
This will add your sources and sourceMap to the compiled JS files. The Chrome inspector should be able to extract the sources.


Android display an alert

Question: <code>  @Override
public void run() {
AlertDialog.Builder ab = new AlertDialog.Builder(DashboardActivity.this);
ab.setMessage("invalid deal id or does not belong to the same organization").
setNegativeButton("OK", dialogClickListener).show();
   }
</code>
when I hit ok alert does not dismiss;
tried
ab.dismiss()
ab.cancel()
any help?
Comment: what abt dialogClickListern where it is?
Answer: <code> AlertDialog alertDialog = new AlertDialog.Builder(DashboardActivity.this).create();

    alertDialog.setMessage("invalid deal id or does not belong to the same organization");

            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Ok"),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

            alertDialog.show();
</code>
Answer: <code>AlertDialog.Builder builder = new AlertDialog.Builder(DashboardActivity.this);
                        builder.setMessage("Look at this dialog!")
                                .setCancelable(false)
                                .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        //do things
                                        dialog.dismiss();
                                    }
                                });
                        AlertDialog alert = builder.create();
                        alert.show();
</code>
This works :)

Android display an alert


Question regarding the proof for the universal property of a quotient space in linear algebra.

Question:
Let $S$ be a subspace of $V$ and let $\tau\in\mathcal{L}(V,W)$ satisfy $S\subset\mathrm{ker}(\tau)$. Then there's a unique linear map $\tau':V/S\to W$ s.t. $\tau'\circ\pi_S=\tau$. Moreover, $\mathrm{ker}(\tau')=\mathrm{ker}(\tau)/S$ and $\mathrm{im}(\tau')=\mathrm{im}(\tau)$.

Here $\pi_S$ is such that $\pi_S(v) = v+S$, $S$ being a subspace of $V$.
This proof is taken from the textbook Advanced Linear Algebra by S. Roman. I'm gonna display part of it, until the part my question arises. It goes as follows:
We define $\tau'$ by the condition $\tau'\circ\pi_S = \tau$. This function is well defined iff $v+S=u+S \implies \tau'(v+S) = \tau'(u+S)$ which is equivalent to each of the following statements:
$$
\begin{align}
v+S = u+ S &\implies\tau v = \tau u\\
v-u\in S &\implies \tau(v-u) = 0\\
x\in S &\implies \tau x = 0\\
S&\subset\mathrm{ker}(\tau)
\end{align}
$$
I'm gonna stop the proof right here, because it is here that my question arises. In the previous statements, why is it $\tau$ instead of $\tau'$? I ask this because $\pi_S v = \pi_S u \implies v-u \in S \iff \tau'(u-v)=0 \iff \tau'(S)=\{0\} \implies S\subset\mathrm{ker}(\tau')$.
Comment: Where is the proof from? Are you quoting it from some source or did you write it yourself?
Comment: @blargoner This proof is from the textbook Advanced Linear Algebra by Steven Roman. I'm gonna edit my post and include this information.
Answer: The proof is wrong. $v+S=u+S\implies\tau'(v+S)=\tau'(u+S)$ isn't what needs to be proved; it's a tautology that a function applied to equal elements yields equal results. What needs to be proved is actually the first of the displayed sequence of statements, because this is what ensures that it makes sense to say "We define $\tau'$ by the condition $\tau'\circ\pi_S = \tau$."


How to move/rearrange position of views on touch event?

Question: Suppose, on my window i have 3 views, main one in the background and 2 up front.
Each view up front contains some content, i'd like to be moved as part of a view upon touch. By "moved" i mean "rearrange positions relative to another view". Upon touch, i'd like to "pick up the view with all of it's content and place it in the position currently occupied by another view"

Where would you get started on something like this?
Answer: Something like this:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UIView *touchedView = [[touches anyObject] view];
    CGPoint location = [[touches anyObject] locationInView:touchedView];
    touchedView.center = location;
}

See also these methods in UIResponder.h:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

Comment: So, how would you move view on the screen relative to another view? Sorry, could you provide further example?
Answer: First you need to create a GestureRecognizer.  Something along the lines of:
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
doubleTap.numberOfTapsRequired = 2;

[self addGestureRecognizer:doubleTap];

and add it to whatever view you want (or all three).  From the sounds of it your main background view makes the most sense.  Then create the doubleTap method, which will make one of your views move to where the other is:
-(void)doubleTap:(id)sender {
     view1.frame = view2.frame;
     [self bringSubviewToFrom:view1];
}

I would also make sure all your subview content has its autoresizingMask set according to how you want the subviews to behave.


swiftmailer - html and email templates

Question: I need to create a HTML email, and someone suggested Swiftmailer. I installed that module, but it's not clear to me how to create HTML.
I enabled SwiftMailer as the sitewide default in the Mail System module, and I added a message like this:
$string = "This is a defined message: You have been send a message - \n" .$params['message'] . '\n click here<button type="button">Click me</button>';

But the HTML isn't picked up. The a tag is a link, but the button is not a button. I also can't apply inline styles.
Additionally, I will need to know how to create multiple email templates, which apply to different email types (I only saw online how to create one, swiftmailer.tpl.php)
Answer: Swiftmailer just sends emails ... it doesn't let you create HTML / plaintext content for emails.
For ease of setting this all up you likely want to use a module that supports the Mime Mail module and then at least use something like Previewable Email Templates (PET) module. Quote from the PET module page:

The Previewable Email Template (PET) module lets you create email templates, with token substitution, which can be previewed by the user before sending. The emails can be sent to one or many email addresses in a flexible way, and the recipients may or may not be Drupal account holders (users).
PET stores templates in a db table, not the variables table, so there is none of the memory usage which goes with the latter.
PET templates are in one place for easy management by site administrators. Emails can be sent one of three ways:

interactively, from a link.
programmatically, in response to any situation.
via a Rules action (D7 only).
Comment: I installed the Mim Mail module, and it was automatically set as the site wide default in the Mail Systems settings section. Now mail wasn't getting sent out (even though drupal did pop up with a message saying it was sent properly). When I set it back to Default Mail System, it worked. What is wrong?
Comment: I dont know you have to check your email logs, php logs, apache logs. "Why email isn't going out" is a Server issue (even if Drupal said it went OK). Did you check your drupal status report page and Mime Mail configuration settings ?
Comment: I don't see any errors in the log, and Mime Mail doesn't have too many settings in the first place. I don't see what else I could set. It can't be a permission thing because I am logged in as Admin
Comment: sorry i have no other advice to give at this time. PHP doesn't send the email, your mail server does. Did an email get written to your mail queue? Is your email setup ok? The answer I've given to the question is all i can help with at this time.
Comment: how can you see if mail has been written to your mail queue?
Comment: SwiftMailer provides simple templates with its [Decorator plugin](http://www.sitepoint.com/sending-email-with-swift-mailer/).
Answer: You should use MIME mail (it requires mailsystem module)

This is a Mime Mail component module (for use by other modules).
It permits users to receive HTML email and can be used by other
  modules. The mail functionality accepts an HTML message body,
  mime-endcodes it and sends it. If the HTML has embedded graphics,
  these graphics are MIME-encoded and included as a message attachment.
  Adopts your site's style by automatically including your theme's
  stylesheet files in a themeable HTML message format If the recipient's
  preference is available and they prefer plaintext, the HTML will be
  converted to plain text and sent as-is. Otherwise, the email will be
  sent in themeable HTML with a plaintext alternative. Allows you to
  theme messages with a specific mailkey. Converts CSS styles into
  inline style attributes. Provides simple system actions and Rules
  actions to send HTML email with embedded images and attachments.

swiftmailer - html and email templates


Simple delay pedal with more headroom

Question: I'm using a Mooer Reecho in my VOX AC30CC2 effects loop. Running the amp clean, it sounds great. However, I like to drive my amp into a mild overdrive, but my Reecho can not handle this. The pedal does not have enough headroom to cope with the volume boost. What can I do to drive my amp and use a delay pedal in the effects loop at the same time?
Comment: Does the AC30 have any level controls on the effects loop? This does sound like a product search question, which would be considered off-topic. Can you edit it to ask for solutions to your headroom problem general and remove the part about asking what pedals would help?
Comment: The AC30 has a -10dB/+4dB switch for the effects loop. I set it to -10dB. Thanks for your feedback. I've edited the question.
Answer: Simple answer - attenuate your signal before if gets to the delay. I know you mention a -10dB attenuation on the AC30, but if that isn't enough just get an volume/attenuators pedal and pop it in the chain before your delay.
If you are more electronically proficient, you could try to alter your effect loop attenuation, but that will not be easy, and will mean future effects may suffer, so my recommendation would be to buy a pedal.

Simple delay pedal with more headroom


Cleaner Implementation when passing Properties to Methods

Question: I am writing an csv import engine for a system I'm working on and I wanted to avoid the kind of code that looks like (repeated for 10's of columns):
var field = GetFieldStringValue(columnCode);
if (IsValidDecimal(field))
{
    currentRow.Amount = Decimal.Parse(field);
}
else
{
    ReportError();
}

In the end I opted for a method that looks like this (with overloads for various types):
    private void SetPropertyOrReportError(Action<decimal?> e, string columnCode)
    {
        if (IsValidDecimal(columnCode))
        {
            var fieldValue = Decimal.Parse(GetFieldStringValue(columnCode));
            e(fieldValue);
        }
        else if (!IsColumRequired(columnCode))
        {
            e(null);
        }
        else
        {
            SetPropertyOrReportError();
        }
    }

That way for each row I end up with code a bit like this:
var currentRow = new ClaimImportHelper();
SetPropertyOrReportError((e) => currentRow.ClaimantName = e, ClaimantNameColumnCode);
SetPropertyOrReportError((e) => currentRow.CustomerName = e, CustomerNameColumnCode);
SetPropertyOrReportError((e) => currentRow.CustomerProject = e, CustomerProjectColumnCode);
SetPropertyOrReportError((e) => currentRow.ClaimDate = e.Value, ClaimDateColumnCode);
SetPropertyOrReportError((e) => currentRow.ClaimSubmitted = e, ClaimSubmittedColumnCode);
SetPropertyOrReportError((e) => currentRow.ExpenseCategory = e, ExpenseCategoryColumnCode);
SetPropertyOrReportError((e) => currentRow.ExpenseType = e, ExpenseTypeColumnCode);
SetPropertyOrReportError((e) => currentRow.Amount = e.Value, AmountColumnCode);
SetPropertyOrReportError((e) => currentRow.PayeeReference = e, PayeeReferenceColumnCode);
SetPropertyOrReportError((e) => currentRow.Detail = e, DetailColumnCode);
SetPropertyOrReportError((e) => currentRow.TransactionDate = e, TransactionDateColumnCode);
parsedItems.Add(currentRow);

Which I think is better since it expresses its intent better. However, it's still not as I'd like it to be, I'd rather be able to call the method like this:
SetPropertyOrReportError(currentRow.ClaimantName, ClaimantNameColumnCode);
SetPropertyOrReportError(currentRow.CustomerName, CustomerNameColumnCode);
SetPropertyOrReportError(currentRow.CustomerProject, CustomerProjectColumnCode);
SetPropertyOrReportError(currentRow.ClaimDate, ClaimDateColumnCode);
SetPropertyOrReportError(currentRow.ClaimSubmitted, ClaimSubmittedColumnCode);

The problem I'm having is that I can't get my head around how to write an Expression that will take a property. How can I do this?
Answer: You can't, basically.
The expression currentRow.ClaimantName, when used as a method argument, will always represent the result of evaluating the getter for the property.
If we ever get the infoof operator, there might be a better approach - but for the moment, I think your lambda option is the best one. Note that you don't need the parentheses around the parameter though - for example:
SetPropertyOrReportError(e => currentRow.Detail = e, DetailColumnCode);


Loop through first row and if Cell Value = "Item Cost" then loop through that column and carry out subtotal in blanks

Question: Very new to VBA but have managed to learn a lot in the last few weeks and stitch together some code for a project at work.
I am struggling with a loop within a loop.
Essentially I want to find every column in Row 1 that has cell value of "Item Cost" then loop down through each row in that column and place a subtotal in the blanks.
Any help with a solution would be greatly appreciated.  It is part of a much larger project but I am at this sticking Point.
Code:
[VBA]
 Sub InsertTotals()

 Dim sh As Worksheet
 Dim rw As Range
 Dim RowCount As Integer

 RowCount = 0

 Set sh = ActiveSheet
 For Each rw In sh.Rows

 If sh.Cells(rw.Row, 1).Value = "Item Cost" Then

    Dim ThisCell As Range
    Dim MySum As Double

    Set ThisCell = rw.offset(-1)

nxt:

Do While ThisCell <> ""
    MySum = MySum + ThisCell
    Set ThisCell = ThisCell.offset(1, 0)
Loop

ThisCell.Value = MySum

If ThisCell.offset(1, 0) <> "" Then
    Set ThisCell = ThisCell.offset(1, 0)
    MySum = 0
    GoTo nxt
End If
End If

Next rw

End Sub

[VBA]
Comment: This code appears very inefficient to me for a simple task like that. You are essentially looping through your entire worksheet twice. How long does it take to execute a single run? You might be able to achieve your goal without VBA by using the SUBTOTAL() worksheet function
Answer: I've changed the way that the start and stop of the ranges to be subtotaled were collected. Additionally, every row has a subtotal at the bottom since there is likely an empty cell there.
Sub Insert_SubTotals()
    Dim sh As Worksheet
    Dim rw As Long, srw As Long, col As Long

    Set sh = ActiveSheet
    With sh
        For col = 1 To Cells(1, Columns.Count).End(xlToLeft).Column
            If .Cells(1, col) = "Item Cost" Then
                srw = 2
                For rw = 2 To .Cells(Rows.Count, col).End(xlUp).Row + 1
                    If IsEmpty(.Cells(rw, col)) And rw > srw Then
                        '.Cells(rw, col).Value = Application.Sum(.Range(.Cells(srw, col), .Cells(rw - 1, col)))
                        .Cells(rw, col).Formula = "=SUM(" & .Cells(srw, col).Address(0, 0) & _
                                    Chr(58) & .Cells(rw - 1, col).Address(0, 0) & ")"
                        .Cells(rw, col).NumberFormat = _
                          "[color5]_($* #,##0.00_);[color9]_($* (#,##0.00);[color15]_("" - ""_);[color10]_(@_)"
                        srw = rw + 1
                    End If
                Next rw
            End If
        Next col
    End With

    Set sh = Nothing
End Sub

I applied a blue Accounting style number format to distinguish the subtotals from the rest of the numbers. Modify that as you see fit. The subtotals remain as =SUM(...) formulas. I've added (and commented) a line that would simply leave the values just above the formula assignment.


creating new view in iPhone application

Question: i just finished my first view in my iPhone app and i want to add a second view to wich the user go when he click in the button in the first view. So i add new view from the librairy window, but i don't see the battery in the top, is that normal ? and how to add it please ??
Answer: Assuming you mean the status bar along the top you can try this code to make sure it is shown:
<code>[[UIApplication sharedApplication] setStatusBarHidden:NO];
</code>
or:
<code>[[UIApplication sharedApplication] setStatusBarHidden:NO animated:YES];
</code>
if you want to animate it coming down.
Cheers.
Comment: THX a lot, but please where should i put it ??
Comment: That's a little difficult to answer without seeing your code but putting it in either the init function of your 2nd view or, better yet, the ViewDidLoad or ViewWillAppear methods should do the trick.

creating new view in iPhone application


Fourier series convergence without sines or cosines converging

Question: Is it possible to have a Fourier series
$$a_0 + \sum_{k=1}^{\infty} \left[a_k\cos(kx) + b_k\sin(kx)\right]$$
converge without either the cosines or the sines converging?
Here is my work so far:
Since the series converges for all $x$, it has to converge when $x = \frac{\pi}{2}$. Then $\sum_{k=1}^{\infty}b_k$ converges.
But I don't know how to go on from here.
Comment: Could you check the value of the series for x = Pi / 2 ? I have the feeling that some a(k) will stay and that some b(k) will disappear.
Answer: Let
$$ f(x) = \lim_{n\to\infty} a_0 + \sum_{k=1}^n a_k \cos(kx) + b_k \sin(kx) .$$
Then we also have
$$ \frac12(f(x)+f(-x)) = \lim_{n\to\infty} a_0 + \sum_{k=1}^n a_k \cos(kx) ,$$
and
$$ \frac12(f(x)-f(-x)) = \lim_{n\to\infty} a_0 + \sum_{k=1}^n b_k \sin(kx) ,$$
This works no matter which kind of limit you use (e.g. pointwise, a.e., in $L^p$, etc).  You can even use different summation methods (e.g. Cesàro).


Is there a way to create a copy of an enum with some field values updated?

Question: I have an enum with several record variants:
enum A {
    Var1 { a: i64, b: i64 },
    Var2 { c: i32, d: i32 },
}

I want to create a modified copy of such an enum (with different behavior for each variant). I know I can do this:
match a {
    A::Var1 { a, b } => A::Var1 { a: new_a, b },
    A::Var2 { c, d } => A::Var2 { c, d: new_d },
}

However each variant has quite a few fields, and I'd prefer not to explicitly pass them all. Is there any way to say "clone this enum, except use this value for field x instead of the cloned value"?
Answer: Not exactly.
There's "functional record update syntax", but it's only for structs:
struct Foo {
    bar: u8,
    baz: u8,
    quux: u8,
}

fn foo() {
    let foobar = Foo {
        bar: 1,
        baz: 2,
        quux: 3,
    };
    let bazquux = Foo { baz: 4, ..foobar };
}

Best you can do without creating structs for each variant is something like this:
let mut altered = x.clone();
match &mut altered {
    A::Var1 { a, .. } => *a = new_a,
    A::Var2 { d, .. } => *d = new_d,
};
altered

Answer: I'm afraid you're hitting one of the restrictions on Rust based on its design and your only real solution is mutation in-place and writing a mutator function or four.
The problem with enums is that you need to match to be able to do anything on them. Until that point, Rust knows or infers very little about what the struct actually is. An additional problem is the lack of any kind of reflection-like ability to allow for the ability to query a type and figure out if it has a field, and the inability to do anything but exhaustively match all contents.
Honestly, the cleanest way may actually depend on the purpose of your mutations. Are they a defined set of changes to an enum based on a business concern of some sort? If so, you may actually want to wrap your logic into a trait extension and use that to encapsulate the logic.
Consider, for instance, a very contrived example. We're building an application that has to deal with different items and apply taxes to them. Said taxes depend on the type of products, and for some reason, all our products are represented by variants of an enum, like so:
    #[derive(Debug)]
    enum Item {
        Food { price: u8, calories: u8 },
        Technology { price: u8 },
    }
trait TaxExt {
    fn apply_tax(&mut self);
}
impl TaxExt for Item {
    fn apply_tax(&mut self) {
        match self {
            &mut Item::Food {
                ref mut price,
                calories: _,
            } => {
                // Our food costs double, for tax reasons
                *price *= 2;
            }
            &mut Item::Technology { ref mut price } => {
                // Technology has a 1 unit tax
                *price += 1;
            }
        }
    }
}

fn main() {
    let mut obj = Item::Food {
        price: 3,
        calories: 200,
    };
    obj.apply_tax();
    println!("{:?}", obj);
}

playground
Assuming you can split your logic like so, it is probably the cleanest way to structure this.


Drush does not work on my Mac

Question: I use MAMP on Mac.
When I try to use drush en omega command on drupal root directory to install omega, But the terminal throw me an error:
drupal-7.23 tangmonk $ drush en omega

Command pm-enable needs a higher bootstrap level to run - you will   [error]
need to invoke drush from a more functional Drupal environment to run
this command.

The drush command 'en omega' could not be executed.                  [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]

Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.

Drush was attempting to connect to:
 Drupal version         :  7.23
 Site URI               :  http://default
 Database driver        :  mysql
 Database username      :  root
 Database name          :  drupal
 Default theme          :  garland
 Administration theme   :  garland
 PHP executable         :  /usr/bin/php
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush version          :  7.0-dev
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/tangmonk/Sites/drupal/drupal-7.23
 Site path              :  sites/default
 File directory path    :  sites/default/files
     * connect the database through a socket. The socket file may be
    wrong or the php-cli may have no access to it in a jailed shell. See
    http://drupal.org/node/1428638 for details.

It seems mysql issue. But my site run perfect.
Comment: Either you're not running this in the web root, or the user you're running Drush with doesn't have read permissions on sites/[SITE]/settings.php
Comment: Are you sure you're running the command from /Users/tangmonk/Sites/drupal/drupal-7.23 and not /Users/tangmonk/Sites/drupal?
Comment: Are you sure you're currently in a Drupal directory?
Comment: @Ambidex, Thanks for your reply, Yes, I am run in a drupal directory.
Comment: @Clive, Yes, I am very sure.
Comment: (sorry in advance) how about using a Vagrant VM to run Drupal and avoid specific environmental issues like these. See this answer I wrote for a full guide to Vagrant on any platform - Mac, Windows, Linux, http://stackoverflow.com/a/15067918/227926 - it includes some out-of-the box ready made Drupal setups
Answer: I run drush command as MAMP Integrated PHP, It works!
I add alias command to my shell:
$ vim ~/.bash_profile
alias drush='/Applications/MAMP/bin/php/php5.5.3/bin/php /opt/drush/drush.php'

Comment: This worked for me, but note that your drush.php could be in a different location than indicated above. For example, mine is located at: ~/pear/share/pear/drush/drush.ph
Answer: This is what worked for me
sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

Changing to 127.0.0.1 in settings.php worked for quite a few too, but not for me.
Infact I had to make sure, it was localhost.
Comment: Thanks for your reply, I've found a better way: **run drush as MAMP Integrated PHP**
Answer: I solved this by adding this to my .bash_profile
export PATH=$PATH:/Applications/MAMP/Library/bin

See: http://www.webbykat.com/2012/06/solving-sh-mysql-command-not-found-mamp-pro-2
Before after running drush status -d I had:

sh: mysql: command not found.
Answer: I HAD the same problem. I think there may be different causes but in mycase
I run
drush status -d

and got
Bootstrap to phase 0. [0 sec, 1.88 MB]                               [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 2.01 MB] [bootstrap]
Cache MISS cid: 6.5.0-alias-path--895a900da5a848eb4b6977657b24c58f       [debug]
[0.01 sec, 2.01 MB]
Cache HIT cid: 6.5.0-commandfiles-0-82a4097a58b8537b29e63894fab2597c     [debug]
[0.01 sec, 2.03 MB]
Bootstrap to phase 0. [0.08 sec, 5.38 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.13 sec,    [bootstrap]
6.22 MB]
Initialized Drupal 7.34 root directory at                               [notice]
/opt/lampp/htdocs/fish-nn.dev [0.14 sec, 6.22 MB]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.14 sec,    [bootstrap]
6.23 MB]
Initialized Drupal site default at sites/default [0.14 sec, 6.23 MB]    [notice]
Cache HIT cid: 6.5.0-commandfiles-2-062e26fa8ebdd8c444d688ab9447c986     [debug]
[0.14 sec, 6.24 MB]
Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.14[bootstrap]
sec, 6.24 MB]
mysql extension for PHP PDO is not installed. Check your php.ini to  [bootstrap]
see how you can enable it. Proceeding with the mysql PDO extension.
[0.15 sec, 6.25 MB]
could not find driver [0.15 sec, 6.26 MB]                            [bootstrap]
Found command: core-status (commandfile=core) [0.15 sec, 6.25 MB]    [bootstrap]
Loading outputformat engine. [0.22 sec, 6.28 MB]                        [notice]
Calling hook drush_core_status [0.22 sec, 6.33 MB]                       [debug]
Returned from hook drush_core_status [0.22 sec, 6.34 MB]                 [debug]
 Drupal version         :  7.34
 Site URI               :  http://default
 Database driver        :  mysql
 Database username      :  root
 Database name          :  fishnn
 Default theme          :  garland
 Administration theme   :  garland
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush version          :  6.5.0
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /opt/lampp/htdocs/fish-nn.dev
 Site path              :  sites/default
 File directory path    :  sites/default/files

through all these lines I was interested by
mysql extension for PHP PDO is not installed. Check your php.ini to  [bootstrap]
see how you can enable it. Proceeding with the mysql PDO extension.
[0.15 sec, 6.25 MB]
could not find driver [0.15 sec, 6.26 MB]                            [bootstrap]

so I run
yum install php-pdo php-mysqli

And got the profit
Comment: Hi and welcome to Drupal Answers. I believe your answer is not applicable to the question's issue.
Answer: If you've already tried various methods for installing drush without success, such as Composer, Brew, etc., you may have collected some conflicting settings. Check your ~/.drush directory and bash profile files for files and settings left over from prior attempts.
Answer: I'm running Windows/Git Bash. For me, the issue was that mysql wasn't in the PATH.
St.Cremer's suggestion was actually helpful.
Running
drush status -d

got me a different error showing me that mysql wasn't recognized as an internal command.
So, if you haven't found a solution yet, chances are that this command might lead you to a solution like it did me.
Answer: I needed to add this to my ~/.profile file:
alias mysql='/Applications/MAMP/Library/bin/mysql'

Drush does not work on my Mac


For every odd $n \in \mathbb{N}$ prove that $\phi(n)$ is not equal $2^{32}$

Question: I have a question:
I proved that If $n \in \mathbb{N}$ is an odd number and $\phi(n)$ is a power of $2$ then $n$ is a product of distinct primes.
Now I need to prove that for every odd $n \in \mathbb{N}$ then  $\phi(n) \neq 2^{32}$.
Can someone give me an advice?
Comment: Euler showed that $2^{32}+1$ is not prime.
Comment: If an odd prime $p$ satisfies $\phi(p)$ is a power of $2,$ then $p$ is a [Fermat prime](https://en.wikipedia.org/wiki/Fermat_number). Then this should show that $\phi(n)\not=2^{32},$ as Fermat primes are not many.
Comment: See also: [Prove that there is no odd $n$ such that $\phi (n) = 2^{32}$](https://math.stackexchange.com/q/1537484)
Answer: Assume there is a number $n=p_1\times p_2\times ...\times p_k$ that $\phi(n) = 2^{32}$.
It is obvious that $\phi(n) = (p_1-1)\times(p_2-1)\times...\times(p_k-1)$, thus all $p_i$ must be one plus a power of 2.
If $p_i > 2^{32} + 1$, then $\phi(n) > 2^{32}$. Thus the values of $p_i$ can be only chosen in a finite set. Thus there is finitely many values of n to try.


Is C-7 chord associated with one of the three minor scales?

Question: I'm writing questions on index cards to help me study music theory.  Some of the questions I make up, including this one: "What minor scale is the jazz chord C–7 associated with?"
I believe the answer is: the Dorian mode of C major.  Hence, there is no minor scale associated with it.  So I'm posting here to confirm that this is correct.
Is it true that a minor chord isn't always associated with one of the three typical minor scales (namely: natural minor, harmonic minor or melodic minor)?
Comment: Doesn't the Dorian mode of C major contain all the notes of C major? Usually called D Dorian. Maybe it should be the Dorian mode of Bb?  It's the thorny one of C Dorian is *not* the same as the Dorian *of* C.
Answer: To your question, in almost all cases involving traditional jazz harmony, a minor chord will be associated with one of the minor scales. However, there are four (not three) minor scales, and dorian is generally considered to be one of them. The four types are:

dorian minor
aeolian minor
melodic minor
harmonic minor

You'll notice natural minor isn't in the list. That's because aeolian minor and natural minor are identical (they both use a ♭6 and a ♭7).
The chord Cmin7 or C–7 does not definitively pair with any one minor scale. When you see this chord, here are the candidate minor scales:

C dorian minor
C aeolian minor

C melodic minor and C harmonic minor are not strong candidates, because both of those scales contain a natural 7th, which would contrast with the flat 7th of C–7. To determine which of the two viable candidates to use (dorian or aeolian), look at the key of the song or at the neighboring chords. For example, if the C–7 chord is contained in this progression:
|  C–7  |  F7  |  BbMaj  |  BbMaj  |
then C dorian minor would be more appropriate than C aeolian. The progression above is a ii-V-I in BbMaj, and it's possible to play over this entire progression only using modes of BbMaj. (In particular, you would play C dorian minor, then F mixolydian, and then Bb ionian.) It would be unconventional to play C aeolian minor in this progression, because the Ab contained in C aeolian would likely clash with the A♮ you would in F mixolydian.
By contrast, consider the tune All the Things you Are, which contains this progression:
|  C–7  |  F–7  |  Bb7  |  EbMaj7  |
Here, it is more conventional to play C aeolian than C dorian over the first measure. The reason is that the C–7 is leading to F–7, which contains an Ab. C aeolian also contains an Ab, and so it will lead nicely into the second measure.
To summarize, there are four types of minor scales, and only two of them would be natural choices for a C–7 chord. Determining which of the two candidates requires an evaluation of surrounding chords and/or the key signature. These two things will tend to favor one of the candidate scales over the other. So the answer to your flashcard question is this: "the jazz chord C–7 is associated with either C dorian minor or C aeolian/natural minor."
Comment: What about Phrygian? With a minor third doesn't it qualify at all? In some sequences, most if not all the notes would work, wouldn't they? +1 again!


Matrix with distinct eigenvectors corresponding to eigenvalues.

Question: Preface: This is part of a university assignment.
I honestly have no idea what this question is asking me to do other than create a 3x3 matrix of sorts.
$\\$
Let $\displaystyle A=\left(\begin{matrix}1&-2 & 0 \\1&4 & 0 \\ 0 & 1 & 0\end{matrix}\right)$
$\\$
$\displaystyle \lambda_1 = 3,\hspace{5mm} \lambda_2 = 2,\hspace{5mm} \lambda_3 = 0$
$\displaystyle v_1 = (-3, 3, 1),\hspace{5mm} v_2 = (-4, 2, 1),\hspace{5mm} v_3 = (0, 0, 1)$
$\\$
Question:
Construct a matrix $P$ whose columns are three distinct eigenvectors corresponding to each distinct eigenvalue you found in the previous question. Find $P^{-1}$, and then verify that $P^{-1}AP$ is equal to a diagonal matrix $D$ having the eigenvalues of $A$ on its diagonal.
Answers in $\LaTeX$ are preferred
Answer: Check that $Av_i = \lambda_i v_i$ (most likely you have done so earlier).
What the question is asking to do is  let $P= \begin{bmatrix}v_1 & v_2 & v_3 \end{bmatrix}$.
After which compute $P^{-1}$ explicitly, possibly by computing RREF of $[\begin{array}{c|c} P & I\end{array}].$
Compute $P^{-1}AP$ explicitly by multiplying the matrices and see if it is equal to $diag({3,2,0})$
Comment: Thank you very much for your answer, I cannot express how appreciative I am for this!