Desconto em um item do formulário, após escolher uma opção de combo

Question: Tenho um formulário em PHP, onde gostaria de criar uma regra de desconto para um item, no caso a sopa. A sopa no cardápio online (formulário) custa R$ 15,50 mas se o cliente selecionar um dos combos (São 4 combos) a Sopa custará R$ 9,90.
O formulário é em PHP e as regras (programação) esta em JS.
Segue a parte em PHP das opções e da Sopa:

Escolha a sua opção:

<input type="radio" name="promo" value="24.90" op="1"> Opção 1: 3 Quentes e 3 Saladas - R$ 24,90

<input type="radio" name="promo" value="27.90" op="2"> Opção 2: 4 Quentes e 4 Saladas - R$ 27,90

<input type="radio" name="promo" value="30.90" op="3"> Opção 3: 5 Quentes e 5 Saladas - R$ 30,90

<input type="radio" name="promo" value="0.00"  op="4"> Opção 4: Monte seu prato à vontade (mínimo de 6 itens)

<input type="button" id="mudaopcao" class="botao" value=" Mudar a minha opção ">

Sopas:

<input type="checkbox" value="15.50"> Minestrone - feijão branco com tofu defumado e legumes em cubos(P) : R$ 15,50 - Quant.: <select></select>

Aqui é o código COMPLETO do arquivo form.js (JS):
var str = "";
var id = "";
var sub = 0.00;
var taxa = 0;
var taxadeentrega = total - taxa;
var total = 0.00;
var qcount = 0;
var scount = 0;
var opc = 0;
var options = "";
for (i=1; i<21; i++){
    options += "<option value='" + i + "'>" + i + "</option>";
}

$( document ).ready(function() {

    $( "div div select" ).html(options);
    $( "div div :text" ).attr("value","1");
    $( "#emporio" ).css("display","block");
    $( "#mudaopcao" ).click(function() {
      location.reload(true);
    });
    function alerta(txt){
        $( "div#alerta" ).html( txt ).show( 0 ).delay( 2500 ).fadeOut( 500 );
    }
function atencao(txt){
        $( "div#atencao" ).html( txt ).show( 0 ).delay( 2500 ).fadeOut( 500 );
    }
    function mens(){
        var d = new Date();
        var n = d.getDate() + "|" + (d.getMonth()+1) + "|" + d.getFullYear() + " - " + d.getHours() + ":" + d.getMinutes();

        $( "div#quentes :checkbox:checked" ).each(function() {
              str = str + $(this).parent().children("strong").text();
              if (opc == 4){
                  var sel = $(this).parent().children("span").children("select").val();
                  str = str + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",");
              }
              str = str + "
";
        })
        $('input[name=quentes]').val(str);
        str = "";

        $( "div#molhos :checkbox:checked" ).each(function() {
              str = str + $(this).parent().children("strong").text();
              if (opc == 4){
                  var sel = $(this).parent().children("span").children("select").val();
                  str = str + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",");
              }
              str = str + "
";
        })
        $('input[name=molhos]').val(str);
        str = "";

        $( "div#saladas :checkbox:checked" ).each(function() {
              str = str + $(this).parent().children("strong").text();
              if (opc == 4){
                  var sel = $(this).parent().children("span").children("select").val();
                  str = str + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",");
              }
              str = str + "
";
        })
        $('input[name=saladas]').val(str);
        str = "";

        $( "div#sobremesas :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              str = str + $(this).parent().children("strong").text() + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",") + "
";
        })
        $('input[name=sobremesas]').val(str);
        str = "";

        $( "div#sucos :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              var val = $(this).parent().children("input:radio:checked").val();
              str = str + $(this).parent().children("strong").text() + " - " + $(this).parent().children("input:radio:checked").attr("l") + ": R$ " + val.replace(".", ",") + " x " + sel + " = R$ " + (val * sel).toFixed(2).replace(".", ",") + "
";
        })
        $('input[name=sucos]').val(str);
        str = "";

        $( "div#bebidas :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              str = str + $(this).parent().children("strong").text() + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",") + "
";
        })
        $('input[name=bebidas]').val(str);
        str = "";

        $( "div#sopas :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              str = str + $(this).parent().children("strong").text() + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",") + "
";
        })
        $('input[name=sopas]').val(str);
        str = "";

        $( "div#emporio :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              str = str + $(this).parent().children("strong").text() + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",") + "
";
        })
        $('input[name=emporio]').val(str);
        str = "";

        str = String(total.toFixed(2)).replace(".", ",");
        $('input[name=mtotal]').val(str);
        str = "";

        str = String(+ taxa.toFixed(2)).replace(".", ",");
        $('input[name=taxadeentrega]').val(str);
        str = "";

        if(opc==1){
            $('input[name=op]').val("3 Quentes e 3 Saladas");
        }else if(opc==2){
            $('input[name=op]').val("4 Quentes e 4 Saladas");
        }else if(opc==3){
            $('input[name=op]').val("5 Quentes e 5 Saladas");
        }else{
            $('input[name=op]').val("");
        }

        if(opc==0){
            $('input[name=nop]').val("");
        } else {
            str = "Opção " + opc + ": ";
            $('input[name=nop]').val(str);
            str = "";
        }

        $('input[name=data]').val(n);
    }

      $("div#quentes :checkbox").click(function(){
          if($(this).prop("checked") == true){
              qcount++;
              if (opc == 1){
                  if (qcount == 4){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 3 pratos quentes, para mais escolha outra opção");
                      qcount = 3;
                  }
                  if (qcount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 pratos quentes");

                  }
                  if (qcount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 prato quente");

                  }
              } else if (opc == 2){
                  if (qcount == 5){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 4 pratos quentes, para mais escolha outra opção");
                      qcount = 4;
                  }
                   if (qcount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 3 pratos quentes");

                  }
                  if (qcount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 pratos quentes");

                  }
                   if (qcount == 3){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 prato quente");

                  }
              } else if (opc == 3){
                  if (qcount == 6){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 5 pratos quentes, para mais escolha outra opção");
                      qcount = 5;
                  }
                    if (qcount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 4 pratos quentes");

                  }
                  if (qcount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 3 pratos quentes");

                  }
                   if (qcount == 3){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 pratos quentes");

                  }
                   if (qcount == 4){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 prato quente");

                  }
              }
          } else if($(this).prop("checked") == false){
              qcount--;
          }
      })

      $("div#saladas :checkbox").click(function(){
          if($(this).prop("checked") == true){
              scount++;
              if (opc == 1){
                  if (scount == 4){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 3 saladas, para mais escolha outra opção");
                      scount = 3;
                  }
                  if (scount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 saladas");
                  }
                  if (scount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 salada");
                  }

              } else if (opc == 2){
                  if (scount == 5){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 4 saladas, para mais escolha outra opção");
                      scount = 4;
                  }
                   if (scount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 3 saladas");
                  }
                  if (scount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 saladas");
                  }
                  if (scount == 3){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 salada");
                  }

              } else if (opc == 3){
                  if (scount == 6){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 5 saladas, para mais escolha outra opção");
                      scount = 5;
                  }
                  if (scount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 4 saladas");
                  }
                  if (scount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 3 saladas");
                  }
                  if (scount == 3){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 saladas");
                  }
                  if (scount == 4){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 salada");
                  }
              }
          } else if($(this).prop("checked") == false){
              scount--;
          }
      })

      $( ":input" ).click(function() {
      total = 0;
      sub = 0;

      if ($( "div#opcoes input:radio:checked" ).length > 0) {
        $( "#mudaopcao, #titulo2, div#quentes :checkbox, div#saladas :checkbox" ).css("display","inline-block");
        sub += $( "div#opcoes input:radio:checked" ).val() * 1;
        if ($( "div#opcoes input:radio:checked" ).attr("op") == 1){
            opc = 1;
            $( "#op2,#op3,#op4,div#quentes span" ).css("display","none");
        } else if ($( "div#opcoes input:radio:checked" ).attr("op") == 2){
            opc = 2;
            $( "#op1,#op3,#op4,div#quentes span" ).css("display","none");
        } else if ($( "div#opcoes input:radio:checked" ).attr("op") == 3){
            opc = 3;
            $( "#op1,#op2,#op4,div#quentes span" ).css("display","none");
        } else if ($( "div#opcoes input:radio:checked" ).attr("op") == 4){
            opc = 4;
            $( "#op1,#op2,#op3,div#quentes span" ).css("display","none");
            $("div#quentes span, div#saladas span").css("display","inline-block");

            $( "div#quentes :checkbox:checked" ).each(function() {
                sub += $( this ).val() * $( this ).parent().find("select").val();
            }) //each quentes

            $( "div#saladas :checkbox:checked" ).each(function() {
                sub += $( this ).val() * $( this ).parent().find("select").val();
            }) //each saladas
        }
      }

       $( "div#molhos :checkbox:checked" ).each(function(i) {
        if (i > 0) {
          sub += $( this ).val() * 1;
        }
    }); // each molhos

        $( "div#sobremesas :checkbox:checked" ).each(function() {
            sub += $( this ).val() * $( this ).parent().children( "select" ).val();
        }) //each sobremesas

        $( "div#sucos :checkbox:checked" ).each(function() {
            sub += $( this ).parent().children( ":radio:checked" ).val() * $( this ).parent().children( "select" ).val();
        }) //each sucos

        $( "div#bebidas :checkbox:checked" ).each(function() {
            sub += $( this ).val() * $( this ).parent().children( "select" ).val();
        }) //each bebidas

        $( "div#sopas :checkbox:checked" ).each(function() {
            sub += $( this ).val() * $( this ).parent().children( "select" ).val();
        }) //each sopas

        $( "div#emporio :checkbox:checked" ).each(function() {
            sub += $( this ).val() * $( this ).parent().children( "select" ).val();
        }) //each emporio

        total += sub;

        //aqui eu pego o cep
var cep = document.getElementById("cep").value;

//verifica se deve incrementar ou não
if(cep == "20040-010" || cep == "22750-009" || cep == "20071-002" || cep == "20090-910" || cep == "20210-010" || cep == "20080-102" || cep == "20230-130" || cep == "20081-250" || cep == "20090-030" || cep == "20090-030" || cep == "20211-340" || cep == "20211-351" || cep == "20221-240" || cep == "20221-250" || cep == "20230-011" || cep == "20230-025" || cep == "20230-150" || cep == "20230-160" || cep == "20230-240" || cep == "20231-016" || cep == "20231-030" || cep == "20231-031" || cep == "20231-050" || cep == "20211-005" || cep == "20231-085" || cep == "20230-014" || cep == "20231-004" || cep == "20021-180" || cep == "20240-180" || cep == "20240-051" || cep == "20211-010" || cep == "20230-170" || cep == "20230-024" || cep == "20240-050" || cep == "20230-050" || cep == "20231-006" || cep == "20090-010" || cep == "20230-901" || cep == "20040-051" || cep == "20241-080" || cep == "20221-901" || cep == "20051-011" || cep == "20021-190" || cep == "20240-200" || cep == "20230-170" || cep == "20231-015" || cep == "20211-350" || cep == "20231-020" || cep == "20061-030" || cep == "20240-050" || cep == "20230-015"){

        //se for um dos ceps acima, incrementa 4 no valor final
    taxa = 4.80;

        //verifica se deve incrementar ou não
}if(cep == "22221-010" || cep == "22221-011" || cep == "22210-906" || cep == "22250-060" || cep == "22250-020" || cep == "22250-902" || cep == "22250-903" || cep == "22250-030" || cep == "22230-020" || cep == "22210-030" || cep == "22210-065" || cep == "22210-901" || cep == "22210-903" || cep == "22210-904" || cep == "22210-902" || cep == "22210-060" || cep == "22210-905" || cep == "22250-110" || cep == "22220-080" || cep == "22220-900" || cep == "22230-075" || cep == "22220-030" || cep == "22231-140" || cep == "22210-050" || cep == "22230-010" || cep == "22250-130" || cep == "22220-050" || cep == "22220-040" || cep == "22230-040" || cep == "22210-040" || cep == "22250-100" || cep == "22250-120" || cep == "22220-060" || cep == "22230-060" || cep == "22230-061" || cep == "22230-902" || cep == "22230-903" || cep == "22230-901" || cep == "22230-030" || cep == "22231-150" || cep == "22210-085" || cep == "22210-080" || cep == "22230-080" || cep == "22250-090" || cep == "22250-070" || cep == "22231-130" || cep == "22250-080" || cep == "22230-000" || cep == "22230-001" || cep == "22230-900" || cep == "22221-000" || cep == "22210-070" || cep == "22230-070" || cep == "22230-050" || cep == "22231-230" || cep == "22240-180" || cep == "22240-090" || cep == "22240-120" || cep == "22240-030" || cep == "22231-210" || cep == "22245-130" || cep == "22240-160" || cep == "22231-170" || cep == "22231-900" || cep == "22240-130" || cep == "22241-020" || cep == "22240-080" || cep == "22240-170" || cep == "22231-220" || cep == "22245-020" || cep == "22245-070" || cep == "22221-110" || cep == "22245-000" || cep == "22231-110" || cep == "22245-030" || cep == "22245-060" || cep == "22240-000" || cep == "22240-003" || cep == "22240-004" || cep == "22240-006" || cep == "22240-005" || cep == "22240-900" || cep == "22221-120" || cep == "22221-130" || cep == "22240-040" || cep == "22231-160" || cep == "22240-020" || cep == "22221-070" || cep == "22245-110" || cep == "22245-120" || cep == "22221-100" || cep == "22231-120" || cep == "22245-140" || cep == "22240-100" || cep == "22231-070" || cep == "22245-050" || cep == "22241-000" || cep == "22241-970" || cep == "22231-100" || cep == "22221-080" || cep == "22231-200" || cep == "22245-010" || cep == "22221-090" || cep == "22221-140" || cep == "22231-090" || cep == "22231-901" || cep == "22240-150" || cep == "22231-080" || cep == "22245-150" || cep == "22245-040" || cep == "22245-100" || cep == "22240-060" || cep == "22240-140" || cep == "22241-010" || cep == "22240-110" || cep == "22231-180" || cep == "22240-070" || cep == "22245-080" || cep == "22245-090" || cep == "22221-150" || cep == "22240-010" || cep == "22231-190"){

        //se for um dos ceps acima, incrementa 5.5 no valor final
    taxa = 6.50;

}if(cep == "20020-010" || cep == "20020-040" || cep == "20020-080" || cep == "20021-060" || cep == "20021-120" || cep == "20021-900" || cep == "20021-903" || cep == "20030-002" || cep == "20030-015" || cep == "20030-013" || cep == "20030-020" || cep == "20030-021" || cep == "20030-060" || cep == "20030-070" || cep == "20030-120" || cep == "20002-080" || cep == "20002-008" || cep == "20003-021" || cep == "20030-905" || cep == "24220-031" || cep == "20002-010" || cep == "20030-015"){

    //se for um dos ceps acima, incrementa 0.7 no valor final
    taxa = 1.5;

}

total += taxa;

if(taxa != 0){

//caso a taxa seja diferente de 0, mostra ao usuário
    document.getElementById("idTaxa").innerHTML = "Custo adicional: R$ " + taxa;
}

        $( "div#total" ).html( "Valor total da sua
encomenda: R$ " + String(total.toFixed(2)).replace(".", ",") );
        $( "div#total" ).css("display", "block");
        $( "#total2" ).html( "R$ " + String(total.toFixed(2)).replace(".", ",") );
      }) //click
      $( "#total2" ).html( "R$ " + String(total.toFixed(2)).replace(".", ",") );

      $( "form" ).submit(function( event ) {
         if (opc == 4 && (qcount + scount)<6){
            event.preventDefault();
            alerta("Você deve escolher, no mínimo, 6 itens, entre os pratos quentes e saladas");
            return false;
        } else if (total < 17.90){
            event.preventDefault();
            alerta("O valor mínimo do pedido é R$ 17,90");
            return false;
        } else if ($("#nome").val()=="" || $("#endereco").val()=="" || $("#email").val()=="" || $("#cep").val()=="" || $("#telefone").val()==""){
            event.preventDefault();
            alerta("Todos os campos de informação são obrigatórios");
            return false;
        }
        mens();
      }); //form

}); // doc ready

Answer: Segue uma solução
Inclua no arquivo form.js:
$( "input[name=promo]" ).on( "click", function() {
    $("#sopa1").val(9.90);
    $("#sopa1v").text("9,90");
});

E no arquivo html
modifique essa linha:

<input id="sopa1" type="checkbox" value="15.50"> Minestrone - feijão branco com tofu defumado e legumes em cubos(P) : R$
15,50
 - Quant.: <select></select>

Veja se resolve a tua dúvida.
Edited: Inseri este código logo abaixo da função alerta no form.js

var str = "";
var id = "";
var sub = 0.00;
var taxa = 0;
var taxadeentrega = total - taxa;
var total = 0.00;
var qcount = 0;
var scount = 0;
var opc = 0;
var options = "";
for (i=1; i<21; i++){
    options += "<option value='" + i + "'>" + i + "</option>";
}

$( document ).ready(function() {

    $( "div div select" ).html(options);
    $( "div div :text" ).attr("value","1");
    $( "#emporio" ).css("display","block");
    $( "#mudaopcao" ).click(function() {
      location.reload(true);
    });
    function alerta(txt){
        $( "div#alerta" ).html( txt ).show( 0 ).delay( 2500 ).fadeOut( 500 );
    }

    $( "input[name=promo]" ).on( "click", function() {
      $("#sopa1").val(9.90);
      $("#sopa1v").text("9,90");
    });

function atencao(txt){
        $( "div#atencao" ).html( txt ).show( 0 ).delay( 2500 ).fadeOut( 500 );
    }
    function mens(){
        var d = new Date();
        var n = d.getDate() + "|" + (d.getMonth()+1) + "|" + d.getFullYear() + " - " + d.getHours() + ":" + d.getMinutes();

        $( "div#quentes :checkbox:checked" ).each(function() {
              str = str + $(this).parent().children("strong").text();
              if (opc == 4){
                  var sel = $(this).parent().children("span").children("select").val();
                  str = str + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",");
              }
              str = str + "
";
        })
        $('input[name=quentes]').val(str);
        str = "";

        $( "div#molhos :checkbox:checked" ).each(function() {
              str = str + $(this).parent().children("strong").text();
              if (opc == 4){
                  var sel = $(this).parent().children("span").children("select").val();
                  str = str + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",");
              }
              str = str + "
";
        })
        $('input[name=molhos]').val(str);
        str = "";

        $( "div#saladas :checkbox:checked" ).each(function() {
              str = str + $(this).parent().children("strong").text();
              if (opc == 4){
                  var sel = $(this).parent().children("span").children("select").val();
                  str = str + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",");
              }
              str = str + "
";
        })
        $('input[name=saladas]').val(str);
        str = "";

        $( "div#sobremesas :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              str = str + $(this).parent().children("strong").text() + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",") + "
";
        })
        $('input[name=sobremesas]').val(str);
        str = "";

        $( "div#sucos :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              var val = $(this).parent().children("input:radio:checked").val();
              str = str + $(this).parent().children("strong").text() + " - " + $(this).parent().children("input:radio:checked").attr("l") + ": R$ " + val.replace(".", ",") + " x " + sel + " = R$ " + (val * sel).toFixed(2).replace(".", ",") + "
";
        })
        $('input[name=sucos]').val(str);
        str = "";

        $( "div#bebidas :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              str = str + $(this).parent().children("strong").text() + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",") + "
";
        })
        $('input[name=bebidas]').val(str);
        str = "";

        $( "div#sopas :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              str = str + $(this).parent().children("strong").text() + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",") + "
";
        })
        $('input[name=sopas]').val(str);
        str = "";

        $( "div#emporio :checkbox:checked" ).each(function() {
              var sel = $(this).parent().children("select").val();
              str = str + $(this).parent().children("strong").text() + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",") + "
";
        })
        $('input[name=emporio]').val(str);
        str = "";

        str = String(total.toFixed(2)).replace(".", ",");
        $('input[name=mtotal]').val(str);
        str = "";

        str = String(+ taxa.toFixed(2)).replace(".", ",");
        $('input[name=taxadeentrega]').val(str);
        str = "";

        if(opc==1){
            $('input[name=op]').val("3 Quentes e 3 Saladas");
        }else if(opc==2){
            $('input[name=op]').val("4 Quentes e 4 Saladas");
        }else if(opc==3){
            $('input[name=op]').val("5 Quentes e 5 Saladas");
        }else{
            $('input[name=op]').val("");
        }

        if(opc==0){
            $('input[name=nop]').val("");
        } else {
            str = "Opção " + opc + ": ";
            $('input[name=nop]').val(str);
            str = "";
        }

        $('input[name=data]').val(n);
    }

      $("div#quentes :checkbox").click(function(){
          if($(this).prop("checked") == true){
              qcount++;
              if (opc == 1){
                  if (qcount == 4){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 3 pratos quentes, para mais escolha outra opção");
                      qcount = 3;
                  }
                  if (qcount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 pratos quentes");

                  }
                  if (qcount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 prato quente");

                  }
              } else if (opc == 2){
                  if (qcount == 5){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 4 pratos quentes, para mais escolha outra opção");
                      qcount = 4;
                  }
                   if (qcount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 3 pratos quentes");

                  }
                  if (qcount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 pratos quentes");

                  }
                   if (qcount == 3){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 prato quente");

                  }
              } else if (opc == 3){
                  if (qcount == 6){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 5 pratos quentes, para mais escolha outra opção");
                      qcount = 5;
                  }
                    if (qcount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 4 pratos quentes");

                  }
                  if (qcount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 3 pratos quentes");

                  }
                   if (qcount == 3){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 pratos quentes");

                  }
                   if (qcount == 4){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 prato quente");

                  }
              }
          } else if($(this).prop("checked") == false){
              qcount--;
          }
      })

      $("div#saladas :checkbox").click(function(){
          if($(this).prop("checked") == true){
              scount++;
              if (opc == 1){
                  if (scount == 4){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 3 saladas, para mais escolha outra opção");
                      scount = 3;
                  }
                  if (scount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 saladas");
                  }
                  if (scount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 salada");
                  }

              } else if (opc == 2){
                  if (scount == 5){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 4 saladas, para mais escolha outra opção");
                      scount = 4;
                  }
                   if (scount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 3 saladas");
                  }
                  if (scount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 saladas");
                  }
                  if (scount == 3){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 salada");
                  }

              } else if (opc == 3){
                  if (scount == 6){
                      $( this ).prop( "checked", false );
                      atencao("Você só pode escolher 5 saladas, para mais escolha outra opção");
                      scount = 5;
                  }
                  if (scount == 1){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 4 saladas");
                  }
                  if (scount == 2){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 3 saladas");
                  }
                  if (scount == 3){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 2 saladas");
                  }
                  if (scount == 4){
                      $( this ).prop( "checked", true );
                      alerta("Você ainda pode escolher 1 salada");
                  }
              }
          } else if($(this).prop("checked") == false){
              scount--;
          }
      })

      $( ":input" ).click(function() {
      total = 0;
      sub = 0;

      if ($( "div#opcoes input:radio:checked" ).length > 0) {
        $( "#mudaopcao, #titulo2, div#quentes :checkbox, div#saladas :checkbox" ).css("display","inline-block");
        sub += $( "div#opcoes input:radio:checked" ).val() * 1;
        if ($( "div#opcoes input:radio:checked" ).attr("op") == 1){
            opc = 1;
            $( "#op2,#op3,#op4,div#quentes span" ).css("display","none");
        } else if ($( "div#opcoes input:radio:checked" ).attr("op") == 2){
            opc = 2;
            $( "#op1,#op3,#op4,div#quentes span" ).css("display","none");
        } else if ($( "div#opcoes input:radio:checked" ).attr("op") == 3){
            opc = 3;
            $( "#op1,#op2,#op4,div#quentes span" ).css("display","none");
        } else if ($( "div#opcoes input:radio:checked" ).attr("op") == 4){
            opc = 4;
            $( "#op1,#op2,#op3,div#quentes span" ).css("display","none");
            $("div#quentes span, div#saladas span").css("display","inline-block");

            $( "div#quentes :checkbox:checked" ).each(function() {
                sub += $( this ).val() * $( this ).parent().find("select").val();
            }) //each quentes

            $( "div#saladas :checkbox:checked" ).each(function() {
                sub += $( this ).val() * $( this ).parent().find("select").val();
            }) //each saladas
        }
      }

       $( "div#molhos :checkbox:checked" ).each(function(i) {
        if (i > 0) {
          sub += $( this ).val() * 1;
        }
    }); // each molhos

        $( "div#sobremesas :checkbox:checked" ).each(function() {
            sub += $( this ).val() * $( this ).parent().children( "select" ).val();
        }) //each sobremesas

        $( "div#sucos :checkbox:checked" ).each(function() {
            sub += $( this ).parent().children( ":radio:checked" ).val() * $( this ).parent().children( "select" ).val();
        }) //each sucos

        $( "div#bebidas :checkbox:checked" ).each(function() {
            sub += $( this ).val() * $( this ).parent().children( "select" ).val();
        }) //each bebidas

        $( "div#sopas :checkbox:checked" ).each(function() {
            sub += $( this ).val() * $( this ).parent().children( "select" ).val();
        }) //each sopas

        $( "div#emporio :checkbox:checked" ).each(function() {
            sub += $( this ).val() * $( this ).parent().children( "select" ).val();
        }) //each emporio

        total += sub;

        //aqui eu pego o cep
var cep = document.getElementById("cep").value;

//verifica se deve incrementar ou não
if(cep == "20040-010" || cep == "22750-009" || cep == "20071-002" || cep == "20090-910" || cep == "20210-010" || cep == "20080-102" || cep == "20230-130" || cep == "20081-250" || cep == "20090-030" || cep == "20090-030" || cep == "20211-340" || cep == "20211-351" || cep == "20221-240" || cep == "20221-250" || cep == "20230-011" || cep == "20230-025" || cep == "20230-150" || cep == "20230-160" || cep == "20230-240" || cep == "20231-016" || cep == "20231-030" || cep == "20231-031" || cep == "20231-050" || cep == "20211-005" || cep == "20231-085" || cep == "20230-014" || cep == "20231-004" || cep == "20021-180" || cep == "20240-180" || cep == "20240-051" || cep == "20211-010" || cep == "20230-170" || cep == "20230-024" || cep == "20240-050" || cep == "20230-050" || cep == "20231-006" || cep == "20090-010" || cep == "20230-901" || cep == "20040-051" || cep == "20241-080" || cep == "20221-901" || cep == "20051-011" || cep == "20021-190" || cep == "20240-200" || cep == "20230-170" || cep == "20231-015" || cep == "20211-350" || cep == "20231-020" || cep == "20061-030" || cep == "20240-050" || cep == "20230-015"){

        //se for um dos ceps acima, incrementa 4 no valor final
    taxa = 4.80;

        //verifica se deve incrementar ou não
}if(cep == "22221-010" || cep == "22221-011" || cep == "22210-906" || cep == "22250-060" || cep == "22250-020" || cep == "22250-902" || cep == "22250-903" || cep == "22250-030" || cep == "22230-020" || cep == "22210-030" || cep == "22210-065" || cep == "22210-901" || cep == "22210-903" || cep == "22210-904" || cep == "22210-902" || cep == "22210-060" || cep == "22210-905" || cep == "22250-110" || cep == "22220-080" || cep == "22220-900" || cep == "22230-075" || cep == "22220-030" || cep == "22231-140" || cep == "22210-050" || cep == "22230-010" || cep == "22250-130" || cep == "22220-050" || cep == "22220-040" || cep == "22230-040" || cep == "22210-040" || cep == "22250-100" || cep == "22250-120" || cep == "22220-060" || cep == "22230-060" || cep == "22230-061" || cep == "22230-902" || cep == "22230-903" || cep == "22230-901" || cep == "22230-030" || cep == "22231-150" || cep == "22210-085" || cep == "22210-080" || cep == "22230-080" || cep == "22250-090" || cep == "22250-070" || cep == "22231-130" || cep == "22250-080" || cep == "22230-000" || cep == "22230-001" || cep == "22230-900" || cep == "22221-000" || cep == "22210-070" || cep == "22230-070" || cep == "22230-050" || cep == "22231-230" || cep == "22240-180" || cep == "22240-090" || cep == "22240-120" || cep == "22240-030" || cep == "22231-210" || cep == "22245-130" || cep == "22240-160" || cep == "22231-170" || cep == "22231-900" || cep == "22240-130" || cep == "22241-020" || cep == "22240-080" || cep == "22240-170" || cep == "22231-220" || cep == "22245-020" || cep == "22245-070" || cep == "22221-110" || cep == "22245-000" || cep == "22231-110" || cep == "22245-030" || cep == "22245-060" || cep == "22240-000" || cep == "22240-003" || cep == "22240-004" || cep == "22240-006" || cep == "22240-005" || cep == "22240-900" || cep == "22221-120" || cep == "22221-130" || cep == "22240-040" || cep == "22231-160" || cep == "22240-020" || cep == "22221-070" || cep == "22245-110" || cep == "22245-120" || cep == "22221-100" || cep == "22231-120" || cep == "22245-140" || cep == "22240-100" || cep == "22231-070" || cep == "22245-050" || cep == "22241-000" || cep == "22241-970" || cep == "22231-100" || cep == "22221-080" || cep == "22231-200" || cep == "22245-010" || cep == "22221-090" || cep == "22221-140" || cep == "22231-090" || cep == "22231-901" || cep == "22240-150" || cep == "22231-080" || cep == "22245-150" || cep == "22245-040" || cep == "22245-100" || cep == "22240-060" || cep == "22240-140" || cep == "22241-010" || cep == "22240-110" || cep == "22231-180" || cep == "22240-070" || cep == "22245-080" || cep == "22245-090" || cep == "22221-150" || cep == "22240-010" || cep == "22231-190"){

        //se for um dos ceps acima, incrementa 5.5 no valor final
    taxa = 6.50;

}if(cep == "20020-010" || cep == "20020-040" || cep == "20020-080" || cep == "20021-060" || cep == "20021-120" || cep == "20021-900" || cep == "20021-903" || cep == "20030-002" || cep == "20030-015" || cep == "20030-013" || cep == "20030-020" || cep == "20030-021" || cep == "20030-060" || cep == "20030-070" || cep == "20030-120" || cep == "20002-080" || cep == "20002-008" || cep == "20003-021" || cep == "20030-905" || cep == "24220-031" || cep == "20002-010" || cep == "20030-015"){

    //se for um dos ceps acima, incrementa 0.7 no valor final
    taxa = 1.5;

}

total += taxa;

if(taxa != 0){

//caso a taxa seja diferente de 0, mostra ao usuário
    document.getElementById("idTaxa").innerHTML = "Custo adicional: R$ " + taxa;
}

        $( "div#total" ).html( "Valor total da sua
encomenda: R$ " + String(total.toFixed(2)).replace(".", ",") );
        $( "div#total" ).css("display", "block");
        $( "#total2" ).html( "R$ " + String(total.toFixed(2)).replace(".", ",") );
      }) //click
      $( "#total2" ).html( "R$ " + String(total.toFixed(2)).replace(".", ",") );

      $( "form" ).submit(function( event ) {
         if (opc == 4 && (qcount + scount)<6){
            event.preventDefault();
            alerta("Você deve escolher, no mínimo, 6 itens, entre os pratos quentes e saladas");
            return false;
        } else if (total < 17.90){
            event.preventDefault();
            alerta("O valor mínimo do pedido é R$ 17,90");
            return false;
        } else if ($("#nome").val()=="" || $("#endereco").val()=="" || $("#email").val()=="" || $("#cep").val()=="" || $("#telefone").val()==""){
            event.preventDefault();
            alerta("Todos os campos de informação são obrigatórios");
            return false;
        }
        mens();
      }); //form

}); // doc ready

Escolha a sua opção:

<input type="radio" name="promo" value="24.90" op="1"> Opção 1: 3 Quentes e 3 Saladas - R$ 24,90

<input type="radio" name="promo" value="27.90" op="2"> Opção 2: 4 Quentes e 4 Saladas - R$ 27,90

<input type="radio" name="promo" value="30.90" op="3"> Opção 3: 5 Quentes e 5 Saladas - R$ 30,90

<input type="radio" name="promo" value="0.00"  op="4"> Opção 4: Monte seu prato à vontade (mínimo de 6 itens)

<input type="button" id="mudaopcao" class="botao" value=" Mudar a minha opção ">

Sopas:

<input id="sopa1" type="checkbox" value="15.50"> Minestrone - feijão branco com tofu defumado e legumes em cubos(P) : R$
15,50
 - Quant.: <select></select>

Comment: Obrigado pela atenção GBTX, aonde eu coloco o codigo do form.js? Logo depois da Sopa?
Comment: $('input[name=sopas]').val(str);
  str = "";

  $( "div#emporio :checkbox:checked" ).each(function() {
     var sel = $(this).parent().children("select").val();
     str = str + $(this).parent().children("strong").text() + ": R$ " + $(this).val().replace(".", ",") + " x " + sel + " = R$ " + (($(this).val() * sel).toFixed(2)).replace(".", ",") + "";
  })

  $( "input[name=promo]" ).on( "click", function() {
    $("#sopa1").val(9.90);
    $("#sopa1v").text("9,90");
});
Comment: Coloquei depois, mas não mudou o valor :(
Comment: Eu já modifico a minha resposta com o código completo.
Comment: Poxa, muito obrigado!
Comment: @AlessandroRamos Postei o código completo.
Comment: perfeito, funcionou!! Muito obrigado!!


É possível somar int com str composta de texto e números em Python?

Question: Fiz essa pergunta Por que no PHP a expressão "2 + '6 maçãs'" é igual a 8? aqui por achar esse comportamento estranho.
E no caso do python?
Eu consigo converter a string '1' str para 1 int.
Exemplo:
1 + int('1') # Imprime: 2

Porém, se eu tentar converter '1 cachorro' str para int ...
int('1 cachorro');

... é gerado um erro:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1 cachorro'

Seria possível fazer com que expressões do tipo 1 + int('1 cachorro') funcione em python?
Se eu precisasse fazer isso (creio que nunca vou precisar), como poderia tratar esse caso?
Comment: A dúvida do Wallace Maxter acabou sendo pra mim também, mas achei a solução aqui: http://pt.stackoverflow.com/questions/42280/como-extrair-d%C3%ADgitos-de-uma-string-em-python-e-som%C3%A1-los-entre-si
Answer:
Seria possível fazer com que expressões do tipo 1 + int('1 cachorro') funcione em python?

Não. Ou você soma inteiros ou concatena strings. Isso faz parte da segurança de tipos do Python.

Se eu precisasse fazer isso (creio que nunca vou precisar), como poderia tratar esse caso?

A única operação razoável seria a concatenação de strings. Se você quiser somar um inteiro numa string em lugares em que o Python tenha localizado números - que seria essa a interpretação mais exótica da sua pergunta -, você teria que escrever sua própria função para realizar isso, e não seria usando o operador de soma.
Comment: @WallaceMaxters E ainda pergunta.
Comment: _loucura_ do PHP vs _sanidade_ do Python! Qual escolher?
Comment: No PHP você só não pode somar um `int` com `array`. Se não gera um Erro fatal (e muitos inocentes caem nessa, sem tratar os dados que vêm da url)!
Answer: Sua pergunta já possui uma resposta na versão em inglês do StackOverflow!
O operador '+' funciona assim:

Se os 2 operandos forem números: efetua a soma
Senão: concatena strings.

Se a string conter apenas números ele consegue converter para inteiro.. caso contrário dá uma exception.
Por isso, no código onde você deseja converter uma string pra int você deve "esperar" que uma exceção aconteça.
string = "abcd"
try:
    i = int(string)
    print i
except ValueError:
    #Trata a exceção
    print 'a string não é um número'

Comment: Desculpa, Pedro, mas ainda não sou muito bom no inglês.
Comment: vou colocar o que é importante na resposta
Comment: Agora, sim. Quando vi o Link, fiquei meio perdido em qual das respostas do SOEN você estava apontando. Dica: Sempre clique em "share" na resposta, pois o link gerado cairá direto na resposta da pergunta :)
Comment: valeu pela dica.. editei o link !
Answer: Para fazer o que queres, penso que pode fazer o seguinte:
int( re.search(r'\d+', '1cachorro).group() )

O que isto vai fazer é pegar na string que colocou, procurar o inteiro e retorna-lo. Depois pode usar esse valor para fazer a sua soma.


how to combine SQL queries in columns

Question: I need rows of result set into columns. I currently have written the query :
SELECT COUNT(*) AS Male FROM add_faculty_override
WHERE gender='Male'
UNION
SELECT COUNT(*) AS Female FROM add_faculty_override
WHERE gender='Female';

This gives me the result as :
male
3          //total number of males
5          //total number of females

What I'd like to have instead as the result set is :
male   female
3        5

Comment: What RDBMS, A Pivot could be used in conjunction with a simple group by.
Comment: @xQbert PIVOT is not needed here. Its quite simple without a PIVOT. PIVOT would just be an overkill
Comment: My Queston has been answerd by Goat CO
Comment: @user3821879 Good, so please mark his answer as correct answer.
Answer: You can do this with a CASE statement:
SELECT COUNT(CASE WHEN gender='Male' THEN 1 END) AS Male
     , COUNT(CASE WHEN gender='Female' THEN 1 END) AS Female
FROM add_faculty_override

If you don't really need both results on one row then you can simply GROUP:
SELECT Gender, COUNT(*) AS Gender_Count
FROM add_faculty_override
GROUP BY Gender

Comment: Can you explain how this works to me so i can use this again?
Comment: @user3821879 Sure thing, the `CASE` statement returns either `1` or `NULL` depending on the criteria (`NULL` is the default when a row doesn't meet any `WHERE` criteria in a `CASE` statement and no `ELSE` is specified), `COUNT()` (like all aggregate functions) ignores `NULL` values, so it's left counting up all occurrences where `gender='Male'` for the first one, and `gender='Female'` for the second. I refer to it as a conditional aggregate, since you're only aggregating items that meet certain criteria.
Answer: You could use this:
SELECT (SELECT     COUNT(gender)
        FROM       add_faculty_override
        WHERE      gender='Male') AS 'Male',

       (SELECT     COUNT(gender)
        FROM       add_faculty_override
        WHERE      gender='Female') AS 'Female'

You can see this here->http://sqlfiddle.com/#!3/4ed9d/1
Hope this helps!!!

how to combine SQL queries in columns


Como associar uma ImageView a uma Classe?

Question: Apesar de ser algo genérico, para tentar esclarecer a minha dúvida, irei dar um exemplo.
Por exemplo, tenho um HashMap<Integer, Piece> com tamanho 64, em que Integer seria posição e Piece, classe para uma peça de tabuleiro. E tenho um layout com 64 ImageView(Quadrado 8x8), querendo relacionar isto, ou seja cada ImageView é uma Piece e a sua posição um Integer?
Como se faz esta associação entre Views e classes?
Answer: Você pode usar o método setTag(Object) da view para guardar nela o seu map, por exemplo. Dá uma lida na  documentaço da classe View


Clarifications needed in Divergence Theorem

Question: Consider this problem:
$F=[4x,x^2y,-x^2z]$ and $S$ is the tetrahedron described by $(0,0,0);(1,0,0);(0,1,0);(0,0,1)$
we have to find the surface integral.
Question 1: Applying divergence theorem $\nabla\cdot F =4$ which implies the surface integral turns into $\int \int \int 4 dV$ or otherwise 4 times the volume of tetrahedron. We know volume of tetrahedron is $\sqrt{2}a^3/12$ which means the answer should be $\sqrt{2}/3$. But the answer is not that.
Question 2: If we split $dV$ into $dxdydz$ and then integrate, the limit my book says should be  $0 to 1-y-z$,$0 to 1$,$0 to 1$ respectively. Can you talk a bit more about it. Intuitively I got an understanding, but how is it different the limits had it been from x+y+z=1?
Question 3: Just for the kicks I tried integrating this on the surface of the tetrahedron. I get the normal vector for only one surface, i.e the plane x+y+z =1 the others, turn into an equation where one of the variable (x,y,z) is zero [as the tetrahedron is bounded by that plane] which implies when turning into parametric form of u-v plane, the r(u,v) will be dependent on only 1 variable. For instance, one of the planes will be $x+z\leq 1$ => r(u,v)=[u,0,1-u] which implies $r_v=0$, hence cross product of $r_u$ and $r_v$ will be zero, hence the integral will be zero on that surface. This was my modus operandi. So I surface integrated over only $x+y+z \leq 1$ and I am getting a pretty way off the answer. Can someone lend me a hand here.
Thanks in advance
Soham
Answer: The volume of a simplex in $\mathbb{R}^n$ (tetrahedron in $\mathbb{R}^3$), one of whose vertices is the origin, is $\frac{1}{n!}$ times the determinant of the matrix with the other vertices as columns. Thus, the volume of your tetrahedron is
$$
\frac{1}{3!}\det\begin{bmatrix}1&0&0\\0&1&0\\0&0&1\end{bmatrix}=\frac16
$$
and $4\cdot\frac16=\frac23$, which is hopefully the correct answer.

The volume integral should be
$$
\int_0^1\int_0^{1-z}\int_0^{1-z-y}4\,\mathrm{d}x\,\mathrm{d}y\,\mathrm{d}z
$$
That is, $z$ can take on any value in $[0,1]$. The integral in $y$ is taken over each particular value of $z$, so $y$ can take any value in $[0,1-z]$. The integral in $x$ is taken over each particular value of $z$ and $y$, so $x$ can take any value in $[0,1-z-y]$.

On the surface $x+y+z=1$, the surface normal is $\nabla(x+y+z-1)=(1,1,1)$. Normalizing this gives the unit normal: $n=\frac{1}{\sqrt{3}}(1,1,1)$.
To integrate over this surface, the integral would be
$$
\begin{align}
&\int_0^1\int_0^{1-y}F\cdot n\sqrt{\left(\frac{\partial z}{\partial x}\right)^2+\left(\frac{\partial z}{\partial y}\right)^2+1}\;\mathrm{d}x\,\mathrm{d}y\\
&=\int_0^1\int_0^{1-y}F\cdot n\sqrt{3}\;\mathrm{d}x\,\mathrm{d}y\\
&=\int_0^1\int_0^{1-y}(4x,x^2y,-x^2z)\cdot(1,1,1)\frac{1}{\sqrt{3}}\sqrt{3}\;\mathrm{d}x\,\mathrm{d}y\\
&=\int_0^1\int_0^{1-y}(4x+x^2y-x^2z)\;\mathrm{d}x\,\mathrm{d}y\\
&=\int_0^1\int_0^{1-y}(4x+x^2y-x^2(1-x-y))\;\mathrm{d}x\,\mathrm{d}y\\
&=\int_0^1\int_0^{1-y}(x^3-x^2+4x+2x^2y)\;\mathrm{d}x\,\mathrm{d}y
\end{align}
$$
The other surfaces should be much simpler.
Answer: Q1: The volume of a regular tetrahedron  of side length $a$ may be $\sqrt{2}a^3/12$; but the tetrahedron $T$ at stake here is not regular. It can be viewed as a pyramid with base area ${1\over2}$ and height $1$, so its volume is ${1\over6}$. This implies that the flux $\Phi$ computed as a volume integral amounts to ${2\over3}$.
Q2: The triple integral in question is
$$\Phi=\int_0^1\Bigl(\int_0^{1-x}\bigl(\int_0^{1-x-y}4\ dz\bigr)\ dy\Bigr)\ dx\ .$$
To compute it you have to begin with the innermost integral: For given $(x,y)\in\Delta_1$ (the base triangle) the allowable $z$ have to satisfy $z\geq0$ and $x+y+z\leq1$. This leads to the integration interval $[0,1-x-y]$ for $z$, and the value of the innermost integral is therefore $=4(1-x-y)=:g(x,y)$. In the second step we have to integrate the function $g$ over $\Delta_1$. For given $x\in[0,1]$ (the base of $\Delta_1$) the allowable $y$ have to satisfy $y\geq0$ and $x+y\leq1$. This leads to the integration interval $[0,1-x]$ for $y$. The value of the integral $\int_0^{1-x} g(x,y)\ dy$ is a function $x\mapsto h(x)$ which in the third step has to be integrated from $0$ to $1$.
Q3: The surface $\partial T$ of our tetrahedron consists of four triangles. In order to compute the  total flux $\Phi:=\int_{\partial T}{\bf F}\cdot d{\bf \vec\omega}$ we therefore have to compute four separate integrals over four parameter triangles.
For the base triangle $\Delta_1$ we use the trivial parametrization ${\bf f}:(x,y)\mapsto(x,y,0)$ with $d\vec\omega=(0,0,-1)\ {\rm d}(x,y)$ (we need the outward normal). Therefore we get
$$\int_{\Delta_1}{\bf F}\cdot d\vec\omega=\int_0^1\int_0^{1-x}\bigl(4x,x^2y,0)\cdot(0,0,-1)\ dy\ dx=0\ .$$
I hope you can do the other three yourself.
Comment: Regarding Q#2, I was not actually asking about the way to integrate but rather the limits. How did they come decide upon the limits
Comment: @Soham: See my edit.


Diferença de desempenho entre C e MatLab

Question: Amigos,
criei dois códigos de criptografia aparentemente idênticos, um em linguagem C e outro em MatLab, o código em MatLab possui mais funções, ou seja, é mais extenso e executa mais funções do que o código em C. Para medir o tempo de execução estou usando a função tic e toc no MatLab, já no código em C estou usando a função clocks (estou usando o CodeBlocks como IDE de programação), porém parece que a medição da um valor muito diferente e não preciso no código em C.
MatLab --> 0,049 segundos.
C --> 1 milisegundo.

Alguém sabe me explicar o porque disso?
Segue o código em C:
main:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include "ti_aes128.h"

    int main( void )
    {
        clock_t Ticks[2];
       Ticks[0] = clock();
      unsigned char state[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
                                   0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};

      unsigned char key1[]   = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                               0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};

      aes_enc_dec(state,key1,0);
      aes_enc_dec(state,key1,1);
       Ticks[1] = clock();
        double Tempo = (Ticks[1] - Ticks[0]) *1000 / CLOCKS_PER_SEC;
        printf("Tempo gasto: %g ms.", Tempo);
        getchar();
        return 0;
    }

ti_aes128:
// foreward sbox
const unsigned char sbox[256] =   {
//0     1    2      3     4    5     6     7      8    9     A      B    C     D     E     F
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //A
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //B
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //C
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //D
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //E
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; //F

// inverse sbox
const unsigned char rsbox[256] =
{ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb
, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb
, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e
, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25
, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92
, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84
, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06
, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b
, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73
, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e
, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b
, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4
, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f
, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef
, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61
, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };

// round constant
const unsigned char Rcon[10] = {
    0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36};

// multiply by 2 in the galois field
unsigned char galois_mul2(unsigned char value)
{
  signed char temp;
  // cast to signed value
  temp = (signed char) value;
  // if MSB is 1, then this will signed extend and fill the temp variable with 1's
  temp = temp >> 7;
  // AND with the reduction variable
  temp = temp & 0x1b;
  // finally shift and reduce the value
  return ((value << 1)^temp);
}

// AES encryption and decryption function
// The code was optimized for memory (flash and ram)
// Combining both encryption and decryption resulted in a slower implementation
// but much smaller than the 2 functions separated
// This function only implements AES-128 encryption and decryption (AES-192 and
// AES-256 are not supported by this code)
void aes_enc_dec(unsigned char *state, unsigned char *key, unsigned char dir)
{
  unsigned char buf1, buf2, buf3, buf4, round, i;

  // In case of decryption
  if (dir) {
    // compute the last key of encryption before starting the decryption
    for (round = 0 ; round < 10; round++) {
      //key schedule
      key[0] = sbox[key[13]]^key[0]^Rcon[round];
      key[1] = sbox[key[14]]^key[1];
      key[2] = sbox[key[15]]^key[2];
      key[3] = sbox[key[12]]^key[3];
      for (i=4; i<16; i++) {
        key[i] = key[i] ^ key[i-4];
      }
    }

    //first Addroundkey
    for (i = 0; i <16; i++){
      state[i]=state[i] ^ key[i];
    }
  }

  // main loop
  for (round = 0; round < 10; round++){
    if (dir){
      //Inverse key schedule
      for (i=15; i>3; --i) {
    key[i] = key[i] ^ key[i-4];
      }
      key[0] = sbox[key[13]]^key[0]^Rcon[9-round];
      key[1] = sbox[key[14]]^key[1];
      key[2] = sbox[key[15]]^key[2];
      key[3] = sbox[key[12]]^key[3];
    } else {
      for (i = 0; i <16; i++){
        // with shiftrow i+5 mod 16
    state[i]=sbox[state[i] ^ key[i]];
      }
      //shift rows
      buf1 = state[1];
      state[1] = state[5];
      state[5] = state[9];
      state[9] = state[13];
      state[13] = buf1;

      buf1 = state[2];
      buf2 = state[6];
      state[2] = state[10];
      state[6] = state[14];
      state[10] = buf1;
      state[14] = buf2;

      buf1 = state[15];
      state[15] = state[11];
      state[11] = state[7];
      state[7] = state[3];
      state[3] = buf1;
    }
    //mixcol - inv mix
    if ((round > 0 && dir) || (round < 9 && !dir)) {
      for (i=0; i <4; i++){
        buf4 = (i << 2);
        if (dir){
          // precompute for decryption
          buf1 = galois_mul2(galois_mul2(state[buf4]^state[buf4+2]));
          buf2 = galois_mul2(galois_mul2(state[buf4+1]^state[buf4+3]));
          state[buf4] ^= buf1; state[buf4+1] ^= buf2; state[buf4+2] ^= buf1; state[buf4+3] ^= buf2;
        }
        // in all cases
        buf1 = state[buf4] ^ state[buf4+1] ^ state[buf4+2] ^ state[buf4+3];
        buf2 = state[buf4];
        buf3 = state[buf4]^state[buf4+1]; buf3=galois_mul2(buf3); state[buf4] = state[buf4] ^ buf3 ^ buf1;
        buf3 = state[buf4+1]^state[buf4+2]; buf3=galois_mul2(buf3); state[buf4+1] = state[buf4+1] ^ buf3 ^ buf1;
        buf3 = state[buf4+2]^state[buf4+3]; buf3=galois_mul2(buf3); state[buf4+2] = state[buf4+2] ^ buf3 ^ buf1;
        buf3 = state[buf4+3]^buf2;     buf3=galois_mul2(buf3); state[buf4+3] = state[buf4+3] ^ buf3 ^ buf1;
      }
    }

    if (dir) {
      //Inv shift rows
      // Row 1
      buf1 = state[13];
      state[13] = state[9];
      state[9] = state[5];
      state[5] = state[1];
      state[1] = buf1;
      //Row 2
      buf1 = state[10];
      buf2 = state[14];
      state[10] = state[2];
      state[14] = state[6];
      state[2] = buf1;
      state[6] = buf2;
      //Row 3
      buf1 = state[3];
      state[3] = state[7];
      state[7] = state[11];
      state[11] = state[15];
      state[15] = buf1;

      for (i = 0; i <16; i++){
        // with shiftrow i+5 mod 16
        state[i]=rsbox[state[i]] ^ key[i];
      }
    } else {
      //key schedule
      key[0] = sbox[key[13]]^key[0]^Rcon[round];
      key[1] = sbox[key[14]]^key[1];
      key[2] = sbox[key[15]]^key[2];
      key[3] = sbox[key[12]]^key[3];
      for (i=4; i<16; i++) {
        key[i] = key[i] ^ key[i-4];
      }
    }
  }
  if (!dir) {
  //last Addroundkey
    for (i = 0; i <16; i++){
      // with shiftrow i+5 mod 16
      state[i]=state[i] ^ key[i];
    } // enf for
  } // end if (!dir)
} // end function

Comment: Pode fornecer o código?
Comment: @mercador  Veja a pergunta editada.
Comment: @Mutante: Pode ser que, no seu SO, a resolução de `clock()` seja só 1 ms; neste caso, você vai ter que usar um contador de alta resolução, que varia de acordo com o SO. Mas não vejo por que um código compilado em C não seja 400 vezes mais rápido que o mesmo código interpretado pelo Matlab...
Answer: Na verdade você não precisa de um temporizador de alta resolução para resolver o seu problema.
O segredo é realizar o seu teste repetidas vezes e depois calcular a média de tempo. Vejá só:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "ti_aes128.h"

#define N (1000000L)

int main( void )
{
    time_t t0, t1, elapsed;
    double ms = 0;
    int i = 0;

    unsigned char state[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
                            0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};

    unsigned char key1[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                            0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};

    /* Recupera momento inicial */
    t0 = time(NULL);

    /* Executa o mesmo Teste N vezes... */
    for( i = 0; i < N; i++ )
    {
        /* Operacoes a serem testadas... */
        aes_enc_dec( state, key1, 0 );
        aes_enc_dec( state, key1, 1 );
    }

    /* Recupera momento final */
    t1 = time(NULL);

    /* Subtrai momento inicial do momento final */
    elapsed = t1 - t0;

    /* Calcula a media de tempo por execucao em milissegundos... */
    ms = ((double)(elapsed * 1000)) / N;

    printf("Media de tempo gasto por operacao: %g ms.\n", ms );

    return 0;
}


WPF: Rotate a rectangle with slider

Question: I'm trying to rotate a rectangle when scrolling slider
there are 2 steps: Click on a rectangle - Scroll the slider.
If I draw only one rectangle, everything is ok.
But when I draw 2 rectangles or more and start rotating, all of my rectangle are rotated together with same angle.
I have no idea about this.
Can anyone help me?
Thanks in advance!
Here is my code: (I found the code for rotating at another post in this page)
<code>    Shape _shape;
    RotateTransform rt = new RotateTransform();
        private void MyCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs)
        {

                        /////////////////////////////////////////////////////
                        //for know which rectangle has been clicked
                        if (MyTransform_type == TRANSFORM_TYPE.ROTATE)
                        {
                            _shape = e.OriginalSource as Shape;
                            if (_shape != null)
                            {
                               _shape = (Shape)e.OriginalSource;
                            }
                        }

                }

        private void MyCanvas_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
                {
                    if (MyTransform_type != TRANSFORM_TYPE.NONE && MyTransform_type != TRANSFORM_TYPE.ROTATE)
                    {
                        if (_shape == null)
                            return;
                        //_shape.ReleaseMouseCapture();
                        Cursor = Cursors.Arrow;
                    }
                }

        private void sldRotate_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
                {
                    if (_shape != null)
                    {
                        _shape.RenderTransform = rt;
                        _shape.RenderTransformOrigin = new Point(0.5, 0.5);
                        var da = new DoubleAnimation(rt.Angle, sldRotate.Value, new Duration(TimeSpan.FromSeconds(0.001)));
                        rt.BeginAnimation(RotateTransform.AngleProperty, da);
                        rt.Angle = sldRotate.Value;
                    }

  }
</code>
Comment: please add the complete code, e.g. where do you set "rt"?
Comment: "rt" is on the top of my code :D
Answer: Your mistake is that you create a single RotateTransform object and assign it to the different shapes. So after clicking on several rectangles, every rectangle has the same rotatetransform instance. If you now change the value of the rotatetransform, every rectangle will rotate...
In order to fix that you should change your sldRotate_ValueChanged method. Check if the current shape has already a rotatetransform. If not then create one, if yes adjust the rotatetransform...
Additionally, if you have such a small animation time, you can just leave it out:
<code>private void sldRotate_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
    if (_shape != null)
    {
        var rt = new RotateTransform();
        rt.Angle = sldRotate.Value;
        _shape.RenderTransform = rt;
        _shape.RenderTransformOrigin = new Point(0.5, 0.5);
    }
}
</code>
Answer: It looks like you are using the same RotateTransform named "rt" for all of your rectangles. The simpliest solution will be:
<code>    private void MyCanvas_MouseRightButtonDown(object sender, MouseButtonEventArgs)
    {
        if (MyTransform_type == TRANSFORM_TYPE.ROTATE)
        {
           _shape = e.OriginalSource as Shape;

           //creating new RotateTransform
           rt=new RotateTransform();

           if (_shape != null)
           {
              _shape = (Shape)e.OriginalSource;
           }
        }
    }
</code>
also you could do
<code>    _shape.RenderTransform = rt;
</code>
in MyCanvas_MouseRightButtonDown after
<code>    _shape = e.OriginalSource as Shape;
</code>
instead of doing it each time, when sldRotate_ValueChanged executes to avoid unneeded assignments.

WPF: Rotate a rectangle with slider


Creating simple slideDown and slideUp animation in css

Question: I have some css like this
  .top-over {
    position: absolute;
    top: 205px;
    z-index: 55;
    width: 100%;
    min-height: 300px;
  }

  @keyframes slideDown {
    0% {
      -webkit-transform: translateY(-420px);
    }

    100% {
      -webkit-transform: translateY(0%);
    }
  }

  .slideDown {
    -webkit-animation-name: slideDown;
    animation-name: slideDown;
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-timing-function: ease;
    animation-timing-function: ease;
    visibility: visible !important;
    z-index: 50;
  }

You will see that i have two classes slideDown and .top-over
.slideDown work just ok, but on .top-over it just jumps no slide effect, does anybody knows what i need to correct that this works to slideUp, thanks
Comment: `translateY(-420)` . A unit is missing here. And you don't need vendor prefix.
Answer: Several notes:

you might want to remove the -webkit- prefixed values since they're not needed in this case. In cases where they are needed, they shouldn't be used either.
Both transform and animation are supported by every modern browser without prefixes.
use the same units across an animation - choose either px or %, not both.
you should post your html code as well. Please make it as minimal as possible and share your snippet.
Answer:

Some content here....

<%--Hope this will work.Thanks in advance--%>
Answer:

Comment: Thanks, but I need pure css, not Jquery
Comment: try to add context to your answer, instead of just copy pasting code. Also the question is for how to create a css animation, if you propose another solution try to give a solid context to why jquery in this instance is the right answer.


Linking content type nodes with each other

Question: I have two content types that I want to link each other. I checked node references, but node references only allows me to link to others when creating a node of that content type. What If I wanted to link two nodes of content types that are already created?
Please let me know if it is possible in Drupal-6.
Thanks
Comment: Then you _edit_ the node and add the reference
Comment: what if i want to add multiple references ? Also what if a User who did not create it want to reference it ?
Comment: See my answer below
Answer: You can actually "link" nodes at any time, you just have to edit the node to add the reference.
If you want to add multiple references, you have to specify this when you set up the node reference field in your content type.  In the configuration page of the node reference field, choose how many references you want to allow (1-10, or unlimited).
For a user to add a reference that did not create the node, make sure the correct permissions are set in admin/user/permissions for the given user role. (ie "edit any EXAMPLE content")
Comment: I am using drupal Commons. But I don't see where I can change the node references when I click on edit ?
Comment: Are you the admin user? Have the template files been modified? Unfortunately there's not much I can tell you with the info given.  The field *should* be visible on the edit page
Comment: Can I setup permission in such a way that users can only edit the reference field ?
Comment: Yes, you should be able to if you have the Content Permissions sub-module of CCK enabled.  Go back to the permissions page and find the **content_permissions module** heading.  Then all of the fields will be listed and you can choose which fields each role can edit, etc


How to find a YouTube dislike button with JavaScript in a Chrome Extension?

Question: I am writing a Google Chrome extension. I don't know JavaScript and I'm trying to identify whether the "dislike" button is active (means blue, because it has been clicked by me at some point and therefore marks that I don't like the video) element in a YouTube video page.
I tried various ways but I am hopeless. A few of my attempts:
//result = document.querySelector("path[d]");
    //var something = document.querySelector('[d=M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v1.91l.01.01L1 14c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .126.96.36.199 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm4 0v12h4V3h-4z" class="style-scope yt-icon]');

Can somebody help me? Interestingly I only find this attribute when inspecting the page, if I look at the page source it't not even present in the page (I have no web development knowledge, I suspect it's some dynamic trick?).
Edit: I use the following at the beginning of my chrome extension background script to make sure the page is loaded:
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {

if (changeInfo.status == 'complete') {
    if (tab.url.indexOf("youtube.com") != -1) {

Answer: As long as YouTube doesn't change things, you can take advantage of the aria-label attribute of button elements.
The one you are looking for starts with "dislike" ("dislike this video along with 89 other people" - the number will probably vary, the rest - probably not).
Try this:
for(var btn of document.getElementsByTagName("button"))
  if(btn.getAttribute("aria-label"))
    if(btn.getAttribute("aria-label").includes("dislike"))
      console.log(btn);

Instead of console.log(btn) you can use btn.click().
Comment: It worked for me - did it work for you?
If so, please select and up-vote my answer.
Answer: Try this:
var dislikeButtonElement = document.querySelector("#top-level-buttons > ytd-toggle-button-renderer").nextElementSibling;
if(dislikeButtonElement.classList.contains("style-default-active")){
    //Dislike button active
    alert("Disliked Video");
}

Be aware that this will only work after the page has fully loaded as YouTube loads almost everything dynamically. On a slower connection, the video may be playing before these buttons have loaded
Comment: Thanks so far. This looks really promising, but somehow it won't find anything with the query. I tried  var document.querySelector(".ytd-menu-renderer"); and document.querySelector("#top-level-buttons"); but still null. I think I am ensuring the page is loaded - I updated my post to show the code snipped I'm using to check if the page is loaded. But somehow it's missing that part and won't find anything. What's the trick here?
Comment: Try opening dev tools whilst on a youtube video and paste this into the console. If it works for you there too, its likely your code is trying to find the button before it exists
Comment: Yep, it's definitely not null when done from the console. Thanks for showing me the console btw. Hmm, I enhanced the condition with tab checking if (changeInfo.status == 'complete' && tab.status == 'complete') - but still the same. I guess I'll have to search a bit more on how to limit it on properly loaded. Thanks so far. In case you also happen to know how to do that, let me know, thx.
Comment: This would probably be useful for that: https://stackoverflow.com/questions/32810912/event-fired-by-youtube-when-video-page-is-loaded


Closed form expression for sequence of values created by differently signed series

Question: Consider a sequence of terms of powers of $m\in\mathbb{R}$ as
$$
M_n = m^0, m^1, m^2, m^3, \ldots, m^n
$$
and create a set that contains all the values of the various signed combinations of these terms. For example, for $M_2 = m^0,m^1,m^2$ we would have our set $S$ containing the values
$$
|m^0 + m + m^2|
$$
$$
|m^0 - m + m^2|
$$
$$
|m^0 + m - m^2|
$$
$$
|m^0 - m - m^2|
$$
Notice that we always keep $m^0$ positive. Now, in the special case of $m=2$ it turns out that our set $S$ will always comprise of the first $2^n$ odd numbers. This means that our example with $M_2$
$$
S = \{1,3,5,7\}
$$
This is very nice because we can create a nice, indexed closed form of our set using the formula
$$
S = \{2k-1 | 1\leq k \leq n\}
$$
which then makes summations incredibly easy.
My question is, does there exist such a closed form expression that iterates over all values of a set $S$, given any $m$ and any $n$?
Comment: Is this for the set with or without duplicates?
Comment: Actually, I think there are only duplicates if $m \in \{-1, 0, 1\}$
Comment: just by the way I defined $m$, technically it can never be any of those listed values, so if those create duplicates you can ignore them. If it makes it easier $m$ is strictly larger than $1$, even though I left it out of the original post in order to possibly generalize, but use the easier case first if you have a thought!
Comment: You claim to always keep $m^0 = 1$ positive, but then you take the absolute value, which will sometimes multiplies through by $-1$. In truth, for $m > 1$, it is $m^n$ that you are always keeping positive.
Answer: Input: $m,n$.
Algorithm: Solve $a_k:=ma_{k-1}-2$, $a_1=2$; and $b_k:=mb_{k-1}-1$, $b_1=1$.
Output: The set $S_{m,n}$ is given by the fractal sequence $$b_n+a_1+a_2+a_1+a_3+a_1+\cdots+a_{n-1}+\cdots+a_1+a_2+a_1$$
Example: For $m=5$, $a_k=\frac{1}{2}(3.5^{k-1}+1)=(2,8,38,188,938,\ldots)$.
$b_k=\frac{1}{4}(3.5^{k-1}+1)=(1, 4, 19, 94, 469, 2344,\ldots)$
$S_{5,5}$ is given by $$469+2+8+2+38+2+8+2+188+2+8+2+38+2+8+2$$ $$S_{5,5}=\{469, 471, 479, 481, 519, 521, 529, 531, 719, 721, 729, 731, 769, 771,
779, 781\}$$
Comment: This is the same answer as TonyK's, with $b_n=1\ldots 1_m-2\ldots2_m$ being the starting value rather than the final value $1\ldots1_m$, and $a_k$ are the values of successive numbers of $0$s and $2$s in difference form.
Answer: If $m$ is an integer $\ge 3$, then $S_n$ has a compact description in base $m$: it consists of all numbers of the form $\underbrace{11\ldots1_m}_{(n+1)\,1\text{'s}}-k$, where $k$ is an $n-$digit number containing only $0$'s and $2$'s.
For instance, if $m=5$ and $n=2$ then $111_5=31_{10}$ and we get
$$S=\{31_{10}-00_5,31_{10}-02_5,31_{10}-20_5,31_{10}-22_5\}=\{31,29,21,19\}$$


Print CCK field "A" if CCK field "B" has a value of "Z"

Question: I want to print a CCK field (we'll call it CCK field "A") only if the value of another CCK field (we'll call it CCK field "B") matches a string. CCK field "B" is a select-list field with two options: "red" and "blue". I'd like to display the value of CCK field "A" only if the value of CCK field "B" is "blue". If the value is "red", then CCK field "A" should not be displayed at all.
How can I do so?
Thanks!
Answer: THIMK! Test the value of Field B before printing Field A.
<code><?php
if(isset($node->field_field_b['und'][0]['value']) && ($node->field_field_b['und'][0]['value'] == 'blue')) {
    if(isset($node->field_field_a['und'][0]['value'])) {
          print $node->field_field_a['und'][0]['value'];
    }
  }
 ?>
</code>
Comment: Great. Happy to help.


Combinatorics with three dice

Question: Question: Three dice are rolled. If X represents the second largest value of the three rolls, derive the probability distribution of X.
Many thanks in advance for all your help!
What I have tried so far:
I tried at first to consider all unique rolls, of which there are 56, and my distribution was:
P(X=1)=6/56
P(X=2)=10/56
P(X=3)=12/56
P(X=4)=12/56
P(X=5)=10/56
P(X=6)=6/56
but then I realised that I had to take into account the different orders. So I then tried the following:
When all three numbers are the same, there are 3! possible ways these numbers can be ordered, so the number of possibilities increases by 36 (6 each for all of 1,2,3,4,5,6).
When two of the numbers are the same, there are 2! possible ways these numbers can be ordered for each case, but the numbers can be written in increasing/decreasing order, so I need to multiply by a factor of 2. 30*4=120 cases.
If the numbers are all different, the middle number is fixed, but the other two numbers can be swapped, so 20*2=40.
This gave me 196 cases to consider. At this point, I became stuck and didn't see a systematic way to derive a distribution. I'm not even sure the number of cases as 196 is correct.
Comment: I have done so, many thanks.
Comment: What attempts have you made to solve this problem? If you put that in your question we will be able to help you better.
Comment: There are $6^3=216$ ordered ways three dice can fall, so you are missing some.
Comment: Thank you Ross! I had gotten my head in a tangle over what could be considered a combination, and forgot, among other things, that 111 was only one combination etc. Your very rigorous explanation has helped me to understand!
Answer: There are $6^3=216$ ways that three different dice can fall.  To have the middle number be $1$ you have to throw $111,112,113,114,115, \text{ or } 116$  The first represents one combination, the others three, so the chance $1$ is the middle number is $1$ is $\frac {16}{216}$.  By symmetry, this is the same as the chance $6$ is the middle number.
To have $2$ the middle number we need $122, 12x, 222, \text { or } 22x$ where $x$ represents a number greater than $2$ so is $4$ possibilities.  $122$ is three throws, $12x$ is $24, 222$ is $1, 22x$ is $12$, so the chance $2$ is the middle number is $\frac {40}{216}$.  By symmetry that is also the chance that $5$ is the middle number.
The chances $3$ and $4$ are the middle number are equal by symmetry and must represent all the rest of the probability.  The chance it is $3$ is then $\frac 12-\frac {16+40}{216}=\frac {13}{54}$

Combinatorics with three dice


Whether an embedding is an automorphism

Question: Let $K/F$ be a field extension and let $\sigma$ be an embedding from $K$ into $K$ over $F$. If $K/F$ is algebraic, prove that $\sigma \in Aut(K)$.
I know how to prove the case when $K/F$ is finite. But I have no idea how to do it if $K/F$ is not finite.
Answer: For $x \in K$ let $R(x) \subseteq K$ denote the set of roots in $K$ of the minimal polynomial of $x$ over $F$. Then $\sigma$ maps every element of $R(x)$ into $R(x)$ and as $\sigma$ is injective the restriction of $\sigma$ to $R(x)$ is so too and as $R(x)$ is finite, it is also surjective, thus there exists $y \in R(x)$ such that $\sigma(y) = x$. Hence $\sigma: K \rightarrow K$ is surjective and thus an automorphism.
Comment: I was wondering that if $\sigma \mid _{K}$ is just an isomorphism from $K$ to $K$, is it still an automorphism?
Comment: @Mod.esty An automorphism is an isomorphism with identical target and source, right? So what would be missing here in your opinion?
Comment: Oh, I am very sorry. I means if $\sigma$ over $F$ is just an isomorphism from $F$ to $F$ which dones't need to be the identical map, is $\sigma$ still an automorphism from $K$ to $K$?
Comment: I see now what you mean. To say that $\sigma$ is an embedding from $K$ to $K$ *over* $F$ means that $\sigma|_{F}$ is the identity, so this assumption was already present in the question.
Answer: Let $\beta\in K$. we want to show that there exists some $\alpha\in K$ such that $\sigma(\alpha)=\beta$. Suppose $p(x)=\text{MiPo}_F(\beta)$. Since the set of roots of $p(x)$ in $K$ is finite and for each root $\gamma$, $\sigma(\gamma)$ is also a root, $\sigma$ is a bijection over the roots and we're done !

Whether an embedding is an automorphism


Can we find sufficient conditions in which this equation have only three distinct real roots

Question: Let us consider the polynomial equation:
$$ξ₁x⁸+ξ₂x⁷+ξ₃ x⁶+ξ₄  x⁵+ξ₅ x⁴+ξ₆  x³+ξ₇  x²+(ξ₈-1)  x+ξ₉ =0$$
where $ξ_{i}$ are real coefficients.
My question is: Can we find sufficient conditions in which this equation have only three distinct real roots.
Comment: It is impossible to have 3 real roots and 5 complex roots, since complex roots of a real polynomials come in pair. you need at least one real double root.
Comment: Obviously not. If $f(z)$ is a polynomial of $n$ degree then there are $n$ distinct zeros of the polynomial. To clarify, are you asking if there is a condition in which there are 3 real roots and 5 complex roots?
Comment: @Aleksandar: Yes.
Comment: Okay, makes complete sense.
Comment: You can rewrite all of this equivalently asking if there are sufficient conditions on the coefficients of a real polynomial of degree $8$ such that it has exactly $3$ distinct real roots.
Answer: Hint:
Since a polynomial of the form:
$p(z)=\sum_{k=0}^m a_{k}z^{k}$
Can be expressed as the following where $\beta_{1},...,\beta_{m}$ are $m$ roots of the polynomial:
$p(z)=a_{0}(z-\beta_{1})...(z-\beta_{m})$
Assume $5$ of the $8$ roots are complex and expand the polynomial. See if there exist conditions in which there could be 3 real and 5 complex roots.
I.e.
$\xi_{1}(x-a)(x-b)(x-c)(x-(\alpha_{1}+i\beta_{1})(x-(\alpha_{2}+i\beta_{2}))...(x-(\alpha_{5}+i\beta_{5}))$
Expand this out and see if there exist conditions in which this could be a polynomial with real coefficients.


Running raco on the Windows command line

Question: I am trying to make a stand-alone Racket executable on the Windows platform. How do I go about running raco from the windows command line? I'm not familiar with it.
If I use the documentation and enter the following command into cmd.exe:

raco exe --gui main.rkt

cmd.exe tells me:

'raco' is not recognized as an internal or external command, operable program or batch file.

Substituting in raco.exe tells me the same thing.
I also tried typing:

'C:\Program Files\Racket\raco.exe' exe --gui .\main.rkt

into powershell and it gave me an Unexpected token 'exe' in expression or statement error.
Comment: Oscar answered the question as you asked it, re using the command line. Just to mention something you probably already know (but someone else might not): Another way to make an executable is in DrRacket. From the **Racket** menu choose **Create Executable**.
Answer: For the first problem: you need to add to windows' %PATH% (an environment variable) the path to the executable. For the second problem: check the correct syntax for the exe command, and/or the "--gui" modifier, they're being misused. For instance, try this after solving the first problem:
$ raco.exe exe main.rkt

The above will create an executable main.exe file.
Comment: I have the same problem: raco says "Unrecognized command: exe".
Answer: Download and install Racket, which includes DrRacket. (Of course, you're welcome to use your preferred text editor, but the tutorials will assume you're using DrRacket.)
Update the PATH environment variable on your system to include the directory that holds the racket application. On Mac OS and Linux, this path will be something like "/path/to/racket/bin". On Windows, it'll be something like "C:\Program Files\Racket". Then, from the terminal, you'll be able to run racket and raco (see raco: Racket Command-Line Tools).
Windows users who haven't altered your PATH before: don't panic. To add the Racket command-line programs to your Windows 10 PATH, click the Windows search box, type the word path, and then click on Edit the system environment variables. Click on the Environment Variables button. In the top window, which contains your user variables, find Path and double-click it to open. Click the New button and either use the Browse button to select your Racket directory, or manually enter its path. Restart your Windows terminal (either the Command Prompt or PowerShell) and now racket and raco should work.


How to use multiple submit within a CTools Modal

Question: I'm using a CTools modal to add a holiday. The topside of that form in the modal displays the already defined holidays with an "X" that will allow you to delete a holiday. I have created a submit button for each that is put in a table with this code (the rows are rendered in a table afterwards).
<code>foreach ($locationVO->Holidays as $holiday) {
    $fid = 'delete' . $holiday['id'];
    $form['holidays'][$fid] =
            array(
                '#name' => 'delete_' . $holiday['id'],
                '#type' => 'image_button',
                '#src' => $crossimg,
                '#attributes' => array('class' => array('delete_holiday')),
                '#return_value' => $holiday['id']
    );
   $field = drupal_render($form['holidays'][$fid]);

   $rows[] = array($holiday['name'], ISOdate2DutchDate($holiday['from']), ISOdate2DutchDate($holiday['to']), $field);
  }
</code>
Everything is rendered ok, but if I try to delete a holiday, the triggering_element and the clicked_button arrays in form_state still always refer to the main submit that I defined in the CTools form_info array. I therefor cannot distinguish between the submits for adding and deleting.
What do I need to do to get my triggering_element to correspond with the selected submit? I also tried specifying a separate '#submit' handler for the delete buttons, but that is never called either.
Other solutions are welcome as well, as long a I can do it without closing/leaving the modal (I already tried with a link to a separate delete handler which worked up until the referral back to the modal).
Thanks!
Answer: Never figured out how to do this, but I worked around the problem by using CTools functionality. In a nutshell I used ctools_ajax_image_button in the table, specified a specific callback for the url and then alter the table with ajax_command_remove, ajax_command_restripe and finally returning it with ajax_render.
This is all based on the CTools AJAX example that deletes rows from a table.


auth_token Node.js > Instagram

Question: Pra fazer um script funcionar eu preciso do auth_token de um aplicativo do instagram, e que segundo instruções eu devo(e estou) fazendo assim:
https://instagram.com/oauth/authorize/?client_id=1627c123e3fc481791e0d6be16ff57a0&redirect_uri=http://yourcallback.com/auth/instagram/callback&response_type=token&display=touch&scope=likes+relationships

Mas ainda recebo os erros:

Instagram {
      "code": 400, "error_type": "OAuthException", "error_message":
   "Redirect URI does not match registered redirect URI"
  }

Alguém sabe indicar o problema?
Answer: Pelos testes que eu já fiz com a API , você precisa ter uma url para colocar em redirect_uri. A url que você está usando não deve ser aceita pela API.
Quando vc registrou seu aplicativo deve ter inserido uma url , deve ser usada essa mesma URL.
O erro que a API devolveu para você diz exatamente isso.

auth_token Node.js > Instagram


Unmounting ReactJS element

Question: I have created an element with ReactJS and appended it to div container and then removed the same element using jQuery.remove().
Do I need to unmount the node that I created with React?
Any help will be appreciated!
Answer: Yes, you should do so. You can remove the element by
React.unmountComponentAtNode(document.getElementById('divsId'));

where the div you are removing the element from has to be the one you were originaly appending it to.
Comment: I think, but don't kill me if I'm wrong -  that if you don't unmount it, the element keeps receiving updates on state changes which will decrease the pages performance. @andrerpena
Comment: Just out of curiosity, what happens if you don't do it?
Answer: Interfering with the DOM causes unnecessary repainting and redrawing which are expensive processes. The best method is to set a flag like so:
getInitialState() {
 isVisible: false
}

toggleVisiblity() {
 var {isVisible} = this.state
 this.setState({isVisible: !isVisible})
}

render() {
 if(isVisible)
  var display =
 Your content

 return(
  <button onClick={this.toggleVisibility}> Click here </button>
  {display}
 )
}

When isVisible is false, React automatically unmounts and when it is true, it mounts. This is a good practice to maybe even add animations.

Unmounting ReactJS element


Is there a way to force the JVM to run on a single processor or Core

Question: In Java, is there a way to force a JVM instance to run on a single CPU/Core.
Additionally is there a way for given thread to figure out what CPU it is running on?
Comment: Generally, this would be operating system-dependent.
Comment: This actually belongs at superuser.com.
Answer: This is not to be controlled at JVM/Java level, but at OS/platform level. In Windows for example, you can go to the Processes tab in the Task Manager and set the Affinity for most of the processes by choosing the appropriate option in the rightclick menu. With this you basically controls which CPU's/cores the process is allowed to use.
Answer:
Is there a way to force the JVM to run on a single processor or Core.

Yes.  There are OS-specific tools for doing this.

In Java, is there a way to force a JVM instance to run on a single CPU/Core.

No.

Additionally is there a way for given thread to figure out what CPU it is running on?

No.  (A thread figuring this out implies that you are doing this in Java ...)
Those answers should be qualified by saying that is is not possible to do these things in pure Java.  You might be able to use JNI to call some OS specific native APIs to do these things.  But it is simpler and cleaner to do the task from the command prompt or from some appropriate OS management GUI.


How do you differentiate good sets from bad sets?

Question: As a referee, How do you differentiate good sets from bad sets?
I'm a beginner volleyball ref. One of my main challenges is identifying double hits. I scanned the USAV rules and didn't see anything obvious about what is and isn't legal. I understand that a set must be "clean" and you must touch it with all the fingers simultaneously. I think the set happens so fast that I am not sure I'm actually seeing one finger/hand touch it any sooner or later than the other fingers or hand. In reality, I don't see how a human can touch a ball legally given the definitions I've heard of how to set a ball.
Comment: Welcome. [Resource requests are off-topic](https://sports.stackexchange.com/help/on-topic) on Sports SE, but we encourage content that is expertise and experience-based, so I have slightly altered your question to further clarify your point of view. If you feel I have altered it too much, do not hesitate to [roll back](https://sports.stackexchange.com/posts/13235/revisions).
Answer: Welcome to the "Art of Refereeing"! I think the best answer to this is from the foreward to the FIVB rulebook (page 10):

a good referee will use the rules to make the competition a fulfilling
  experience for all concerned.

Double touches and carries are always going to be judgement calls on the part of the referee, and how you make those calls should depend on the skill level of the participants. If you're refereeing a beginners' league, then you should allow more leeway when judging a double touch or a carry than you should if you're refereeing the Olympic final - if you used the Olympic standard in a beginners' tournament, you'd probably end up calling a fault on every single set and that isn't going to produce a fulfilling experience for the players.
The question this obviously leaves is how do you know how strictly to call faults in any particular competition - the answer to that is probably to watch some matches in the competition and see how plays are called, and then set your standard to match that - as that's what the players in the competition will expect. Of course, if the organising committee for the competition has given guidance to be more or less strict on a particular point, then follow that as well.
Answer: My advice would be to carefully watch the warming up at the net. Although you might be tempted to watch the attackers, try to watch the setter. They will clearly show (e.g. through facial expressions) whether or not they're happy with the set, not only result-wise (could the attacker hit it), but also technically.
You will get a good feel for their own expectations; try to match those with your own judgement during the game.
Secondly, take the context of each set into consideration; standing still with a pass arriving spot-on 'deserves' a better set than one the setter has to run for and direct in an awkward angle. Also, a non-setter who takes over the set can be allowed some more clumsiness.
Many referees will also use signs as 'the ball turned more than once around its axis after the set', or try to hear the double-touch. Be sure to only use this sign as a backup for your other observations, weighing these in with your own experiences.
Answer: I would turn things around. If you can definitely see - in real time - more than one touch during the set (ie touches by separate fingers or hands were definitely not simultaneous) then that is the only time you can call a double hit. As the answer from Philip Kendall explains, your definition of "not simultaneous" may be stricter for high level teams and more lenient for beginners.
Remember that ball handling is one thing that players may never question the referee on - as it is quite context dependent. However it is up to you to draw a line and maintain it - throughout the match. Always try to use the technical terminology (catch and throw) rather than informal terms (like carry).
Comment: Pedantically, the term is "catch", not "catch and throw". FIVB Rule 9.3.3.


Is there anyone successfully running a mail server in google cloud?

Question: Mail servers cannot resolve to my SMTP mail server in google cloud. Can someone please help? Its a mailcow server
Comment: Nobody can help because you have provided absolutely no relevant details. Please edit your question.
Comment: So what are the issues you are having?
Comment: Ok let me try again. I have setup a mail server which I have hosted in google cloud on a Linux vm with docker. I'm having issues with Port 25 being blocked and so the SMTP server is unreachable, so the server is not sending or receiving emails. I want to know if there is another way I could configure the server such that I can get around the SMTP server only being available thru port 25? I also asking if  there is anyone who is running their own mail servers hosted on GCP and maybe they can share their experience? Hope i'm beginning to make sense.
Comment: Google already has an email service, that's probably why they are blocking yours.  try a different provider.
Answer: Google Cloud blocks SMTP port 25 egress. This prevents traditional SMTP servers from functioning. You can use other ports such as 465/587 but that is typically used to login to a traditional SMTP server (Gmail, Workplace, O365, Zoho, etc) for email forwarding.
In summary, you cannot host a traditional email server in Google Cloud. You can implement email forwarders.