Is the sum of two projections a projection?

Question: Let $ S $ and $ T $ be two linear subspaces of $ \Bbb{R}^{2} $. Then is the sum of the projections $ P_{S} $ and $ P_{T} $ (i.e., $ P_{S} + P_{T} $) a projection?
I don't think it is since the projection rule doesn't hold ($ P_{M}^{2} $ does not equal $ P_{M} $), but I was hoping someone could solidify this. It would be very much appreciated!
Comment: Well if I understand what you are asking I think the answer is true, as projection is indeed a linear transformation
Answer: The sum is a projection iff $$
p_1 \circ p_2 = - p_2 \circ p_1
$$
because
\begin{align}
(p_1 + p_2)\circ (p_1 + p_2) - (p_1 + p_2) &=
\color{red}{p_1 \circ p_1} + p_1 \circ p_2 + p_2 \circ p_1
+  \color{blue}{p_2 \circ p_2}
- \color{red}{p_1} - \color{blue}{p_2} \\&=
p_1 \circ p_2 + p_2 \circ p_1
\end{align}
Comment: if they are orthogonal, then $p_1\circ p_2 = 0$ and $p_2\circ p_1 = 0$ and the equation is true.
Comment: +1 nice and simple especially marking terms that get cancelled in same color.
Comment: so I start this one with (Ps+Pt)^2-(Ps+Pt)? and solve from there as you did?
Comment: what you look for is when the expression is 0. So the sum is a projector iff the first equation is true.
Comment: would this answer be different if it was on a Hilbert space?
Comment: this has nothing to do with the question.
Comment: so I am not allowed to ask???....
Comment: of course you are. and the answer is: no, it is not different.
Comment: So then I could also show it by showing that they are orthogonal to each other
Answer: Another condition is that the vector spaces need to be perpendicular. Here is the full proof.
Let $V_1, V_2$ be closed subspaces of the Hilbert space $H$ and let $p_{V_1}$ and $p_{V_2}$ denote the orthogonal projections on $V_1$ and $V_2$, respectively. Show that $p_{V_1} + p_{V_2}$ is a projection onto some closed subspace if and only if $V_1 \perp V_2$.
First, assume that $p_{V_1} + p_{V_2}$ is a projection. Thus, for any $x$, $p_{V_1}, p_{V_2}$, and $p_{V_1} + p_{V_2}$ are idempotents. Therefore,
\begin{equation}
\begin{split}
p_{V_1}(x) + p_{V_2}(x)
& = (p_{V_1} + p_{V_2})(x)\\
& = (p_{V_1} + p_{V_2})^2(x)\\
& = (p_{V_1} + p_{V_2}) \Big((p_{V_1} + p_{V_2})(x) \Big)\\
& = p_{V_1}\Big((p_{V_1} + p_{V_2})(x)\Big) + p_{V_2}\Big((p_{V_1} + p_{V_2})(x)\Big)\\
& = p_{V_1}p_{V_1}(x)+p_{V_1}p_{V_2}(x)+p_{V_2}p_{V_1}(x)+p_{V_2}p_{V_2}(x)\\
& = p_{V_1}(x)+p_{V_1}p_{V_2}(x)+p_{V_2}p_{V_1}(x)+p_{V_2}(x)\\
\end{split}
\end{equation}
which implies that
$$p_{V_1}p_{V_2}=-p_{V_2}p_{V_1}$$
For simplicity, denote $p_{V_1}=p$ and $p_{V_2}=q$.
Thus, for all $x$ we have that
$$pq=-qp$$
Using the fact that $p$ and $q$ are idempotent, by multiplying both sides of the equation by $p$ on the left and $q$ on the right we get
$$pq=-pqpq$$
Also notice that if we take $pq=-qp$ and multiply both sides from the left and from the right by $p$, we get
$$pqp=-pqp$$
But this means that for any $x$,
$$pqp(x)=pqp(\frac{1}{2}x)+pqp(\frac{1}{2}x)=0$$
Thus, multiplying both sides by $p$ on the left yields
$$pqpq(x)=0$$
for all $x$. Thus, from the first relation we obtained, we get
$$pq(x)=-pqpq(x)=0$$
Therefore, $\forall x \in V_2$, we get
$$pq(x)=p(x)=0$$
Thus, since $x$ was an arbitrary element of $V_2$, we get that $V_2 \perp V_1$.
Conversely, assume that $V_1 \perp V_2$. Since the sum of closed orthogonal subspaces of a Hilbert space is a closed subspace,  we know that $V_1+V_2$ is a closed subspace of $H$. Let $V:=V_1+V_2$. Since $V$ is closed, $p_V$ is defined. Thus, to prove that $p_{V_1} + p_{V_2}$ is a projection, it is enough to show that
$$p_{V_1} + p_{V_2}=p_V$$
Let $x \in H$. Then $x=p_V(x)+p_{V^{\perp}}(x)$ Since $p_V(x) \in V$, $p_V(x)=x_1+x_2$, where $x_1 \in V_1$ and $x_2 \in V_2$. This gives us
\begin{equation}
\begin{split}
(p_{V_1} + p_{V_2})(x)
& =p_{V_1}(x) + p_{V_2}(x)\\
& =p_{V_1}\Big(p_V(x)+p_{V^{\perp}}(x)\Big) + p_{V_2}\Big(p_V(x)+p_{V^{\perp}}(x)\Big)\\
& =p_{V_1}\Big(x_1+x_2+p_{V^{\perp}}(x)\Big) + p_{V_2}\Big(x_1+x_2+p_{V^{\perp}}(x)\Big)\\
& =x_1+p_{V^1}p_{V^{\perp}}(x)+x_2+p_{V^2}p_{V^{\perp}}(x)\\
&=x_1+x_2\\
&=p_V(x)
\end{split}
\end{equation}
where we used the fact that $p_{V^1}p_{V^{\perp}}(x)=0$, since any element orthogonal to $V$ is orthogonal to $V_1$, and $p_{V^2}p_{V^{\perp}}(x)=0$, since any element orthogonal to $V$ is orthogonal to $V_2$. Thus, $p_{V_1} + p_{V_2}$ is a projection, as desired.
Comment: This is a great answer.
Comment: is this also true for the sum of n orthogonal projections?
Answer: A linear operator $P$ is a projector iff $P^2=P$.  We have:
$$
(P_s+P_t)^2=P_s^2+P_t^2+P_sP_t+P_tP_s= P_s+P_t+P_sP_t+P_tP_s
$$
So the the sum is a projector iff $P_sP_t+P_tP_s=0$
Comment: How would I then show that it is equal to 0? Do I have to use Hilbert space or inner products?
Comment: the question is not if "the two projectors commute".


Como fazer um loop com input select PHP?

Question: Tenho um array com nome de $c que fiz através de um explode preciso fazer a contagem com o for para ver se é selected. O problema está que ele faz o echo do option 2 ou quantas vezes houverem registros. Alguém tem alguma solução para isto?
foreach($interesse_compra as $ic)
{
   $c = explode(";",$ic->cidade);
}

for($i = 0; $i < count($c);$i++)
{
   foreach($cidades as $cidade)
   {
      $select = $cidade->f_cidade == $c[$i] ?  "selected" : "";
      echo "<option value='".$cidade->f_cidade."'$select>".$cidade->f_cidade."</option>";
   }

}

Comment: pq `$c = explode(";",$ic->cidade);` fica dentro do foreach? dessa forma o `count()` só sera feita no último elemento de `$interesse_compra`.
Comment: É um select de múltipla seleção? Ou seja, pode ter várias opções selecionadas?
Comment: o foreach está ali pq eu uso codeigniter. Mas esta parte está normal. $c está se dividindo em 3 partes. Ai faco a contagem. Só que na contagem ele está duplicando o meus options claro e obvio pq está refazendo o mesmo processo baseado no $C[$i]. Entendeu @rray?
Comment: Sim é um select de multiplas escolhas... estou trazendo os dados do banco na parte de ediçao e preciso saber os que foram selecionados. Só que eles estão salvos separados por pono e virgula. @KaduAmaral
Comment: Por que o `explode` está dentro de um foreach? Se é um loop, todo esse código não deveria estar dentro dele também?
Comment: Pode colocar na pergunta o conteúdo de `$interesse_compra` e `$cidades`? Pode imprimi-los com `var_dump($interesse_compra)` e colocar a saída na pergunta.
Answer: Fiz uma versão simplificado do seu código, parti do ponto que $c contém todas as cidades disponíveis e que $cidades possui os itens a serem selecionados.
É feita um comparação se com in_array() se valor atual($cidade) existe em $c caso possitivo $select recebe selected, caso contrario recebe uma stringa vazia.

<form>
<select multiple size="8">
<?php
    $c = ['Rio Branco', 'Maceió','Macapá','Manaus','Salvador','Fortaleza','Brasília','Vitória','Goiânia', 'Curitiba'];
    $cidades = ['São Luís','Salvador','Cuiabá','Curitiba','Campo Grande','Belém','Maceió','Belo Horizonte'];

    foreach($cidades as $cidade){
        $select = in_array($cidade, $c)  ? $select = 'selected="selected"' : "";
        printf('<option value="%s" %s>%s</option>'. PHP_EOL , $cidade, $select, $cidade);
    }
?>
</select>
</form>

Exemplo - phpfiddle
Answer: Pela descrição do problema, você precisa verificar se a cidade selecionada pertence a sua lista de cidades.
Para isso utilize as funções array_map() e in_array():
$interesse = 'Recife;Campinas;Alagoas';
$cidades = ['Rio de Janeiro', 'São Paulo', 'Salvador', 'Piracicaba', 'Belo Horizonte', 'Recife'];

$interesse_array = explode(';', $interesse);

array_map(function($c) use ($cidades) {
    $selecionado = in_array($c, $cidades) ? "selected" : "false";
    echo "<option value='$c' selected='$selecionado'>$c</option>\n";
}, $interesse_array);

Saída:
<option value='Recife' selected='selected'>Recife</option>
<option value='Campinas' selected='false'>Campinas</option>
<option value='Alagoas' selected='false'>Alagoas</option>

Veja exemplo funcionando no ideone.


Taxonomy with adjacent cities

Question: I have a content type 'company' with a related tax-term: 'city'.
With a view I can search for companies based on 'city' with autocomplete.
Is there a way I can relate adjacent cities into the same tax-term 'city'?
If not, I would have to create a new tax-term into the content type 'company' and select for each company the adjacent cities. That is a lof of work.
Geo lookup is not an option, because we want te select which adjacent cities belongs to a specific city.
For example:
Tax-term: city
City A
-- City B // adjacent city of 'city a'
-- City C // adjacent city of 'city a'
-- City D // adjacent city of 'city a'
City B
City C
City D

As you can see, City B, C and D exists in the tax-term but also are children of 'city A'. It should be an alias, because otherwise the children will have all a different ID, so that won't work.
Hope it is clear ...
Comment: Vocabularies aren't structured like that, you can't have terms that are aliases or shortcuts to other terms. What you're describing would usually be achieved using an entity reference field
Comment: Regardless, you can't achieve what you've descried with taxonomy alone. All terms at any level of a vocabulary need to be real entities, not virtual
Comment: First, I created an entity reference field. But I could not use this in the view ... then I asked my question here.
Comment: I understand, that were also my thoughts ...
Comment: If I use an entity reference field in the city-tax-term, and add those cities here. Could I collect those ID's with code and use these values as filter value in the view? Those ID's must be collected after hitting the search button...
Comment: @user3086053 I think entity references might be possible with clever use of Relationships. But I think there is a much simpler option: Grouped filters in Exposed Views. Grouped filters is where you can "suggest" hierarchy without setting it expressly in Taxonomy. For example set grouped filters to "City A", "City B", "City C",    "City A and City B and City C".
Answer: I would like to share my own working solution. If you see any improvements, please correct me. That would be helpful. If not I hope this script can be helpful for someone else...
I've created my own module and used this function to alter the query:
<?php

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\taxonomy\Entity\Term;

function search_cities_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
    // machine_name of view
    if ($view->id() == 'zoek_een_bedrijf') {
        foreach ($query->where as &$condition_group) {
            foreach ($condition_group['conditions'] as &$condition) {
                // check which field must be changed
                if ($condition['field'] == 'node__field_stad.field_stad_target_id = :node__field_stad_field_stad_target_id') {
                    $value = $condition['value'];
                    // get ID from taxonomy term
                    $city_id = $value[':node__field_stad_field_stad_target_id'];
                    // load taxonomy term info
                    $term = Term::load($city_id);
                    // load reference field with taxonomy term ID's
                    $term_field = $term->get('field_aangrenzende_gemeenten')->getValue();
                    $cities = array();
                    // add ID from parent taxonmy term
                    array_push($cities, $city_id);
                    // add taxonomy terms from reference field (children)
                    //print_r($term_field);
                    foreach ($term_field as $key => $value) {
                        array_push($cities, $value['target_id']);
                    }
                    // update the condition before sending query to database
                    $condition = array(
                        'field' => 'node__field_stad.field_stad_target_id',
                        'value' => $cities,
                        'operator' => 'IN',
                    );
                }
            }
        }
    }
}

Taxonomy with adjacent cities


Implementar funcionalidade Seguir/Deixar de Seguir

Question: Estou desenvolvendo um sistema de seguidores, criei uma página que faz uma busca de usuários registrados. Você digita em um input um nome, e ele verifica se tem algum registro com esse nome no banco de dados.
Coloquei do lado de cada nome que retorna do banco de dados, um botão "Seguir" para caso a pessoa queira seguir o usuário. Porém, quero também que caso a pessoa já tenha seguido aquele usuário, não apareça o botão de seguir, mas sim, o botão de "Deixar de Seguir".
Criei o botão e adicionei na página, tentei implementar sozinho mas não consegui, então me indicaram fazer um SELECT de todos os usuários, salvar isso em um array, e depois em um loop, verificar com o in_array() se a pessoa que está logada, já seguiu o usuário que retornou da busca, mas não consegui fazer funciona! A query busca está funcionando corretamente, onde estou errando?
Função SELECT:
<?php

    include 'fconnect.php';
    include 'fdesconnect.php';

    function select($tabela,$coluna="*",$where=NULL,$ordem=NULL,$limite=NULL) {

        // Query de consulta
        $sql= "SELECT {$coluna} FROM {$tabela} {$where} {$ordem} {$limite}";

        // conectou?

        if($conexao= connect()) {

            // Conseguiu consultar?
            if($query= mysql_query($sql,$conexao)) {
                // Encontrou algo?
                if (mysql_num_rows($query)>0) {

                    $resultados_totais = array();
                    while ($resultado = mysql_fetch_assoc($query)) {
                        $resultados_totais[] = $resultado;
                    }

                    // Fecha conexão
                    desconnect($conexao);

                    return $resultados_totais;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
?>

Página que realizo a busca e mostra os botões, deixei apenas as partes essenciais.
$idsession = $_SESSION['ID'];
$consulta2 = select("u636623377_users", "*", "WHERE fname LIKE '%$q%'");
$consulta3 = select("u636623377_follows", "idfollowed", "WHERE idfollower = '$idsession'");

Resultado da Busca...

                                        Usuário

                                        Cidade
                                        Estado

                                <?php if($consulta2 == true){
                                    for ($i=0;$i<count($consulta2);$i++) {

                                        $idatual = $consulta2[$i]['id'];
                                ?>

                                        <img class="img-circle" src="assets/img/img_profile/<?php echo $consulta2[$i]['photoperf'] ?>" style="width: 60px; height: 60px;">

<?php echo $consulta2[$i]['fname'] ?>

<?php echo $consulta2[$i]['city'] ?>

<?php echo $consulta2[$i]['state'] ?>

                                                <a href="profile.php?link=<?php echo $consulta2[$i]['profile'] ?>" class="label label-primary">Ver Perfil

                                                <?php if($consulta2[$i]['id'] == $_SESSION['ID']){}else{ ?>

                                                <?php if(in_array($idatual, $consulta3)){ ?>
                                                <a href="php/scripts/disfollow.php?id=<?php echo $consulta2[$i]['id'] ?>" class="label label-danger">Deixar de Seguir
                                                <?php }else{ ?>
                                                <a href="php/scripts/follow.php?id=<?php echo $consulta2[$i]['id'] ?>" class="label label-success">Seguir
                                                <?php } } ?>

                                <?php } } ?>

$consulta2 é o que busca os usuários no banco de dados.
$consulta3 é o que busca todos os usuários que a pessoa logada segue.

var_dump na variável $consulta3:

idfollower é o id da pessoa que seguiu.
idfollowed é o id da pessoa que foi seguida.
Answer: Acho que existe uma maneira bem mais fácil de resolver o problema.
Solução 1:
Substitua a linha:
if(in_array($idatual, $consulta3)){

Por:
if(in_array($idatual, $consulta3['idfollowed'])){

Ideia: o in_array deveria ser para o idfollowed, já que é ele que contem o idsession.

Solução 2:
Etapa 1: Primeiro altere o $consulta3:
Vamos lá, substitua a linha:
$consulta3 = select("u636623377_follows", "idfollowed", "WHERE idfollower = '$idsession'");

Por:
$consulta3 = select("u636623377_follows", "idfollowed", "WHERE idfollower = '$idsession' AND idfollowed = '$consulta2['id']'");

Ideia: Ele irá selecionar o que tiver o idfollower igual à sessão atual e também tiver o idfollowed igual ao id do perfil que está vendo.

Então,  em seu SELECT() retorna false se o mysql_num_rows for igual à 0. Logo, se não encontrar o $consulta3 será false, perfeito.
Etapa 2: Altere o if Deixar de seguir:
Substitua a linha:
<?php if(in_array($idatual, $consulta3)){ ?>

Por:
<?php if($consulta3){ ?>

- Ideia: Se o $consulta for false ele irá exibir 'Seguir', se não irá exibir 'Deixar de seguir'.
Solução (pós-var_dump):
Utilize loop:
<? $total = count($consulta3);
    for($i =0; $i < $total; $i++){
       if($consulta3[$i]['followed'] == $idatual){ ?>

           <a href="php/scripts/disfollow.php?id=<?php echo $consulta2[$i]['id'] ?>" class="label label-danger">Deixar de Seguir
       <?php }else{ ?>
           <a href="php/scripts/follow.php?id=<?php echo $consulta2[$i]['id'] ?>" class="label label-success">Seguir
       <? }
    } ?>

Seria uma solução, ou utilizar o foreach, mas, seguiria a mesma logica.
Comment: Infelizmente, nenhuma das duas funcionou... :c
Comment: Atualizei depois do var_dump.


which of the following are homeomorphic?

Question:
well, I have forgotten how to identify ellipse, hyperbola,circle straightline from the general equation of conic, so is there any other way to identify these homeomorphic or not?
a) B is an ellipse, b) B is an hyperbola, c) B is an complement of a closed ellipse.
please help.
Comment: Those are  not in general form (no mixed terms). So you only need to complete squares.
Comment: @Patience, please get some graph paper and draw some pictures. This is upsetting.
Comment: You could plot them on Wolfram Alpha.
Comment: Thank you for the comment of azrael, I have calculated that $(a)$ A is an hyperbola so is not homeomorphic to B,

$(b)$ both are hyperbola so homeomorphic, but still confused about $c$
Comment: Hint for (c): $x^2 - 2 x + 1 = (x-1)^2$
Answer: A is a circumference in a. and b. while a disk in c. so...
a. Yes, homeomorphism by isometric transformation to overlay the centers, and then by projection of one onto the other.
b. No, the circumference is compact, while the hyperbola is not
c. No, same reason as b


Colocar a função switch do angularJS dentro de laço while php

Question: Eu coloque a função swicth do angular, dentro de while no PHP. Na hora de executar apenas o primeiro laço que dá certo o restante a função não funciona. Ja coloquei os nomes ng-app e ng-controller diferentes todos laços, mas assim mesmo funciona apenas o primeiro laço.

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link type="text/css" rel="stylesheet" href="..\bootstrap\css\bootstrap.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <link type="text/css" rel="stylesheet" href="..\css\style.css">

    <title>Alter Students Data</title>

Alter Data Students

                        <form role="form" method="post" action="alter_std.php">
                            <fieldset>
                                <?php
                                include("../database/db_conection.php");
                                    $view_students_query="select * from students";//select query for viewing students.
                                    $run=mysqli_query($dbcon,$view_students_query);//here run the sql query.
                                    $cont = 0;
                                    while($row=mysqli_fetch_array($run))//while look to fetch the result and store in a array $row.
                                    {

                                        $std_code=$row[0];
                                        $std_name=$row[1];
                                        $std_birth=$row[2];
                                        $std_grade=$row[3];
                                        $std_edu=$row[4];
                                        $std_last=$row[5];
                                ?>

                                        <button class="btn btn-primary btn-block btn-sm" type="button" data-toggle="collapse" data-target="<?php echo '#alter'.$cont.'std'; ?>" aria-expanded="false" aria-controls="<?php echo 'alter'.$cont.'std'; ?>" style="white-space:normal; width:100%; ">
                                         <?php echo $std_name; ?>
                                        </button>

                                        <div class="collapse btn-block" id="<?php echo 'alter'.$cont.'std'; ?>">

                                                <input class="form-control" placeholder="Name Student" name="nameStd" id="nameStd" type="text" autofocus>

                                                <input class="form-control" placeholder="Date of Birth" name="birthStd" id="birthStd" type="text" onfocus="(this.type='date')" onblur="(this.type='text')">

                                            <div ng-app=<?php echo "switch".$cont."altStd";?> >
                                                <div ng-controller=<?php echo "Grade".$cont; ?> >

                                                        <select class="form-control" ng-model="selection" ng-options="item for item in items" id="eduStd" name="eduStd" value={{selection}} required>
                                                        <option value="" disabled selected hidden> Education</option>
                                                        </select>

                                                            <select class="form-control" id="gradeStd" name="gradeStd" required>
                                                                <option value="" disabled selected hidden> Grade</option>
                                                                <option value="1st grade" > 1st grade </option>
                                                                <option value="2nd grade" > 2nd grade </option>
                                                                <option value="3rd grade" > 3rd grade </option>
                                                                <option value="4th grade" > 4th grade </option>
                                                                <option value="5th grade" > 5th grade </option>

                                                            </select>

                                                            <select class="form-control" id="gradeStd" name="gradeStd" required>
                                                                <option value="" disabled selected hidden> Grade</option>
                                                                <option value="6th grade" > 6th grade </option>
                                                                <option value="7th grade" > 7th grade </option>
                                                                <option value="8th grade" > 8th grade </option>
                                                                <option value="9th grade" > 9th grade </option>
                                                            </select>

                                                            <select class="form-control" id="gradeStd" name="gradeStd" required>
                                                                <option value="" disabled selected hidden> Grade</option>
                                                                <option value="1st grade" > 1st grade </option>
                                                                <option value="2nd grade" > 2nd grade </option>
                                                                <option value="3rd grade" > 3rd grade </option>
                                                            </select>

                                                <select class="form-control" id="lastyear" name="lastyear" required>
                                                    <option value="" disabled selected hidden>Last year's situation </option>
                                                    <option>Approved</option>
                                                    <option>Classified</option>
                                                    <option>Disapproved</option>
                                                    <option>First year of study</option>
                                                    <option>Stopped going</option>
                                                </select>

                                            <input class="btn btn-lg btn-success btn-block" type="submit" value="register" name="registerStd" >

                                <?php
                                echo "";
                              ?>

                              <?php
                                        $cont = $cont + 1;
                                    }
                                ?>
                            </fieldset>
                        </form>

Está a função que coloquei dentro do While no php.

function(angular) {
   'use strict';
   angular.module(SwicthControler;, ['ngAnimate'])
   .controller('GradeController', ['$scope', function($scope) {
   $scope.items = ['Elementary School', 'Middle School', 'High School'];
    //$scope.selection = $scope.items[0];
}]);
      })(window.angular);
Answer: Esse aqui é apenas um exemplo da função que usei.

function(angular) {
   'use strict';
   angular.module('SwicthControler', ['ngAnimate'])
   .controller('GradeController', ['$scope', function($scope) {
   $scope.items = ['Elementary School', 'Middle School', 'High School'];
    //$scope.selection = $scope.items[0];
}]);
      })(window.angular);


If $db_prefix is "assumed to be a string", then does Drupal automatically sort what is a sharable table in the DB?

Question: <code>$db_prefix = 'drupal_';
</code>
I've found many examples of installations which pick through the tables and place these in an array. And then there is the example of the site I am migrating where it only contained the above string. So, does Drupal sort it all out in the case of this simple string?
What is the big idea I feel I am missing about multi-sites?
(haha the mysteries of the D framework!)
Answer: $db_prefix can either be a string or an array, have a look at the documentation: Share a single database across multiple sites, the db_prefix_tables function take care of this job.
Comment: $db_prefix is a [global](http://api.drupal.org/api/drupal/globals/6) and is defined in setting, but the function applies it on every db_query call.
Comment: Is this function automatically applied from the settings.php file during the boot strap phase? Then the choice of using an array or string is limited or use all of the tables (even though some of the tables are apparently not shareable)?


Forms API #states with multiple radios

Question: I've got one radios element:
$form['trip_radios'] = array(
  '#type' => 'radios',
  '#options' => array(
    'new' => t('Create a new trip'),
    'existing' => t('Use an existing trip'),
  )
);

I've got some #states prepared:
$trip_states = array(
  'visible' => array(
    ':input[name="trip_radios"]' => array(
      'value' => 'new'
    )
  )
);

And some other elements that use $trip_states for their #states:
$form['itinerary_radios'] = array(
  '#type' => 'radios',
  '#options' => array(
    'new' => t('Create a new itinerary'),
    'existing' => t('Use an existing itinerary'),
  ),
  '#states' => $trip_states
);

$form['title'] = array(
  '#type' => 'textfield',
  '#title' => 'Itinerary name',
  '#required' => FALSE,
  '#states' => $trip_states
);

The title form element (and many others) properly listens to the #states condition and works just fine. However, itinerary_radios always shows up no matter what (if anything) is checked on trip_radios. Why does a visible condition on a radios element's #states not listen to another radios value?
Answer: In misc/states.js, it looks for the closest form-item, form-submit, or form-wrapper. Here's the line:
$(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value);

This does not play well with the way radios are themed, and states.js does not find anything to toggle. Wrapping the itinerary_name radios in a container and applying #states to the container item is what I would call the quickest workaround.
$form['itinerary_radios'] = array(
  '#type' => 'container',
  '#attributes' => array(),
  'radios' => array(
    '#type' => 'radios',
    '#options' => array(
      'new' => t('Create a new itinerary'),
      'existing' => t('Use an existing itinerary'),
    ),
  ),
  '#states' => $trip_states
);

Comment: Will it work in a text field?
Comment: I guess another option is to set `'#tree' => TRUE` on a wrapping `#type => 'container'` or fieldset.

Forms API #states with multiple radios


Is it possible to add multiple fields within a single component?

Question: <code>    $form['value'] = array(
        '#type' => 'textfield',
        '#title' => t('Webservice URL'),
        '#default_value' => $component['value'],
        '#description' => t('The default value of the field.'),
        '#size' => 60,
        '#maxlength' => 1024,
        '#weight' => 0,
    );
</code>
I want to make a second textfield in my component where I can specify the second part of my Webservice URL and then concatenate them in my rendering. How can I add a second textfield to my webform_edit?
Comment: What is this form for? Do you need to save the concatenated url or only render it?
Answer: For one of my projects I spend almost whole week trying to find similar functionality it turns out that you cannot render the input of two fields as one entry from webform result due to the fact that webform creates separate database entry for every field. I solve my problem by just creating multiple fields value_1 value_2 and so on and when exporting result concatenate them in Excell (stupid I know :-) and does not work for your case) . There is module Webform Add More but it only use the same aproach but hides the extra fields and shows them when needed. If you are willing to switch from webform you can try EntityForms this way you can use regular Drupal fields to get entered values and embedding Entityforms on Nodes using Entity Reference
Comment: [Entity Reference]  -   [1]: https://drupal.org/project/entityreference
Answer: You can use Webform Structured Text module to achieve this
Answer: You should use Paragraphs module. This is just awesome. Found a helpful article: https://www.gyanblog.com/gyan/drupal-how-add-multiple-fields-single-button/
Paragraphs module is so powerful, it has lot of other use cases as well. The best part is, no coding required.


how does expectation maximization work in coin flipping problem

Question: joriki:
Thanks for your answer regarding the expectation maximization work relating to the coin flipping problem ( how does expectation maximization work? ).
You have explained how the probability of coin A or coin B are selected for each set of observations.
For example, you have told us how to derive the 0.8,0.2 given the current bias estimates θA=0.6 and θB=0.5 in the 2nd row.
Can you help me understand how how do we go from that probability distribution (0.8, 0.2) to the expectation (7.2H, 0.8T) for coin A in the 2nd row as well.
Same as the question asked by Martin, the total number of tosses should be 10 rather than 7.2H + 0.8T = 8?
Many thanks here.
Comment: I could not make comments on previous thread, so I have to make a another thread for it, Thank t.b for adding this link below joriki's answer.
Comment: @anon: Interesting -- it seems pinging doesn't work when the user to be pinged hasn't figured in the thread yet. I found this because t.b. pinged me underneath my answer to the question linked to.
Answer: Thanks for the personalized question -- I don't think I ever got one of those before :-)
The answer lies in this part of the tutorial linked to in Martin's question:

Rather than picking the single most likely completion of the missing coin assignments on each iteration, the expectation maximization algorithm computes probabilities for each possible completion of the missing data, using the current parameters $\hat\theta(t)$. These probabilities are used to create a weighted training set consisting of all possible completions of the data. Finally, a modified version of maximum likelihood estimation that deals with weighted training examples provides new parameter estimates, $\hat\theta(t+1)$. By using weighted training examples rather than choosing the single best completion, the expectation maximization algorithm accounts for the confidence of the model in each completion of the data (Fig. 1b).

So the $7.2$ tails and $0.8$ heads shouldn't add up to $10$ by themselves; they are weighted contributions to the actual result $(9,1)$, weighted in proportion to the probabilities that this result would occur given the current bias estimates. Since we calculated that proportion to be $0.8:0.2$, a contribution of $0.8\cdot(9,1)=(7.2,0.8)$ is added to the column for coin A and a contribution of $0.2\cdot(9,1)=(1.8,0.2)$ is added to the column for coin B. Together, they add up to $(9,1)$ (since we obtained the weights by normalizing their sum to $1$). Thus, the more likely it seems, according to the current bias estimates, that this row was produced by coin A, the more of it we add to the column for coin A.
Note that we're not calculating an expectation value in the columns; we're merely adding up fractions of heads and tails in proportion to the likelihood that they came from this coin, and in the end we take the overall ratio of heads and tails to get a new bias estimate; there's no need for the heads and tails to add up to anything or to form an expectation value in either of the columns individually.
I hope that makes it clearer; if not, you may have to explain in more detail why you think those values should add up to $10$.
Comment: Thank your very much. It does help me understand EM relating to this coin flip example now. Thank you again for your clear and straightforward explanations here.
Comment: @user19262: You're quite welcome :-)
Comment: Hi, Joriki:I post another coins flipping question which is related to the same example, can you take a look at that question if you have time.The link is http://math.stackexchange.com/questions/82913/pdf-equation-for-tossing-2-coins-50-times-given-the-probability-of-landing-head. Many thinks here.
Comment: @joriki : absolutely clear explanations. Both on the original post and this post :-)


Repetir if novamente quando a validação falha

Question: ConvInicial = str(input('Você: '))

if ConvInicial == 'Não estou passando bem' or ConvInicial == 'Estou com dor' or ConvInicial == 'Preciso de ajuda':
print('O que você está sentindo?')
RespDor = input('Você: ')
if RespDor == 'Estou com dor de cabeça' or RespDor == 'Dor de cabeça' or RespDor == 'Minha cabeça dói':
    Randomizar = ['Neosaldina', 'Dorflex', 'Advil', 'Tylenol', 'Aspirina', 'Naldecon']
    Randomizar = random.choice(Randomizar)
    print('Você pode usar um {} para aliviar sua dor!'.format(Randomizar))
else:
print('Não entendi, poderia ser mais claro?')

Quando o usuário inserir um valor que não está no if, ele vai parar no else, porém eu gostaria que quando isso acontecesse, recomeçasse novamente o if até o usuário inserir um valor correspondente ao que eu programei. O que eu posso fazer para que isso aconteça?
Answer: Quando você quer que repita algo deve usar a estrutura de while. Então poderia fazer algo assim:
ConvInicial = str(input('Você: '))
if ConvInicial == 'Não estou passando bem' or ConvInicial == 'Estou com dor' or ConvInicial == 'Preciso de ajuda':
    while True:
        print('O que você está sentindo?')
        RespDor = input('Você: ')
        if RespDor == 'Estou com dor de cabeça' or RespDor == 'Dor de cabeça' or RespDor == 'Minha cabeça dói':
            Randomizar = random.choice(['Neosaldina', 'Dorflex', 'Advil', 'Tylenol', 'Aspirina', 'Naldecon'])
            print('Você pode usar um {} para aliviar sua dor!'.format(Randomizar))
            break; #para encerrar o laço de repetição
        else:
            print('Não entendi, poderia ser mais claro?')

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Obrigado, eu tinha tentando mas estava dando erro, acredito que a indentação estava errada
Answer: Eu recomendo você ler a respeito de laços de repetição, for e while. Depois disso procure ler algo a respeito de funções e recursividade.
Isso é uma das bases da programação em muitas linguagens, sem esse conteúdo seu código vai ficar muito limitado.
De qualquer forma, aqui está um exemplo:
ConvInicial = str(input('Você: '))

if ConvInicial == 'Não estou passando bem' or ConvInicial == 'Estou com dor' or ConvInicial == 'Preciso de ajuda':
    print('O que você está sentindo?')
    while True:
        RespDor = input('Você: ')
        if RespDor == 'Estou com dor de cabeça' or RespDor == 'Dor de cabeça' or RespDor == 'Minha cabeça dói':
            Randomizar = ['Neosaldina', 'Dorflex', 'Advil', 'Tylenol', 'Aspirina', 'Naldecon']
            Randomizar = random.choice(Randomizar)
            print('Você pode usar um {} para aliviar sua dor!'.format(Randomizar))
            break
        else:
            print('Não entendi, poderia ser mais claro?')

Answer: Tenho várias considerações quanto ao seu código:
ConvInicial = str(input('Você: '))

if ConvInicial == 'Não estou passando bem' or ConvInicial == 'Estou com dor' or ConvInicial == 'Preciso de ajuda':
print('O que você está sentindo?')
RespDor = input('Você: ')
if RespDor == 'Estou com dor de cabeça' or RespDor == 'Dor de cabeça' or RespDor == 'Minha cabeça dói':
    Randomizar = ['Neosaldina', 'Dorflex', 'Advil', 'Tylenol', 'Aspirina', 'Naldecon']
    Randomizar = random.choice(Randomizar)
    print('Você pode usar um {} para aliviar sua dor!'.format(Randomizar))
else:
print('Não entendi, poderia ser mais claro?')

São elas:

O retorno de input sempre é uma string, não precisa fazer str(input()) (Python 3);
Ao iniciar o programa, o usuário irá ter que responder "Você" sem conhecer a pergunta, e isso não faz sentido para quem não conhece o programa;
Você pode substituir uma cadeia de "ous" numa condição pelo operador in;
Cuidado com a indentação, ela muda o código completamente se utilizada errada;
A partir do Python 3.6, recomenda-se utilizar as f-string para interpolação;

Minha solução ficaria parecida com:
from random import choice

sentimentos = ['Não estou passando bem', 'Estou com dor', 'Preciso de ajuda']
sintomas = ['Estou com dor de cabeça', 'Dor de cabeça', 'Minha cabeça dói']
remedios = ['Neosaldina', 'Dorflex', 'Advil', 'Tylenol', 'Aspirina', 'Naldecon']

sentimento = input('Como está se sentindo hoje?')

if sentimento in sentimentos:
    sintoma = input('O que está sentindo?')
    if sintoma in sintomas:
        remedio = choice(remedios)
        print(f'Você pode tomar um {remedio} para aliviar sua dor')
    else:
        print('Desculpe-me, mas não sei o que fazer nesses casos')
else:
    print('Desculpe-me, mas não sei o que fazer nesses casos')

Adicionando isso dentro de um laço, como pediu, ficaria:
from random import choice

sentimentos = ['Não estou passando bem', 'Estou com dor', 'Preciso de ajuda']
sintomas = ['Estou com dor de cabeça', 'Dor de cabeça', 'Minha cabeça dói']
remedios = ['Neosaldina', 'Dorflex', 'Advil', 'Tylenol', 'Aspirina', 'Naldecon']

while True:
    sentimento = input('Como está se sentindo hoje?')
    if sentimento in sentimentos:
        while True:
            sintoma = input('O que está sentindo?')
            if sintoma in sintomas:
                remedio = choice(remedios)
                print(f'Você pode tomar um {remedio} para aliviar sua dor')
                break
            else:
                print('Desculpe-me, mas não sei o que fazer nesses casos')
        break
    else:
        print('Desculpe-me, mas não sei o que fazer nesses casos')

Veja funcionando no Repl.it


Two searchable.xml activities in one AndroidManifest.xml

Question: I have an Android app which has a few different activities for browsing articles and images downloaded from RSS.
I'd like to be able to offer to hook up the search button to the Search dialog, using the a searchable.xml file. I've managed to do this with one search, using:
<activity android:name=".search.SearchResultsActivity"
    android:label="@string/search_results_activity_title" >
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    <meta-data android:name="android.app.searchable"
        android:resource="@xml/searchable_articles"/>
</activity>

and in the <application />
<meta-data android:name="android.app.default_searchable"
    android:value=".search.SearchResultsActivity" />

I can now launch the Search dialog from any activity, and it launches the SearchResultsActivity.
I would now like to be able to search for images when the user is an ImageListActivity, using a searchable_images.xml, and use the default everywhere else.
I have a SearchResultsImageActivity which includes the following meta-data element, and used the same element in the ImageListActivity.
<meta-data android:name="android.app.searchable"
    android:resource="@xml/searchable_images"/>

On pressing the search button in the ImageListActivity, I get the default search from searchable_articles.xml.
If I change the default_searchable to SearchResultsImageActivity, the image search is always launched, and the article search is never launched.
If I remove the default_searchable meta-data element altogether, and add searchable meta-data only selected activities, no search is launched.
I'm fairly sure this should be possible, but I don't know what I'm doing wrong.
Comment: Did you figure this out?
Comment: I don't think you can do it using xml since the resource is a one to one with an Intent. You might be able to switch out the resource in you code.
Answer: In your Manifest file update the ImageListActivity activity tag
<activity
    android:name=".ImageListActivity"
    ...

    <meta-data
        android:name="android.app.default_searchable"
        android:value=".SearchResultsImageActivity" />
</activity>

So when you will trigger native search in ImageListActivity it will invoke the SearchResultsImageActivity and default one for others.
Assuming SearchResultsImageActivity is searchable.
Answer: One way I did this was to create fake activities then switch out the activities when you need them.
<activity android:name="activitySearchMain" />
  <activity android:name="activitySearchSub1">
    <intent-filter>
      <action android:name="android.intent.action.SEARCH" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.ALTERNATIVE" />
      <category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
      <data android:scheme="user" />
    </intent-filter>
  </activity>
  <activity android:name="activitySearchSub2">
    <intent-filter>
      <action android:name="com.sample.twitter.action.SEARCH" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.ALTERNATIVE" />
      <category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
      <data android:scheme="user" />
    </intent-filter>
</activity>

Create two class that are named for the sub activities.
then create intents like this when component is clicked...
Intent sourceIntent = getIntent();
Intent newIntent = new Intent(this, activitySearchSub2.class);
newIntent.setAction(activitySearchSub2.ACTION2);
newIntent.setData(sourceIntent.getData());
startActivity(newIntent);
finish();

and call the intents from onClick when a button is clicked or some other component is click:
Comment: I've not come across this activity within an activity pattern. I'm not clear what this is doing.
Comment: Its a way to switch out activities when clicking buttons but allowing you to keep the main activity in the background.  Useful when doing searches on a document from say an RSS feed.
Answer: If you override the search function in just that activity, it should prevent the search call from going up to the application level.  The return value controls if the call is propagated up.
@Override
public boolean onSearchRequested() {
    onPromptSearch();
    return false;  // don't go ahead and show the search box
}


start to preload content after a complete page load

Question: i am trying to make the preloading work in such a way that the components i wish to preload start to load after successfully loading the page.
for example,
i have index.php. i want it to load up completely.
as soon as it loads up i want to start loading the other components.
to make things clear. i have a nav that makes use of large size images. if i load them along with the index.php file, it would increase load up time of the page. i wish for those large images to load after completely rendering index.php?
am i making sense? is it possible?
Answer: The images are loaded almost in parallel to the PHP program execution. That is actually depends on the time it takes to execute your PHP program, the speed transfer of the data that you output to the browser etc.
You shouldn't try to load those images after processing index.php, that wouldn't help, because that your server is the one who process the PHP script, while the browser is the one who should fetch the images.
Having your PHP program to output the image tags as soon as possible is good and improves user experience.
Answer: I don't think you understand how a webpage works. The index.php file will execute everything it needs before any HTML output even begins processing, which takes mere milliseconds. Then HTML will begin to load everything in the order it appears on the page. The page doesn't wait for the images to finish loading before it displays anything. It will display the outline of the page as it has been loaded so far and as the images finish loading simply insert them into the correct place. It sounds to me like what you want is already the way things work.
Answer: Just attach your preloading function to the window object's 'load' event.  Load fires after the page (and all external resources) are completely loaded.
This is different from the "DOMReady" event that various libraries like JQuery provide (as in Ivo's answer).  $(document).ready(fn) will fire off once the DOM is ready (meaning the complete http document has been received/parsed) but does not wait for external resources (images, css, etc) to download.
Instead, you want $(window).load():

That will trigger your preLoadStuff handler after all images, etc, are completely loaded.
Answer: $(document).ready(function() { YOUR CODE HERE });
http://api.jquery.com/ready/
Comment: Not quite -- this solution will fire code when the DOM is ready, but will not wait for external resources to load.  In this case, it seems he wants to wait until all the stuff referenced in his markup is completely loaded, and then execute code to preload other images.
Comment: All markup is completely loaded when the DOM is ready, which means page is ready to be visualized in the browser. He can add custom made function which will load his JavaScript (other than jquery) and images and trigger it on $(document).ready()


Como fazer Redirect na página com Django

Question: Como fazer redirect passando um objeto como parametro no django já tentei
redirect() e HttpResponseRedirect mas não consigo enviar um objeto para página no response, toda vez que aperto f5 ele quer reenviar a requisição. Como
resolver esse problema ?
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from webapp.metodos.gauss import Gauss
from django.urls import reverse

import numpy as np
import csv
import io

def index(request):
    if request.method == 'POST':
        matriz = readCSV(request)
        return render(request, 'index.html', {'matriz': matriz})
    return render(request, 'index.html')

def gauss(request):
    if request.method == 'POST':
        g = Gauss()
        matriz = readCSV(request)
        resultado = g.executar(matriz)
        return render(request, 'gauss.html', {'resultado': resultado})
    return render(request, 'gauss.html')

def gaussjordan(request):
    return render(request, 'gaussjordan.html')

def fatoracaolu(request):
    return render(request, 'fatoracaolu.html')

def readCSV(request):
    data = request.FILES['file'].read().decode('UTF-8')
    io_string = io.StringIO(data)
    matriz = np.loadtxt(io_string, delimiter=',', dtype=int)
    return matriz

    <form class="form-group" action="{% url 'index' %}" method="POST"
                   enctype="multipart/form-data">
                        {{ form.file }}
                        {% csrf_token %}
            <input type="submit" value="Executar">
            <input type="file" name="file" id="arquivo" required />
    <form>

Comment: Você está querendo redirecionar para uma pagina após o submit de um form? Poderia postar o código completo da view?
Comment: correto quero redirecionar passando um objeto que vai ser carregado na pagina alterei código coloquei form
Comment: Coloque o código da view, onde você processa o form, todo o código se possível, porquê creio que utilizar um CCBV será melhor, mas para dizer como fazer, precisarei ver a view.
Comment: coloquei toda código da view e form no html
Answer: Tente alterar o render do Return do seu if para Redirect.
Ex:
def gauss(request):
    if request.method == 'POST':
        g = Gauss()
        matriz = readCSV(request)
        resultado = g.executar(matriz)
        return redirect('gauss')
    return render(request, 'gauss.html')

Comment: editado Fernando, erro de bios rs
Answer: Aparentemente seu problema é a estrutura de views que você está pensando.
Seria muito mais simples você passar resultado ou None para o template, e no template você mostra o resultado apenas se ele existir. Exemplo:
def gauss(request):
    resultado = None
    if request.method == 'POST':
        g = Gauss()
        matriz = readCSV(request)
        resultado = g.executar(matriz)

    return render(request, 'gauss.html',  {'resultado': resultado})

Já para redirecionar o usuário para outra URL no Django você deve retornar um objeto do tipo HttpResponseRedirect passando uma URL para o construtor.
from django.http import HttpResponseRedirect

def my_view(request):
    return HttpResponseRedirect("https://pt.stackoverflow.com/")
    # ou
    return HttpResponseRedirect("/minha-pagina/")
    # ou
    return HttpResponseRedirect("minha-pagina/relativa")

Mas essa não é maneira mais comum de se fazer o redirecionamento, geralmente se usa uma função utilitária disponibilizada pelo próprio Django, seria a função django.shortcuts.redirect.
Ela é mais comumente utilizada pois ela trata de montar a URL automaticamente para você, basta que você passe:

Um model que implemente o método get_absolute_url():
from django.shortcuts import redirect

def my_view(request):
    ...
    obj = MyModel.objects.get(...)
    return redirect(obj)

Se você verificar o código fonte verá que basta ser qualquer objeto que tenha um atributo invocável chamado get_absolute_url, não sendo obrigatório ser um Model.
Uma string representando uma view (você pode passar os argumentos para a view assim como você faz quando usa django.urls.reverse):
from django.shortcuts import redirect

def my_view(request):
    ...
    return redirect('some-view-name', foo='bar')

Passar uma string que representa um URL (mesmo comportamento de quando você usa HttpResponseRedirect)
from django.shortcuts import redirect

def my_view(request):
    ...
    return redirect('https://pt.stackoverflow.com/')

Para entender melhor, você pode (e deve) verificar o código da função django.shortcut.redirect, você verá que ela não faz muito mais do que chamar a função resolve_url. O código da função resolve_url é curto e se encontra mais abaixo de redirect no mesmo arquivo.


Do all guitars eventually require a neck reset?

Question: String tension contributes to creep in the wood of a guitar neck over time. I have heard that a neck reset is an eventual necessity for acoustic guitars even if they are meticulously cared for.
Is it the same for electric guitars and basses? And, is it feasible to DIY?
Comment: Over what sort of time period? I've kept several guitars - acoustic and electric (solid) for 40 to 50 yrs with no need for this.
Comment: For the bass I'm looking at in particular, I am researching how old it is now... I bought it second-hand around 12 years ago
Answer: An Epiphone acoustic, MIJ, which I bought second-hand 50 yrs ago, has never needed touching. My Tele - '76 - the same. A Shergold, ('78) which was played on hundreds of gigs for 25 yrs+ again, no problem. So while there is a very slight chance that 'creep' might affect a guitar, so far, it's not any of mine - of which I have many older editions - including basses.
If it did happen, I'd say it's adjustment of trussrod initially, but that would be a small diy adjustment. Of course, where (and how) it's kept, and what the weather conditions in the area may be contributory factors.
Answer: In theory yes, in practise no.
Case in point…
My 1964 Strat & 1976 Rikki 4001. I adjusted both neck truss-rods when I got them, simply because I didn't like how they were set before.
They haven't needed touching since.
The Strat I did in the mid 90's, the Rikki in 1990.
So in practise, I'd call 30 years pretty stable.


should weights be scaled too?

Question: I am using supervised learning algorithms (specificly SVM) on my data.
I know that scaling was needed for my input data. however as I am also adding weights (using pairwise comparison), I am not sure if my weights need to be scaled as well.
I don't mean normalizing the weights.
Answer: If you are talking about data weights, I dont know. In fact I am not sure that any of the standard SVM implementations have data weights (each data point has a weight). If you are talking about CLASS weight, at least in the libSVM implementation, they are multiplicative terms
-wi weight: set the parameter C of class i to weight*C, for C-SVC (default 1)
(from the libSVM page http://www.csie.ntu.edu.tw/~cjlin/libsvm/ )
so there is no gain in scaling them.
Comment: Hi thanks for that, yes scaling would  not have worked with the regular matlab svm, it works better with libsvm.  SVM normalizes everything.

should weights be scaled too?


Matrix for Mixed Boundary Value Problem

Question: My friend and I have been working on numerical solving the following equation $$-u'' = f$$ with $x \in [0,1]  $ ,  $ u'(0) = 0$, $u(1) = 0$.
Analytically, we found the eigenvalues and eigenfunctions $\lambda_n = \frac{(2n-1)\pi^2}2$ and $y_n(x)= cos(\frac{(2n-1)x\pi}2)$
But we don't know how to find the right matrix for a finite difference method havign discretized the Neumann condition as $U_0 - U_1 = 0$
Can anyone provide some help?
Answer: I take it that you have the difference equation
$$\frac{U_{i+1}-2U_i+U_{i-1}}{(\Delta x)^2}=-\lambda_nU_i$$
The Neumann boundary condition is the same as having the mirror image of the solution on the other side of $x=0$. Thus one could assume $U_{-1}=U_1$ and the left boundary difference equation reads
$$\frac{2U_1-2U_0}{(\Delta x)^2}=-\lambda_nU_0$$
EDIT: Come to think of it, that isn't very accurate. If you start with
$$\begin{align}U_0&=U_0\\
U_1&=U_0+hU_0^{\prime}+\frac12h^2U_0^{\prime\prime}+\frac16h^3U_0^{\prime\prime\prime}\\
U_2&=U_0+2hU_0^{\prime}+2h^2U_0^{\prime\prime}+\frac43h^3U_0^{\prime\prime\prime}\end{align}$$
Then, since $U_0^{\prime}=0$
$$8U_1-U_2=7U_0+2h^2U_0^{\prime\prime}$$
So a better difference equation would be
$$\frac{-7U_0+8U_1-U_2}{2(\Delta x)^2}=-\lambda_nU_0$$
Answer: Before you connect your analytic analysis to FDM scheme, here is FDM Scheme to solve the Poisson equation in one dimension.j
Let $x_0=0$ and $x_5=1$ with uniform step size $\Delta x$.
For $i=1, 2, 3, 4$,
\begin{equation}
 -u''(x_i) = \frac{-U_{i+1} + 2 U_{i} - U_{i-1}}{\Delta x^2} + o(\Delta x^2).
\end{equation}
In particular, $i=0$, (at Neumann boundary condition node, $x_0$),
\begin{equation}
 \frac{-U_{1} + 2 U_{0} - U_{-1}}{\Delta x^2} = \frac{-U_{1} + U_{0}}{\Delta x^2}
\end{equation}
since $U_0-U_{-1} = 0$.
Therefore your matrix system will be
\begin{equation}
\frac{1}{\Delta x^2}
\begin{bmatrix}
 1 & -1 & 0 & 0 & 0 \\
 -1 & 2 & -1 & 0 & 0 \\
 0 & -1 & 2 & -1 & 0 \\
 0 & 0 & -1 & 2 & -1 \\
 0 & 0 & 0 & -1 & 2
\end{bmatrix}
\begin{bmatrix}
 U_0\\U_1\\U_2\\U_3\\U_4
\end{bmatrix}
=
\begin{bmatrix}
 F_0\\F_1\\F_2\\F_3\\F_4
\end{bmatrix}.
\end{equation}

Matrix for Mixed Boundary Value Problem


Prove $\tan(A+B+Y)=\frac{\tan A+\tan B+\tan Y-\tan A\tan B\tan Y}{1-\tan A \tan B-\tan B\tan Y-\tan Y\tan A}$

Question: I have to prove this most difficult trigonometric identity.
$$\tan(A+B+Y)=\frac{\tan A+\tan B+\tan Y-\tan A\tan B\tan Y}{1-\tan A \tan B-\tan B\tan Y-\tan Y\tan A}.$$
I know
$$\tan(A+B)=\frac{\tan A+\tan B}{1-\tan A\tan B}$$
My problem is with the extra $Y$ in this problem. What can I do about I think I know a solution which is to do $\tan(A+B)$ then $\tan(B+Y)$ but I am not sure how to apply it.
Comment: @FernandoMartinez Let this be an opportunity to learn it. It is not hard.
Comment: (-1) I understand, it is very comfortable when other people put in order your post. But now its time to learn some $\TeX$.
Comment: I just dont understand latex its not my fault.
Comment: Take a look at [this giudeline](http://meta.math.stackexchange.com/questions/107/faq-for-math-stackexchange/117#117)
Comment: Can you remove the thumbs down at least it breaking my....heart
Comment: I will try to post latex but errors may occur....
Comment: Now try $\tan(A+B+C+D)$ - these $\tan$ formulae are beautiful things.
Answer: With all these simple solutions available, how about a complex one?

The argument of the product of two complex numbers is the sum of their arguments.
The imaginary part of a complex number divided by its real part is the tangent of its argument.

Consider the product
$$
\begin{align}
&(1+i\tan(A))(1+i\tan(B))(1+i\tan(Y))\\
&=1-\tan(A)\tan(B)-\tan(B)\tan(Y)-\tan(Y)\tan(A)\\
&+i\,(\tan(A)+\tan(B)+\tan(Y)-\tan(A)\tan(B)\tan(Y))\tag{1}
\end{align}
$$
Using 1. and 2., $(1)$ says that
$$
\tan(A+B+Y)=\frac{\tan(A)+\tan(B)+\tan(Y)-\tan(A)\tan(B)\tan(Y)}{1-\tan(A)\tan(B)-\tan(B)\tan(Y)-\tan(Y)\tan(A)}\tag{2}
$$
Answer: We have
$$
\tan(A+B+C)=\tan(A+(B+C))=\frac{\tan A+\tan(B+C)}{1-\tan A \tan(B+C)}=
$$
$$
\frac{\tan A+\frac{\tan B+\tan C}{1-\tan B \tan C}}{1-\tan A\frac{\tan B+\tan C}{1-\tan B\tan C}}=
\frac{\tan A+\tan B+\tan C-\tan A\tan B\tan C}{1-\tan A\tan B-\tan B\tan C-\tan C\tan A}
$$
In the last step we multiplied the numerator and the denominator by $1-\tan B\tan C$.
Comment: It makes sense thanks.
Answer: Replacing $B$ by $B+Y$ in your expression for $\tan(A+B)$ gives
$$\dfrac{\tan A + \tan(B+Y)}{1 - \tan A \tan(B+Y)}$$
Expanding gives
$$\dfrac{\tan A + \frac{\tan B + \tan Y}{1 - \tan B \tan Y}}{1 - \tan A \frac{\tan B + \tan Y}{1 - \tan B \tan Y}}$$
Multiplying through by $1 - \tan B \tan Y$ gives
$$\frac{\tan A(1 - \tan B \tan Y) + \tan B + \tan Y}{1 - \tan B \tan Y - \tan A(\tan B + \tan Y)}$$
And simplifying gives you what you want.
Comment: Very help answer thanks.
Answer: Do $a=\tan A, b= \tan B$ and $y = \tan Y$. Then,
\begin{eqnarray}
\tan (A+B+Y) &=& \dfrac{\tan(A+B) + \tan(Y)}{1-\tan(A+B)y}\\
&=& \dfrac{\dfrac{a+b}{1-ab}+y}{1 - \Big(\dfrac{a+b}{1-ab}\Bigr)y}\\
&=& \dfrac{\dfrac{a+b+(1-ab)y}{1-ab}}{\dfrac{1-ab - (a+b)y}{1-ab}}\\
&=& \dfrac{a+b+y -aby}{1-ab-ay-by}.\\
\end{eqnarray}
Answer: Just use the sum formula twice:
$$
\begin{align*}
\tan(A+B+Y)=\tan((A+B)+Y) &= \frac{\tan(A+B)+\tan Y}{1-\tan(A+B)\tan Y}\\
&=\frac{\left(\frac{\tan A +\tan B}{1-\tan A\tan B}\right)+\tan Y}{1-\left(\frac{\tan A +\tan B}{1-\tan A\tan B}\right)\tan Y}\\
&= \frac{(\tan A + \tan B)+ \tan Y(1-\tan A\tan B)}{(1-\tan A\tan B)-(\tan A + \tan B)\tan Y}\\
&=\frac{\tan A + \tan B + \tan Y - \tan A\tan B\tan Y}{1-\tan A\tan B-\tan A\tan Y-\tan B\tan Y}
\end{align*}
$$
Comment: Although all responses are good Fernando likes this one especially.
Answer: Just like when you use an eraser on pencil written paper stuff, erase $b$ and in its place write $B+C$ wherever it comes.
You know
$$\tan(A+b)=\frac{\tan A+\tan b}{1-\tan A\tan b}$$
It becomes:
$$\tan(A+B+C)=\frac{\tan A+\tan (B+C)}{1-\tan A\tan (B+C)}$$
Now expand and simplify... that's it!
Remember, this way you can even go to next step( for practice) to expand $\tan(A+B+C+D) !$
Suggest (for practice) use procedure in this thread outlined by robjohn
$$ (1+i\tan(A))(1+i\tan(B))(1+i\tan(Y)) (1+i\tan(Z))$$
to appreciate how it goes in complex algebra and trig connections .


Multiple columns instead of 1

Question: I'm trying to list multiple columns for a series of 3 tables where it can identify multiple owners for a single house, however I'm trying to figure out what to search for to help me accomplish what I'm looking for.
Inventory
--------------------
ID | House Address |
--------------------
1  | 123 Main St   |
--------------------
2  | 436 East St   |
--------------------

Contacts
----------------
ID | Name      |
----------------
1  | Billy Bob |
----------------
2  | Mary Ann  |
----------------
3  | Gilligan  |
----------------
4  | Skipper   |
----------------

Owners
-----------------------
InvID  |  ContactsID  |
-----------------------
1      | 2            |
-----------------------
2      | 1            |
-----------------------
2      | 3            |
-----------------------
2      | 4            |
-----------------------

Ideal Result
----------------------------------------------
Address     | Owner1    | Owner2   | Owner3  |
----------------------------------------------
123 Main St | Billy Bob | Gilligan | Skipper |
----------------------------------------------
436 East St | Mary Ann  |          |         |
----------------------------------------------

I've tried Joining these tables however it doesn't give the expected output.  If someone could point me in a direction to research I would be glad to find the answer myself however at this point I'm scratching my head for what I'm looking for.
One solution that I've tried:
Select
    Inventory.Address,
    Contacts.FirstName + ' ' + Contacts.LastName AS 'Owner',
    Contacts.Phone
From Inventory
LEFT JOIN Owners
ON Owners.InventoryID = Inventory.ID
LEFT JOIN Contacts
ON Contacts.ID = Owners.ContactID

This gives me all the information that I need, just not in the format I was hoping to achieve.
Comment: You need to PIVOT result, specify database you use
Answer: Consider the following query with nested derived tables that uses a calculated row number to present Owners 1-3 in separate columns.
This should work as a general solution across most RDMSs as it uses ANSI SQL syntax not restricted to any specific Pivot(), Over(), or CTE() functions:
SELECT
   Address,
   Max([Owner_1]) As Owner1,
   Max([Owner_2]) As Owner2,
   Max([Owner_3]) As Owner3
FROM
  (SELECT Address,
         CASE RowNumber = 1 THEN [Name] END As Owner_1,
         CASE RowNumber = 2 THEN [Name] END As Owner_2,
         CASE RowNumber = 3 THEN [Name] END As Owner_3
  FROM
       (SELECT Owners.InvID, Owners.[Contacts ID], Inventory.Address, Contacts.Name,
              (SELECT Count(*) FROM Owners t1
               WHERE t1.[Contacts ID] <= Owners.[Contacts ID]
               AND t1.InvID = Owners.InvID) As RowNumber
       FROM Owners
       LEFT JOIN Inventory ON Owners.InvID = Inventory.ID
       LEFT JOIN Contacts ON Owners.[Contacts ID] = Contacts.ID
  ) As dT1
) As dt2
GROUP BY Address;

With Output as the following:
Address      Owner1     Owner2      Owner3
123 Main St  Mary Ann
436 East St  Billy Bob  Gilligan    Skipper

Multiple columns instead of 1


Error de sintaxe em Graphql

Question: Bom dia pessoal, estou estudando Graphql sozinho e encontrei essa dificuldade, criei uma api que faz cadastros e retorna alunos, quando fui fazer uma consulta no playground ela fica dando error de sintaxe, alguém sabe o motivo da sintaxe estar errada, já li todos os erros e modifiquei e nada funciona.
Answer: Apos ficar umas horas aqui tentando e tentando, descobri que você pode fazer as declarações da variável tudo na parte abaixo e só passar ela na mutation. A imagem e muito descritível, e só olhar ai e utilizar de exemplo.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Error de sintaxe em Graphql


$md dialog quando carrega a página

Question: Preciso abrir o modal $md dialog quando carrego página, alguma sugestão?
$scope.showAdvanced = function(ev) {
    $mdDialog.show({
      controller: DialogController,
      templateUrl: 'dialog1.tmpl.html',
      parent: angular.element(document.body),
      targetEvent: ev,
    })
};

Answer: Você pode usar o $timeout:
$timeout($scope.showAdvanced, 0);

Não esqueça de injetar a dependência do $timeout para que funcione corretamente.
Comment: @SamuelSouza Isso aí
Answer: Consegui aqui também dessa forma:
 $mdDialog.show({
    controller: DialogController,
    templateUrl: 'modalDialog.html',
    scope: $scope,
  });

$md dialog quando carrega a página


Should AWS Security groups allow internet traffic?

Question: Ok, so I created a default Elastic Beanstalk Application and getting this reported as High Risk, and happens on all Regions that are connected to the VPC Network (which is not a public IP, only the Load Balancer subnets are).

AWS Security groups allow internet traffic

The site is public, so shouldn't this be normal?  Or is there a way to not allow Security Groups internet traffic and still keep the site publicly visible to users who visit it?  I'm just not sure if there is a way to fix this High Security Risk that's being reported.  Is this an actual Security Risk?  If so, any idea how to fix this problem?  I am also receiving the following Security Risk here:

AWS Default Security Group does not restrict all traffic

Why would I want to restrict all traffic?  Is there a way to do this and still make the site publicly visible on the internet?  Please note, running a wordpress site.
Should this not allow Internet Access?  Sorry if this is a dumb question.
And seeing this as well:

AWS EC2 instances with Public IP and associated with Security Groups have Internet Access

I don't think these instances need access to the internet to be displayed on the internet, but not sure how to fix this.
EDIT
Here are my Security Groups inbound and outbound rules:

Do I need to remove the Inbound Rule for this in order to fix this, but still keep internet working on the site?  This is the Security Group for the VPC Network, btw, is this the correct one?
Load Balancer Settings from EB here:
Comment: Post your Load Balancer and EB instance security group settings / screenshots. We can't guess what you've got there and why.
Comment: Ok, does this help you any? What I've read online, says you have to have Inbound set to port 80 and outbound set to All traffic in order to have a public site accessible to everyone on the internet.  Is this not correct?
Comment: This is the Security Group attached to the VPC btw, is this the one you need?
Comment: Do I need to remove Inbound and Outbound on the VPC Security Group and the Load Balancer would run it instead?
Comment: I am now thinking this is due to VPC, which I don't even think is needed on the Elastic Beanstalk Environment, but was on the older Environment before.  Everything is streaming from the site itself, so I think it has to do with the VPC, what are your thoughts?
Answer:

AWS Security groups allow internet traffic

Normal for a web server

AWS Default Security Group does not restrict all traffic

Remove all the rules from the default security group, and use a custom security group.
Update: Best practice is not to use the default security group, and to remove all rules from that group. That way anything that uses the default security group is obviously using a default rather than a deliberate selection, which generally means it needs attention and to be changed to use an appropriate security group.

AWS EC2 instances with Public IP and associated with Security Groups have Internet Access

That's the whole point of it I think
Comment: Best practice is not to use the default security group, and to remove all rules from that group. That way anything that uses the default security group is obviously using a default rather than a deliberate selection, which generally means it needs attention and to be changed to use an appropriate security group.
Comment: You're welcome. You learn a lot in AWS preparing for the security certification, and going through PCI compliance for an AWS based system.
Comment: If I'm going to change to a different Security Group, what's the point of removing all rules from the default Security Group?  Just curious, and thank you very much for your input on this.
Comment: I believe other sites on here might be using the default security group.  I don't think the site I am working on is.  So I don't think removing all rules will help.  I did edit it to only allow ports 80 and 443 for inbound, and All traffic for outbound.  So hopefully that fixes the majority of these issues.
Comment: Thanks for the more details on this.  You da Man, Tim!


Is there a correct way to turn off UAC, User Account Control, in Windows Server 2008?

Question: Is there a correct way to turn off UAC, User Account Control, in Windows Server 2008?
I have found an article at Microsoft explaining the various settings. It looks like it is just a matter of disabling "User Account Control: Run all administrators in Admin Approval Mode", but I wanted a second opinion.
Comment: I understand the implications of turning UAC off. And am only considering this for a very particular situation, on a test/development server.
Comment: OK, then. Some people disable UAC just because "is annoying". I my opinion is an essential feature nowadays from a security point of view, since the AV detect rate is quite low from several years ago.
Answer: Yes, just use that setting, but in my opinion the correct way of turning off UAC is leaving it enabled :-), at least once the server is configured and all required applications installed.
Using an option provided by the Windows interface or by Group Policy is better in almost all situations than using a registry hack.


How can user select attributes for a product when clicking on an add-to-cart link?

Question: I'm trying to work out the best way of displaying an attribute selection form when a user clicks on an add to cart link (not on a product node). Ideally display a form in a shadowbox with attribute selection and quantity fields and a submit button. I feel like this option must exist somewhere, but I haven't found it.
Any pointers for me?
Answer: Very old one but why not answer?
Use Ubercart Cart LInks module (included in Ubercart Core). I think it allows links that operates on the cart, like empty cart or add a product what I guess includes product attributes.
Here it's explained, but is very old page, check module documentation.
http://www.ubercart.org/node/1427


Azure App Service Set Custom ConnectionTimeout in ApplicationHost.config

Question: On our ASP.NET MVC website hosted on Azure App Service we'd like to force a timeout for requests that take longer than 15 seconds. Here's a simple action that always takes longer than 15 seconds (i.e. infinite loop) that we've been testing with...
    public ActionResult TimeoutTest()
    {
        var i = 1;
        while (true)
        {
            i++;
        }
        return new HttpStatusCodeResult(200);
    }

By default, if I do a GET on that action in a browser, I'll get a "500 - The request timed out" error after two minutes, which agrees with the "connectionTimeout" default setting in the webLimits section of ApplicationHost.config.
So...unless I'm mistaken, it should be enough to change this connectionTimeout value to 15 seconds. To do this, I understand one needs to use a transform-based approach for the ApplicationHost.config file (XDT), as explained here.
I did this with the following applicationHost.xdt file...
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.applicationHost>
      <webLimits xdt:Transform="SetAttributes(connectionTimeout)" connectionTimeout="00:00:15"/>
</system.applicationHost>
</configuration>

...after which I added the file in the right place (d:/home/site/applicationHost.xdt). I restarted my site and saw in the logs that the transform was successfully applied:
2016-04-20T08:40:44 Start 'site' site extension transform
2016-04-20T08:40:44 StartSection Executing SetAttributes (transform line 4, 18)
2016-04-20T08:40:44 on /configuration/system.applicationHost/webLimits
2016-04-20T08:40:44 Applying to 'webLimits' element (no source line info)
2016-04-20T08:40:44 Set 'connectionTimeout' attribute
2016-04-20T08:40:44 Set 1 attributes
2016-04-20T08:40:44 EndSection Done executing SetAttributes
2016-04-20T08:40:44 Successful 'D:\home\site\applicationHost.xdt' site extension transform
2016-04-20T08:40:44 sandboxproc.exe complete successfully. Ellapsed = 316.00 ms

[Edit]: I have also checked the applicationhost.config directly after the transform, and the new value is there:
    ...
    </sites>
    <webLimits connectionTimeout="00:00:15" />
  </system.applicationHost>
  <system.webServer>
    <asp>
    ...

Despite all this, if I hit my action method above again, it still times out after two minutes instead of 15 seconds.
My question: Does anybody know why this timeout setting isn't being respected?
I'm aware of this post, which looks like it took exactly the same approach (and seemed to work?).
Answer: What about using executionTimeout instead, through the Web.Config?
<system.web>
    <httpRuntime executionTimeout="30" />
    <compilation debug="false" />
</system.web>

For a MVC project, you should add the following code to force the value to be applied to the request:
System.Web.HttpContext.Current.GetType().GetField("_timeoutState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(System.Web.HttpContext.Current, 1);

If you want every request to respect this setting, you can create an action filter:
public class Timeoutter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        System.Web.HttpContext.Current.GetType().GetField("_timeoutState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(System.Web.HttpContext.Current, 1);
        base.OnActionExecuting(filterContext);
    }
}

Add register it in the RegisterGlobalFilters method called in the Global.asax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new Timeoutter());
    filters.Add(new HandleErrorAttribute());
}

Please see:

https://msdn.microsoft.com/en-us/library/e1f13641(v=vs.85).aspx
http://forums.asp.net/p/1715081/4723882.aspx?Re+web+config+executionTimeout+not+working+in+ASP+NET+MVC
.NET Execution Timeout Not Taking Effect in an MVC Web Project
Comment: Thanks, yes, I'm aware of that one too. It's also set to 15 seconds and doesn't seem to make a difference either.
Comment: I've added more details above.


Symfony 4 - Use service in my form (in query_builder)

Question: in my symfony 4 project, in my form, I would like to use a service to complete a select. So, I did this :
Form
public function buildForm(FormBuilderInterface $builder, array $options, GroupeValidateursService $groupeValidateursService)
{
    // $groupeValidateursService = $options['groupeValidateursService'];

    $builder
        ->add('defaultGroupeValidateurs', EntityType::class, [
            'class' => GroupeValidateurs::class,
            'label' => "Service par défaut",
            'placeholder' => "Sélectionnez un service",
            'query_builder' => function () use ($groupeValidateursService) {
                return $groupeValidateursService->getNotDefaultGroups();
            },
            'choice_label' => 'nom',
        ]);
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => ParametresAdmin::class,
        'groupeValidateursService' => GroupeValidateursService::class,
    ]);
}

Controller:
$formDeleteDefaultGroupe = $this->createForm(DeleteDefaultGroupeType::class, $parametresAdmin, [
            "groupeValidateursService" => $this->groupeValidateursService,
        ]);

If I make a dump die in my service function, it's ok, I've an object array like in a query of a repository.
But I've this error :

Expected argument of type "Doctrine\ORM\QueryBuilder", "array" given

I think that it has a problem when I'm returning the array from my function service :
/**
 * Retourne tous les groupes sauf celui par défaut
 *
 * @return array
 */
public function getNotDefaultGroups()
{
    $groupes = $this->repoGroupeValidateurs->findAll();
    $default = $this->getDefaultGroupe();

    $otherGroups = [];

    foreach ($groupes as $groupe) {
        if ($groupe != $default) {
            $otherGroups[] = $groupe;
        }
    }

    return $otherGroups;
}

So I don't understand what's wrong
EDIT : I tried like this :
public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
        ->add('defaultGroupeValidateurs', ChoiceType::class, [
            'label' => "Service par défaut",
            'placeholder' => "Sélectionnez un service",
            'choices' => $options['groupeValidateursService']->getNotDefaultGroups(),
            'choice_label' => function ($choice, $key, $value) {
                return $value->getNom();
            }
        ]);
}

But I've this error :

Call to a member function getNom() on string

So, I replaced $value->getNom() by $choice->getNom().
But now I've this error :
Argument 1 passed to Symfony\Component\Form\FormRenderer::renderBlock() must be an instance of Symfony\Component\Form\FormView, string given

$formDeleteDefaultGroupe = $this->createForm(DeleteDefaultGroupeType::class, $parametresAdmin, [
            "groupeValidateursService" => $this->groupeValidateursService
        ]);
        $formDeleteDefaultGroupe->handleRequest($request);

Answer: EntityType requires QueryBuilder in parameters. You are using anonymous function for option 'query_builder' which return array. You must return QueryBuilder instead:
use Doctrine\ORM\EntityRepository;

$builder
    ->add('defaultGroupeValidateurs', EntityType::class, [
        'class' => GroupeValidateurs::class,
        'label' => "Service par défaut",
        'placeholder' => "Sélectionnez un service",
        'query_builder' => function (EntityRepository $entityRepository) {
            return $entityRepository->createQueryBuilder('gv')
                ->where('gv.group != :defaultGroup')
                ->setParameters(['defaultGroup' => 'someDefaultGrupIdentifier']);
        },
        'choice_label' => 'nom',
    ]);

Your second choice if you really want to use function from your service is to use ChoiceType where you can pass choices as option:
$builder->add('defaultGroupeValidateurs', ChoiceType::class, [
    'choices' => $options['groupeValidateursService']->getNotDefaultGroups(),
    'choice_label' => function ($choice, $key, $value) {
        return $value->getTitle()
    }
]);

More info: https://symfony.com/doc/current/reference/forms/types/entity.html#using-a-custom-query-for-the-entities
More info: https://symfony.com/doc/current/reference/forms/types/choice.html#example-usage


How do I adapt this program in VBA so that the original temperature is placed in a cell next to the converted temperature?

Question: This is my code... It keeps saying
SubConvertTemp()
Centigrade=MsgBox(Do you want to convert to centigrade?"),vbYesNo)
InputNumber=Val(InputBox("Enter a temperature for conversion?"))
If Centigradde= vbYes Then
ConvertedTemp= ((9/5 *InputNumber)+32)
MsgBox((InputNumber & " degrees C converts to " & ConvertedTemp &" Degrees F."))
Else: ConvertedTemp=(5/9)*(InputNumber-32)
MsgBox(InputNumber & "degrees F converts to " & ConvertedTemp & "degrees C.")
Worksheets.("Sheet 1).Cells(InputNumber,ConvertedTemp).Offset(-1,0).Value="Name"
end sub

This code keeps saying syntax error? Not sure why
Comment: So many mistake in syntax.
Comment: What actually you want to do.
Answer: A very small number of "syntax"typos:
Sub ConvertTemp()
    Centigrade = MsgBox("Do you want to convert to centigrade?", vbYesNo)
    InputNumber = Val(InputBox("Enter a temperature for conversion?"))
    If Centigradde = vbYes Then
        ConvertedTemp = ((9 / 5 * InputNumber) + 32)
        MsgBox ((InputNumber & " degrees C converts to " & ConvertedTemp & " Degrees F."))
    Else
        ConvertedTemp = (5 / 9) * (InputNumber - 32)
    End If
    MsgBox (InputNumber & " degrees F converts to " & ConvertedTemp & " degrees C.")
    Worksheets("Sheet1").Cells(InputNumber, ConvertedTemp).Offset(-1, 0).Value = "Name"
End Sub

EDIT#1:
A better version:
Option Explicit

Sub ConvertTemp()

    Dim Centigrade As String, InputNumber As Variant, ConvertedTemp As Double

    Centigrade = MsgBox("Do you want to convert to centigrade?", vbYesNo)
    InputNumber = Val(InputBox("Enter a temperature for conversion?"))
    If Centigrade = vbYes Then
        ConvertedTemp = ((9 / 5 * InputNumber) + 32)
        MsgBox ((InputNumber & " degrees C converts to " & ConvertedTemp & " Degrees F."))
    Else
        ConvertedTemp = (5 / 9) * (InputNumber - 32)
    End If
    MsgBox (InputNumber & " degrees F converts to " & ConvertedTemp & " degrees C.")
    Worksheets("Sheet1").Cells(InputNumber, ConvertedTemp).Offset(-1, 0).Value = "Name"
End Sub


How do I know that the number is halfway in between

Question: I was shown the following:
$$ 0.110 < 0.1101 < 0.111$$
and told that the middle number is halfway in between those two numbers. Is this correct? How can I see that?
Update:
If I add a zero to the first and the last number, I get:
$$ 0.1100 < 0.1101 < 0.1110$$
Now, let write out the last two digits and we can see the relationship:
$$ \underbrace{00 < 01 < 10}_{base-2} = \underbrace{0 < 1 < 2}_{base-10} $$
Comment: Place a $0$ at the end of the first and last numbers
Comment: I've done it and updated my answer, can you please see if that's what you meant?
Answer: Calculate the average of $0.110$ and $0.111$, by adding them and dividing the result by $2$ (keep in mind that it is binary), and see that you get $0.1101$.
Comment: I see, thanks. Is there an easier way to see this relationship, like the one suggested by Ahmed
Comment: @Maximus Mathematically equivalent, but perhaps more intuitive is to calculate the differences $0.1101 - 0.110$ and $0.111 - 0.1101$ and see that you get the same number.
Comment: thanks, can you please tell me whether the logic presented in my update is valid?
Comment: @Maximus It seems valid, yes. But I wouldn't _phrase_ it like that. What you have done is the following: 1) Multiply all the numbers by $1000$ 2) Subtract $1100$ 3) Convert to base ten to inspect the values. Perhaps you should convince yourself that none of these three steps ruins  the "halfwayness" that you're checking for.
Comment: thanks. Here is the other explanation. Can I say that the number is always two times more that the number following it? For example, in the fraction `0.111=0+1/2+1/4+1/8` the second number is two times larger than the third, so any number `0.111...(1*X)` will be two times larger, than `0.111...(0*X)1`?
Answer: \begin{align}
0.1100 &= 2^{-1} + 2^{-2} \\
0.1101 &= 2^{-1} + 2^{-2} + 2^{-4} \\
0.1110 &= 2^{-1} + 2^{-2} + 2^{-3} = 2^{-1} + 2^{-2} + 2\cdot2^{-4}
\end{align}
Therefore, the difference between $0.1100$ and $0.1101$ as well as between $0.1101$ and $0.1110$ is $2^{-4}$, and hence $0.1101$ does indeed lie halfway between the two other numbers.
Comment: thanks, this explanation seems the most intuitive to me


Regex trouble, capture until find space or endline

Question: I'm trying to capture the following match:

"url: https://www.anysite/anything"

But sometime the string comes:

"url: https://www.anysite/anything another word"

But i just only want to match

"url: https://www.anysite/anything"

whether or not the "another word" comes.
So, my logic is capture until find the first space after the url address, or end of string.
My REGEX IN PHP is:
preg_match("/(Url|url)(\:|\b)(\s\b|\b).+(\s|$)/",$linestring,$url_string);

But it always bring the "another word" too, instead of bring only until space.
Answer: The . is greedy unless the quantifier is made ungreedy with a ? or the U modified.
(Url|url)(\:|\b)(\s\b|\b).+?(\s|$)

Your actually can simplify it a bit further:
[Uu]rl(?::|\b)\s?\b.+?(?:\s|$)

If you want the URL bit capture the .+? with ().
[Uu]rl(?::|\b)\s?\b(.+?)(?:\s|$)

https://regex101.com/r/urq2fM/2/
Answer: One way to capture until the first space is to use \S+, which matches any sequence of one or more non-space characters:
url:?\s*(\S+)

By using the i flag we can avoid having to test for Url or url or URL etc. We can use preg_replace to simplify usage, replacing the string with just the captured group:
$url = preg_replace('/url:?\s*(\S+).*/i', '$1', $string);

e.g.
$strings = array("url: https://www.anysite/anything",
                 "url: https://www.anysite/anything another word");

foreach ($strings as $string) {
    $url = preg_replace('/url:?\s*(\S+).*/i', '$1', $string);
    echo "$url\n";
}

Output:
https://www.anysite/anything
https://www.anysite/anything

Demo on 3v4l.org


Determine the corresponding rate of increase of the water level height in the cylinder

Question: How do I go about doing this?
An ice cube of $16\,\text{cm}^3$ is melting on a mesh as shown below. Each side of the ice cube is
melting at a constant rate of $0.02\,\text{cm/s}$. Determine the corresponding rate of increase of the
water level height in the cylinder, when half of the volume of ice has melted, considering that
water expands by about $10\%$ when frozen. The cylinder has a radius of $2$ cm.
How do I start this? I'm quite bad at math so I'm not sure what formulas or rules to use.
Comment: This is a simple calculus problem. You have a rate of change of the sides of the cube, which translates to a non-constant rate of volume change. That volume of ice, when melted, corresponds to a volume of water (1.1 mL ice to 1 mL water).

The question asks for the rate of increase of the water height, which will not be constant (it will be quick to rise at first as the large ice cubes decrease in size quickly, and rise more slowly later on when the small ice cubes decrease in size slowly. This is a phenomenon most people are familiar with: ice melting in a drink).
Answer: I can't see the diagram but here is how you can get started:
First, an ice cube of initial volume 16 cm^3 has 6 sides, each melting at an equal rate of 0.02 cm/sec. This means that each face of the cube is approaching the center point of the cube at 0.02 cm/s, and therefore the ice cube is shrinking.
If S_t is the surface area of each side of the cube (in cm^2) at time "t" then the flow rate of melting ice $F_t$ is $6*0.02*S_t/1.1 $(accounting for water being 10% denser than ice).
If V_t ( in cm^3) of ice has melted (we assume equally from all sides) then the surface area at time "t" is given by:
$$ S_t = (16 -V_t)^{2/3} \implies F_t =  6*0.02*(16-V_t)^{2/3}/1.1$$
Now you just divide $F_t$ by the area of the cylinder to get the rate of rise.
Answer:
For a cylinder, such as a cylinder of water held in a cylindrical glass, volume $V,$ radius $r,$ and height $h$:
$$V_\text{cylinder} = \pi r^2 h$$
Let's find the derivative with respect to $h.$ Since the formula is first order with respect to $h,$ the derivative is easy. It's just:
$$\frac {dV_\text{cylinder}}{dt} = \pi r^2 \frac{dh}{dt}$$
For a cube, volume $V,$ sidelengths $s:$
$$V_\text{cube} = s^3$$
The problem is a bit unclear on if s is decreasing at a rate of $0.02$ cm/s, or $2\cdot0.02$ cm/s. I'll solve as $0.02$ cm/s.
Take the derivative of the second equation:
$$\frac{dV_\text{cube}}{dt} = V_\text{cube}' = 3s^2 \frac {ds}{dt}$$
Use the above equation along with the rate of decrease from the problem statement ($0.02$ cm/s) to find the general equation for the change in volume of the cube:
$$\frac{dV_\text{cube}}{dt} = 3s^2 (0.02\text{ cm}/\text{s})$$
Now find the side length when half the volume of the cube has melted. When half the volume has melted, $V_\text{half} = (0.5)(16) = 8\text{ cm}^3 = s_\text{half}^3$
$$\implies s_\text{half} = \sqrt[3]{8} = 2$$
Now substitute this into the first equation we found:
$$\frac{dV_\text{cube}}{dt} = 3s^2 (0.02\text{ cm}/\text{s})$$
$$\implies \frac{dV_\text{half}}{dt} = 3(2)^2 (0.02\text{ cm}/\text{s}) = 0.24\text{ cm}^3/\text{s}$$
Now we have the rate of ice melting. multiply that by the scaling factor:
$$0.24\text{ cm}^3/\text{s of ice} = \frac 1 {1.1} 0.24\text{ cm}^3/\text{s} \text{ of water} = \frac {24}{110}\text{ cm}^3/\text{s of water}$$
Now we have the rate of volume of water appearing from the melted ice. Use the formula for the volume of a cylinder to find the rate of change of height:
$$\frac {dV_\text{cylinder}}{dt}= \frac {24}{110} \text{ cm}^3/\text{s} = \pi r^2 \frac{dh}{dt}$$
$$\implies \frac{dh}{dt} = \frac {24}{440\pi} \text{ cm}/\text{s}$$
Simplifying,
$$\frac {24}{440\pi} \text{ cm}/\text{s} = \frac {3}{55\pi} \text{ cm}/\text{s}$$


tempo da requisição em AJAX

Question: Bom faço uma requisição via AJAX, assim posso colocar um load na tela e removê-lo quando o AJAX carregar a pagina.
O problema é que preciso fazer o load aparecer apenas se a requisição demorar mais de 2 segundos.
Estou fazendo assim:
$(document).ready(function () {
            $(".loading").show();
            $.ajax({
                url: 'APP?pagina=<?= $pagina ?>',
                success: function (response) {
                    $("#app").html(response);
                    $(".loading").hide();
                }
            });
        });

loading é a DIV que contam o loading, e ela so pode aparecer se a requisição demorar mais de 2 segundos.
Alguém sabe fazer isso?
Comment: você conhece o timeout?
Comment: Sim tentei usar ele aqui mais estava dando errado, pois a div estava aparecendo depois de 2 segunda e não saia mais da tela. Acho que eu não estava fazendo da forma correta
Answer: Dá pra utilizar um combo com status de variável e o setTimeout.
var showLoader = false;

$(document).ready(function () {
  var timeoutLoader = setTimeout(function () {
    showLoader = true;
    $(".loading").show();
  }, 2000); // 2000ms = 2 segundos

  $.ajax({
    url: 'APP?pagina=<?= $pagina ?>',
    success: function (response) {
      if (showLoader) {
        showLoader = false;
      } else {
        clearTimeout(timeoutLoader);
      }

      $(".loading").hide();
      $("#app").html(response);
    }
  });
});

Você cria uma variável de status do loader, deixando ela inicialmente como false.
Antes da chamada do AJAX, cria-se um timeout de 2 segundos e caso o tempo termine e a chamada AJAX não tiver terminado, o loader irá aparecer.
Quando a chamada finalizar, irá verificar o status do loader através da variável showLoader, se for true, esconde o loader, se não, limpa o timeout, para que ele não execute e mostre o loader.

Existem outras formas de fazer, mas essa é uma delas. Uma observação: 2 segundos é um tempo curto, veja se há realmente a necessidade disso na sua chamada AJAX, veja se ela demora muito ou é muito rápida.
Comment: Obrigado deu certo, em questão dos 2 segundos eu pensei assim. O site em média demora menos de 2 segundos para carregar, porém em relatórios pode demorar até 10 segundos, por isso quero que o loading só apareça quando a pagina demorar. Entendeu?
Comment: Tem um problema na sua resposta, o load não some da página.
Comment: Talvez tenha dado conflito no `clearTimeout` ao esconder o _loader_. Editei a pergunta e estarei escondendo o _loader_ mesmo se ele não aparecer.
Comment: ok vlw amigo deu certo

tempo da requisição em AJAX