multiple attribute form output

Question: i have had made a number of changes to the below program but am really stumped on my last task-  i need a multiple attribute to pull multiple 'teams' data (points,goal difference etc) with php form. i can get single teams to work but not multiple. see screen attached and heres my code below.
![enter image description here][1]

    <title>Table</title>

<?php

 if ($_SERVER["REQUEST_METHOD"] == "POST"  ){

    $tablesPage = "http://www.bbc.com/sport/football/tables";

    if(!empty($_POST["team"])){

        $teamData= getTeamData($_POST["team"] , $tablesPage); //get associative array of team data

        if(!empty($_POST["data"]) && $_POST["data"] == "results"){

            echo getResults($teamData);
        } else if(!empty($_POST["data"]) && $_POST["data"] == "position"){

            echo getPosition($teamData);

        } else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){

            echo getPoints($teamData);

        } else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){

            echo getDifference($teamData);

        }
    }
}

function getPosition($teamData){
    /*This function takes an array of team data and returns a string containing the name of the team and its position in the leauge */

    return  "Team ". $teamData["team"]  ." are currently number " . $teamData["position"] . "  in the league " ;
}

function getResults($teamData){
    /*This function takes an array of team data and returns a string containing the results of the team */

    return  $teamData["team"]  ." have won " . $teamData["won"] . " , drawn " . $teamData["drew"] . " , and lost " . $teamData["lost"] . "  games to date  " ;
}

function getPoints($teamData){
    /*This function takes an array of team data and returns a string containing the points and calculates the old two points system */
    $oldpoints = $teamData["won"] * 2 + $teamData["drew"];

    return  $teamData["team"]  ." have " . $teamData["points"] . " points under the current system " .  "
 Under two points for a win they would have " . $oldpoints ;
}

function getDifference($teamData){
    /*This function takes an array of team data and returns a string containing the name of the team and its goal difference in the leauge */

    return  $teamData["team"]  ." goal difference is " . $teamData["difference"] . " at the moment " ;
}

function getTeamData($team, $tablesPage){
    /* This function takes a webpage url and the name of a team as two string arguments. e.g. getTeam(""http://www.bbc.com/sport/football/tables", "liverpool")
    It returns an array of data about the team.

    You don't need to understand what this function does just that it returns an array which contains keya and values. The values map to the following keys:
    "position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points"

    */
    $html = new DOMDocument();
    @$html->loadHtmlFile($tablesPage); //use DOM
    @$xpath = new DOMXPath($html); //use XPath
    $items = $xpath->query('//td/a[text()="' . $team . '"]/../..'); //get the relevant table row
    $values[] =  array();
    foreach($items as $node){
        foreach($node->childNodes as $child) {
        if($child->nodeType == 1) array_push($values, $child->nodeValue); //KLUDGE
        }
    }
    $values[2]  = substr($values[2], -1); //KLUDGE
    $values = array_slice( $values, 2, count($values)-4); //KLUDGE
    $keys = array("position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points");
    return array_combine($keys, $values);
}

?>

Select a team and a data item about that team
<form  method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="team[]" multiple="multiple" size="3">
<option value=""></option>
  <option value="Everton">Everton</option>
  <option value="Arsenal">Arsenal</option>
  <option value="Chelsea">Chelsea</option>
  <option value="Man Utd">Man Utd</option>
  <option value="Liverpool">Liverpool</option>
</select>
<select name="data">
  <option value="position">position</option>
  <option value="results">results</option>
  <option value="two points for a win">two points for a win</option>
  <option value="goal difference">goal difference</option>
<select>
<input type="submit" value="Get Data"></input>
</select>
</form>

Comment: Just delete the lines that start /*debug */. Please remember to accept the answer if you like it :-)
Comment: Have removed the debug code from the answer.
Answer: Here is the code that you need to replace. I have left the 'debug' code in so you can see what is happening. just delete it when you are done.
Removed debug code.
Tested code: PHP 5.3.18 on windows xp.
<?php

 if ($_SERVER["REQUEST_METHOD"] == "POST"  ){

    $tablesPage = "http://www.bbc.com/sport/football/tables";

    if(!empty($_POST["team"])){

        // remember that the $_POST['team'] is an array of team names
        foreach($_POST['team'] as $currentTeam) {
            $teamData= getTeamData($currentTeam , $tablesPage); //get associative array of team data

            if(!empty($_POST["data"]) && $_POST["data"] == "results"){

                echo getResults($teamData);
            } else if(!empty($_POST["data"]) && $_POST["data"] == "position"){

                echo getPosition($teamData);

            } else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){

                echo getPoints($teamData);

            } else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){

                echo getDifference($teamData);

            }
            echo '
';
        } // end currentTeam
    }
}

Comment: brilliant ! i had taken a different path and it was driving me mad!how do i prevent the output at the start ie.

 array(3) { [0]=> string(7) "Arsenal" [1]=> string(7) "Chelsea" [2]=> string(7) "Man Utd" } Arsenal have won 19 , drawn 7 , and lost 7 games to date
Chelsea have won 22 , drawn 6 , and lost 5 games to date
Man Utd have won 17 , drawn 6 , and lost 10 games to date

multiple attribute form output


BB10 simulator magnify off

Question: In BB10 simulator, I clicked settings>accesibility>magnify. Then screen become larger. I closed the settings application.
Now again I opened settings application to off magnify(unmagnify). But it is not scrolling down to accessiblity. Please find the image here. So please let me know how to unmagnify this or else let me know how to wipe out the simulator data.
Answer: The simulator you're using is 10.0.10 which is fairly old. Try downloading the latest version of the simulator (10.3.0) here: https://developer.blackberry.com/devzone/develop/simulator/simulator_installing.html to see if that solves the issue.

BB10 simulator magnify off


How to merge two queries to make result like in picture?

Question: I have two queries, how to merge the query to make result like in picture?
Query 1:
SELECT id_realkinbel,GROUP_CONCAT(progres) AS label FROM realkinbel

Query 2:
SELECT progres, GROUP_CONCAT(CONCAT_WS(',', BTLKeu, BTLFis, BLKeu, BLFis) separator '|') AS data FROM realkinbel;

Answer: You can GROUP_CONCAT progress as well like this:
SELECT id_realkinbel,
    GROUP_CONCAT(CAST(progres AS CHAR)) AS label,
    GROUP_CONCAT(CONCAT_WS(',', BTLKeu, BTLFis, BLKeu, BLFis) separator '|') AS data
FROM realkinbel;

But it will be better if you use some column to GROUP BY. Otherwise it will group all rows and return a single row.


Drupal form disable form error message or use ajax validate instead of #require

Question: I have a complex form. Which will let users to select some drop-down items to add a food diary record.
Currently, I'm using this

if (!form_get_errors()) {.....}

to decide whether to insert new record to database or not. (in "function adddiary_form_submit($form, &$form_state)" area).
If a user did not select all fields correctly, I use this

"$commands = array();  $commands[]=ajax_command_alert('Please select all fields!');  return array('#type' => 'ajax', '#commands' => $commands);
          }"

to show a alert window to notified the user.
However, my problem is that the error message produce by Drupal will not show directly on the add record page (diary/add) because I use a ajax on submit button, and instead it show on the page I assign to redirect to (diary/list).

$form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
      '#executes_submit_callback' => FALSE,
      '#ajax' => array(
          'callback' => 'adddiary_form_submit',
           ),
      );

I'm not good at coding. I also try to use ajax validate but not working.
Do anyone know how to make the error message disable? or reset? or show directly in the current page instead of showing up when a record is already insert into database.(kind of strange right?)
Or how to use ajax? to check every select list is selected...
I have no idea how to make this work correctly.
I tried my best to describe the situation. If you still not clear, you may ask for detail.
Hope someone may help me with this, I've already look up information to achieve this form for a week.
Thanks@@~!
<?php

function adddiary_menu(){
    return array(
        'diary/add' => array(
            'title' => 'Add Diary',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('adddiary_page'),
            'access arguments' => array('access content'),
        )
    );
}

function adddiary_permission() {
  return array(
    'adddiary module' => array(
      'title' => t('Add diary module permission'),
  ));
}

function adddiary_page($form, &$form_state) {

    if (user_access('adddiary module')) {
    //Allowed

    $form['date'] = array(
    '#type' => 'date_popup',
    //'#title' => 'Date',
    '#default_value' => date('Y-m-d'),
    '#date_format' => 'Y-m-d',
    //'#date_label_position' => 'within',
    '#date_year_range' => '-0:+0',
    );

    $form['time'] = array(
    '#title' => t('Time'),
    '#type' => 'radios',
    '#options' => array(
        1 => t('Breakfast'),
        2 => t('Lunch'),
        3 => t('Dinner'),
       ),
    '#required' => TRUE,
    );

    $form['type'] = array(
    '#type' => 'select',
    '#title' => 'Food',
    '#options' => array(
        1 => t('Type1'),
        2 => t('Type2'),
        3 => t('Type3'),
        4 => t('Type4'),
        5 => t('Type5'),
        6 => t('Type6'),
       ),
    '#required' => TRUE,
    );

    //Type1
    $query1 = db_select('food_profile');
    $query1->fields('food_profile', array('ID', 'type','name'));
    $query1->condition('type', '1', '=');
    $query1->orderBy('name', 'ASC');
    $results1 = $query1->execute();

    $options1 = array();
    foreach ($results1 as $result1) {
    $options1[$result1->ID] = $result1->name;
    }

    $form['type1'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '1'),
        ),
    ),
    '#options' => $options1,
    );

    //Type2
    $query2 = db_select('food_profile');
    $query2->fields('food_profile', array('ID', 'type','name'));
    $query2->condition('type', '2', '=');
    $query2->orderBy('name', 'ASC');
    $results2 = $query2->execute();

    $options2 = array();
    foreach ($results2 as $result2) {
    $options2[$result2->ID] = $result2->name;
    }

    $form['type2'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '2'),
        ),
    ),
    '#options' => $options2,
    );

    //Type3
    $query3 = db_select('food_profile');
    $query3->fields('food_profile', array('ID', 'type','name'));
    $query3->condition('type', '3', '=');
    $query3->orderBy('name', 'ASC');
    $results3 = $query3->execute();

    $options3 = array();
    foreach ($results3 as $result3) {
    $options3[$result3->ID] = $result3->name;
    }

    $form['type3'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '3'),
        ),
    ),
    '#options' => $options3,
    );

    //Type4
    $query4 = db_select('food_profile');
    $query4->fields('food_profile', array('ID', 'type','name'));
    $query4->condition('type', '4', '=');
    $query4->orderBy('name', 'ASC');
    $results4 = $query4->execute();

    $options4 = array();
    foreach ($results4 as $result4) {
    $options4[$result4->ID] = $result4->name;
    }

    $form['type4'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '4'),
        ),
    ),
    '#options' => $options4,
    );

    //Type5
    $query5 = db_select('food_profile');
    $query5->fields('food_profile', array('ID', 'type','name'));
    $query5->condition('type', '5', '=');
    $query5->orderBy('name', 'ASC');
    $results5 = $query5->execute();

    $options5 = array();
    foreach ($results5 as $result5) {
    $options5[$result5->ID] = $result5->name;
    }

    $form['type5'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '5'),
        ),
    ),
    '#options' => $options5,
    );

    //Type6
    $query6 = db_select('food_profile');
    $query6->fields('food_profile', array('ID', 'type','name'));
    $query6->condition('type', '6', '=');
    $query6->orderBy('name', 'ASC');
    $results6 = $query6->execute();

    $options6 = array();
    foreach ($results6 as $result6) {
    $options6[$result6->ID] = $result6->name;
    }

    $form['type6'] = array(
    '#type' => 'select',
    '#states' => array(
        'visible' => array(
            ':input[name="type"]' => array('value' => '6'),
        ),
    ),
    '#options' => $options6,
    );

    $form['portion'] = array(
    '#title' => t('Portion'),
    '#type' => 'select',
    '#options' => array(
        1 => t('1'),
        2 => t('2'),
        3 => t('3'),
        4 => t('4'),
        5 => t('5'),
       ),
    '#required' => TRUE,
    );

    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#executes_submit_callback' => FALSE,
    '#ajax' => array(
        'callback' => 'adddiary_form_submit',
         ),
    );

    return $form;
    } else {
    //Access denied
    drupal_goto("user/login");
  }
}

function adddiary_form_validate($form, &$form_state) {

}

function adddiary_form_submit($form, &$form_state) {
    if (!form_get_errors()) {
    $food_ID = form_result_helper($form_state);

    $result = db_query('SELECT name, calorie, protein, fat, fat_1, fat_2, fat_3, cho, cho_1, cho_2, mineral, mineral_1, mineral_2, mineral_3, mineral_4 FROM {food_profile} n WHERE ID = :food_ID', array(':food_ID' => $food_ID));
    foreach($result as $item) {
        $name = $item->name;
        $calorie = $item->calorie;
        $protein = $item->protein;
        $fat = $item->fat;
        $fat_1 = $item->fat_1;
        $fat_2 = $item->fat_2;
        $fat_3 = $item->fat_3;
        $cho = $item->cho;
        $cho_1 = $item->cho_1;
        $cho_2 = $item->cho_2;
        $mineral = $item->mineral;
        $mineral_1 = $item->mineral_1;
        $mineral_2 = $item->mineral_2;
        $mineral_3 = $item->mineral_3;
        $mineral_4 = $item->mineral_4;
    }

    global $user;
    $timestamp = strtotime($form_state['values']['date']);
    $query = db_insert('food_diary')
    ->fields(array(
      'user' => $user->name,
      'uid' => $user->uid,
      'date' => $timestamp,
      'time' => $form_state['values']['time'],
      'type' => $form_state['values']['type'],
      'food_ID' => $food_ID,
      'portion' => $form_state['values']['portion'],
      'food' => $name,
      'calorie' => $calorie,
      'protein' => $protein,
      'fat' => $fat,
      'fat_1' => $fat_1,
      'fat_2' => $fat_2,
      'fat_3' => $fat_3,
      'cho' => $cho,
      'cho_1' => $cho_1,
      'cho_2' => $cho_2,
      'mineral' => $mineral,
      'mineral_1' => $mineral_1,
      'mineral_2' => $mineral_2,
      'mineral_3' => $mineral_3,
      'mineral_4' => $mineral_4,
    ))
    ->execute();

    drupal_set_message(t('Record Added!!!!'));

    //redirect to particular page
    ctools_include('ajax');
    $commands[] = ctools_ajax_command_redirect('diary/list');
    return array('#type' => 'ajax', '#commands' => $commands);
    }
    else {
    $commands = array();
    $commands[]=ajax_command_alert('Please select all fields!');
    return array('#type' => 'ajax', '#commands' => $commands);
    }
}

function form_result_helper($form_state) {
  $type_name = $form_state['values']['type'];
  $food_ID = t('No food Selected');
  $food = '';
  switch ($type_name) {
    case 1 :
       $food = $form_state['values']['type1'];
       $food_ID = $form_state['values']['type1'];
    break;
    case 2 :
        $food = $form_state['values']['type2'];
        $food_ID = $form_state['values']['type2'];
    break;
    case 3 :
        $food = $form_state['values']['type3'];
        $food_ID = $form_state['values']['type3'];
    break;
    case 4 :
        $food = $form_state['values']['type4'];
        $food_ID = $form_state['values']['type4'];
    break;
    case 5 :
        $food = $form_state['values']['type5'];
        $food_ID = $form_state['values']['type5'];
    break;
    case 6 :
        $food = $form_state['values']['type6'];
        $food_ID = $form_state['values']['type6'];
    break;
  }
  return $food_ID;
}

Answer: So your issue is about displaying the system message on the page when an ajax submit is triggered right? So based on Ajax framework, you need to add the ff. to your $commands array like so:
$commands[] = ajax_command_prepend(NULL, theme('status_messages'));

Hope it works for you.
EDITED
I investigated more and found noticed that the form AJAX callbacks needs to return the whole form or a part of that form that needs to be updated and I remembered that when forms are submitted using AJAX, it displays the error and/or success messages inside the form because the form itself is the one being rebuilt. This is a simple example:
/**
 * Form adddiary_addform.
 */
function adddiary_addform($form, &$form_state) {
  // This wraps the form and will be the target for the submit callback.
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  $form['text'] = array(
    '#type' => 'textfield',
    '#title' => t('Text'),
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => '_adddiary_addform_submit_callback',
      // This targets the
 and it's contents.
      'wrapper' => 'box',
    ),
    '#value' => t('Submit'),
  );

  return $form;
}

/**
 * Form validation for adddiary_addform.
 */
function adddiary_addform_validate($form, &$form_state) {
  if ($form_state['values']['text'] != 'leo') {
    form_set_error('text', t('It\'s supposed to be leo.'));
  }
}

/**
 * Form submit for adddiary_addform.
 */
function adddiary_addform_submit($form, &$form_state) {
  drupal_set_message('normal form submitted');
  // This will fire if JS is not enabled in the browser.
  // Just might come in handy but you can of course improve it.
  $form_state['redirect'] = 'node';
}

/**
 * Form submit callback for adddiary_addform.
 */
function _adddiary_addform_submit_callback($form, &$form_state) {
  if ($errors = form_get_errors()) {
    // We return the whole form so that the message from form_set_error or
    // drupal_set_message will be included in the form's AJAX content updating.
    return $form;
  }
  else {
    // If we have no errors, then we can redirect now to whatever page you want.
    ctools_include('ajax');
    ctools_add_js('ajax-responder');
    $commands[] = ctools_ajax_command_redirect('node');
    print ajax_render($commands);
    exit;
  }
}

Sorry for another edit again, I updated the ff. functions: adddiary_addform_submit and _adddiary_addform_submit_callback. Please take a look again. I think this would fit your needs now.
Comment: Hello! Thank you! Yeah, I want it to display~ I add this line to $commands array and the message still not show up... But it won't show on the redirect page too. So it's work I think! Thank you again^^!
Comment: Hi! I added additional information cause I was really interested on the issue and it bugged me since I wasn't working with AJAX submitted forms for a while. Now, with the example I added all your validations and form success redirects can be placed inside the normal form submit function.
Comment: Sorry I had another update to complete the functionality where you'll be redirected to another page after a successful form submission w/c also displays the message. Hope it's all going good on your end. :)
Comment: Hello Leo! Wow!!! Amazing! The error message shows now! Then I don't have to use the annoying alert window! Thank you again! It's very kind of you^^
Comment: Good day Weldon! That's awesome! You're very welcome! :)


Como passar o id para a função de exclusão

Question: Estou criando uma to-do list, consigo criar os campos com as tarefas, e os elementos com javascript, porém quando clico no botão de fechar, o único campo que desaparece é o último. Eu coloco os elementos criados em um array em forma de objeto e atribuo um valor a cada array criado, mas não consigo passar esse valor pra função de exclusão de forma que o botão exclua todo o campo. O que posso fazer?

var myNodelist = document.getElementsByTagName("LI");
var index = 0;
var array = [];

for (var i = 0; i < myNodelist.length; i++) {
  var span = document.createElement("SPAN");
  var txt = document.createElement("button");
  var xis = document.createTextNode("\u00D7");

  span.appendChild(txt);
  txt.appendChild(xis);
  txt.className = "close";
  myNodelist[i].appendChild(txt);

}

var close = document.getElementsByClassName("close");
for (var i = 0; i < close.length; i++) {
  close[i].onclick = function() {
    var div = this.parentElement;
    div.style.display = "none";
  }
}

function newElement() {

  var li = document.createElement("input");
  var ul = document.createElement("input");
  var done = document.createElement("input");
  done.setAttribute("type", "checkbox");
  var inputText = document.getElementById("myInput").value;
  var inputDate = document.getElementById("time").value;

  done.className = "checkIn";
  li.value = inputText;
  li.className = "valor";
  ul.value = inputDate;
  ul.className = "data";

  var span = document.createElement("SPAN");
  var txt = document.createElement("button");
  var xis = document.createTextNode("\u00D7");

  span.appendChild(txt);
  txt.appendChild(xis);
  txt.className = "close";

  if (inputText === '') {
    alert("Você precisa digitar algo primeiro!");
  } else {
    document.getElementById("recent").appendChild(done).style.width = "20px";
    document.getElementById("recent").appendChild(li);
    document.getElementById("recent").appendChild(ul).style.width = "90px";
    document.getElementById("recent").appendChild(span);

  }

  array.push({
    inputtexto: li,
    inputdata: ul,
    close: txt
  })
  index++;

  for (var i = 0; i < close.length; i++) {
    close[i].onclick = function() {
      var div = this.parentNode;
      div.style.display = "none";
      done.style.display = "none";
      li.style.display = "none";
      ul.style.display = "none";
    }
  }
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

  <form method="POST" action="">
    Título:
    <input type="text" id="myInput" name="titulo">
    Prazo:
    <input type="date" id="time" name="data" />

    Add
  </form>

Comment: Tem vários problemas no código, sendo um dos mais diretos este `close.lenght` em que `length` tá mal escrito. A ideia de criar os nós todos à mão é para aprender? Porque essa criação de html fica muito mais simples criando uma string com o novo html e alterando diretamente com `innerHTML`. O `for (var i...) { close[i] =function(){..` tem também um problema de closures
Comment: lenght corrigido. Sim, ainda estou aprendendo por isso prefiro fazer tudo à mão e com javascript puro.Agradeço se você puder me ajudar.
Answer: O correto é você criar um container (ou wrapper) (uma div ou um span, por exemplo) para cada item adicionado. Da forma que está fazendo, os elementos ficam sem uma referência própria. Veja abaixo a estrutura de como ficam os item adicionados:

  checkbox
  input texto
  input datepicker

    botao X

  checkbox
  input texto
  input datepicker

    botao X

Veja que os itens, que deveriam pertencer a um mesmo grupo, possuem como referência comum apenas a div-pai id="recent", tornando o trabalho complicado, pois fico sem poder selecionar os elementos-filhos que eu quero.
Como mencionado, crie uma div para agrupar os elementos, ficando assim:

    checkbox
    input texto
    input datepicker

      botao X

    checkbox
    input texto
    input datepicker

      botao X

Fiz as alterações comentadas na função abaixo:
function newElement() {
  var li = document.createElement("input");
  var ul = document.createElement("input");
  var done = document.createElement("input");
  var lista = document.createElement("div"); // criar uma div para agrupar os itens
  lista.setAttribute("class", "itens"); // atribuí uma classe à div
  done.setAttribute("type", "checkbox");
  var inputText = document.getElementById("myInput").value;
  var inputDate = document.getElementById("time").value;

  done.className = "checkIn";
  li.value = inputText;
  li.className = "valor";
  ul.value = inputDate;
  ul.className = "data";

  var span = document.createElement("SPAN");
  var txt = document.createElement("button");
  var xis = document.createTextNode("\u00D7");

  span.appendChild(txt);
  txt.appendChild(xis);
  txt.className = "close";

  if (inputText === '') {
    alert("Você precisa digitar algo primeiro!");
  } else {
    document.getElementById("recent").appendChild(lista); // adiciono a div à div-pai
    ultimo_item = document.getElementsByClassName("itens").length-1; // conto quantas divs possui e subtraio por 1 para pegar o index, que começa com 0
    document.getElementsByClassName("itens")[ultimo_item].appendChild(done).style.width = "20px"; // daqui pra baixo eu adiciono os elementos dentro da div
    document.getElementsByClassName("itens")[ultimo_item].appendChild(li);
    document.getElementsByClassName("itens")[ultimo_item].appendChild(ul).style.width = "90px";
    document.getElementsByClassName("itens")[ultimo_item].appendChild(span);

  }

  array.push({
    inputtexto: li,
    inputdata: ul,
    close: txt
  })
  index++;

  for (var i = 0; i < close.length; i++) {
    close[i].onclick = function() {
      var div = this.parentNode.parentNode; // seleciono o avô do span que oculta o item
      div.style.display = "none"; // oculto a div
    }
  }
}

Comment: Obrigada pela resposta
Comment: @JessicaKeilla De nada! Obg!
Answer:
O problema de maior, assim como o @DvD já tinha dito é mesmo o fato de faltar um elemento html para englobar cada nova linha que é inserida, pois os campos são inseridos de forma seguida, acabando por não ter nenhum elemento pai que os agrupe. Isso dificulta a ação de esconder.
O código que tem inicialmente antes da função newElement não é necessário pois tenta adicionar elementos com base na quantidade de
 do documento, mas não ha nenhum.
Cada vez que adiciona um novo elemento ao html não precisa de um for para atribuir todas as funções de click dos closes, mas sim apenas a do elemento que foi adicionado.
Tem um problema de closures em:
 for (var i = 0; i < close.length; i++) {
     close[i].onclick = function() {

Porque o i vai acabar por não ter escopo do for e todos os closes irão referir o ultimo i. Considere o seguinte exemplo verificável do problema:

const spans = document.querySelectorAll(".s");

for (var i = 0; i < spans.length; ++i){
  spans[i].onclick = function(){
    console.log("click no span numero " + i);
  }
}
Clique nos números que se seguem:
1
2
3
4
5

Aqui vê claramente que o i não tem escopo do for e acaba sendo o mesmo para todos os elementos. Para além disso fica no valor em que saiu do for que é 5 e so temos spans de 0 a 4.
Neste momento uma das formas mais simples de resolver este problema é declarando o i com let que garante o escopo do for e faz com que o closure funcione como esperado:

const spans = document.querySelectorAll(".s");

for (let i = 0; i < spans.length; ++i){
  spans[i].onclick = function(){
    console.log("click no span numero " + i);
  }
}
Clique nos números que se seguem:
1
2
3
4
5

Acertando esses pormenores o seu código ficaria assim:

var index = 0;
var array = [];

//obter o elemento do html apenas uma vez
const recent = document.getElementById("recent");

function newElement() {
  var li = document.createElement("input");
  var ul = document.createElement("input");
  var done = document.createElement("input");
  done.setAttribute("type", "checkbox");
  var inputText = document.getElementById("myInput").value;
  var inputDate = document.getElementById("time").value;

  done.className = "checkIn";
  li.value = inputText;
  li.className = "valor";
  ul.value = inputDate;
  ul.className = "data";

  var span = document.createElement("SPAN");
  var txt = document.createElement("button");
  var xis = document.createTextNode("\u00D7");
  var newdiv = document.createElement("div");

  span.appendChild(txt);
  txt.appendChild(xis);
  txt.className = "close";

  if (inputText === '') {
    alert("Você precisa digitar algo primeiro!");
  } else {
    //todos os elementos são adicionados ao novo div que os agrupa
    newdiv.appendChild(done).style.width = "20px";
    newdiv.appendChild(li);
    newdiv.appendChild(ul).style.width = "90px";
    newdiv.appendChild(span);
    recent.appendChild(newdiv); //novo div adicionado ao recent
  }

  array.push({
    inputtexto: li,
    inputdata: ul,
    close: txt
  });
  index++;

  //clique do close apenas definido para o elemento adicionado
  txt.onclick = function() {
      this.parentNode.parentNode.style.display="none";
  }
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

  <form method="POST" action="">
    Título:
    <input type="text" id="myInput" name="titulo">
    Prazo:
    <input type="date" id="time" name="data" />

    Add
  </form>

No entanto, e assim como tinha já dito em comentários, a construção de novo html fica muito mais simplificada com strings. Estas strings guardam toda a estrutura html a adicionar já com atributos e classes, e é aplicada diretamente no innerHTML.
Exemplo com strings e innerHTML:

const inputText = document.getElementById("myInput");
const inputDate = document.getElementById("time");
const recent = document.getElementById("recent");

function newElement() {
  if (inputText.value === '') {
    alert("Você precisa digitar algo primeiro!");
    return;
  }

  let newHtml = `

                   <input type="checkbox" class="checkIn" style="width:20px;">
                   <input type="text" value="${inputText.value}">
                   <input type="text" value="${inputDate.value}" style="width:90px;">
                   <button class="close">\u00D7</button>

`;
   recent.innerHTML += newHtml;

   for (let l of document.querySelectorAll(".linha .close")){
      l.onclick = function() {
        this.parentNode.parentNode.style.display="none";
      }
   }
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

  <form method="POST" action="">
    Título:
    <input type="text" id="myInput" name="titulo">
    Prazo:
    <input type="date" id="time" name="data" />

    Add
  </form>

Neste ultimo caso como o innerHTML é aplicado diretamente no
 torna-se necessário voltar a aplicar os eventos de close a todas as linhas.
Comment: Obrigada por responder e pela matéria do link, pois, foi muito esclarecedora.


Difference in seconds between two TDateTime variables

Question: Looking for a code sample that returns the difference in seconds between two TDateTime values.    Specifically, I am trying to compare two TDateTime values and if greater than a second threshold it will run a specific method.
Thanks!
Answer: Try the SecondsBetween function which is part of the DateUtils unit.
Sample of use
SecondsBetween(Now, IncSecond(Now,10))

Will return 10
Comment: As an interesting aside, the function may return something other than 10 since Now is called twice!
Answer: Call SecondsBetween from the DateUtils unit. For example:
Assert(SecondsBetween(MyAnswer, RRUZsAnswer)=7)

Comment: Probably the former
Comment: Were you guys continuously refreshing the question list? Or did you have software tracking?


Metric space equivalence

Question: Let $(X,d)$ be a metric space.
$$\exists c \quad \exists x\in X \quad \forall y\in X : d(x,y) \lt c \Longleftrightarrow \exists c \quad \forall x\in X \quad \forall y\in X : d(x,y) \lt c$$
I really have problems showing $"\Rightarrow"$
Answer: Note that the $c$'s on both sides don't have to be the same. Thus, suppose the first statement holds. Then let $C = 2c$. Now let $y,z\in X$ be arbitrary. Then we have $$d(y,z) \leq d(x,y)+d(x,z) < c+c = C$$
Comment: Thats so simple but brilliant. Thank you!

Metric space equivalence


I want a new line to be made with number when using word wrap in vs code

Question: vs code
I am using word wrap to break large lines, but i want to make a new line number instead of using the same number for many lines because when i am trying to move the cursor with arrows, when is on the same line it goes even further. If you see the picture i want to goes as:lines 19,20,21
Comment: add new line characters where appropriate
Comment: Line wraping doesn't work like that. Its an editor feature, not a formatting tool, in other words; the VS Code feature **"word-wrap"** will not do what you are asking for. Don't get all hot and bothered yet though, not all is lost, there are plenty of tools out there that can break lines for you. These tools are called code formatting tools. I could recomend one, however; you failed to include the language that you are writing. They are not hard to find though, most languages have 1 or 2 that are much more popular than others.
Answer: VSCode word wrap only changes the way your code is being displayed, not the actual file content.
If you want to format the code into several lines, your best solution would be to use a code formatter. HTML formatting is supported out of the box in VSCode.
To do this, in your settings.json (Ctrl + P and type >Preferences: Open Settings (JSON) in the command palette) add "html.format.wrapAttributes": "force-aligned", after which go back into your .html file and select Format Document in the right click menu.
Answer: before i click enter
Thank your for your response, the truth is that your advices helped me a lot and 90% works. Sometimes it does not,  i uploaded the picture just to show you why and i am not requesting an answer. On the image if i click enter and break the line 119 everything works great.
Thank you
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Construction of sequence from convergent susbsequences

Question: Is it possible to construct the following?

A sequence that contains subsequences converging to every point in the infinite set $\{{1, 1/2, 1/3, 1/4, 1/5, ...}\}$ and no subsequences converging to points outside of this set.
Answer: No: if there are subsequences converging to $\frac1n$ for each $n\in\Bbb Z^+$, there will necessarily be a subsequence converging to $0$. It is possible to make $\{0\}\cup\left\{\frac1n:n\in\Bbb Z^+\right\}$ the set of limits of convergent subsequences, however. For instance, you can use the sequence
$$\left\langle 1,1,\frac12,1,\frac12,\frac13,1,\frac12,\frac13,\frac14,1,\ldots\right\rangle\;.$$


How do I fix the errors I get after removing the comment field from a content type?

Question: After I removed the comment field from the user interface, and uninstalled the Comments module, I can't open any Article node.
In the Drupal log, I find this message.

InvalidArgumentException: Field comment is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 580 of core/lib/Drupal/Core/Entity/ContentEntityBase.php).
  Drupal\Core\Entity\ContentEntityBase->get("comment") (Line: 17)
  gavias_sanbro_preprocess_node(Array, "node", Array) (Line: 287)
  Drupal\Core\Theme\ThemeManager->render("node", Array) (Line: 437)
  Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
  Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
  Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent{closure}() (Line: 582)
  Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
  Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object,
  Object) (Line: 117)
  Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
  Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, "kernel.view", Object)
  call_user_func(Array, Object, "kernel.view", Object) (Line: 111)
  Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch("kernel.view", Object) (Line: 156)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
  Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
  Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
  Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
  Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 657)
  Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

How can I fix this issue?
Comment: This is the error from apache webserver :  Uncaught PHP Exception InvalidArgumentException: "Field comment is unknown." at /var/www/eierc/core/lib/Drupal/Core/Entity/ContentEntityBase.php line 580
Comment: Drupal log message after i enabled verbose: https://pastebin.com/s3wPwhYx
Comment: Please always add such information to your question instead of pasting it into the comments. This will help others to suggest steps to perform for solving your issue.
Answer: Given your error stacktrace:
Check function gavias_sanbro_preprocess_node() (Line: 287 in your gavias_sanbro.theme theme file).
This preprocessing function obviously tries to access the comment field without checking, whether it exists. As you uninstalled the field, it is causing your exception.
You may comment out, remove, or alter the code accordingly.


How to find the equation of a normal line when the slope of the tangent is equal to zero?

Question: given : $x^2+6x+2y-8=0$ at $x = 3$
$y = \frac{17}{2}$
$y' = 0 = m_T$
I was able to find the equation of the tangent line which is $y=\frac{17}{2}$ by using the point-slope formula however, when finding $m_N$ (slope of the normal line), I would get an indeterminate.
$m_T ( m_N )= -1$
$m_N = -\frac{1}{0} $
thus, gives me : $y - \frac{17}{2} = -\frac{1}{0}(x-3)$
how do I solve this equation?
I know that the equation of the normal line is $x=3$, which I found by graphing, however I just wanted to know if I can show my solution through an equation.
am I not breaking any rules by doing this?  $-0(y-\frac{17}{2})=1(x-3)$
Answer: HINT
The equation for a vertical line is in the form $$x=k$$
More in general, to avoid indeterminate form, note that the line equation in implicit form is $ax+by=c$ and the condition for the line to be normal with the line $dx+ey=f$ is given by
$$ad+be=0$$
Answer: Recall that the normal line must be perpendicular to the tangent line and they both meet at the point of your curve (namely where $x=3$ in this particular case). In this situation, your tangent line is horizontal and therefore the normal line must be a vertical line since it has to be perpendicular to your tangent line. Vertical lines have the form
$$x=k$$
for some $k$. In your case, the normal line must pass by the point $\left(3,\frac{17}2\right),$ thus have equation $x=3$.
The method that you outline above works for most situations. In fact, it works as long as your tangent line is not vertical or horizontal. The reason why it fails in that situation is that the normal line is not a function of $y$ in terms of $x$. As you can see from the graph, for $x=3$, your normal line has infinitely $y$ values. But this will be the case whenever your derivative at a point is $0$. In that case, you know that the  normal line must be of the form $x=k$ by the argument above.
Answer: It looks there is an error in calculation. The function is
$$y=-\frac12x^2-3x+4, y(3)=-9.5.$$
The slope of tangent at $x=3$ is
$$m_T=y'(3)=-3-3=-6.$$
The slope of normal (perpendicular to tangent) is
$$m_N=-\frac{1}{m_T}=\frac16.$$
The equation of normal passing through $(3,-9.5)$ is
$$-9.5=\frac{1}{6}\cdot 3+b \Rightarrow b=-10 \Rightarrow y_N=\frac16x-10.$$


Clarinet low e quite sharp

Question: I've got a Bb clarinet (german buffet e11), which plays well and appears to have the typical tuning issues clarinets have on different notes - except that my low E (and the corresponding B) is very sharp. Perhaps my searching skills are lacking, but the only information that comes up is either about the actual E-flat key (presumably on a bass clarinet) or people's low E being too flat.
If I leave the bell hanging on by a sliver of cork and blow too hard, then the pitch is almost in tune with the rest of the instrument. Playing normally, even with the bell pulled out as much as possible, leaves the note painfully out of tune.
What, if anything, (I'm imagining aftermarket bells or maybe barrel extenders) can be done to lower the pitch of a low E?
Answer: First: make absolutely sure it's out of tune. This requires playing while NOT looking at a tuner, and letting someone else observe the pitches of, say, C down to the bottom E.
If in fact it's only the E, then at least you know that changing the barrel or adjusting any hole diameter will be useless.  I've done a brief search thru online stores & it doesn't appear that anyone makes a Bb bell extension (tho' there's plenty for the Eb soprano).  I'd take your axe to someone who's experienced w/ clarinet repair and see if they can swap in a different bell (more likely a different bore than a different length) to improve the pitch accuracy.
Comment: I did so, and it is indeed only the E. I'm not currently nearby anyone who does clarinet repair, but I will keep it in mind for later. Accepting this , since I guess explaining how a solution doesn't  (currently) exist is a solution itself.
Comment: Just for "fun,"  try lining the inside of the bell (use painter's tape or something similar that's easy to remove) to decrease the bore and see if that makes any difference at all.
Answer: Are you sure the low E key pad or the bell joint are not leaking?  I can't think of any other reason for this problem, unless the instrument was made wrong, which doesn't seem likely.  Get someone to press the E pad down while you play and check it out.

Clarinet low e quite sharp


Angularjs ui bootstrap - put html inside popover

Question: I'm using official angular bootstrap directives .
I want to use of of it's popovers .
In the documentation it says that if you want to insert html inside the popover you should use popover-html, like bellow :
     <button popover-html="{{getTag()}}" type="button" class="btn btn-default">Dynamic Popover</button>
     <button popover-html="Just fucin show me !" type="button" class="btn btn-default">Click me </button>

But this will raise the following console error :

Error: [$parse:syntax] Syntax Error: Token '<' not a primary expression at column 1 of the expression [sdfsdfsdf] starting at [sdfsdfsdf].
  http://errors.angularjs.org/1.4.3/$parse/syntax?p0=%3C&p1=not%20a%20primary%20expression&p2=1&p3=%3Ca%3Esdfsdfsdf%3C%2Fa%3E&p4=%3Ca%3Esdfsdfsdf%3C%2Fa%3E

You can see the plunker
Thanks
Answer: Just remove the brackets and the $compile function:
HTML:
<button popover-html="getTag()" type="button" class="btn btn-default">Dynamic Popover</button>

JS:
$scope.getTag = function(){
   return 'sdfsdfsdf';
}


Some Laravel Anonymous Component Props always use default values

Question: I have an anonymous component layout.blade.php that has the following props and how they are used, some meta tags have been removed for brevity:
@props([
    'meta' => [
        'title' => 'Some title',
        'description' => 'Some description',
        'url' => 'https://somesite.com',
        'image' => 'images/banner.png',
    ],
    'robots' => 'index, follow',
    'keywords' => 'some, comma, separated, keywords'
])

<!DOCTYPE html>

        <meta name="description" content="{{ $meta['description'] }}">
        <meta name="robots" content="{{ $robots }}" />
        <meta name="keywords" content="{{ $keywords }}" />

        <meta property="og:type" content="website" />
        <meta property="og:title" content="{{ $meta['title'] }}"/>
        <meta property="og:description" content="{{ $meta['description'] }}" />
        <meta property="og:url" content="{{ $meta['url'] }}" />
        <meta property="og:image" content="{{asset($meta['image'])}}" />

        <meta property="twitter:title" content="{{ $meta['title'] }}" />
        <meta property="twitter:description" content="{{ $meta['description'] }}" />

        <link rel="canonical" href="{{ $meta['url'] }}"/>
        <title>{{ $meta['title'] }}</title>

Whenever I pass data via a controller e.g.:
return(view('plans.index', [
    'plans' => auth()->user()->plans()->get(),
    'robots' => 'noindex'
]));

The meta prop will always resolve to the correct values passed, whether that is default or something I provide.
In the case of robots and keywords they always are the defaults provided. I can't find any documentation that explains this behaviour and can't see where I am going wrong.
EDIT:
An example of how the layout is being called is below:
<x-layout>
    @section('content')

        @include('partials.hero')

        @include('partials.explainer')

        @include('partials.form')

    @endsection
</x-layout>

Comment: Can you show us how you call to layout? you might not passing the parameters correctly
Comment: Added an example to the question
Answer: As the documentation says, You should PASS the variables you want to the anonymous component, so you should call your layout component as so:
<x-layout :robots="$robots" :keywords="$keywords">

data-properties-attributes
Comment: Thanks, but how can I make it conditional so if that variable is not passed to the view then it won't fail? Why does the $meta tag work exactly as intended?
Comment: You should use the `@props` directive as you use in your question, it can have a default values but it can be overwriten if you pass other values. about the meta variable, I can't examine it without see your all code, you might register it as global variable in one of your service providers or you are doing something different, You can try what I suggested and open a new question for the meta variable beahvior
Comment: Thanks for the help. I think it would be better for me to use a class based component as that can handle optional attributes better.


Regex detecting global variables in PHP

Question: I am trying to write a regex that in the example below would only match with $session = $_POST['session'];
Line #1: if (isset($_POST['session'])) {$session = $_POST['session'];}
Line #2: $session = $_POST['session'];

The following regex works correctly only with the second line:
(\$.)=.(\$_POST.*);
On the first line this regex does match with
$_POST['session'])) {$session = $_POST['session'];

Answer: I imagine your regex actually had a .* instead of just .
(\$.*)=.(\$_POST.*);
    ^

.*s are generally pretty dangerous (in terms of over matching) since they match anything, and as much as they can. From a quick google I see that

A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

So I'd advise restricting the match to at most a combination of letters, numbers and underscores (conveniently all covered by \w). I'd then recommend changing the second .* to only match characters up to the next ; using [^;]+ to avoid overmatching of the tail end of the expression, and also instead of using . to match spaces, explicitly match whitespace with \s*. Leaving you with:
(\$\w+)\s*=\s*(\$_POST[^;]+);

RegExr Example
Answer: You can try with:
(\$[^$= ]*) ?= ?(\$_POST\[[^]]*\])

Comment: agree this might be all OP wants, but if you remove the whitespace before the `{` in line 1 this would still match incorrectly
Comment: @OGHaza Thanks, I've edited my answer with also `$_POST` improvement.

Regex detecting global variables in PHP


Issue for a "two dimentionnal 'add another item' " with FormStateInterface::getTriggeringElement()

Question: I'm learning drupal 8. I want create a page who contain a 'two dimensionnal' 'add another item' form. My code works well almost, but I have a strange behavior when I add rooms to a house (there is a strange value in my debug logs from the FormStateInterface::getTriggeringElement(), see to the bottom for the code and log)
First : I have two structures, houses and rooms. The user can create some houses and for each house, he can create some rooms :

When I add some houses, the form works fine :

When I add some rooms to the last house, the form works fine too :

But when I add some rooms to any "no-last" house, the form doesn't work fine (in the screenshot, I click one time to the "add room" in the block house '1', the label of the "house 1" became "house 2" (?!) and on click add 5 rooms (?!) :

Here my code and a strange debug log, I don't explain why I get this value (from the getTriggeringElement() in the room_addMoreSubmit callback and this is the problem I think)
<?php

namespace Drupal\projet\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class HouseForm extends FormBase {

  public function getFormId(){
    return 'custom_rooms_form';
  }

  function buildForm(array $form, FormStateInterface $form_state) {

    $house_count = $form_state->get('house_count');

    if (is_null($house_count)) {
      $house_count = 1;
      $form_state->set('house_count', $house_count);
    }

    $form['house'] = array(
        //'#tree' => TRUE,
        '#prefix' => '
',
        '#suffix' => '
'
    );

    for ($house_delta = 0; $house_delta < $house_count; $house_delta++) {
      if (!isset($form['house'][$house_delta])) {

        $room_count[$house_delta] = $form_state->get('room_count_'.$house_delta);

        if (is_null($room_count[$house_delta])) {
          $room_count[$house_delta] = 1;
          $form_state->set('room_count_'.$house_delta, $room_count[$house_delta]);
        }

        dd($room_count, "room_COUNT");

        $form['house'][$house_delta]['room'] = array(
            '#type' => 'fieldset',
            '#title' => t('house : '.$house_delta),
            //'#tree' => TRUE,
            '#prefix' => '
',
            '#suffix' => '
'
        );

        for ($room_delta = 0; $room_delta < $room_count[$house_delta]; $room_delta++) {
          if (!isset($form['house'][$house_delta]['room'][$room_delta])) {
            $room = array(
                '#type' => 'textfield'
            );
            $check = array(
                '#type' => 'checkbox'
            );
            $form['house'][$house_delta]['room'][$room_delta] = array(
                '#type' => 'fieldset',
                '#title' => t('room : '.$house_delta.'.'.$room_delta),
            );
            $form['house'][$house_delta]['room'][$room_delta]['text'] = $room;
            $form['house'][$house_delta]['room'][$room_delta]['check'] = $check;
          }
        }

        $form['house'][$house_delta]['room']['add'] = array(
            '#type' => 'submit',
            '#name' => 'add',
            '#value' => t('Add room'),
            '#attributes' => array('class' => array('field-add-more-submit'), 'house_delta' => array($house_delta)),
            '#submit' => array(array(get_class($this), 'room_addMoreSubmit')),
            '#ajax' => array(
                'callback' => array($this, 'room_addMoreCallback'),
                'wrapper' => 'room-replace-'.$house_delta,
                'effect' => 'fade',
            ),
        );

      }
    }

    $form['house']['add'] = array(
        '#type' => 'submit',
        '#name' => 'add',
        '#value' => t('Add house'),
        '#attributes' => array('class' => array('field-add-more-submit')),
        '#submit' => array(array(get_class($this), 'house_addMoreSubmit')),
        '#ajax' => array(
            'callback' => array($this, 'house_addMoreCallback'),
            'wrapper' => 'house-replace',
            'effect' => 'fade',
        ),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Create'),
    );

    return $form;
  }

  public function room_addMoreSubmit(array $form, FormStateInterface $form_state) {
    dd($form_state->getTriggeringElement(), "room : getTriggeringElement()"); // below, the log when I add a room to the house '1' (result see above  with the last screenshot: "the house 1" became "house 2" and one click add 5 rooms)
    $house = $form_state->getTriggeringElement()["#array_parents"][1];
    $c = $form_state->get('room_count_'.$house) + 1;
    $form_state->set('room_count_'.$house, $c);
    $form_state->setRebuild(TRUE);
  }

  public function room_addMoreCallback(array $form, FormStateInterface $form_state) {
    $house = $form_state->getTriggeringElement()["#array_parents"][1];
    return $form['house'][$house]['room'];
  }

  public function house_addMoreSubmit(array $form, FormStateInterface $form_state) {
    dd($form_state->getTriggeringElement()["#array_parents"], "house : getTriggeringElement()");
    $c = $form_state->get('house_count') + 1;
    $form_state->set('house_count', $c);
    $form_state->setRebuild(TRUE);
  }

  public function house_addMoreCallback(array $form, FormStateInterface $form_state) {
    return $form['house'];
  }

}

The log ('dd' in the room_addMoreSubmit) when I click on the "add room" button in the house "1":

When I click on the "add room" button in the house number 1, getTriggeringElement return the array parents of the add button. And, as you can see, the parent is "2" not "1" (the house 1)
So when I click on the "add room" button of the house 1, this is the house "2" which is identified and not the house "1".
I don't understand why...Use the getTriggeringElement is not the good way ?
Comment: It is most likely the good old issue with deltas. Drupal still uses numbers(0,1,2,3..) and that in ajaxified forms is pure hell(I've run into it many many times). So in Drupal 8 I always use uuids and if necessary reset keys before saving the values into storage since Drupal expects numeric deltas everywhere.
Comment: uuid and reset...can you provide me a sample example ?=)
Comment: https://gist.github.com/ivanjaros/e0ce01dc262c1ffffc3d
Answer: I don't know, if this is the error, but i always try to make the names unique when building forms, for example:
$form['house'][$house_delta]['room']['add'] = array(
            '#type' => 'submit',
            '#name' => 'add-room-to-house' . $house_delta,

Comment: Thanks for answer =) If I set an unique name like you show, how can I get the good unique name from the room_addMoreSubmit callback ?
Comment: Before you get the name "add", and you don't know, which button this is, after that, each button has it's own name and you can indentify the button.
Comment: But I need know which button is triggered from the callback function, thanks that I increment the "room_count_i" variable. Without this variable, I don't know how many room there are in each house
Comment: When each element in your form has it's own #name-attribute, you and most important the form api of drupal should have no problem to identify the correct triggering element.
Comment: Im sorry, I don't understand. If I don't use the room_count var in the callback and I name elements as you say, how the form know (by example) there are 4 rooms in the house 1 ,2 rooms in the house 2 ...? when I rebuild the form
Comment: That was not your question, you asked about the triggering element. To count the elements you can use the $form array.
Comment: I need to know what button is triggered, then, from the callback function I increment the room_count_i ( i => the house id). Then when I rebuild the form, I must know how many field room there are for each house. Thats why I need know wich button "add room" is triggered when I click on a "add" button =)
Comment: I'm stupid x) I don't read correctly your first answer, and set the name as you say debug my issue. Indeed, the unique name was the issue. Thanks you a lot, and sorry again x)


Using Entity Framework Code First Migrations on multiple Oracle Schemas

Question: I am struggling to see how to use Entity Framework Code First migrations to target multiple identical Oracle databases, where each database exists in its own schema.  I have found others with the same issue - looking at several forums, and almost the exact issue has been here raised before:
Schema independent Entity Framework Code First Migrations
We serve several clients with their own self-hosted Oracle databases, and we develop against our Oracle database containing many copies of the client databases, with each client separated into their own user/schema, for example:
Client 1

Table 1
Table 2

Client 2

Table 1
Table 2

The problem stems from the insistence that an explicit schema is used with Code First migrations, either "dbo", (the Code First default) or another schema specified by:
modelBuilding.HasDefaultSchema("SchemaName")

This will mean that a set of migrations targeting SQL Server databases, using default schema "dbo", can be used to update any matching database (Either Client 1 or Client 2 in the example above).
However, on an Oracle system, the migrations will end up being tied to a specific schema, meaning the migrations would only work for one of these, i.e. if the migrations were generated against the Client 1 schema, but the app was pointed at Client 2, it would not work.
Here are a collection of ideas I've had for dealing with this problem, and solutions I have tried:

Using HasDefaultSchema(String.Empty).  This fails when generating an initial migration, with the error: "Value cannot be null. Parameter name: seqOwner".  This suggests to me that the OracleMigrationSqlGenerator is not intended to work without specific Schema names.
Finding some way to pull the Oracle user name out of the current connection string, and use that as the schema name in the migration.  I've already had to do this in the app itself, to stop Entity Framework looking in the "dbo" Schema for an Oracle database, but that was done by examining ConfigurationManager.ConnectionStrings when the model is built, I'm not sure how the same would be achieved from inside migration code.
Similar to #2, but just using a variable somewhere - maybe in the appsettings element in the Web.config, to store the Oracle schema, and referring to that from inside the migration code.  An Oracle migration script would then refer to this variable instead to find out the schema.  Both this and #2 seem very hacky though.

How could the above be achieved, and would there be any major issues with using approach 2/3 above?  I feel I must be missing something very simple here.
Answer: Lots of problems here about it.
Solution :
You need to set to correct Schema.
modelBuilding.HasDefaultSchema("SchemaName")

In my case there is no problem to set hardcoded, but on other cases i think the better solution is app.conf/web.config configuration ...


Relacionamento 0..1 na prática

Question: Tendo as seguintes tabelas:

pedido
endereço
mesa

Os pedidos podem ser efetuados na pizzaria, ou seja, para uma mesa. Pode ser uma entrega(endereço) ou pode ser um pedido para viagem, onde ele não pertence a ninguém. No SQL da tabela pedido, no momento tenho o seguinte:
CREATE TABLE pedido
(
cod_ped INT NOT NULL,
cod_mesa INT,
cod_end INT,
val_ped DECIMAL(18,2),
tipo_ped CHAR(1) NOT NULL,
data_ins DATETIME,
CONSTRAINT pk_cod_ped
PRIMARY KEY(cod_ped),
CONSTRAINT fk_cod_mesa
FOREIGN KEY (cod_mesa)
REFERENCES mesa(cod_mesa),
CONSTRAINT fk_cod_end
FOREIGN KEY (cod_end)
REFERENCES endereco(cod_end),
);

Porém, como explicado, um mesmo pedido pode pertencer tanto a 1 mesa/endereço quanto a nenhum. Criando a chave estrangeira, estaria obrigando este pedido a ter um endereço e uma mesa. Como resolver este problema?
Answer: Se um campo for chave estrangeira, e ao mesmo tempo puder receber um valor nulo, então ele não obrigado a ter valor. Porém, se tiver valor, tem que ser referente à tabela referenciada.
Então, do jeito vc que criou está certo. Basta mandar valor nulo nos campos cod_mesa e cod_end que será um pedido para viagem.

Relacionamento 0..1 na prática


Why godbolt generate different asm output than my actual asm code in Visual Studio?

Question: Here's the code generated by godbolt.
Here's the same code generated by Visual studio on my main.asm file (enabled by Project->C/C++->Output Files->Assembly With Source Code (/FAs) under Assembler Output field):
<code>; Listing generated by Microsoft (R) Optimizing Compiler Version 19.15.26732.1

    TITLE   c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
    .686P
    .XMM
    include listing.inc
    .model  flat

INCLUDELIB OLDNAMES

EXTRN   __imp____std_terminate:PROC
EXTRN   @__security_check_cookie@4:PROC
EXTRN   __imp____CxxFrameHandler3:PROC
PUBLIC  ??$?RABNABN@?$less@X@std@@QBE_NABN0@Z       ; std::less<void>::operator()<double const &,double const &>
PUBLIC  ??$clamp@NU?$less@X@std@@@std@@YAABNABN00U?$less@X@0@@Z ; std::clamp<double,std::less<void> >
PUBLIC  ??$clamp@N@std@@YAABNABN00@Z            ; std::clamp<double>
PUBLIC  _main
PUBLIC  ?ProcessOptimized@MyPlugin@@QAEXH@Z     ; MyPlugin::ProcessOptimized
PUBLIC  ?Process@MyPlugin@@QAEXH@Z          ; MyPlugin::Process
PUBLIC  ??1MyPlugin@@QAE@XZ             ; MyPlugin::~MyPlugin
PUBLIC  ??0MyPlugin@@QAE@XZ             ; MyPlugin::MyPlugin
PUBLIC  ?ProcessOptimized@Param@@QAEXHH@Z       ; Param::ProcessOptimized
PUBLIC  ?Process@Param@@QAEXHH@Z            ; Param::Process
PUBLIC  ??0Param@@QAE@XZ                ; Param::Param
PUBLIC  __real@3ff0000000000000
PUBLIC  __real@400921fb54442d18
PUBLIC  __real@4024000000000000
PUBLIC  __real@406fe00000000000
PUBLIC  __xmm@00000003000000020000000100000000
PUBLIC  __xmm@400921fb54442d18400921fb54442d18
PUBLIC  __xmm@406fe00000000000406fe00000000000
EXTRN   __chkstk:PROC
EXTRN   ___security_cookie:DWORD
EXTRN   __fltused:DWORD
;   COMDAT __xmm@406fe00000000000406fe00000000000
CONST   SEGMENT
__xmm@406fe00000000000406fe00000000000 DB 00H, 00H, 00H, 00H, 00H, 0e0H, 'o'
    DB  '@', 00H, 00H, 00H, 00H, 00H, 0e0H, 'o@'
CONST   ENDS
;   COMDAT __xmm@400921fb54442d18400921fb54442d18
CONST   SEGMENT
__xmm@400921fb54442d18400921fb54442d18 DB 018H, '-DT', 0fbH, '!', 09H, '@'
    DB  018H, '-DT', 0fbH, '!', 09H, '@'
CONST   ENDS
;   COMDAT __xmm@00000003000000020000000100000000
CONST   SEGMENT
__xmm@00000003000000020000000100000000 DB 00H, 00H, 00H, 00H, 01H, 00H, 00H
    DB  00H, 02H, 00H, 00H, 00H, 03H, 00H, 00H, 00H
CONST   ENDS
;   COMDAT __real@406fe00000000000
CONST   SEGMENT
__real@406fe00000000000 DQ 0406fe00000000000r   ; 255
CONST   ENDS
;   COMDAT __real@4024000000000000
CONST   SEGMENT
__real@4024000000000000 DQ 04024000000000000r   ; 10
CONST   ENDS
;   COMDAT __real@400921fb54442d18
CONST   SEGMENT
__real@400921fb54442d18 DQ 0400921fb54442d18r   ; 3.14159
CONST   ENDS
;   COMDAT __real@3ff0000000000000
CONST   SEGMENT
__real@3ff0000000000000 DQ 03ff0000000000000r   ; 1
CONST   ENDS
; Function compile flags: /Ogtp
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
;   COMDAT ??0Param@@QAE@XZ
_TEXT   SEGMENT
??0Param@@QAE@XZ PROC                   ; Param::Param, COMDAT
; _this$ = ecx

; 23   :    Param() { }

    xorps   xmm0, xmm0
    mov eax, ecx
    movsd   QWORD PTR [ecx], xmm0
    movsd   QWORD PTR [ecx+16], xmm0
    movsd   xmm0, QWORD PTR __real@4024000000000000
    movsd   QWORD PTR [ecx+32], xmm0
    movsd   xmm0, QWORD PTR __real@3ff0000000000000
    movsd   QWORD PTR [ecx+48], xmm0
    movsd   QWORD PTR [ecx+64], xmm0
    ret 0
??0Param@@QAE@XZ ENDP                   ; Param::Param
_TEXT   ENDS
; Function compile flags: /Ogtp
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\xstddef
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
;   COMDAT ?Process@Param@@QAEXHH@Z
_TEXT   SEGMENT
$T1 = -24                       ; size = 8
$T3 = -16                       ; size = 8
$T2 = -8                        ; size = 8
_voiceIndex$ = 8                    ; size = 4
_blockSize$dead$ = 12                   ; size = 4
?Process@Param@@QAEXHH@Z PROC               ; Param::Process, COMDAT
; _this$ = ecx

; 25   :    inline void Process(int voiceIndex, int blockSize) {

    push    ebp
    mov ebp, esp
    sub esp, 24                 ; 00000018H

; 26   :        double *pB = b[voiceIndex];

    mov eax, DWORD PTR _voiceIndex$[ebp]
    xorps   xmm5, xmm5

; 32   :            // some other code (that will use phase, like sin(phase))
; 33   :
; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    movsd   xmm2, QWORD PTR __real@400921fb54442d18
    push    esi
    mov esi, ecx
    shl eax, 11                 ; 0000000bH
    push    edi
    movsd   QWORD PTR $T1[ebp], xmm2
    mov ecx, 256                ; 00000100H
    movsd   QWORD PTR $T2[ebp], xmm5
    movsd   xmm3, QWORD PTR [esi+48]
    lea edx, DWORD PTR [esi+2128]
    movsd   xmm1, QWORD PTR [esi]
    add edx, eax
    mulsd   xmm3, QWORD PTR [esi+32]
    movsd   xmm4, QWORD PTR [esi+64]
    npad    11
$LL4@Process:
    movsd   xmm0, QWORD PTR [edx-2048]
    mulsd   xmm0, xmm3
    addsd   xmm0, QWORD PTR [edx]
    mulsd   xmm0, xmm4
    comisd  xmm0, xmm2
    movsd   QWORD PTR $T3[ebp], xmm0
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm

; 5669 :    return (_DEBUG_LT_PRED(_Pred, _Max_val, _Val)

    jbe SHORT $LN10@Process
    movaps  xmm0, xmm2
    jmp SHORT $LN11@Process
$LN10@Process:
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\xstddef

; 287  :        return (static_cast<_Ty1&&>(_Left)

    comisd  xmm5, xmm0
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm

; 5669 :    return (_DEBUG_LT_PRED(_Pred, _Max_val, _Val)

    lea eax, DWORD PTR $T2[ebp]
    lea edi, DWORD PTR $T3[ebp]
    cmovbe  eax, edi
    movsd   xmm0, QWORD PTR [eax]
$LN11@Process:
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp

; 31   :        for (int sampleIndex = 0; sampleIndex < blockSize; sampleIndex++) {

    add edx, 8

; 32   :            // some other code (that will use phase, like sin(phase))
; 33   :
; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    addsd   xmm1, xmm0
    sub ecx, 1
    jne SHORT $LL4@Process

; 35   :        }
; 36   :
; 37   :        mPhase = phase;
; 38   :    }

    pop edi
    movsd   QWORD PTR [esi], xmm1
    pop esi
    mov esp, ebp
    pop ebp
    ret 8
?Process@Param@@QAEXHH@Z ENDP               ; Param::Process
_TEXT   ENDS
; Function compile flags: /Ogtp
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
;   COMDAT ?ProcessOptimized@Param@@QAEXHH@Z
_TEXT   SEGMENT
_v_phase$ = -16                     ; size = 16
_voiceIndex$ = 8                    ; size = 4
_blockSize$dead$ = 12                   ; size = 4
?ProcessOptimized@Param@@QAEXHH@Z PROC          ; Param::ProcessOptimized, COMDAT
; _this$ = ecx

; 39   :    inline void ProcessOptimized(int voiceIndex, int blockSize) {

    push    ebx
    mov ebx, esp
    sub esp, 8
    and esp, -16                ; fffffff0H
    add esp, 4
    push    ebp
    mov ebp, DWORD PTR [ebx+4]
    mov DWORD PTR [esp+4], ebp
    mov ebp, esp

; 40   :        double *pB = b[voiceIndex];

    mov eax, DWORD PTR _voiceIndex$[ebx]
    mov edx, ecx
    shl eax, 11                 ; 0000000bH
    xorps   xmm3, xmm3
    xorps   xmm2, xmm2
    sub esp, 16                 ; 00000010H
    xorps   xmm7, xmm7
    mov ecx, 128                ; 00000080H

; 41   :        double *pC = c[voiceIndex];
; 42   :        double phase = mPhaseOptimized;
; 43   :        double bp0 = mNoteFrequency * mHostPitch;

    movsd   xmm5, QWORD PTR [edx+48]
    mulsd   xmm5, QWORD PTR [edx+32]

; 44   :
; 45   :        __m128d v_boundLower = _mm_set1_pd(0.0);
; 46   :        __m128d v_boundUpper = _mm_set1_pd(PI);
; 47   :        __m128d v_radiansPerSampleBp0 = _mm_set1_pd(mRadiansPerSample * bp0);

    movsd   xmm6, QWORD PTR [edx+64]

; 48   :        __m128d v_radiansPerSample = _mm_set1_pd(mRadiansPerSample);
; 49   :
; 50   :        __m128d v_pB0 = _mm_load_pd(pB);
; 51   :        v_pB0 = _mm_mul_pd(v_pB0, v_radiansPerSampleBp0);
; 52   :        __m128d v_pC0 = _mm_load_pd(pC);
; 53   :        v_pC0 = _mm_mul_pd(v_pC0, v_radiansPerSample);
; 54   :
; 55   :        __m128d v_pB1 = _mm_setr_pd(0.0, pB[0]);

    movsd   xmm0, QWORD PTR [eax+edx+80]
    movups  xmm4, XMMWORD PTR [eax+edx+80]
    movups  xmm1, XMMWORD PTR [eax+edx+2128]
    mulsd   xmm5, xmm6
    unpcklpd xmm3, xmm0

; 56   :        v_pB1 = _mm_mul_pd(v_pB1, v_radiansPerSampleBp0);
; 57   :        __m128d v_pC1 = _mm_setr_pd(0.0, pC[0]);

    movsd   xmm0, QWORD PTR [eax+edx+2128]
    add eax, 2136               ; 00000858H
    unpcklpd xmm2, xmm0
    add eax, edx

; 58   :        v_pC1 = _mm_mul_pd(v_pC1, v_radiansPerSample);
; 59   :
; 60   :        __m128d v_phaseAcc1;
; 61   :        __m128d v_phaseAcc2;
; 62   :        __m128d v_phase = _mm_set1_pd(phase);

    movsd   xmm0, QWORD PTR [edx+16]
    unpcklpd xmm5, xmm5
    unpcklpd xmm6, xmm6
    mulpd   xmm4, xmm5
    mulpd   xmm1, xmm6
    mulpd   xmm3, xmm5
    mulpd   xmm2, xmm6
    unpcklpd xmm0, xmm0
    npad    2
$LL4@ProcessOpt:

; 63   :
; 64   :        for (int sampleIndex = 0; sampleIndex < blockSize; sampleIndex += 2, pB += 2, pC += 2) {
; 65   :            // some other code (that will use phase, like sin(phase))
; 66   :
; 67   :            v_phaseAcc1 = _mm_add_pd(v_pB0, v_pC0);

    addpd   xmm1, xmm4

; 68   :            v_phaseAcc1 = _mm_max_pd(v_phaseAcc1, v_boundLower);
; 69   :            v_phaseAcc1 = _mm_min_pd(v_phaseAcc1, v_boundUpper);
; 70   :            v_phaseAcc2 = _mm_add_pd(v_pB1, v_pC1);
; 71   :            v_phaseAcc2 = _mm_max_pd(v_phaseAcc2, v_boundLower);
; 72   :            v_phaseAcc2 = _mm_min_pd(v_phaseAcc2, v_boundUpper);
; 73   :            v_phase = _mm_add_pd(v_phase, v_phaseAcc1);
; 74   :            v_phase = _mm_add_pd(v_phase, v_phaseAcc2);
; 75   :
; 76   :            v_pB0 = _mm_load_pd(pB + 2);

    movups  xmm4, XMMWORD PTR [eax-2040]
    addpd   xmm2, xmm3

; 77   :            v_pB0 = _mm_mul_pd(v_pB0, v_radiansPerSampleBp0);
; 78   :            v_pC0 = _mm_load_pd(pC + 2);
; 79   :            v_pC0 = _mm_mul_pd(v_pC0, v_radiansPerSample);
; 80   :
; 81   :            v_pB1 = _mm_loadu_pd(pB + 1);

    movups  xmm3, XMMWORD PTR [eax-2048]
    maxpd   xmm1, xmm7
    maxpd   xmm2, xmm7
    minpd   xmm1, XMMWORD PTR __xmm@400921fb54442d18400921fb54442d18
    minpd   xmm2, XMMWORD PTR __xmm@400921fb54442d18400921fb54442d18
    addpd   xmm0, xmm1
    movups  xmm1, XMMWORD PTR [eax+8]
    addpd   xmm0, xmm2

; 82   :            v_pB1 = _mm_mul_pd(v_pB1, v_radiansPerSampleBp0);
; 83   :            v_pC1 = _mm_loadu_pd(pC + 1);

    movups  xmm2, XMMWORD PTR [eax]
    add eax, 16                 ; 00000010H
    movaps  XMMWORD PTR _v_phase$[ebp], xmm0
    mulpd   xmm4, xmm5
    mulpd   xmm1, xmm6
    mulpd   xmm3, xmm5

; 84   :            v_pC1 = _mm_mul_pd(v_pC1, v_radiansPerSample);

    mulpd   xmm2, xmm6
    sub ecx, 1
    jne SHORT $LL4@ProcessOpt

; 85   :        }
; 86   :
; 87   :        mPhaseOptimized = v_phase.m128d_f64[blockSize % 2 == 0 ? 1 : 0];

    movsd   xmm0, QWORD PTR _v_phase$[ebp+8]
    movsd   QWORD PTR [edx+16], xmm0

; 88   :    }

    mov esp, ebp
    pop ebp
    mov esp, ebx
    pop ebx
    ret 8
?ProcessOptimized@Param@@QAEXHH@Z ENDP          ; Param::ProcessOptimized
_TEXT   ENDS
; Function compile flags: /Ogtp
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
;   COMDAT ??0MyPlugin@@QAE@XZ
_TEXT   SEGMENT
??0MyPlugin@@QAE@XZ PROC                ; MyPlugin::MyPlugin, COMDAT
; _this$ = ecx

; 97   :        // fill b
; 98   :        for (int voiceIndex = 0; voiceIndex < voiceSize; voiceIndex++) {
; 99   :            for (int sampleIndex = 0; sampleIndex < bufferSize; sampleIndex++) {

    movaps  xmm2, XMMWORD PTR __xmm@00000003000000020000000100000000
    xorps   xmm0, xmm0
    movaps  xmm3, XMMWORD PTR __xmm@406fe00000000000406fe00000000000
    xor edx, edx
    push    esi
    mov esi, ecx
    push    edi

; 14   :    alignas(16) double mPhase = 0.0;

    movsd   QWORD PTR [esi], xmm0

; 97   :        // fill b
; 98   :        for (int voiceIndex = 0; voiceIndex < voiceSize; voiceIndex++) {
; 99   :            for (int sampleIndex = 0; sampleIndex < bufferSize; sampleIndex++) {

    lea ecx, DWORD PTR [esi+88]

; 15   :    alignas(16) double mPhaseOptimized = 0.0;

    movsd   QWORD PTR [esi+16], xmm0

; 16   :    alignas(16) double mNoteFrequency = 10.0;

    movsd   xmm0, QWORD PTR __real@4024000000000000
    movsd   QWORD PTR [esi+32], xmm0

; 17   :    alignas(16) double mHostPitch = 1.0;

    movsd   xmm0, QWORD PTR __real@3ff0000000000000
    movsd   QWORD PTR [esi+48], xmm0

; 18   :    alignas(16) double mRadiansPerSample = 1.0;

    movsd   QWORD PTR [esi+64], xmm0
$LL7@MyPlugin:

; 100  :                double value = (sampleIndex / ((double)bufferSize - 1));

    movd    xmm0, edx
    lea eax, DWORD PTR [edx+2]
    pshufd  xmm1, xmm0, 0
    lea ecx, DWORD PTR [ecx+32]
    movq    xmm0, xmm2
    add edx, 4
    paddd   xmm1, xmm0
    cvtdq2pd xmm0, xmm1
    divpd   xmm0, xmm3

; 101  :
; 102  :                mParam1.b[voiceIndex][sampleIndex] = value;

    movlpd  QWORD PTR [ecx-40], xmm0
    movhpd  QWORD PTR [ecx-32], xmm0
    movd    xmm0, eax
    pshufd  xmm1, xmm0, 0
    movq    xmm0, xmm2
    paddd   xmm1, xmm0
    cvtdq2pd xmm0, xmm1
    divpd   xmm0, xmm3
    movlpd  QWORD PTR [ecx-24], xmm0
    movhpd  QWORD PTR [ecx-16], xmm0
    cmp edx, 256                ; 00000100H
    jl  SHORT $LL7@MyPlugin

; 103  :            }
; 104  :        }
; 105  :
; 106  :        // fill c
; 107  :        for (int voiceIndex = 0; voiceIndex < voiceSize; voiceIndex++) {
; 108  :            for (int sampleIndex = 0; sampleIndex < bufferSize; sampleIndex++) {

    lea edi, DWORD PTR [esi+2128]
    xor eax, eax
    mov ecx, 512                ; 00000200H
    rep stosd

; 109  :                double value = 0.0;
; 110  :
; 111  :                mParam1.c[voiceIndex][sampleIndex] = value;
; 112  :            }
; 113  :        }
; 114  :    }

    pop edi
    mov eax, esi
    pop esi
    ret 0
??0MyPlugin@@QAE@XZ ENDP                ; MyPlugin::MyPlugin
_TEXT   ENDS
; Function compile flags: /Ogtp
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
;   COMDAT ??1MyPlugin@@QAE@XZ
_TEXT   SEGMENT
??1MyPlugin@@QAE@XZ PROC                ; MyPlugin::~MyPlugin, COMDAT
; _this$dead$ = ecx

; 115  :    ~MyPlugin() { }

    ret 0
??1MyPlugin@@QAE@XZ ENDP                ; MyPlugin::~MyPlugin
_TEXT   ENDS
; Function compile flags: /Ogtp
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\xstddef
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
;   COMDAT ?Process@MyPlugin@@QAEXH@Z
_TEXT   SEGMENT
$T2 = -28                       ; size = 8
$T4 = -20                       ; size = 8
$T3 = -12                       ; size = 8
_blockSize$dead$ = 8                    ; size = 4
?Process@MyPlugin@@QAEXH@Z PROC             ; MyPlugin::Process, COMDAT
; _this$ = ecx

; 117  :    void Process(int blockSize) {

    push    ebp
    mov ebp, esp
    sub esp, 28                 ; 0000001cH

; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    movsd   xmm2, QWORD PTR __real@400921fb54442d18
    xorps   xmm5, xmm5

; 117  :    void Process(int blockSize) {

    push    esi
    mov esi, ecx

; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    movsd   QWORD PTR $T2[ebp], xmm2

; 117  :    void Process(int blockSize) {

    push    edi

; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    movsd   QWORD PTR $T3[ebp], xmm5
    mov edx, 256                ; 00000100H
    movsd   xmm3, QWORD PTR [esi+48]

; 27   :        double *pC = c[voiceIndex];

    lea ecx, DWORD PTR [esi+2128]

; 28   :        double phase = mPhase;
; 29   :        double bp0 = mNoteFrequency * mHostPitch;

    movsd   xmm1, QWORD PTR [esi]
    mulsd   xmm3, QWORD PTR [esi+32]
    movsd   xmm4, QWORD PTR [esi+64]
    npad    3
$LL9@Process:

; 32   :            // some other code (that will use phase, like sin(phase))
; 33   :
; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    movsd   xmm0, QWORD PTR [ecx-2048]
    mulsd   xmm0, xmm3
    addsd   xmm0, QWORD PTR [ecx]
    mulsd   xmm0, xmm4
    comisd  xmm0, xmm2
    movsd   QWORD PTR $T4[ebp], xmm0
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm

; 5669 :    return (_DEBUG_LT_PRED(_Pred, _Max_val, _Val)

    jbe SHORT $LN15@Process
    movaps  xmm0, xmm2
    jmp SHORT $LN16@Process
$LN15@Process:
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\xstddef

; 287  :        return (static_cast<_Ty1&&>(_Left)

    comisd  xmm5, xmm0
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm

; 5669 :    return (_DEBUG_LT_PRED(_Pred, _Max_val, _Val)

    lea eax, DWORD PTR $T3[ebp]
    lea edi, DWORD PTR $T4[ebp]
    cmovbe  eax, edi
    movsd   xmm0, QWORD PTR [eax]
$LN16@Process:
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp

; 31   :        for (int sampleIndex = 0; sampleIndex < blockSize; sampleIndex++) {

    add ecx, 8

; 32   :            // some other code (that will use phase, like sin(phase))
; 33   :
; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    addsd   xmm1, xmm0
    sub edx, 1
    jne SHORT $LL9@Process

; 118  :        for (int voiceIndex = 0; voiceIndex < voiceSize; voiceIndex++) {
; 119  :            mParam1.Process(voiceIndex, blockSize);
; 120  :        }
; 121  :    }

    pop edi

; 37   :        mPhase = phase;

    movsd   QWORD PTR [esi], xmm1

; 118  :        for (int voiceIndex = 0; voiceIndex < voiceSize; voiceIndex++) {
; 119  :            mParam1.Process(voiceIndex, blockSize);
; 120  :        }
; 121  :    }

    pop esi
    mov esp, ebp
    pop ebp
    ret 4
?Process@MyPlugin@@QAEXH@Z ENDP             ; MyPlugin::Process
_TEXT   ENDS
; Function compile flags: /Ogtp
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
;   COMDAT ?ProcessOptimized@MyPlugin@@QAEXH@Z
_TEXT   SEGMENT
_v_phase$31 = -16                   ; size = 16
_blockSize$dead$ = 8                    ; size = 4
?ProcessOptimized@MyPlugin@@QAEXH@Z PROC        ; MyPlugin::ProcessOptimized, COMDAT
; _this$ = ecx

; 122  :    void ProcessOptimized(int blockSize) {

    push    ebx
    mov ebx, esp
    sub esp, 8
    and esp, -16                ; fffffff0H
    add esp, 4
    push    ebp
    mov ebp, DWORD PTR [ebx+4]
    mov DWORD PTR [esp+4], ebp
    mov ebp, esp
    mov edx, ecx
    xorps   xmm3, xmm3
    xorps   xmm2, xmm2
    sub esp, 16                 ; 00000010H

; 40   :        double *pB = b[voiceIndex];

    mov ecx, 128                ; 00000080H
    movsd   xmm6, QWORD PTR [edx+48]
    lea eax, DWORD PTR [edx+2136]
    mulsd   xmm6, QWORD PTR [edx+32]

; 41   :        double *pC = c[voiceIndex];
; 42   :        double phase = mPhaseOptimized;
; 43   :        double bp0 = mNoteFrequency * mHostPitch;
; 44   :
; 45   :        __m128d v_boundLower = _mm_set1_pd(0.0);
; 46   :        __m128d v_boundUpper = _mm_set1_pd(PI);
; 47   :        __m128d v_radiansPerSampleBp0 = _mm_set1_pd(mRadiansPerSample * bp0);

    movsd   xmm7, QWORD PTR [edx+64]

; 54   :
; 55   :        __m128d v_pB1 = _mm_setr_pd(0.0, pB[0]);

    movsd   xmm0, QWORD PTR [edx+80]
    movsd   xmm5, QWORD PTR [edx+16]
    movups  xmm4, XMMWORD PTR [edx+80]
    movups  xmm1, XMMWORD PTR [edx+2128]
    mulsd   xmm6, xmm7
    unpcklpd xmm3, xmm0

; 57   :        __m128d v_pC1 = _mm_setr_pd(0.0, pC[0]);

    movsd   xmm0, QWORD PTR [edx+2128]
    unpcklpd xmm7, xmm7
    unpcklpd xmm6, xmm6
    unpcklpd xmm2, xmm0
    xorps   xmm0, xmm0

; 48   :        __m128d v_radiansPerSample = _mm_set1_pd(mRadiansPerSample);
; 49   :
; 50   :        __m128d v_pB0 = _mm_load_pd(pB);
; 51   :        v_pB0 = _mm_mul_pd(v_pB0, v_radiansPerSampleBp0);

    mulpd   xmm4, xmm6

; 52   :        __m128d v_pC0 = _mm_load_pd(pC);
; 53   :        v_pC0 = _mm_mul_pd(v_pC0, v_radiansPerSample);

    mulpd   xmm1, xmm7

; 56   :        v_pB1 = _mm_mul_pd(v_pB1, v_radiansPerSampleBp0);

    mulpd   xmm3, xmm6

; 58   :        v_pC1 = _mm_mul_pd(v_pC1, v_radiansPerSample);

    mulpd   xmm2, xmm7

; 59   :
; 60   :        __m128d v_phaseAcc1;
; 61   :        __m128d v_phaseAcc2;
; 62   :        __m128d v_phase = _mm_set1_pd(phase);

    unpcklpd xmm5, xmm5
    npad    13
$LL9@ProcessOpt:

; 63   :
; 64   :        for (int sampleIndex = 0; sampleIndex < blockSize; sampleIndex += 2, pB += 2, pC += 2) {
; 65   :            // some other code (that will use phase, like sin(phase))
; 66   :
; 67   :            v_phaseAcc1 = _mm_add_pd(v_pB0, v_pC0);

    addpd   xmm1, xmm4

; 68   :            v_phaseAcc1 = _mm_max_pd(v_phaseAcc1, v_boundLower);
; 69   :            v_phaseAcc1 = _mm_min_pd(v_phaseAcc1, v_boundUpper);
; 70   :            v_phaseAcc2 = _mm_add_pd(v_pB1, v_pC1);
; 71   :            v_phaseAcc2 = _mm_max_pd(v_phaseAcc2, v_boundLower);
; 72   :            v_phaseAcc2 = _mm_min_pd(v_phaseAcc2, v_boundUpper);
; 73   :            v_phase = _mm_add_pd(v_phase, v_phaseAcc1);
; 74   :            v_phase = _mm_add_pd(v_phase, v_phaseAcc2);
; 75   :
; 76   :            v_pB0 = _mm_load_pd(pB + 2);

    movups  xmm4, XMMWORD PTR [eax-2040]
    addpd   xmm2, xmm3

; 77   :            v_pB0 = _mm_mul_pd(v_pB0, v_radiansPerSampleBp0);
; 78   :            v_pC0 = _mm_load_pd(pC + 2);
; 79   :            v_pC0 = _mm_mul_pd(v_pC0, v_radiansPerSample);
; 80   :
; 81   :            v_pB1 = _mm_loadu_pd(pB + 1);

    movups  xmm3, XMMWORD PTR [eax-2048]
    maxpd   xmm1, xmm0
    maxpd   xmm2, xmm0
    minpd   xmm1, XMMWORD PTR __xmm@400921fb54442d18400921fb54442d18
    minpd   xmm2, XMMWORD PTR __xmm@400921fb54442d18400921fb54442d18
    addpd   xmm5, xmm1
    movups  xmm1, XMMWORD PTR [eax+8]
    addpd   xmm5, xmm2

; 82   :            v_pB1 = _mm_mul_pd(v_pB1, v_radiansPerSampleBp0);
; 83   :            v_pC1 = _mm_loadu_pd(pC + 1);

    movups  xmm2, XMMWORD PTR [eax]
    add eax, 16                 ; 00000010H
    movaps  XMMWORD PTR _v_phase$31[ebp], xmm5
    mulpd   xmm4, xmm6
    mulpd   xmm1, xmm7
    mulpd   xmm3, xmm6

; 84   :            v_pC1 = _mm_mul_pd(v_pC1, v_radiansPerSample);

    mulpd   xmm2, xmm7
    sub ecx, 1
    jne SHORT $LL9@ProcessOpt

; 85   :        }
; 86   :
; 87   :        mPhaseOptimized = v_phase.m128d_f64[blockSize % 2 == 0 ? 1 : 0];

    movsd   xmm0, QWORD PTR _v_phase$31[ebp+8]
    movsd   QWORD PTR [edx+16], xmm0

; 123  :        for (int voiceIndex = 0; voiceIndex < voiceSize; voiceIndex++) {
; 124  :            mParam1.ProcessOptimized(voiceIndex, blockSize);
; 125  :        }
; 126  :    }

    mov esp, ebp
    pop ebp
    mov esp, ebx
    pop ebx
    ret 4
?ProcessOptimized@MyPlugin@@QAEXH@Z ENDP        ; MyPlugin::ProcessOptimized
_TEXT   ENDS
; Function compile flags: /Ogtp
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\xstddef
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm
; File c:\repos\analysis_vectorization\analysis_vectorization\main.cpp
;   COMDAT _main
_TEXT   SEGMENT
_counterProcessing$1$ = -4304               ; size = 4
_counterProcessing$ = -4304             ; size = 8
_bp0$1$ = -4296                     ; size = 8
_v_radiansPerSample$1$ = -4288              ; size = 16
$T3 = -4264                     ; size = 8
_v_phase$38 = -4256                 ; size = 16
$T4 = -4256                     ; size = 8
$T2 = -4232                     ; size = 8
tv1040 = -4224                      ; size = 16
tv1039 = -4208                      ; size = 16
_myPlugin$ = -4192                  ; size = 4176
__$ArrayPad$ = -4                   ; size = 4
_main   PROC                        ; COMDAT

; 129  : int main() {

    push    ebp
    mov ebp, esp
    and esp, -16                ; fffffff0H
    mov eax, 4312               ; 000010d8H
    call    __chkstk
    mov eax, DWORD PTR ___security_cookie
    xor eax, esp
    mov DWORD PTR __$ArrayPad$[esp+4312], eax

; 16   :    alignas(16) double mNoteFrequency = 10.0;

    movsd   xmm0, QWORD PTR __real@4024000000000000

; 99   :            for (int sampleIndex = 0; sampleIndex < bufferSize; sampleIndex++) {

    lea ecx, DWORD PTR _myPlugin$[esp+4392]
    movsd   xmm1, QWORD PTR __real@406fe00000000000
    xorps   xmm2, xmm2

; 16   :    alignas(16) double mNoteFrequency = 10.0;

    movsd   QWORD PTR _myPlugin$[esp+4344], xmm0

; 99   :            for (int sampleIndex = 0; sampleIndex < bufferSize; sampleIndex++) {

    xor eax, eax

; 17   :    alignas(16) double mHostPitch = 1.0;

    movsd   xmm0, QWORD PTR __real@3ff0000000000000

; 129  : int main() {

    push    esi
    push    edi

; 14   :    alignas(16) double mPhase = 0.0;

    movsd   QWORD PTR _myPlugin$[esp+4320], xmm2

; 15   :    alignas(16) double mPhaseOptimized = 0.0;

    movsd   QWORD PTR _myPlugin$[esp+4336], xmm2

; 17   :    alignas(16) double mHostPitch = 1.0;

    movsd   QWORD PTR _myPlugin$[esp+4368], xmm0

; 18   :    alignas(16) double mRadiansPerSample = 1.0;

    movsd   QWORD PTR _myPlugin$[esp+4384], xmm0
$LL11@main:
    movd    xmm0, eax

; 99   :            for (int sampleIndex = 0; sampleIndex < bufferSize; sampleIndex++) {

    lea ecx, DWORD PTR [ecx+8]

; 100  :                double value = (sampleIndex / ((double)bufferSize - 1));

    cvtdq2pd xmm0, xmm0
    inc eax
    divsd   xmm0, xmm1

; 101  :
; 102  :                mParam1.b[voiceIndex][sampleIndex] = value;

    movsd   QWORD PTR [ecx-8], xmm0
    cmp eax, 256                ; 00000100H
    jl  SHORT $LL11@main

; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    movsd   xmm6, QWORD PTR __real@400921fb54442d18

; 108  :            for (int sampleIndex = 0; sampleIndex < bufferSize; sampleIndex++) {

    lea edi, DWORD PTR _myPlugin$[esp+6448]
    mov ecx, 512                ; 00000200H

; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    movsd   QWORD PTR $T2[esp+4320], xmm6

; 108  :            for (int sampleIndex = 0; sampleIndex < bufferSize; sampleIndex++) {

    xor eax, eax

; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    movsd   QWORD PTR $T3[esp+4320], xmm2

; 108  :            for (int sampleIndex = 0; sampleIndex < bufferSize; sampleIndex++) {

    rep stosd
    movsd   xmm3, QWORD PTR _myPlugin$[esp+4352]
    xorps   xmm0, xmm0
    mulsd   xmm3, QWORD PTR _myPlugin$[esp+4368]

; 55   :        __m128d v_pB1 = _mm_setr_pd(0.0, pB[0]);

    movaps  xmm4, xmm2
    movsd   xmm1, QWORD PTR _myPlugin$[esp+4384]

; 56   :        v_pB1 = _mm_mul_pd(v_pB1, v_radiansPerSampleBp0);
; 57   :        __m128d v_pC1 = _mm_setr_pd(0.0, pC[0]);

    movsd   xmm5, QWORD PTR _myPlugin$[esp+4336]

; 130  :    MyPlugin myPlugin;
; 131  :
; 132  :    long long numProcessing = 5;
; 133  :    long long counterProcessing = 0;

    movlpd  QWORD PTR _counterProcessing$[esp+4320], xmm0

; 55   :        __m128d v_pB1 = _mm_setr_pd(0.0, pB[0]);

    movsd   xmm0, QWORD PTR _myPlugin$[esp+4400]
    movaps  xmm7, xmm3
    mulsd   xmm7, QWORD PTR _myPlugin$[esp+4384]

; 56   :        v_pB1 = _mm_mul_pd(v_pB1, v_radiansPerSampleBp0);
; 57   :        __m128d v_pC1 = _mm_setr_pd(0.0, pC[0]);

    mov edi, DWORD PTR _counterProcessing$[esp+4324]
    mov esi, DWORD PTR _counterProcessing$[esp+4320]
    unpcklpd xmm4, xmm0
    movsd   xmm0, QWORD PTR _myPlugin$[esp+6448]
    movups  XMMWORD PTR tv1040[esp+4320], xmm4
    movaps  xmm4, xmm2
    unpcklpd xmm1, xmm1
    unpcklpd xmm4, xmm0
    movups  XMMWORD PTR tv1039[esp+4320], xmm4
    movsd   xmm4, QWORD PTR _myPlugin$[esp+4320]
    movsd   QWORD PTR _bp0$1$[esp+4320], xmm3
    unpcklpd xmm7, xmm7
    movaps  XMMWORD PTR _v_radiansPerSample$1$[esp+4320], xmm1
    npad    8
$LL2@main:

; 134  :
; 135  :    // I'll only process once block, just for analysis
; 136  :    while (counterProcessing++ < numProcessing) {

    add esi, 1

; 26   :        double *pB = b[voiceIndex];

    lea ecx, DWORD PTR _myPlugin$[esp+6448]

; 134  :
; 135  :    // I'll only process once block, just for analysis
; 136  :    while (counterProcessing++ < numProcessing) {

    mov DWORD PTR _counterProcessing$1$[esp+4320], esi

; 26   :        double *pB = b[voiceIndex];

    mov edx, 256                ; 00000100H

; 134  :
; 135  :    // I'll only process once block, just for analysis
; 136  :    while (counterProcessing++ < numProcessing) {

    adc edi, 0
    npad    10
$LL29@main:

; 34   :            phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);

    movsd   xmm0, QWORD PTR [ecx-2048]
    mulsd   xmm0, xmm3
    addsd   xmm0, QWORD PTR [ecx]
    mulsd   xmm0, QWORD PTR _myPlugin$[esp+4384]
    comisd  xmm0, xmm6
    movsd   QWORD PTR $T4[esp+4320], xmm0
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm

; 5669 :    return (_DEBUG_LT_PRED(_Pred, _Max_val, _Val)

    jbe SHORT $LN35@main
    movaps  xmm0, xmm6
    jmp SHORT $LN36@main
$LN35@main:
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\xstddef

; 287  :        return (static_cast<_Ty1&&>(_Left)

    comisd  xmm2, xmm0
; File c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\algorithm

; 5669 :    return (_DEBUG_LT_PRED(_Pred, _Max_val, _Val)

    lea eax, DWORD PTR $T3[esp+4320]
    lea esi, DWORD PTR $T4[esp+4320]
    cmovbe  eax, esi
    movsd   xmm0, QWORD PTR [eax]

// ...
</code>
(Note: I've removed some lines because StackOverflow limit it.)
Its pretty different. Also, I see the code generated by VS is a bit redundant i.e. search for string <code>phase += std::clamp(mRadiansPerSample * (bp0 * pB[sampleIndex] + pC[sampleIndex]), 0.0, PI);</code>: there are many.
Which settings am I missing?. I've matched the same MSVC version (19.15), on a X86 build, placing also the actual optimization I have.
Comment: Compilation command in godbolt is not even close to typical VS project command, most of essential options (such as `/EHsc`, `/Zc`, `/MD`) are missing. Also compiler vesion on godbolt is a bit different.
Comment: godbolt.org filters out unused labels and assembler directives by default, but you can disable these filters in the compiler panel.
Comment: But why VS also redundant some codes?
Comment: Ask Microsoft for details?
Comment: Also, AFAIK, Microsoft does not guarantee that the VC-compiler is consistent between compilations. It may generate different (but functionally equivalent) code on subsequent invocations.
Comment: @Johan: really? Why? :D Where can I get more details about this?
Answer: It doesn't seem that you're using the same compiler flags. The assembly dump from Visual Studio shows that each function was optimized with the flags <code>/Ogtp</code>, which are used internally when you specify <code>/Og</code> in the command line. On the other hand, in the godbolt version, you used <code>/Ot /O2</code>, which internally correspond to <code>/Ogtpy</code>. If I manually add the <code>/Oy</code> flag, the code becomes slightly different, but still not the same as the one generated by Visual Studio.
I realize that the compiler versions are not exactly the same, but the difference between 19.15.26726.0 and 19.15.26732.1 is very minor and probably only includes bug fixes. I think there are other flags that are different. You can go to the Property Pages of your project and find all the compiler options that have been used in the "All Options" and "Additional Options" panes. In the Release build, many options are used other than <code>/arch:SSE2 /Ot /O2</code>. Note that <code>/arch:SSE2</code> is the default, so you don't have to explicitly specify it. Also, <code>/O2</code> implies <code>/Ot</code>. So <code>/arch:SSE2 /Ot /O2</code> is equivalent to <code>/O2</code>.
Comment: @InstructionPointer This is a C# compiler option, not MSVC. Anyway, I don't think that option influences the generated CIL code (the C# compiler generates CIL code, not native code).
Comment: Would using the -deterministic option influence any of the assembly or just the binary output? I found this article: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/deterministic-compiler-option
Answer: There are multiple paths to a destination.
Roger Orr gave a good talk at an ACCU conference on the quirks of compiling. For example, a simple "hello world" will generate 98 lines of asm in GCC but 6,704 in MSVC.
To quickly and simply answer your question: in your Godbolt link the version is <code>19.15.26726.0</code> and your main.asm file <code>19.15.26732.1</code>
Close, but maybe enough to make this difference?
<code>19.15.26726.0</code>
<code>19.15.26732.1</code>
MSVC is particularly weird, you can output asm with GCC then use that asm to pass through GCC again and get the same machine code. You can't in MSVC. So maybe if the versions were exactly the same, you would still get different asm, that'd be a fun experiment to run, this article shows you how to run two different versions of MSVC side by side in Visual Studio.
Comment: While MSVC produces asm output files, they aren't [assemble-able](https://stackoverflow.com/questions/21182665/compile-64-bit-hello-world-assembly-output-from-msvc2012): *we made the call to no longer support assembling C/C++ generated listing files. In other words, the listing files are for informational purposes only.*
Comment: MSVC is weird in that it's asm output includes (stand alone definitions for) other related functions.  And yeah, I think I've read it doesn't always exactly match the machine code you'd get if you don't ask for asm.  Anyway, I think you can't reliably just assemble its asm output to get a usable `.obj`.  You can with GCC; in fact GCC *always* compiles to asm and then assembles that separately; it doesn't have a built-in assembler.  (Running `gcc -c foo.s` makes the gcc front-end run the `.s` through `as`.)
Comment: *that the disassembler might take a second to resynchronize between instructions and data.*  That doesn't make sense.  First of all, normal Godbolt output is the compiler's asm output, not disassembly of a binary.  2nd, compiler-generated object files have metadata that separates code from data, and symbol names for the tops of functions.  Godbolt fires of batch jobs that compile and then disassemble to tmp files, not one shared filename so you can't get into a situation where the disassembler is reading a file while it's being modified by a compiler.  You're always getting some snapshot.
Comment: thank you @PeterCordes as always for your guidance. I got carried away so just deleted that whole last part. I need to learn more about this metadata in the object files.