In finding the moment generating function why do we multiply by $e^{tx}$ for each pmf term?

Question: The moment generating function that is associated with the discrete random variable $X$ and pmf $f(x)$ is defined as:
$$M(t) = E\left[e^{tX}\right] = \sum_{x \in S} e^{tx} f(x).$$
Where does this $e^{tx}$ come from? This vaguely looks like an integrating factor from differential equations.
Also, I find it strange that when we take the derivative of $M(t)$ we don't say "lets take the partial derivative with respect to t" but isn't this what we're doing, treating $x$ as a constant? Why do we use the derivative notation instead of the partial derivative operator?
Answer: There's a potential ambiguity in your question:
If you're asking (a) "Why is $e^{tX}$ inside the expectation?" then the answer is 'that's the definition of the moment generating function'.
On the other hand, if you're asking (b) "Given we want $E(e^{tX})$, why does $e^{tX}$ appear in the summation?", this would be because that's how expectation works.
That is, for the continuous case $E[g(X)] = \int g(x) f(x) dx$ (indeed, some authors seem to regard that law as a definition of expectation).

Why do we use the derivative notation instead of the partial derivative operator?

Because $X$ isn't regarded an argument of $M$, $t$ is. If it were $M(X,t)$, then we'd write $\partial$, but it's $M_X(t)$, so we write $d$. This isn't some accident of notation, however - it really is a function of $t$ we're dealing with, though calculated with respect to the distribution of $X$. Inside the integral/sum, $x$ is actually a dummy variable; it could as easily be represented by $u$, or any other dummy, and $M$ is certainly not a function of the dummy variable in any sense. You might think of $X$ like an indexing variable (since it determines which $M$ you get), but if $M$ is to be regarded as a function of something to do with $X$, it's really $F_X$ (through $dF$) that $M$ is a function of.
Answer: If $X$ is a discrete random variable taking its vales in $S$ and $h$ is a non negative function, then
$$\mathbb E[h(X)]=\sum_{x\in S}h(x)\mathbb P\{X=x\}.$$
Indeed, we formally have
$$\mathbb E[h(X)]=\mathbb E[h(X)\chi_{\bigcup_{x\in S}\{X=x\}}]=\sum_{x\in S}\mathbb E[h(X)\chi_{\{X=x\}}].$$
Now we use this with the map $x\mapsto e^{tx}$, where $t$ is fixed.
We don't need the partial derivative as there is no ambiguity: we can only take the derivative with respect to $t$.


Adicionar virgula a cada palavra

Question: Ex.:
$str = "texto de teste";
// RESULTADO ESPERADO
$keywords = "texto, de, teste";

Comment: Isso mesmo, com  `str_replace()`, veja se isso resolve o seu problema, tem outras abordagem. Você pode verificar as funções do php na documentação, veja a do str_replace, => http://php.net/manual/en/function.str-replace.php . É normal não lembrar a ordem dos argumentos de algumas funções ;)
Comment: Se `$descricao` é um string não é mais fácil trocar os espaços em branco por virgulas?
Comment: Realmente não pensei nisso.. parece que estou complicando a situação, removendo os espaços e adicionando uma virgula.. pode dizer-me como posso fazer isso? creio que deva ser com str_replace, mas não tenho noção na prática..
Comment: Obrigado, consegui fazer com a ajuda do site 'php.net' e também a de Vaati.
De qualquer forma, deu certo.
Só não irei dar sua resposta como correta porque ele deixou bem claro, e se futuramente alguém tiver a dúvida, verá a resposta logo abaixo!
Comment: Eu sugiro, trabalhar com `array('word 1','word 2','word 3')` nesse caso, aí seria só dar um `$string_virgulas = implode(',', $dados_array)`.
Comment: Essa solução não seria nada prática Ivan, melhor usar funções de manipulação de string ao invés de criar arrays, etc.
Answer: str_replace(" ", ", ", $descricao);

Sempre que encontro um espaço ( ' ' ), substituo por vírgula mais espaço ( ', ' )
Comment: Haha acontece amigo. De início é sempre assim. Mas, já que você está iniciando com PHP, qualquer dúvida sobre ele, veja nesse site aqui (já coloquei ele no tópico que fala sobre esse método 'str_replace':
http://php.net/manual/pt_BR/function.str-replace.php
Comment: Obrigado pela ajuda!
Olha só como eu estava tentando:
str_replace($descricao.' ' , $descricao.',' , $descricao);
Só deve ser dito aonde irá ser alterado no ultimo parametro, não é?! rs
Answer: Eu faria um pouco diferente, usaria regex para remover os espaços adicionais.
<?php
$exemplo = "texto de teste     com muitos   espaços talvez   erros de digitação";
$tags = preg_replace('/\s+/', ', ', $exemplo);
echo $tags . PHP_EOL;

$tags_2 = str_replace(" ", ", ", $exemplo);
echo $tags_2 . PHP_EOL;

Saídas:
Saída preg_replace texto, de, teste, com, muitos, espaços, talvez, erros, de, digitação
Saída do código do str_replace texto, de, teste, , , , , com, muitos, , , espaços, talvez, , , erros, de, digitação
Percebe a diferença? Espero que tenha o ajudado.
PS.: esta não é a "maneira correta", é só uma maneira alternativa, para quando existem espaços em demasia.
Answer: Baseado no seu exemplo, bastaria fazer isso:
$descricao = 'titulo de teste';
//aqui ele limpa espaços duplos, e substitui por um espaço
$descricao = preg_replace('/\s+/', ' ',$descricao);
$keywords = explode(' ',$descricao);
$listaComVirgula = implode(', ', $keywords);
echo $listaComVirgula;

Comment: @Otto, "kiss  - keep it simple stupid principle" já li sobre isso sim, eu sei onde há problema, e sei que poderia resolver fazendo isso: `$descricao = preg_replace('/\s+/', ', ',$descricao);`, mas o caso é abstrato, eu quis me basear na pergunta. Entendeu. Para toda pergunta há "n" respostas que eu poderia dar, no caso, é mais para mostrar na prática o uso do `implode()`. Não me pareceu ofensivo, mas pretensioso.
Comment: Convenhamos .... funciona mas fica feio demais né
Comment: A resposta apresentada não é para ter beleza, é para elucidar a questão. Feiura é uma questão de ponto de vista.
Comment: Ivan não querendo ser ofensivo ... você já leu algo sobre KISS ? não estou dizendo que sua maneira esta errada, porém por que utilizar 5 linha se podemos fazer em 1 ? é questão de lógica.
Comment: Galera, independente da maneira utilizada para responder a questão, vale ressaltar a vontade de vocês de ajudar, e fico feliz em saber que para caso há N soluções possíveis. Sou iniciante em PHP e tenho aprendido bastante aqui no stackoverflow.
De qualquer forma, obrigado!

Adicionar virgula a cada palavra


AngularJS select required

Question: I'm having some issues with setting up the validation for a select. the code reads like
HTML
<form name="customerForm" novalidate="novalidate" data-ng-submit="submit()">

        {{ 'CountryRequired' | translate }}

    {{ 'Country' | translate }}
    <select id="ddlCountries" name="country" class="form-control"
        data-ng-model="selectedCountry"
        data-ng-options="option.text for option in countries track by option.id"
        data-ng-change="countryChange()" required="required">
        <option value="" selected="selected">{{ 'SelectCountry' | translate }}</option>
    </select>
</form>

JS Controller
$scope.countries = [];
countryService.getCountries().then(function (results) {
    $scope.countries = results.data;
}, function (error) {
    console.log(error.data.message);
});

$scope.$watch('customer.country', function (id) {
    // Select the value on the dropdown list
    $scope.selectedCountry = { id: id };
});

$scope.countryChange = function () {
    $scope.customer.country = $scope.selectedCountry.id;
};

$scope.submit = function () {
    if ($scope.customerForm.$valid) {
        customerService.postCustomerForm($scope.customer).success(
            function (data, status, headers, config) {
                /*success callback*/
            }).error(function (data, status, headers, config) {
                alert("Submitting form failed!");
        });
    } else {
        console.log("Invalid fields");
    }
};

I've tried different things like setting selected="selected" on the select but didn't work. Also tried required and ng-required without luck.
Am I missing something or doing it wrong?
Answer: The problem is that you reset select model so original one you defined is replaced with a new one. Look at this piece of code:
$scope.$watch('customer.country', function(id) {
    $scope.selectedCountry = {id: id};
});

In this code you overwrite $scope.selectedCountry with totally new object, so the model which has been used for setting up form validation is destroyed and new validation is never build.
In your case you can update selectedCountry model like this:
$scope.$watch('customer.country', function(id) {
    if (id) {
        $scope.selectedCountry.id = id;
    }
});

But better, remove wather all together, you don't need it since you have ngChange directive, where you can update selectedCountry.id.
Demo: http://plnkr.co/edit/CXDRdRYxZn38FnanOqid?p=preview
Comment: How would you do then the selected value? If I use the the value from `customer.country` after I select a value the int changes to an object there may be a better way than the $watch and the change function
Comment: If you need watch then use it, just don't reassign entire model object.

AngularJS select required


How to use Rules to send separate email to every user referenced in user reference field?

Question: I have a node with a user reference field, in which a user can select unlimited users who they have a relationship with. I'd like for the saving of this node to trigger a separate email to be sent (via Rules) to each user chosen in that reference field, or a single email with all of those users BCC'ed. Currently, the "send mail" action with "node:field-friends-you-wish-to-invite:0:mail" selected in the "To" field of the Rule only sends an email to the first user selected in the list, no matter how many other users have been selected.
How can this be accomplished?
Answer: You should create a rule that looks like so (in Rules export format):
{ "rules_send_email_to_selected_email_ids" : {
    "LABEL" : "Send eMail to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to [current-email-id:value]." } },
            { "mail" : {
                "to" : "[current-email-id:value]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Some more details about the above rule:

Rules Event: After saving new content of type "Article" (adapt the type to fit your needs, ie to XYZ).
Rules Action: a "loop" for all selected values of a multi value select list (which contains the eMail IDs), with machine name field_email_addresses (adapt the machine name to fit your needs). For each item (= current_email_id), an eMail is created with some subject and message that also contains the title and url of the node being created. Note: this will send 1 separated eMail to each of the selected eMail IDs (there is no way to send a single eMail to all selected eMail IDs).

If you have the Rules UI enabled, you can import the above rule in your own site, after you adapt the machine names of the content type and the field name containing the list of eMail Ids.
After you're convinced the rule works as expected, you may want to remove the Rules Action that displays a message after the node is saved (with drupal_message).
Video tutorial: have a look at the List and loops video which show a similar scenario.
Update
If you don't have such field with eMail IDs, but a field which is an entity reference field to user ids, then you can use a minor variation of the above rule. Instead of field_email_addresses, you'd want to loop over the list of users (indicated via the user reference field, let's assume it's named field_user_ids). And for each "item" (which I'd name "current_userid"), in the "to" field you'd use the current-userid:mail token for the user being processed. Here is how such rule could look like (in Rules export format):
{ "rules_send_email_to_selected_user_ids" : {
    "LABEL" : "Send eMail to selected user IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" }
    },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-user-ids" ] },
          "ITEM" : { "current_userid" : "Current user ID" },
          "DO" : [
            { "drupal_message" : { "message" : "An eMail about this new content with title \u0022[node:title]\u0022 and URL [node:url] will be delivered to eMail ID [current-userid:mail]." } },
            { "mail" : {
                "to" : "[current-userid:mail]",
                "subject" : "You have new mail ...",
                "message" : "New content was created with title [node:title] ... You can read about it at [node:url].",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

Comment: @hockey2112 : OK, I see your point ... Check my expanded answer (the update part of it, near the end).
Comment: Thanks for this, but it's not exactly what I described. My users do not know the email addresses of their "friends". That's why I need the rule to interpret the users referenced in the Entity Reference field and then send the emails to those users' account email addresses automatically. In other words, the person creating the content would select "User A" and "User B" from the reference field, and the rule would then send an email to "email@example.com" and "email@example.com".


Is all linear equation with real solution solvable using 3x3 matrix? If not why?

Question: I believe that all 2 variable with enough information could be solved using the matrix
If given:
2x+5y = 11
3x+7y = 20
we could solve this by doing the following:
[[2, 5], [3, 7]] [x, y] =[11,20]
and we can move the like term to one side and got
[x, y] =[11, 20][[2, 5], [3, 7]]-1
and after some calculation we arrived at
[x, y] = [23, -7]
however I am not so sure about 3 variable equations because my friend claims this equation have a solution and yet the determinant is 0 and thus is not solvable using matrix
they are:
3x+5y+7z=9491    -eq1
5x+7y+9z=12233    -eq2
7x+9y+11z=14975    -eq3
where:
x=13,
y=27,
z=1331
is there something that I am missing or is it like what my friend is saying that the matrix has a limitation when solving linear equation?
Comment: How would you solve $2x+4y= 9,$ and $4x + 8y= 18$?  (the second is an integer multiple of the first, hence Infinite solutions.)  How would you solve $2x + 3y =10,$ and $4x +6y =10$  (equivalent to $2x+3y= 5$)?  There are no solutions, because the equations are inconsistent..  So a system of equations is not necessarily going to give a unique solution for each variable.
Comment: @amWhy I see what trick my friend had play on me now. when eq3-eq2 it will produce the same coefficient of eq2-eq1 and thus infinite amount of solution and thus his solution is just one pair of valid solutions.
Comment: Determinant is not zero for the given $3×3$ system.
Comment: @amWhy maybe you wanted to address your message to another user? I muscalculated the determinant (it is really zero), but I didn´t claim the rest of what you´re pointing out :)
Answer: Every system of linear equations can be expressed as a matrix equation. In general, the following two are equivalent:
$$\left. \begin{eqnarray}
a_{11} x_1 + a_{12} x_2 + \ldots + a_{1n} x_n & = & b_1 \\
a_{21} x_1 + a_{22} x_2 + \ldots + a_{2n} x_n & = & b_2 \\
& \cdots \\
a_{m1} x_1 + a_{m2} x_2 + \ldots + a_{mn} x_n & = & b_m
\end{eqnarray} \right\} \iff
\begin{bmatrix}
a_{11} & a_{12} & \ldots & a_{1n} \\
a_{21} & a_{22} & \ldots & a_{2n} \\
&& \ddots \\
a_{m1} & a_{m2} & \ldots & a_{mn}
\end{bmatrix}
\begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix} = \begin{bmatrix} b_1 \\ b_2 \\ \vdots \\ b_m \end{bmatrix}$$
We would often write the right-hand side as $A \mathbf{x} = \mathbf{b}$, where $A$ is the matrix with all the coefficients, $\mathbf{x}$ is the vector of unknowns and $\mathbf{b}$ is the vector of values on the right-hand side of the equality.
Also, one of the following statements will be true for any such system:

There is a unique solution for $\mathbf{x}$ in terms of the $A$ and $\mathbf{b}$;
There is no valid solution; or
There are an infinite number of valid solutions.

To figure out which one of these is the case, you need to know whether you have exactly enough information to "undo" the matrix multiplication or not. If $m = n$, i.e. you have an equal number of equations and unknowns, then the following statements are equivalent:

The system has a unique solution;
The matrix $A$ is invertible;
The determinant of $A$ is non-zero;
The rows of $A$ are linearly independent, meaning that none of the rows $a_{i \cdot}$ can be written in terms of the other rows as $c_1 a_{1 \cdot} + c_2 a_{2 \cdot} + \ldots + c_m a_{m \cdot}$.

In other words - if you have 3 equations in 3 unknowns, and if you can't combine two of the equations to get something that has the same coefficients as the third one, then there is definitely exactly one solution to all the equations, and if you know how to invert a 3x3 matrix then you can find it by writing $\mathbf{x} = A^{-1} \mathbf{b}$.
However, if $A$ is not invertible (either because its determinant is zero or because it's not even square), then you can't directly tell whether you're in case 2 (no solutions) or 3 (infinite solutions) without some extra work which basically boils down to:

Remove all redundancy from the system;
Do you have any contradictory information left? If yes, then there are no solutions, if no, there are infinitely many solutions.

For example, if you have $x + 2y = 4$ and $3x + 6y = 12$, then we can take $\mbox{Eqn 2} \rightarrow (\mbox{Eqn 2} - 3 \times \mbox{Eqn 1})$ which leaves $0 = 0$ (meaning that the second equation was redundant to the first), and we're left with a single equation in two variables with infinitely many solutions, including $(2, 1)$, $(4, 0)$, $(5, -\frac{1}{2})$ and so on.
On the other hand, if we have $x + 2y = 4$ and $3x + 6y = 13$, then doing $\mbox{Eqn 2} \rightarrow (\mbox{Eqn 2} - 3 \times \mbox{Eqn 1})$ leaves us with $0 = 1$, a clear contradiction, so our system has no solutions.
Notice that in both cases $\det \begin{bmatrix} 1 & 2 \\ 3 & 6 \end{bmatrix} = 1 \times 6 - 2 \times 3 = 0$, which is why we're in this situation in the first place.
There are ways to do these operations using matrices, including something called Gaussian elimination, but I won't go into the details here.
Comment: This does not address "method" but Wolfram Alpha offer solutions
[here](https://www.wolframalpha.com/input?i=solve+3x%2B5y%2B7z%3D9491%2C++++5x%2B7y%2B9z%3D12233%2C++7x%2B9y%2B11z%3D14975+over+integers).
Comment: $c_1, c_2, \ldots$ are *any* possible values. So I mean that no matter how you try to write, for example, row 1 as a combination of the other rows of the matrix, you will fail. Same for row 2, row 3, and so on. On the other hand, if you can find that (for example) three times row 1 plus seven times row 2 gives you row 3, then those rows are linearly *dependent*.
Comment: This answer is very insightful! thank you so much not only did you only answer my problem which is can i solve a system of equation of 3 variable using matrix but also explain how there is 4 condition that is connected/equivalent to  to each other. However I don't understand this point "The rows of A are linearly independent, meaning that none of the rows ai⋅ can be written in terms of the other rows as c1a1⋅+c2a2⋅+…+cmam⋅." What is c1, c2 c3... Do you mean b1,b2,b3....?


Limit of t-score as r->0 (for Pearson's correlation)

Question: I have a very basic question. The t-score used in the significance test for the Pearson's correlation is given by:
$$
t = r \frac{\sqrt{(n-2)}}{\sqrt{(1-r^2)}},
$$
where $n$ is the sample size and $r$ is the correlation.
Does this mean it is impossible to detect a statistically significant zero correlation ($r=0$) as in that case $t \rightarrow 0$? Or am I misinterpreting the above equation?
Comment: On the contrary, I think it would be great if you posted a self-answer explaining what you've learned.
Comment: Welcome to Cross Validated! What do you mean by a "statistically significant correlation ($r=0$)?
Comment: Then what's the issue?
Comment: I meant to say that if we decide on some threshold (p=0.05) for the significant test, we would compute the t-score and find the corresponding p-value to see if it exceeds 0.05 or not. As $t$ becomes larger, the likelihood of passing the test increases. As $t \rightarrow 0$, the likelihood of passing the text should also decrease (am thinking in terms of the area under the curve). Does this make more sense?
Comment: 1) As $t$ approaches zero, why shouldn't the likelihood of passing the test decrease? // 2) Why do you think that large a $t$ means a high p-value?
Comment: I guess I am agreeing with you. As $t \rightarrow 0$, I think the likelihood of passing the text should decrease (analogous to small z-score values). And conversely, a large $t$ means it is likelier the null is rejected, again similar to how we would interpret a large z-score.
Comment: My confusion is arising for the case $r=0$. In that case, $t=0$. Is $t=0$ not going to fail the significance test regardless of what significance level we choose? For any chosen significance level $\alpha$, we want $t > t_{crit}$ for the test to pass, where $t_{crit}$ is the critical value corresponding to $\alpha$. But $t > t_{crit}$ is never going to be satisfied if $t=0$.
Comment: @fivethirds assuming your null hypothesis is $r=0$ (there is no correlation) and your alternate hypothesis is $r \neq 0$ for the significance test, is there any reason you want to "pass" the significance test (more specifically, reject the null hypothesis) when the test statistic suggest $r$ is effectively zero? Not "passing" the test simply means there is no evidence for us to believe otherwise than what we already assumed ($r=0$).
Comment: If $t=0$. either we observed the $r=0$ proposed by the null hypothesis, or we have a sample size of $2$, but then we're always going to get an empirical correlation of $r=1$ or an undefined $r$.
Comment: Dave and B. Liu: Thanks for your responses. I see that I was confusing myself unnecessarily. Normally we are looking for an "effect" (e.g., drug effects) that would be confirmed by rejecting the null. In my application, it so happens that the theory makes a prediction of zero correlation, which happens to be the null result. So if I am unable to reject the null (because $t=0$) that is indeed confirming the theory. I now realize all this sounds self-evident! Please feel free to delete this entire thread as it is not adding much to the discourse :)
Comment: The question seems to me to potentially be conflating $\rho\to 0$ with $r\to 0$. A small $|t|$-value doesn't have a low probability to reject, it's absolutely guaranteed not to reject. Low probability occurs when $\rho$ is small (because $|t|$ might still sometimes be large enough to be in the rejection region).
Answer: I sorted out my confusion. As I indicated in the comment thread, the source of my confusion was that in my particular application a physical theory makes a prediction that the two variables I was analyzing have a zero correlation. This happens to be the null result. I was finding that for very low $r$, the p-value was not small enough to reject the null. But that just means the calculated $r$ is too small to be indistinguishable from zero (for the chosen confidence level), which in effect means the data is not inconsistent with the prediction by the theory.
Comment: Your last sentence contains a common mistake. A high p-value does not confirm the null hypothesis. It means that the data you have collected are not inconsistent with the null hypothesis. This does not preclude the data being *more* consistent with a different value, however. (In many cases (the technical term is *maximum likelihood estimation*), there is an argument that the most likely value is the estimated value, not the value under the unrejected null hypothesis.)
Comment: Thanks for your response! I will modify my answer accordingly.
Comment: "that the most likely value is the estimated value, not the value under the unrejected null hypothesis".

Does this point become less of an issue if the estimated value is not too different from the value under the unrejected null hypothesis? That is what is happening in my case. The values of $r$ for which I am unable to reject the null hypothesis ($r=0$) are pretty small to begin with ($r \sim 0.05$).
Comment: What is your tolerance for "close enough to zero" or "basically zero"? // You might be interested in equivalence testing.
Comment: "What is your tolerance for "close enough to zero" or "basically zero"?" I was trying to ground this in the significance test itself. Inability to reject the null means my estimated value of $r$ (say, 0.05) is "basically zero." It it weren't, then I would have been able to reject the null. At least, that was my thinking. [Edit: I will also look up equivalence testing. Thanks.]


How to create programmatically menu links with just created nodes during installation profile in aegir ?can't get nid!

Question: I am creating a set of nodes in an installation profile.  When I try to create menu links for them in the same PROFILE_NAME.install, the links don't get created.
I have also tried creating the menus links in a separate module, and using hook_update_N() to enable them, but that also does not work.
When I uninstall the module and reactivate it, it creates correctly my menu's links correctly.
I tried to use hook_install_tasks() and put it in MYPROFILE_NAME.profile or MYPROFILE_NAME.install, but this also doesn't work.
How can I create menu links for nodes created as part of an installation profile?
My code for creating the nodes in MY_PROFILE_NAME.install is:
// creation of my nodes (same content for all)
   $nodi = array(
       // i have other 14 nodes
      'title' => array('Home'),
       // i have other 14 paths for the nodes
      'path' => array('home'),
   );
$titoli = array();
$titoli = $nodi['title'];
$percorsi = array();
$percorsi = $nodi['path'];
//CREAZIONI DEL CONTENUTO PROGRAMMATICAMENTE
  for($i = 0; $i< count($titoli); $i++){
$testo_body = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec feugiat velit eget metus placerat,varius eros facilisis. Aenean aliquam imperdiet nisl ut dapibus...';
           $node = new stdClass(); // nuovo oggetto nodo
           $lingua = 'it';
           $node->type = "page"; //
           $node->title = $titoli[$i];
           $node->language = $lingua;
           $node->path = array('alias' => $percorsi[$i]); // i think here is the problem !!!
           $node->uid = 1; // admin
           $node->status = 1;
           // Body field
           $body_field_info = field_info_field('body');
           if (field_is_translatable('node', $body_field_info)) {
              $body_lingua = field_valid_language($lingua);
           }else{
              $body_lingua = LANGUAGE_NONE;
           }
           $node->body[$body_lingua][0]['value'] = $testo_body;
           $node->body[$body_lingua][0]['summary'] = 'text...';
           $node->body[$body_lingua][0]['format'] = 'full_html';
           $node = node_submit($node); // Prepare node for a submit
           node_save($node); // After this call we'll get a nid

And my code for creating the menu links is:

    // Create a Home link in the main menu.
  $path = drupal_lookup_path('source', 'home');
  $item = array(
    'link_path' => $path,
    'router_path' => $path,
    'link_title' => st('Home'),
    'menu_name' => 'main-menu',
    'weight' => -50,
    'customized' => 1,
    'plid' => 0, // Parent menu item, 0 if menu item is on top level
  );
  menu_link_save($item);
  menu_rebuild();

Update 2
The menus are created in the menu_links table but with empty link_path so i can't get the nid created nodes.
I treid also to override the install_finished() and put my function for creating menus in .install or in .profile files, but it's the same.
Any ideas?
Answer: You can add a menu item using this
$item = array(
        'menu_name' => 'menu-name',
        'link_title' => 'Link title',
        'link_path' => 'node/'. $nid,
      );
menu_link_save($item);
//don't forget to clear menu cache after saving menu item
menu_cache_clear_all();

Hope this will help
Updated Answer
As I looked into Drupal 7 standard profile installation file, that is standard.install (Line no 413), you can see "Home" link creation there.
// Create a Home link in the main menu.
  $item = array(
    'link_title' => st('Home'),
    'link_path' => '<front>',
    'menu_name' => 'main-menu',
  );
  menu_link_save($item);

  // Update the menu router information.
  menu_rebuild();

Comment: @Ossama, please see my updated answer.
Comment: @Ossama, if it helps you, please upvote and mark it as correct, Thanks.
Comment: Thank you for your answer, but i already used the menu_link_save() and it works nice, my problem is that it doesn't work in MY_PROFILE_NAME.install and else separately in a module if called from the profile .install, it works only when i activate the module after the installation process.
Comment: Make sure your node is created before saving link.
Comment: the problem was 'customize' => 1, that i did not type first, now how can i know if my nodes are already created before creating the menus?shall i make a query on the db table?
Comment: @ossama, How are you creating the node now?
Comment: look at my update.
Answer: $nodi = array(
        'title' => array(
                 'Home' ,
                 'Presentazione' ,
                         'Obiettivi' ,
                         'Comitato organizzatore' ,
                         'Patrocini' ,
                         'Edizioni passate' ,
                        // 'Calendario eventi' ,
                 'Materiali' ,
                         'Cartelle stampa' ,
                         'Documentazione' ,
                         'Video' ,
                 'Dove siamo' ,
                 'Contatti',
        ),
        'path' => array(
                 'home' ,
                 'presentazione' ,
                         'obiettivi' ,
                         'comitato-organizzatore' ,
                         'patrocini' ,
                         'edizioni-passate' ,
                  //'calendar-node-field-date/month' ,
                 'materiali' ,
                         'cartelle-stampa' ,
                         'documentazione' ,
                         'video' ,
                 'dove-siamo' ,
                 'contatti',
        ),
    );
    $titoli = array();
    $titoli = $nodi['title'];
    $percorsi = array();
    $percorsi = $nodi['path'];
    $miei_path = array();
    $alias = array();

    //CREAZIONI DEL CONTENUTO PROGRAMMATICAMENTE
      for($i = 0; $i< count($titoli); $i++){
        //SE È IL CALENDARIO O GALLERIA DELLE IMMAGINI NON CREARE LE PAGINE PERCHÉ CI SONO GIÀ

               $testo_body = 'Lorem ipsum dolor ..';
               $node = new stdClass(); // nuovo oggetto nodo
               $lingua = 'it';
               $node->type = "page";

               node_object_prepare($node); // Set some default values.

               $node->title = $titoli[$i];
               $node->language = $lingua; //non settato LANGUAGE_NONE
               $node->path['pathauto'] = 0;
               $node->uid = 1; // admin
               $node->status = 1;
               $node->comment = 0;
               $node->promote = 0;
               $node->moderate = 0;
               $node->sticky = 0;
               // Body field
               $body_field_info = field_info_field('body');
               if (field_is_translatable('node', $body_field_info)) {
                  $body_lingua = field_valid_language($lingua);
               }else{
                  $body_lingua = LANGUAGE_NONE;
               }
               $node->body[$body_lingua][0]['value'] = $testo_body;
               $node->body[$body_lingua][0]['summary'] = 'Questo è un testo esempio.';
               $node->body[$body_lingua][0]['format'] = 'full_html';
              $node = node_submit($node); // Prepare node for a submit

               $node->path = array('alias' => ('content/'.$percorsi[$i]));         // Setting a node path
              node_save($node); // After this call we'll get a nid

              $mio_path = $node->nid;
              $miei_path[$i] = $mio_path;
              $mio_alias[$i] = $node->path['alias'];
              watchdog(WATCHDOG_INFO, "E' stato creato il nodo " . $titoli[$i] . " correttamente, con alias  ".$percorsi[$i] ."---- " . $mio_alias[$i]. "   ".var_dump($node->path), $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL);
              $fornt = "node/".$miei_path[0];
              variable_set('site_frontpage', $fornt);
        }

Comment: i simply add an array $miei_path to save inside it all my node->nid to be used as value for link_path.


Cantor's Intersection Theorem with closed sets

Question: Cantor's Intersection Theorem states that "if $\{C_k\}$ is a sequence of non-empty, closed and bounded sets satisfying $C_1 \supset C_2 \supset C_3 \dots$, then $\bigcap_{n \ge 1} C_n$ is nonempty.
If the term "compact sets" is replaced by "closed sets", the statement is not true. It makes sense to me, but couldn't find such a counterexample for it.
Comment: If a counterexample exists, it'll have to make use of the difference between "closed" and "compact." This difference is boundedness.
Comment: You can create an ellipsis in MathJax by using `\dots`.
Comment: yah I noticed that the integer set is closed but unbounded, but not sure it is a valid example..@T.Bongers
Answer: Consider the sequence $C_n = [n, \infty)$.
Comment: There is no real number which belongs to $C_n$ for every $n$, so the intersection is empty.
Comment: why the intersection of these sets is empty? Is it because we can't find such a number in every set?


Why isn't the gamma function defined so that $\Gamma(n) = n! $?

Question: As a physics student, I have occasionally run across the gamma function
$$\Gamma(n) \equiv \int_0^{\infty}t^{n-1}e^{-t} \textrm{d}t = (n-1)!$$
when we want to generalize the concept of a factorial.  Why not define the gamma function so that
$$\Gamma(n) = n!$$
instead?
I realize either definition is equally good, but if someone were going to ask me to choose one, I would choose the second option.  Are there some areas of mathematics where the accepted definition looks more natural?  Are there some formulas that work out more cleanly with the accepted definition?
Comment: http://mathoverflow.net/questions/20960/why-is-the-gamma-function-shifted-from-the-factorial-by-1
Comment: The accepted answer on that MO question doesn't really reflect community consensus; I am much more willing to support Emerton's comment.
Comment: With the $\Pi$ function, there is something gratifying about writing the volume of an $n$ ellipsoid with radii $r_1, \ldots, r_n$ as $$\frac{\pi^{n/2}}{\Pi(n/2)}\prod_{k=1}^n r_k$$ Look at all that pi!
Comment: @Nate Thanks for the link.  I checked Wikipedia and the archives on this site, but didn't look at MathOverflow.
Comment: This thread is ancient.  But I've added a new answer.  See below.
Answer: I find it more illuminating to see what that extra $ t^{-1} $ does to the integral.  As a generalization of the factorial, $ \Gamma $ is inherently multiplicative*.  On the other hand, integration, which is essentially a sum, is inherently additive.  Thinking about it this way it seems a bit odd that an integral could give an appropriate generalization.  However, there is a simple function that takes the (positive) multiplicative reals to the reals under addition: the logarithm.  Thinking of gamma as $$ \Gamma(s) = \int_0^{\infty} t^s e^{-t} \frac{dt}{t} $$
we see that the natural log arises naturally (what's the first thing to come to mind when you see $ \frac{dt}{t} \: $?) in this context (and there are no pesky $s-1$'s left).
I haven't done much with integration theory (so I'm not sure my terminology is correct), but I believe this intuitive argument may be made rigorous by considering the integral formula for $ \Gamma(s) \: $ as an integral over the positive reals under multiplication (i.e. the interval $ (0,+\infty) $ ) with respect to the multiplicative Haar measure.
*note that by "multiplicative" I just mean that it's realized as a product, not that it's a multiplicative arithmetic function or anything like that
Comment: Concerning the last paragraph. Yes, that's precisely right. The measure $\frac{dt}{t}$ is the Haar measure on the multiplicative reals: by the substitution rule we have $\frac{d(at)}{at} = \frac{dt}{t}$ so that the measure is invariant under multiplication. Note that this is precisely Emerton's point in the MO-link in one of the comments above.
Answer: $$
\Gamma(\alpha) = \int_0^\infty x^{\alpha-1} e^{-x}\,dx.
$$
Why $\alpha-1$ instead of $\alpha$?  Here's one answer; there are probably others.  Consider the probability density function
$$
f_\alpha(x)=\begin{cases} \dfrac{x^{\alpha-1} e^{-x}}{\Gamma(\alpha)} & \text{for }x>0 \\[12pt] 0 & \text{for }x<0 \end{cases}
$$
The use of $\alpha-1$ instead of $\alpha$ makes the family $\{f_\alpha : \alpha > 0\}$ a "convolution semigroup":
$$
f_\alpha * f_\beta = f_{\alpha+\beta}
$$
where the asterisk represents convolution.
Comment: (I know this is old) Couldn't you just write the probability function as (using the "pi" function) this? $$\frac{x^{\alpha}e^{-x}}{\Pi(\alpha)}$$
Comment: @NotNotLogical : If you write it that way, then you don't have a convolution semigroup.
Comment: Your PDF is undefined at $0$. I think you wanted one of the cases to be $\ge$ or $\le$ so that $f_\alpha(0)=0$?
Comment: @SimplyBeautifulArt : PDFs are not defined pointwise. What is of interest about them is what you get when you integrated them over a set. So defining it at an isolated point just isn't a thing.
Answer: A completely simple explanation is provided in the first section here.
EDIT: Consider a general gamma density function. That is, a function $f(x;c,\lambda)$, $x>0$, of the form $f(x;c,\lambda) = \lambda^c x^{c-1}e^{-\lambda x} / \Gamma(c)$, where $c$ and $\lambda$ are arbitrary positive constants. The counterpart with respect to the alternative definition, $\tilde \Gamma (p) := \int_0^\infty  {t^p e^{ - t} \,{\rm d}t}$, is a function $f(x;c,\lambda)$, $x>0$, of the form $f(x;c,\lambda) = \lambda^{c+1} x^{c}e^{-\lambda x} / \tilde \Gamma(c)$, where $c > -1$ and $\lambda > 0$. Obviously, the former form is preferable.


How to conditionally render fields with a different formatter

Question: I have a content type with two fields one called display which is a simple list and the other is an entityreference field.
I would like to change how the entity reference field is rendered depending on which option is selected in the first field.
I have custom formatters installed and I have created two custom formatters so I need a way of changing the #formatter based on the result in the first field.
I've tried a hook_preprocess_node() and also changing it in a custom tpl file but neither seem to render the field any differently to how it is set in the manage field UI.
Answer: I would try using the Context module API and adding a new reaction plugin.
Comment: Yeah I think the overhead of context is a little overkill
Answer: In the end I did this in the tpl file for my content type using field_view_field(), I hide both fields the one that contains the option and the second that contains the data. I then use a case statement to set the correct formatter.
<code>  hide($content['field_display_mode']);
  hide($content['field_link']);
  print render($content);
  $links_display_mode = $content['field_display_mode']['#items']['0']['value'];
  switch($links_display_mode) {
    case 1:
      $links_formatter = 'custom_formatters_entry_form_display_one';
      break;
    case 2:
      $links_formatter = 'custom_formatters_entry_form_display_two';
  }
  $field_link = field_view_field('node', $node, 'field_link', array('label' => 'hidden', 'type' => $links_formatter));
  print render($field_link);
</code>


Default method in interface in Java 8 and Bean Info Introspector

Question: I have a little problem with default methods in Interface and BeanInfo Introspector.
In this example, there is interface: Interface
public static interface Interface {
    default public String getLetter() {
        return "A";
    }
}

and two classes ClassA and ClassB:
public static class ClassA implements Interface {
}

public static class ClassB implements Interface {
    public String getLetter() {
        return "B";
    }
}

In main method app prints PropertyDescriptors from BeanInfo:
public static String formatData(PropertyDescriptor[] pds) {
    return Arrays.asList(pds).stream()
            .map((pd) -> pd.getName()).collect(Collectors.joining(", "));

}

public static void main(String[] args) {

    try {
        System.out.println(
                formatData(Introspector.getBeanInfo(ClassA.class)
                        .getPropertyDescriptors()));
        System.out.println(
                formatData(Introspector.getBeanInfo(ClassB.class)
                        .getPropertyDescriptors()));
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }

}

And the result is:
class
class, letter

Why default method "letter" is not visible as property in ClassA? Is it bug or feature?
Comment: I deleted my answer as it was a brain-fart. My 2 cents is it's a bug. If ClassC extends ClassB and provides no code, it shows `class, letter`. So it's not a case of only reporting about the immediate class.
Answer: I guess, Introspector does not process interface hierarchy chains, even though with Java 8 virtual extention methods (aka defenders, default methods) interfaces can have something that kinda sorta looks like property methods. Here's a rather simplistic introspector that claims it does: BeanIntrospector
Whether this can be considered a bug is somewhat of a gray area, here's why I think so.
Obviously, now a class can "inherit" from an interface a method that has all the qualities of what's oficially considered a getter/setter/mutator. But at the same time, this whole thing is against interface's purpose -- an interface can not possibly provide anything that can be considered a property, since it's stateless and behaviorless, it's only meant to describe behavior. Even defender methods are basically static unless they access real properties of a concrete implementation.
On the other hand, if we assume defenders are officially inherited (as opposed to providing default implementation which is a rather ambiguous definition), they should result in synthetic methods being created in the implementing class, and those belong to the class and are traversed as part of PropertyDescriptor lookup. Obviously this is not the way it is though, otherwise the whole thing would be working. :) It seems that defender methods are getting some kind of special treatment here.
Answer: Debugging reveals that this method is filtered out at Introspector#getPublicDeclaredMethods():
if (!method.getDeclaringClass().equals(clz)) {
    result[i] = null; // ignore methods declared elsewhere
}

where clz is a fully-qualified name of the class in question.
Since ClassB has custom implementation of this method, it passes the check successfully while ClassA doesn't.
Comment: @SotiriosDelimanolis Yes, it gets filtered out as well. But then in scope of `processPropertyDescriptors()` method which is almost 200 lines long it is added back :)
Comment: What about inherited methods? Wouldn't those get filtered out as well?
Answer: I think also that it is a bug.
You can solve this using a dedicated BeanInfo for your class, and by providing somthing like that :
/* (non-Javadoc)
 * @see java.beans.SimpleBeanInfo#getAdditionalBeanInfo()
 */
@Override
public BeanInfo[] getAdditionalBeanInfo()
{
    Class<?> superclass = Interface.class;
    BeanInfo info = null;

    try
    {
        info = Introspector.getBeanInfo(superclass);
    }
    catch (IntrospectionException e)
    {
        //nothing to do
    }

    if (info != null)
        return new BeanInfo[] { info };

    return null;
}

Answer: We noticed the same problem, particularly with Java EL and JPA. This is likely to affect multiple frameworks that use Introspector to discover properties that follow the JavaBean convention.
There is an official Bug opened. I thought I would add this for reference since it is creating problems for multiple frameworks.

https://bugs.openjdk.org/browse/JDK-8071693
https://github.com/openjdk/jdk/pull/13544

The official Fix version is 21. I asked if it could possibly be backported to 17.
EDIT
More Info for EL specific issues: https://github.com/jakartaee/expression-language/issues/43
There may be at least a partial fix in Jakarta EE 10.
However, there is a fully working workaround for EE < 10 and JDK < 21. You can simply make a BeanInfo class that describes the properties inherited from the interface. Here, MyClass is inheriting aProperty getter/setters from an interface. To expose these to the JDK Introspector, simply create a BeanInfo class:
public class MyClassBeanInfo extends SimpleBeanInfo {

    @Override
    public BeanInfo[] getAdditionalBeanInfo() {
        return new BeanInfo[] { new SimpleBeanInfo() {
            @Override
            public PropertyDescriptor[] getPropertyDescriptors() {
                try {
                    return new PropertyDescriptor[] { new PropertyDescriptor("aProperty", MyClass.class, "getAProperty", "setAProperty") };
                } catch (final IntrospectionException e) {
                    throw new RuntimeException(e);
                }
            }
        } };
    }
}

Reference: https://docs.oracle.com/javase/8/docs/api/java/beans/BeanInfo.html
Answer: This is because you only have your method on Interface and ClassB, not on ClassA directly. However it sounds to me like a bug since I'd expect that property to showup on the list. I suspect Inrospector did not catch up with Java 8 features yet.


Angular 7 getting value of selected date from Kendo UI date picker

Question: My App Component.html has a basic navigation and a date picker, like so...

            <kendo-datepicker
                (valueChange)="onChange($event)"
                [(value)]="value">
            </kendo-datepicker>

<router-outlet></router-outlet>

The component.ts is set up in the following way:
import { Component, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-root',
  encapsulation: ViewEncapsulation.None,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  @Input() value: Date = new Date();
  @Output() dateChanged: EventEmitter<Date> = new EventEmitter<Date>();

  constructor() {}

  public onChange(value: Date): void {
    this.dateChanged.emit(value);
  }
}

I've got some pages that have a grid control calling a service, but the date is currently hard-coded, and this all works fine.  I want the ability to refresh the grid data based on the selected date from the above date picker, essentially, I will click on the datapicker, the emitted value will be passed to a method in the component with the grid controller.
Controller with Grid:
import { Component, OnInit, Input } from '@angular/core';
import { GridDataResult, DataStateChangeEvent } from '@progress/kendo-angular-grid';
import { DataSourceRequestState } from '@progress/kendo-data-query';
import { DataService } from '../services/DataService.service';

import { Observable } from 'rxjs/Observable';
import { State } from '@progress/kendo-data-query';

@Component({
  templateUrl: './grid.component.html',
  styleUrls: ['./grid.component.css']
})
export class GridComponent implements OnInit {

  public products: GridDataResult;
  public state: DataSourceRequestState = {
      skip: 0,
      take: 25
  };
  @Input() value: Date = new Date();

  constructor(private dataService: DataService) { }

  ngOnInit() {
     this.dataService.fetch(this.state).subscribe(r => this.products = r);
  }

  public dataStateChange(state: DataStateChangeEvent): void {
    this.state = state;
    this.dataService.fetch(state)
        .subscribe(r => this.products = r);
}

}

Comment: @christiandev, so I started looking at your issue a little more in detail, and I realized that OnChanges WILL not work for you. You are trying to go across a `router-outlet` and parent/child communication does not work across `router-outlet`. So you will have to create a service like CeritT recommended. He does a good job explaining this, but if you have any questions, feel free to reach out. I use Angular/Kendo everyday for my work.
Comment: Where is your grid controller? Is it a service, or another component? Currnetly you are outputting `dateChanged` from `AppComponent` which seems to be your main component, where do you listen this emitted event?
Comment: @CeritT, I have added the controller with the Grid
Comment: Why don't you use the OnChanges Lifecycle hook to listen for an incoming date on your grid component. The question you asked is 'How to Get the Value out of Kendo UI DatePicker' but I think your real problem is listening for an input change to make a new dataService call.
Comment: @CMR, this sounds correct - are you suggesting the same approach as CeritT suggested below?
Comment: @christiandev , No CeritT is suggesting to create a service and expose the Kendo Data Change as an observable that you can subscribe to in your grid component. This would 100% work, but it looks to me you already have the Date Input on your grid class, so what you really need is a way to detect when that input changes so you can refresh the grid, which is why I recommended the OnChanges lifecycle hook. I could give you a more formal answer if you wish.
Comment: @CMR, that would be great - I kind of understand how that works in a parent-child relationship, but I can't seem to apply it here.  Any help would be great.
Answer: You can use Subject to listen changes on your date input.
First create a date service.
@Injectable()
export class DateService {

  public chosenDate: Observable<Date>;
  private dateSubject: Subject<Date>;

  constructor() {
    this.dateSubject = new Subject<Date>();
    this.chosenDate = this.dateSubject.asObservable();
  }

  dateChanged(newDate:Date){
    this.dateSubject.next(newDate);
  }

}

Then in your Grid Controller, inject this service and subscribe to chosen date from service where you need in your component.

constructor(private service: DateService){

this.service.chosenDate.subscribe((date: Date) => {
    // do something useful with date
});

and finally on your date field change event, put this code to pass new date to the service
this.service.dateChanged(date);

Edit: Here I made an example for you, demonstrating the solution. I'm sure you can easilty implement this in your code.
DEMO
Comment: Thanks - I will try this today.
Comment: Hi @christiandev, i couldn't have time to check SO lately, how things worked out for you? Did you give it a try?
Comment: Yes, I have just got it working - many thanks.  I'm just looking a the best way to set a default value for the date until a date is selected now.
Comment: You can initialize `date` property, `date:Date = new Date();` in your grid controller. And use [DatePipe](https://angular.io/api/common/DatePipe) to format it as you need.


Finding Element with Constantly Changing Xpath

Question: I am new to coding Selenium in Python and, I have been trying to find this button through name, id, xpath, and then click on it but nothing has worked.
The issue is, I cannot find the button because the xpath is constantly changing, and the ID name is just "button", which locating it that way would not work either because there are a lot of other buttons on the page. How can I located the element?
Here is the sites HTML:

    <input type="button">
    Male

    <input type="button">
    Female

Here is what I have tried:
clickGender = browser.find_element_by_xpath("b27296be-e8da-4d5a-acb6-d1674bf88568")

Any help is greatly appreciated.
Comment: is `b27296be-e8da-4d5a-acb6-d1674bf88568` the constantly changing id? you want to click the male button?
Comment: Try this `find_element_by_xpath("//li[contains(.,'Male')]")`.
Answer: As per the HTML you have shared to find the dynamic button corresponding to the text as Male or Female and then click on it you have to induce WebDriverWait for the element to be clickable and you can use the following solution:

Male:
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@data-componentname='gender']//li//span[contains(.,'Male')]//preceding::input[1]"))).click()

Female:
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@data-componentname='gender']//li//span[contains(.,'Female')]//preceding::input[1]"))).click()

Note: You need the following imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Answer: You need to use find_element_by_id:
clickGender = browser.find_element_by_id("b27296be-e8da-4d5a-acb6-d1674bf88568")

Answer: Your XPATH should be this (assuming you want to select the 'Male' button):
//li[span/text()='Male']

Answer:
To find the button with text that contains "Male", use this:

driver.find_element_by_xpath("//li[contains(string(), 'Male')]/input[contains(@type,'button')]")

To find the button with text that contains "Female", use this:

 driver.find_element_by_xpath("//li[contains(string(), 'Female')]/input[contains(@type,'button')]")


Is it ok to use volunteers for prospective cohort studies

Question: Prospective cohorts are ones where the exposure is known but not the disease outcome.
Volunteer bias is where volunteers tend to be healthier.
I've been told because of this volunteer bias, we should not use volunteers for our epidemiology experiments.
I can see why this is true in the case of prevalence studies. Volunteers tend to smoke less and thus we will underestimate the prevalence of smoking if we only get volunteers.
But I don't see why this must be true for prospective cohort studies.
Let's say there's been a nuclear accident and we rush to attract volunteers from those who've been exposed to radiation. All my volunteers, exposed and unexposed, are very fit and don't smoke.
Their general better health could mean they recover better from radiation. One could say this skews results. However, given that my other unexposed volunteers are equally healthy - wouldn't this be a fair comparison? Is there still volunteer bias here?
Comment: "Volunteer bias is where volunteers tend to be healthier." or less healthy, when you ask volunteers to have a CoVid-swap those with symptoms could be more inclined to get their results.
Answer: First and foremost we must be clear, that experiments and studies are never perfect and bias and skewed results are the norm, not the exception. There is just so many things you simply cannot blind people for. If you study high-dose cortisone against placebo, those with the red faces, the high blood pressure and the sleeping problems are the cortinsone group. Thus a sentence like

we should not use volunteers for our epidemiology experiments.

should be carefully worded and understood more as "if you have better alternatives avoid volunteer groups and if you need to investigate volunteers consider possible influences on the result carefully".
So maybe in your nuclear plant you have so many volunteers that are very eager to be open about any body complaints and report them. Maybe you ask yes/no-questions like "did you have headaches or muscle complaints within the last 5 days" and all your body-complaint-centered volunteers report to have had headaches or muscle complaints - you will hit a ceiling effect in that question and will not find how exposure to radiation lowers the frequency and intensity of headaches.
Maybe all those health-centered volunteers do not take illegal drugs or do not come to work tired. You will not find any radiation effect that affects only those taking that modern illegal drug or the accidents that only happen if a worker is tired and radiated.
I know these are not very convincing examples and appear to be taken out of thin air -- that is because they are. However, they are not totally impossible and thus you will have to think (and reason) about possible biases if you investigate volunteers, but you will have to do that with any study group you choose and you better start that in the planning of a study then in the final analysis.
Comment: so does using volunteers in a prospective cohort study introduce bias?
Answer: Your question:

"However, given that my other unexposed volunteers are equally healthy

wouldn't this be a fair comparison? Is there still volunteer bias here?"

The comparison of exposure versus non-exposure among the volunteers yields an unbiased estimate of the effect of exposure among people who are like the volunteers (internal validity) but the findings may not be generalizable to people who not like the volunteers--lacks external validity.  For example, if volunteers are more healthy than the general population (they usually are) and the cohort study comparing exposed with non-exposed among volunteers finds no effect of exposure, one cannot conclude that there is no effect of exposure in the general (less healthy) population—there is (potential) bias.
EXPLANATION
An epidemiologic cohort study is a non-experimental (observational) study design which assesses the association between one or more exposures and the development of (or mortality due to) one or more diseases.  The goal is to draw causal inferences about the effect of exposure and the development of (or mortality from) the disease.
As explained in this excellent 2010 review article by Song and Chung (and elsewhere):

"The hallmark of a cohort study is defining the selected group of
subjects by exposure status at the start of the investigation. A
critical characteristic of subject selection is to have both the
exposed and unexposed groups be selected from the same source
population." [bolded for emphasis]

https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2998589/
Song JW, Chung KC. Observational studies: cohort and case-control studies. Plast Reconstr Surg. 2010;126:2234-2242. doi:10.1097/PRS.0b013e3181f44abc
People in cohort studies are seldom completely representative samples of the population for many reasons.  It is difficult to identify representative samples.  Some people identified as part of a representative sample don't want to be in the cohort study.  Thus, in practice, people in a cohort study where the study interacts with the people in the study are always volunteers.
NOTE:  Some cohort studies involve only computer record-linkage and this can be done (with approval by an Institutional Review Board) without interaction of the study with the people whose records are used in the study.  Thus, there is no issue related to volunteerism.
Famous cohort studies such as the British Doctor's study, the Framingham Study, and three iterations of Nurses' Health Studies all enrolled only volunteers.
These links are to articles about the history of these landmark cohort studies and how the people in the study entered the study as volunteers.
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5298160/
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4159698/
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4981810/
There are numerous other examples.
Use of a non-representative sample, for example, volunteers, in a cohort study affects the external generalizability (also called the external validity) of the results.  For example, nurses who volunteered to be in the Nurses' Health (cohort) study cohort were preponderantly white and their educational attainment was higher than that of all women in the United States.  The findings of the study about the association of an exposure with a disease association might not be generalizable (applicable) to non-white women or women with educational attainment different from nurses.
See Bao et al. (cited above) for discussion of generalizability in the Nurses' Health Study I.
An important source of bias in cohort studies arises because of loss-to-follow-up where there is differential loss-to-follow-up comparing the exposed and unexposed.
See this classic (pay-walled) paper.
Greenland S. Response and follow-up bias in cohort studies. Am J Epidemiol. 1977 Sep;106:184-7. doi: 10.1093/oxfordjournals.aje.a112451
A benefit of enrolling volunteers in a cohort study is that the volunteers are (presumably) interested in the study and thus are less likely to be lost-to-follow-up.


Make a int returning function behave as an lvalue and rvalue

Question: I hope I am technically accurate in formulating this query. While lvalues and rvalues are new to me as an in-depth topic, I could not help but draw similarities between how some functions tend to behave dually and how it relates to this. I assume lack of proper terminologies is causing my research into this topic futile, but I want to know how to approach implementation to the following two definitions of the same function index_at:
int number = matrix_.index_at(row_val, col_val)
matrix_.index_at(row_val, col_val) = 200;

Any references to help guide me in this regard are highly appreciated. Thank you.
Comment: "Any references" - you made a pun and didn't even know it!
Comment: It's worth noting that this question has nothing to do with Rvalues. The `index_at(...) = ...` syntax would idiomatically be done using only Lvalues. Rvalues are a completely different thing used for efficiently stealing data from expiring objects. Really this is just about having a function that returns a mutable reference
Comment: @Human-Compiler precisely what I could not put a finger on. This does clarify it a lot.
Answer: Those are not definitions of functions; they seem to be invocations of member functions.
Are those two different functions? Not necessarily. If that member function is declared like so:
int& index_at(std::size_t row, std::size_t col);

then this same member function could be used on both lines. It is possible to define such functions! A classic example is the std::vector::at() function (or rather its non-const variant): It is implemented essentially (*) as:
T& at(std::size_t pos) { return *(this->data() + pos); }

where data() returns a pointer to the first element in the allocated space for the std::vector.
std::vector::at() is also an example of how your two member function invocations could be of different members:
I hope this answers your question.

(*) Plus bounds checking, which I am ignoring here.
Comment: Note that the actual `vector::at` will also do bounds checking, but that just gets in the way of making the point.
Comment: @MarkRansom: I did say "essentially"... see edit.
Comment: @einpoklum `vector::operator[]` might have been a better example to choose from
Comment: @RemyLebeau: Yes, but I didn't want to confuse OP with operator overloading.


Custom launcher app icon issue?

Question: I got all list of installed applications with details (app_name ,app package_name,app_icon).
I attached Screenshots ,which display what issue i still facing.

This is my code

App List Adapter JAVA
App List Cell_layout XML ,in XMl i also set imageView scalType but its not working.
App List Activity JAVA
Comment: I think issue in android manifest file.
Comment: i provide my manifest file check it any thing missing.
Comment: there is no issue! from where I m looking at it! there you have wrap content for both height and width ! my best guess here I can is the size of images you have there is not ok! for some icons are making them like this!
Comment: may be shadow and invisible background space is causing the spacing issue! check your icon images in any photoshop tool
Comment: @Rizwanatta  how can i get and open  that app icon which i mention on the screensorts in photoshop?
Comment: so those are icons of already installed apps!  sorry I took it wrong for that!  for now just make your App List Cell_layout XML  for imageView fixed size (50dp,50dp) instead of wrap_content for now!
Answer: so those are icons of already installed apps! for now just make your App List Cell_layout XML for imageView fixed size (~50dp,~50dp) instead of wrap_content
for now do this!  it should solve the issue for now ok!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center|top"
    android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="@dimen/_10sdp">

            <ImageView
                android:id="@+id/ivAppIcon"
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:id="@+id/tvAppLabel"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="@dimen/_5sdp"
                android:ellipsize="end"
                android:lines="1"
                android:maxEms="10"
                android:text="--"
                android:textColor="@color/colorWhite" />
        </LinearLayout>

Comment: **Yes**  its work  i set iamgeView
   android:layout_width="@dimen/_40sdp"
   android:layout_height="@dimen/_40sdp"

**Thanks**
Comment: accept the answer please so that It could help other people too! welcome @Arbaz.in
Comment: Please  suggest me if i forgot to put any other file  in my question.
Answer: Check It..
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.adruser.annotationdemo">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".interfaceclass.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity android:name=".interfaceclass.SecondActivity"/>
</application>

</manifest>

Comment: can you please explain whats wrong with my manifest file?
i put this line in to android manifest for set activity as a home activity
Comment: home is referred to  ADW Launcher, and LAUNCHER refer is used to specify which of your activities can be launched.
Comment: Yes, you are right ,but i want to launch my android activity as a HOME launcher

Custom launcher app icon issue?


How do I get my background image to load before Javascript program runs?

Question: I am trying to get my HTML background Image to load before my JavaScript program loads. Currently the JavaScript program loads and then after the program is done the Background image will show. I am rather new to coding so any help would be appreciated.
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>

˚

Answer: The background image should be set using the CSS background-image property. Try replacing your background tag with style="background-image: url('9-RPS-example.png')"

Comment: I couldn't seem to get this to work. Still wouldn't load the image.
Comment: I apologize, I didn't look at your code close enough. The background image can't be set that way. I'll update my answer.
Comment: I have added  and window.addEventListener('load', function() { javascript here }); with no luck. Program loads before background.


summation of series (binomial theorem)

Question: I need help in solving this question.
If $n \in N$,$n\ge 3$
then the value of $(1)n-\frac{(n-1)}{1!}+\frac{(n-1)(n-2)^2}{2!}-\frac{(n-1)(n-2)(n-3)^2}{3!}+.....$ upto n terms
any help hint will do.
My attempt:
$S=\sum_{r=0}^n(n-r) {(n-1)\choose r}$. after this i am not able to do it.
Comment: Is the denominator of the fourth terms $1!$ or $3!$ ?
Comment: I do not understand the question, can you also provide some examples and the things you have tried to prove it ?
Comment: Also, is the exponent of $n-3$ in the fourth term $3,$ or indeed $2$?
Comment: Did you forget an $(-1)^r$ factor in the summand?
Answer: Let $ n\in\mathbb{N}^{*} : $
Denoting $ S_{n} $ your summation, $ R_{n}=\sum\limits_{r=0}^{n-1}{\left(n-1-r\right)\binom{n-1}{r}} $, we have :
$$ S_{n}=\sum_{r=0}^{n-1}{\left(n-r\right)\binom{n-1}{r}}=\sum_{r=0}^{n-1}{\binom{n-1}{r}}+\sum_{r=0}^{n-1}{\left(n-1-r\right)\binom{n-1}{r}}=2^{n-1}+R_{n} $$
Now making a change of index by symmetry in $ R_{n} $, we get that : $$ R_{n}=\sum_{r=0}^{n-1}{\left(n-1-r\right)\binom{n-1}{r}}=\sum_{r=0}^{n-1}{r\binom{n-1}{r}} $$
Thus, $$ 2R_{n}=\sum_{r=0}^{n-1}{\left(n-1\right)\binom{n-1}{r}}=\left(n-1\right)2^{n-1} $$
Hence $$ S_{n}=2^{n-1}+\left(n-1\right)2^{n-2}=\left(n+1\right)2^{n-2} $$

summation of series (binomial theorem)


Array de posição de memória

Question: Estou fazendo uma implementação de um jogo em assembly no Proteus.
Eu sorteio dois números aleatórios de 1 até 99 e preciso gerar no LCD uma imagem referente aos números que eu gerei.
Exemplo: Se eu gerar o número 1 a imagem que vai aparecer no display é

Se eu gerar o número 2 a imagem que vai aparecer no display é

Implementação foi feita da seguinte maneira:
.DATA
SEED DW 0 ;Armazena o número aleatório de 1 ~ 99
NUMBER1 DW 0 ;Guarda o primeiro número gerado
NUMBER2 DW 0 ;Guarda o segundo número gerado

IMG_NUMBER1 DW ? ;variavel aux para armazenar a IMG do primeiro numero gerado
IMG_NUMBER2 DW ? ;variavel aux para armazenar a IMG do segundo numero gerado

IMG_NUMERO_1 db 8, 6
db 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 030H,0D0H,010H,010H,010H,010H,010H,010H,060H,080H,000H,000H,000H,000H,000H,000H
db 000H,000H,000H,000H,000H,000H,080H,060H,010H,010H,010H,010H,010H,010H,0D0H,030H
db 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,00CH,034H
db 0C2H,001H,000H,000H,000H,000H,000H,000H,000H,000H,001H,001H,002H,002H,002H,002H
db 002H,002H,002H,002H,001H,001H,000H,000H,000H,000H,000H,000H,000H,000H,001H,0C2H
db 034H,00CH,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 0F0H,00FH,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 000H,000H,000H,000H,004H,0FEH,000H,000H,000H,000H,000H,000H,000H,000H,00FH,0F0H
db 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 003H,01CH,060H,080H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 000H,000H,000H,000H,002H,003H,002H,000H,000H,000H,000H,000H,080H,060H,01CH,003H
db 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
db 000H,000H,000H,000H,001H,001H,002H,002H,002H,004H,004H,004H,008H,008H,010H,020H
db 020H,010H,008H,008H,004H,004H,004H,002H,002H,002H,001H,001H,000H,000H,000H,000H
db 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H

IMG_NUMERO_2 db 8,6
DB 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 030H,0D0H,010H,010H,010H,010H,010H,010H,060H,080H,000H,000H,000H,000H,000H,000H
DB 000H,000H,000H,000H,000H,000H,080H,060H,010H,010H,010H,010H,010H,010H,0D0H,030H
DB 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,00CH,034H
DB 0C2H,001H,000H,000H,000H,000H,000H,000H,000H,000H,001H,001H,002H,002H,002H,002H
DB 002H,002H,002H,002H,001H,001H,000H,000H,000H,000H,000H,000H,000H,000H,001H,0C2H
DB 034H,00CH,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 0F0H,00FH,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 000H,000H,004H,082H,042H,022H,01CH,000H,000H,000H,000H,000H,000H,000H,00FH,0F0H
DB 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 003H,01CH,060H,080H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 000H,000H,003H,002H,002H,002H,003H,000H,000H,000H,000H,000H,080H,060H,01CH,003H
DB 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H
DB 000H,000H,000H,000H,001H,001H,002H,002H,002H,004H,004H,004H,008H,008H,010H,020H
DB 020H,010H,008H,008H,004H,004H,004H,002H,002H,002H,001H,001H,000H,000H,000H,000H
DB 000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H,000H

..... IMG_NUMERO_3, IMG_NUMERO_4 ... até 99

No código escrevi assim para gerar o número aleatório e guardar nas variáveis auxiliares para comparação no final do jogo:
CALL RANDOM
MOV NUMBER1, SEED ;Guarda o primeiro numero gerado
CALL RANDOM
MOV NUMBER2, SEED ;Guarda o segundo numero gerado

Eu tenho NUMBER1 e NUMBER2 os valores dos números aleatórios gerados.
Eu fiz da seguinte maneira para buscar o número gerado e armazenar a posição de memória da imagem referente ao número: ( Armazeno em BL antes de chamar COMPARE_NMB, o valor 0 para buscar a imagem do NUMBER1 e 1 para a NUMBER2; Em AX contém o valor do NUMBER*)
COMPARE_NMB:
   PUSHF
   PUSH BX
   PUSH AX
   PUSH CX

   CMP AX, 1
   JE JE_1 ;PULA PRO METODO SE FOR 1
   CMP AX, 2
   JE JE_2 ;PULA PRO METODO SE FOR 2
   CMP AX, 3
   JE JE_3
   ... assim por diante até 99 ...

Para cada Just Equals eu chamo assim:
JE_1:
    LEA SI, IMG_NUMERO_1
JMP CONTINUE
JE_2:
    LEA SI, IMG_NUMERO_2
JMP CONTINUE
....

CONTINUE:
   CMP BL, 0 ;VERIFICAR AONDE ARMAZENAR
   JE ARMAZENAR_IMG1
   JNE ARMAZENAR_IMG2
...
ARMAZENAR_IMG1:
    MOV IMG_NUMBER1, SI
JMP FINALIZAR
ARMAZENAR_IMG2:
    MOV IMG_NUMBER2, SI
JMP FINALIZAR

Mas não acho que é a melhor solução.
Alguém saberia um método mais prático?
Criar uma nova variável e armazenar como fosse um array de posições de memória, se eu querer a imagem1 eu somente iria fazer posicoesImagens[NUMBER1], ou imagem2, posicoesImagens[NUMBER2], algo assim.

Obs: Sim, atualmente eu gerei 99 variáveis para armazenar cada imagem referente a cada número. Meu editor está até travando pela quantidade de informações no código.
Escrevi 500 linhas só para comparar qual é o número gerado.
E tive que escrever 2178 linhas referente as imagens de cada número.
DS significa Data Segment.
Comment: Não programo em Assembly, logo não sei se você fez aí, mas ... Não tem como fazer um `loop` pra armazenar os valores em cada variável, acrescentando +1 no nome da variável??
 Pesquisando aqui, encontrei [este link que fala sobre loop no assbemly](https://www.tutorialspoint.com/assembly_programming/assembly_loops.htm), talvez possa ser útil. É possível compilar online seu código para teste [AQUI!](https://www.tutorialspoint.com/assembly_programming/try_asm.php)
Comment: @MarcosHenzel não sei como fazer o que você está falando, meu conhecimento está conforme eu coloquei no código acima. Quero remover as 500 linhas de comparações que eu fiz e opcionalmente se alguém souber algum método para que em vez de criar 99 variáveis dos números, eu precise criar apenas 1 imagem e colocar o número no centralizado dentro dessa imagem em tempo de execução.
Comment: Não trabalho com Assembly, mas no seu caso não seria mais apropriado o uso de alguma matriz (array)? Nesta página deve haver alguma informação útil: https://www.tutorialspoint.com/assembly_programming/assembly_arrays.htm
Comment: Para extender as sugestões, uma array seria essencialmente uma lista de ponteiros, que são "localizações" ou endereços de uma imagem específica. No seu caso poderia ser uma array de imagens (ordem de menor para maior), ou, quis dizer, uma array de ponteiros de uma imagem específica. Cada ponteiro deve ter o mesmo tamanho em bytes. Para pegar a localização (ou endereço) do ponteiro basta fazer `endereçoDaLista + númeroDaImagem * tamanhoDoPonteiro`, por exemplo. Infelizmente não sei muito assembly, por isso não posso ajudar tanto :/
Comment: @PolarDigit bem, mas é isso que eu quero fazer, mas não tenho conhecimento de como fazer. Criar uma nova variável e armazenar como fosse um array de posições de memória, se eu querer a **imagem1** eu somente iria fazer `posicoesImagens[1]`, ou **imagem2**, `posicoesimagem[2]`, algo assim.
Comment: @M8n sim, conforme coloquei ali. 8,6
Comment: A posição da primeira imagem está começando do 1, mas poderia começar no 0. Isso vai depender de como a array é armazenada na memória tbm.
Comment: (Meu comentário ficou meio confuso, mas blz :v)
Answer: Imagino que todas as imagens tenham o mesmo tamanho, logo, basta você armazenar num vetorzão. Aí na hora de acessar você só precisa do endereço inicial e do salto a fazer, então ficaria simplesmente:
endereco_inicial + (salto * tamanho_de_cada_imagem)

Outra coisa a pensar é que a única coisa que muda entre as imagens é o número central, então ocuparia menos espaço você definir o badge e imprimir o número dentro do badge.
Inclusive os próprios números basta ter de 0 a 9 a única coisa que muda é a posição onde você irá imprimir, então dá para economizar bastante espaço, mas claro que fazendo isso você teria um código um pouco maior para poder fazer as diferentes impressões.
Answer: Cria a imagem com o nome por exemplo img_01.jpg, img_02.jpg...img_99.jpg
e usa um substring (não sei como é feito em assembly) para abrir a imagem que corresponde ao número
algo do Tipo:
"img_" + suavariavel + ".jpg"
"img_" & suavariavel & ".jpg"

Array de posição de memória


Mouseover tablerow background color in VUE

Question: I am trying to change the background color on a Table row in VUE. I want the background color of the table row to be changed to black when the mouse is hovered and back to default when it is not. The table row already has a condition on it. However I am still trying something like this

Answer: @onmouseover expects a JavaScript statement or function. On mousing over the table row you're assigning the string 'black' to a variable called color. Since this variable is not related to the
 in any way it doesn't accomplish anything.
You can accomplish your goal instead with CSS.
tr:hover {
  background-color: black;
}

If you absolutely had to do this programmatically, you could do something like this:
<template>

    table row content

</template>

You'll need @mouseleave to do the opposite of @mouseenter to simulate a toggle effect. Also notice that the event names don't include the word "on". In Vue you omit that, so for example onclick is just @click
Comment: I thought about that but I was hoping if there is a feature in vue to do that. I have a v-if question posted as well. If you can check that would be thankful
Comment: You _could_ hack together a way to do it programmatically, but unless you have additional requirements the CSS solution is the simplest.  I've edited the answer to show this.


Compare return of count from sql query in python/databricks?

Question: I would like to return the sql count result and if the count is greater than 0 I would like to induce a fail func.
However, I am getting an error. I assume this is because the id_of_zero_count is a string and it cannot be compared against an integer?
id_of_zero_count = sql(""" SELECT count(*) cnt FROM schema.table where ID = 0 """.format(val))
#BU.collect[0][0] returns the value of the first row & first column

display(id_of_zero_count)

if id_of_zero_count > 0:
  print("Quality check not passed")
  induce_fail_func()

This is the error that is returned:
TypeError: '>' not supported between instances of 'DataFrame' and 'int'

TypeError                                 Traceback (most recent call last)
<command-873419207778593> in <module>
----> 1 if id_of_zero_count > 0:
      2   print("Quality check not passed")
      3   induce_fail_func()

TypeError: '>' not supported between instances of 'DataFrame' and 'int'

Answer: The sql query returns a dataframe, you should see that in your display call.
You can get the first element of the first row instead:
if id_of_zero_count.first()[0] > 0:
  print("Quality check not passed")
  induce_fail_func()

Comment: It returns TypeError: 'DataFrame' object is not callable


Flood control IP bypass whitelist

Question: I am utilising Services to open up some login resources on my site and as a result if multiple users incorrectly try to sign in the entire external website will be blocked because of flood control.
Is there a way to add an IP whitelist to the flood so that there can be an unlimited number of requests from those IPs without them being blocked?
Answer: Try flood_unblock module and flood_control I think both will help you with your requirements, choose the best based on your use case.
Comment: Ive tried both these modules, but they are a one change for all users/ips. I want to be able to create a whitelist so that specific IPs never go into flood. My workaround at the moment until i find a more elegant solution is to clear the flood if it matches a specific IP, so as to never block that address.

Flood control IP bypass whitelist


How to interpret PCA loadings?

Question: While reading about PCA, I came across the following explanation:

Suppose we have a data set where each data point represents a single student's scores on a math test, a physics test, a reading comprehension test, and a vocabulary test.
We find the first two principal components, which capture 90% of the variability in the data, and interpret their loadings. We conclude
  that the first principal component represents overall academic
  ability, and the second represents a contrast between quantitative
  ability and verbal ability.

The text states that PC1 and PC2 loadings are $(0.5, 0.5, 0.5, 0.5)$ for PC1 and $(0.5, 0.5, -0.5, -0.5)$ for PC2, and offers the following explanation:

[T]he first component is proportional to average score, and the second component measures the difference between the first pair of scores and the second pair of scores.

I am not able to understand what this explanation means.
Comment: Somehow @ttnphns's answer goes into a lot of mathematical  details, but I think the original question was really straightforward: why does the loadings vector for PC1 of (0.5, 0.5, 0.5, 0.5) mean that the first component is "proportional to average score"? Well, the answer is that the loadings are [proportional to the] coefficients in linear combination of original variables that makes up PC1. So your first PC1 is the sum of the all four variables times 0.5. Which means it's proportional to the average of the four variables. And similar with PC2. I think this answers the original question.
Comment: @amoeba - Do you know how hard it is to come across such a simple explanation of loadings. Somehow, everywhere it is a mouthful of jargon bile all over me before i decide to move on to next explanation on google. Thank you!
Answer: Loadings (which should not be confused with eigenvectors) have the following properties:

Their sums of squares within each component are the eigenvalues
(components' variances).
Loadings are coefficients in linear
combination predicting a variable by the (standardized) components.

You extracted 2 first PCs out of 4. Matrix of loadings $\bf A$ and the eigenvalues:
A (loadings)
         PC1           PC2
X1   .5000000000   .5000000000
X2   .5000000000   .5000000000
X3   .5000000000  -.5000000000
X4   .5000000000  -.5000000000
Eigenvalues:
    1.0000000000  1.0000000000

In this instance, both eigenvalues are equal. It is a rare case in real world, it says that PC1 and PC2 are of equal explanatory "strength".
Suppose you also computed component values, Nx2 matrix $\bf C$, and you z-standardized (mean=0, st. dev.=1) them within each column. Then (as point 2 above says), $\bf \hat {X}=CA'$. But, because you left only 2 PCs out of 4 (you lack 2 more columns in $\bf A$) the restored data values $\bf \hat {X}$ are not exact, - there is an error (if eigenvalues 3, 4 are not zero).
OK. What are the coefficients to predict components by variables? Clearly, if $\bf A$ were full 4x4, these would be $\bf B=(A^{-1})'$. With non-square loading matrix, we may compute them as $\bf B= A \cdot diag(eigenvalues)^{-1}=(A^+)'$, where diag(eigenvalues) is the square diagonal matrix with the eigenvalues on its diagonal, and + superscript denotes pseudoinverse. In your case:
diag(eigenvalues):
1 0
0 1

B (coefficients to predict components by original variables):
    PC1           PC2
X1 .5000000000   .5000000000
X2 .5000000000   .5000000000
X3 .5000000000  -.5000000000
X4 .5000000000  -.5000000000

So, if $\bf X$ is Nx4 matrix of original centered variables (or standardized variables, if you are doing PCA based on correlations rather than covariances), then $\bf C=XB$; $\bf C$ are standardized principal component scores. Which in your example is:

PC1 = 0.5*X1 + 0.5*X2 + 0.5*X3 + 0.5*X4 ~ (X1+X2+X3+X4)/4
"the first component is proportional to the average score"
PC2 = 0.5*X1 + 0.5*X2 - 0.5*X3 - 0.5*X4 = (0.5*X1 + 0.5*X2) - (0.5*X3 + 0.5*X4)
"the second component measures the difference between the first pair of scores and the second pair of scores"

In this example it appeared that $\bf B=A$, but in general case they are different.

Note: The above formula for the coefficients to compute component scores, $\bf B= A \cdot diag(eigenvalues)^{-1}$, is equivalent to $\bf B=R^{-1}A$, with $\bf R$ being the covariance (or correlation) matrix of variables. The latter formula comes directly from linear regression theory. The two formulas are equivalent within PCA context only. In factor analysis, they are not and to compute factor scores (which are always approximate in FA) one should rely on the second formula.

Related answers of mine:
More detailed about loadings vs eigenvectors.
How principal component scores and factor scores are computed.
Comment: Good point, @Nick, this is indeed not possible, as the total variance of a $4\times4$ correlation matrix must be $4$, so two PCs both with eigenvalues $1$ must account for $50\%$ of the variability. I am not explaining this to you, of course, but for other possible readers of this thread. The ttnphns's answer remains correct though (+1), we just have no other choice as to ignore the number $90\%$ reported by the OP.
Comment: If 2 components out of 4 account for 90% of variability how come their eigenvalues sum to 2?
Comment: Nick, I believe this a question to the OP. He didn't give the data or covariance/correlation matrix. All we had from him is a (rather unrealistic) loading matrix of 2 first PCs.
Answer: Although years are passed since last comments, I think the answer to the original question should be toward a more qualitative interpretation on how to read a "loadings matrix" (regardless of the assumptions we used to build it). If the vertical 'weights' are all the same (as in the original case for PC1 with all 0.5) it means that for PC1 all variables have same weight (0.5). If all variables have same weight it means that the 'scores' (in the PC matrix which is the matrix of the original data matrix projected along the eigenvectors) are proportional to th average of scores in the original data matrix. So PC1 tells me to evaluate a generic student based on its PC scores average (which is different in this case from the original average by a factor of 2x)
In relation to the second question, it's true that mathematically it's the difference between the scores of the two pairs, but the analysis of the PC2 tell us something about where the student is good or bad (as defined by PC1): so we can say that x1 and x2 move together and as much as x1 (and x2) is far from the average of its scores, x3 (and x4) is far from the average of its scores by the same amount in the opposite direction => as much more a student is good in math and phisics its scores in read/vocabulary decreas by the same amount.
So in conclusion by reading the Loadings Matrix we can formulate hypothesis that can be verified by looking in the 'PC matrix' and the 'scores': if you average the row for a generic student you can say how much he is good or bad by just looking at the value (don't forget that we decide that high/low means good/bad), if you then pick x1 (or x2) you can expect they are similar (both high or both low) and you can say from that if that student is good or bad in that subject, and by consequence you can expect he's bad or good  in x3 (or x4).

How to interpret PCA loadings?


Puxar somente itens que forem do usuário

Question: Fala pessoal, tenho 1 banco e dados com 2 tabelas até agora a primeira tabela é responsavel por cadastrar os usuario com o nome "usuarios", a outra tabela é onde quero cadastrar os eventos no Full_calendar com JS, meu código atual consigo puxar tudo que está lá, porém gostaria de aparecer os eventos indiduais de cada usuarios.
Segue meu código de busca em PHP:

<?php

include 'conexao.php';

$query_events = "SELECT id, title, color, start, end, usuario FROM events";

$resultado_events = $conn->prepare($query_events);
$resultado_events->execute();

$eventos = [];

while($row_events = $resultado_events->fetch(PDO::FETCH_ASSOC)){
    $id = $row_events['id'];
    $title = $row_events['title'];
    $color = $row_events['color'];
    $start = $row_events['start'];
    $end = $row_events['end'];

    $eventos[] = [
        'id' => $id,
        'title' => $title,
        'color' => $color,
        'start' => $start,
        'end' => $end,
        ];
}

echo json_encode($eventos);

?>

e as informações das tabelas:
events = id, title, color, start, end, usuario
usuarios = id, nome, usuario, email, senha
gostaria de mostrar no calendário só o que é de cada usuário quando ele logar, o sistema de login já está funcionando
Answer: Você deve utilizar a cláusula WHERE na sua query de consulta de eventos para filtrar pelo usuário autenticado.
Supondo que seu usuário está na $_SESSION no índice usuario, e o valor armazenado nesta variável seja apenas o seu id, e também que a coluna usuario na tabela events é a chave estrangeira de usuario; adicione a seguinte linha para concatenar o filtro:
$query_events = "SELECT id, title, color, start, end, usuario FROM events ";
$query_events .= " WHERE usuario = '".$_SESSION['usuario']."'";

O restante de seu código aparentemente não precisará de mais alterações.
Rápida explicação da cláusula
A cláusula WHERE é lida QUANDO, então a leitura da SQL seria algo próximo de: "SELECIONE id, title, color, start, end, usuario DA TABELA events QUANDO usuario = valor"
Comment: obrigado pela ajuda, porém não esta buscando, não estou conseguindo criar $_SESSION['usuario'] ao logar, tenho esse código:
Comment: acho que vou filtrar pelo ID, mas queria pelo usuario
Comment: se você colocar o código que grava o usuário autenticado na sessão me ajuda a te ajudar, de início estou fazendo suposições, quando disse usuário me referi a qualquer valor q vc esteja usando como chave primária e estrangeira. Se está usando o nome do usuário, basta fazer os ajustes no código de exemplo


border on submit button image

Question: I trying to get the image border to go away on a submit button and just can't seem to find the magic code to fix it.
<input name="Insert" type="image" id="Insert" alt="Register"
          width="189" height="38" border="0"
          src="../../images/register.png"
          onmouseover="MM_swapImage('Insert','','../../images/register_f2.png',1)"
          onmouseout="MM_swapImgRestore()" />

Answer: style="border: 0px;" should do it.
Comment: That was it... I'm sure glad it was an easy one!
Answer: Works for me.
You may have some CSS that is being set by a selector with more specificity.
Use an inspection tool like Firebug to examine the exact CSS being applied.

border on submit button image


Drupal custom module code working differently for logged in users and anonymous users

Question: I have the below simple if else condition for a custom module form page in buildForm method for recommendation submission. I would like my form to be displayed to all user who visit for the first time and submits and cannot submit again from the same url. If the url is used again it should just display the thank you message(if already submitted). The below code wrks perfectly if the user is logged in. Like if the user is logged in, he comes and submit, thank you message is displayed everything is saved in DB correctly. The problem comes when anonymous user comes. The page loads as expected. But after filling up the details and submit button is clicked. It reloads and the same form is displayed again(instead of the thank yo message) and then if I submit again it displays validation errors even though the fields are there and gives the thank you message. Can anyone explain me why its behaving differently for logged in and anonymous users.
    public function buildForm(array $form, FormStateInterface $form_state)
    {
       if($this->CheckRecommendationStatus())
       {
          $form = array();
          $form['form_label'] = [
          '#type' => 'processed_text',
          '#text' => t('<h3Thank you already submitted
'),
          ];
        }
        else if($this->validateUrl())
        {
           $form = array();
           //it will have controls and submit button.if submit is clicked those values will be saved
        }
        return $form;
     }
     //This below method check the Database whether already the submission is made or not
     public function CheckRecommendationStatus()
     {
           $this->setUniqueIdentifier(htmlspecialchars($_GET["rec"]));
           $query = \Drupal::database()->select('m_tablename', 'mr');
           $query->fields('mr',array('id'));
           $query->condition('mr.column_name',$this->getUniqueIdentifier());
           $query->range(0,1);
           $results = $query->execute()->fetchAll();
           return $results;
     }

Comment: This would be so much easier to read in Drupal's [coding standards](https://www.drupal.org/docs/develop/standards/coding-standards).
Answer: This sounds like a caching issue. Check the cache api and make sure to set the $form['#cache'] appropriately.
When the anonymous user submits the form, it's submitted fine, but when the form loads the second time Drupal doesn't know that it should not be serving the original cached form.
You can quickly confirm that it is a caching issue by set the form to not be cached like:
$form['#cache'] = [
  'max-age' => 0,
];

Comment: the thing is that for authenticated users, all forms are currently uncacheable because they CSRF protection. However, for anonymous users, you are hitting the dynamic page cache, which by default does not consider the query argument when caching, you would need to add url.query_args.rec cache context. Note that max-age 0 is additionally not respected by the internal page cache, so you might also need to use \Drupal::service('page_cache_kill_switch')->trigger(); so it is not cached there
Comment: It looks like a caching issue. Even though manually I am giving incorrect querystring value, still it loads correctly with previous details.  I tried the above code  before the if condition, it did'nt work.
Comment: You will need to add it below, just before the `return $form;` as you completely reset the form variable within each if case
Comment: Perfect its working as expected. Thanks a lot. But why did it work for logged in users. Caching is different for them.
Comment: I think because caching is not enabled by default for logged in users. But I think that changed with a recent release, or is changing soon?