definition of weak formulation

Question: the definition of weak formulation on wiki is:
Let $V$ a Banach space. We want to find the solution $u \in V$ of the equation:
$$Au=f$$
where $A:V \rightarrow V'$ and $f \in V'$. This is equivalent to finding $u\in V$  such that for all $v\in V$ holds:
$$ [Au](v)=f(v)$$
Here, we call $v$ a test vector or test function.
We bring this into the generic form of a weak formulation, namely, find $ u\in V$  such that,
$$ a(u,v)=f(v)\quad \forall v\in V$$
by defining the bilinear form
$a(u,v):=[Au](v)$.
In poisson's equation we use the bilinear form ( $V=H^1_0(\Omega)$) :
$$ a(u,v)=\int _{\Omega }\nabla u\cdot \nabla v\,dx$$
I don't understand how the equation:
$$a(u,v)= (Au,v)_{H^1_0(\Omega)} \longrightarrow \int_{\Omega}\nabla u \nabla v \; dx = -\int_{\Omega}(\nabla^2 u)  v \; dx$$
is correct when $V=H^1_0(\Omega)$ (i should use Green's identity but $\nabla^2u$ is not defined in $H^1$).
I know that:
$$\int _{\Omega }\nabla u\cdot \nabla v\,dx=\int _{\Omega }fv\,dx.$$
is well defined but i don't understand how $$a(u,v)= (Au,v)_{H^1_0(\Omega)}$$
is well defined in $H^1$
Answer: In the case of the Poisson equation, Lax-Milgram's lemma, tells you that the problem of finding $u\in H_0^1(\Omega)$ such that
$$
-\int_{\Omega} \nabla u \cdot \nabla v  = \int_{\Omega} fv, \quad \forall v \in H_0^1(\Omega)
$$
has one and only one solution. This is the weak solution. A different question, that you can pose after you have guaranteed the existence of a weak solution, is wether that weak solution is actually regular, for instance if $\nabla^2 u \in H^1$, or even if $u \in C^2(\Omega)$. In a way, you derive the weak form from the classical equation but then they become separate equations (until you eventually prove that both problems have the same solution).
Comment: if i find $u \in H^1_0(\Omega)$ such that
$$ \int _{\Omega }\nabla u\cdot \nabla v\,dx=\int _{\Omega }fv\,dx.$$ how do i know (using the definition) that $u$ is the weak solution of Poisson's equation?
Comment: You can establish that $\nabla^2 u = f$ almost everywhere in $\Omega$. See for instance https://www.math.ualberta.ca/~xinweiyu/527.1.11f/lec14.pdf

definition of weak formulation


Can NICs/vSwitches be 'shared' on a Hyper-V 2016 host?

Question: I've been reading documentation until my vision is blurred.
I'm sure this has a simple solution, but all the docs I'm finding go into excruciating detail on how to set something up—nothing on whether a particular configuration is a good fit for my situation.
I have a Hyper-V 2016 host with two physical NICs. All the VMs (PDC included) are bound to a vSwitch that's bound to one of the NICs; that cable goes to a physical switch to which all the workstations are connected. Straightforward stuff. It's been working for years.
Now I need to plug a NAS device into the second physical NIC so that it can see the PDC on the first. (I can't plug the NAS into the physical switch because that switch has to stay at 10/100 for our older CAT5 cabling. The NAS needs Gb speeds. We tried a Gb switch there and we were getting intermittent dropped connections on workstations.)
Is VLAN the solution for this? Teaming? Bridging? I'm lost, I'm afraid. And my eyes are swimming for the tech docs I'm trying to decode.
The NICs are 192.168.2.11 and 192.168.2.21, respectively. The VMs are on 192.168.2.11.
--EDIT--
As it turns out, bridging is not an option. This is Hyper-V Server, so there's no GUI. Ref. here: "Network Bridge can be set up or removed only through Network Connections."
Comment: Don't know about Hyper-V but with VMware you just add both NICs to the same vSwitch and configure your choice of load balancing or failover. When you use the 2nd NIC as dedicated link to the NAS you'll have to use another network address or it'll mess up the routing.
Comment: @Zac67 — I just checked, and alas it's a one-to-one relationship on Hyper-V. Not sure why; it sounds like a reasonable configuration.
Comment: @Zac67 Neither load balancing nor failover would work in this situation. Neither of those bridge. Hyper-V does support bonding for load balancing and failover, but again, that's not bridging.
Answer:
Connect the first NIC of the server to the gigabit switch.
Connect the NAS to the gigabit switch.
Connect the 10/100 switch to the gigabit switch.
Comment: I'm pretty sure I tried that yesterday when I was onsite. But I was pretty frazzled by that time, so I can't be 100% sure. It sure sounds like it should work, so I can't imagine why it didn't (if it didn't). I'll check it again next time I'm over there in a few days. In the meantime, is there a software solution I can try?
Comment: What version of Hyper-V is your server?
Comment: Hyper-V Server 2016.
Comment: I found someone onsite who could help me with this. As it turns out, the reason it didn't work yesterday was because of a bad Gb switch. We swapped in another one and poof! everything lit right up.
Answer: For software only options, I see two alternatives.
1) Add a vswitch attached to the second NIC of the Hyper-V host. Add a second NIC to the VM's that need access to the NAS. This second NIC (and the NAS) must be on a separate subnet from the first NIC/vswitch.
2) Add a vswitch attached to the second NIC of the Hyper-V host. Add another VM with 2 NICs, each connected to the two vswitches. Install something in that VM to do routing. This could be a linux VM, or Windows running RRAS.
(I don't think Hyper-V Server supports RRAS, but if it does, that is a third option.)
Comment: I like this one (#1). I wish I could give it two upvotes. I'll definitely keep it in mind for future situations. Thanks much for the writeup.
Comment: Do you have any suggestion for the latest problem [here](https://serverfault.com/q/865853/218519)?
Answer: You can set up a bridge, where both of your NICs are members. This means that your server will act as a switch, which has two ports that are your NICs.
After this, you can assign an IP address to your NAS from the 192.168.2.0/24 network.
Comment: Interesting. I don't think a bridge can be created without the GUI component, though (this is Hyper-V Server). I seem to remember running into this problem a while back.


What is being differentiated in this example that uses the Euler-Lagrange equation?

Question:
In this example of using the Euler-Lagrange equation, I am struggling to understand as to what the term being differentiate with respect to $x$ in line $(2.30)$ came from (it's not one of the partial derivatives of $F$ with respect to $y$ or $y'$). I am thinking that it might be from the equation: $$F_{y'y'}y'' = F_y - F_{y'y}y' - F_{y'x}$$
  where $F_{y'x} = 0$. But the term I am confused about isn't even equal to $F_{y'}$.
Answer: For any magic there is a simple scientific explanation. In this case it is called Beltrami identity. Since the function $F$ does not depend explicitly on $x$, the Euler-Lagrange equation is equivalent (modulo to constants $y'=0$) to the following equation
$$
F-y'F_{y'}=C,
$$
which after the differentiation and simplification becomes
$$
\frac{y}{\sqrt{1+y'^2}}=C.
$$
Here we recognize our old fellow in the LHS.
Answer: Note that 2.29 says that $yy'' = 1+(y')^2$. Rewriting, we get $1+(y')^2 - yy'' = 0$, which implies $$\frac{y'(1+(y')^2 - yy'')}{(1+(y')^2)^{3/2}} = 0$$where the left-hand side happens to be equal to $$\frac d{dx}\left(\frac{y}{\sqrt{1+(y')^2}}\right)$$This function that we differentiate is constructed explicitly to make this work. It is, so to speak, pulled out of a magician's hat in order to get a single derivative on one side so that we may integrate. It is a common enough technique when solving differential equations. When you see terms like $yy''$ and $(y')^2$ flying around, then at least to me it smells of product or quotient rule, and I would try to rearrange it into something that works, but this is so complicated that I think it would've taken me a long time to find.


Como prevenir o cache em requisições Ajax no IE 6?

Question: Tenho o código abaixo, para atualizar uma DIV em uma página:
var req;

// FUNÇÃO BUSCA ROMANEIOS PARA EXIBIR NA TELA DE MENU.
function buscarRomaneio() {

// Verificando Browser
if(window.XMLHttpRequest) {
   req = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
   req = new ActiveXObject("Microsoft.XMLHTTP");
}

// Arquivo PHP juntamente com o valor digitado no campo (método GET)
var url = "PesquisaRomaneio.php";

// Chamada do método open para processar a requisição
req.open("Get", url, true);

// Quando o objeto recebe o retorno, chamamos a seguinte função;
req.onreadystatechange = function() {

    // Exibe a mensagem "Buscando..." enquanto carrega
    if(req.readyState == 1) {
        document.getElementById('resultado').innerHTML = 'Buscando Romaneios...';
    }

    // Verifica se o Ajax realizou todas as operações corretamente
    if(req.readyState == 4 && req.status == 200) {

    // Resposta retornada pelo PesquisaRomaneio.php
    var resposta = req.responseText;

    // Abaixo colocamos a(s) resposta(s) na div resultado
    document.getElementById('resultado').innerHTML = resposta;
    }
}
req.send(null);
}
setInterval(buscarRomaneio, 60000); //Envia a informação a cada minuto

O que ocorre é o seguinte: Em qualquer navegador a função funciona normalmente. Menos no IE6, que será o caso exclusivo que irei usar (coletor de dados). A função funciona uma vez e para. Dou F5 inúmeras vezes e não muda nada. Só muda se eu limpo o cache ou fecho e abro o navegador.
Como se trata de um Windows CE 6, é tudo muito limitado. Tem algo que posso fazer nesse código para resolver esse problema?
Comment: Windows CE 6, IE6, cara, se tiver a chance, bota fogo nisso!
Comment: Se você está trabalhando em uma empresa em que o diretor insiste em usar o IE6, então já passou da hora de você enviar o seu currículo por aí e fazer umas entrevistas.
Comment: Qual é a versão do jQuery que você está usando?
Comment: O problema foram os coletores comprados... o valor foi alto e todos vieram nessa configuração. Estou mexendo no codigo e conforme altero ele os dados somem/aparecem.....
Comment: @GuilhermeNascimento aberta.
Comment: Quem negativou, pode me dizer o que posso melhorar? A dúvida é valida, não entendi o porque do -1
Comment: @Diego eu não negativei, mas suponho que seja porque no titulo e tag fala jquery e no código não tem nada sobre jQuery. Vou editar e lhe dar +1
Comment: @GuilhermeNascimento, foi mal. A pressão aqui está grande e me perdi nos termos. Desculpe. E obrigado pela resposta, resolveu o problema :)
Answer: Este problema de cache ocorria até mesmo nos Internet Explorer mais modernos (quando usando o ActiveX) e às vezes ocorre em outras situações, variando conforme o resultado do back-end.
As soluções práticas são:

Ajustar o cache via servidor no seu PHP:
Edite o PesquisaRomaneio.php e adicione isso no topo, deve vir antes de tudo:
<?php
$g = gmdate('D, d M Y H:i:s');
header('Expires: ' . $g . ' GMT');
header('Last-Modified: ' . $g . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');

//Código restante abaixo

Adicionar uma query string de sufixo para evitar o cache. Esta é a mesma técnica que o jQuery utiliza para quando você adiciona cache: false. Faça assim:
// Arquivo PHP juntamente com o valor digitado no campo (método GET).
var url = "PesquisaRomaneio.php";

// Adiciona ? se não tiver query string. Caso contrário adiciona &.
url += url.indexOf("?") === -1 ? "?" : "&";

// Adiciona o sufixo para evitar cache.
url += "_=" + (new Date().getTime());

// Chamada do método open para processar a requisição.
req.open("GET", url, true);

Dica
Recomendo trocar o setInterval pelo setTimeout. Isso porque o setInterval não espera, o que pode ocasionar em requisições simultâneas causando efeitos colateiras. Veja algumas respostas sobre o assunto:

https://pt.stackoverflow.com/a/111149/3635
https://pt.stackoverflow.com/a/77765/3635
https://pt.stackoverflow.com/a/77861/3635

Então, poderia mudar o código para algo como:
function buscarRomaneio() {

    // Verificando Browser
    if (window.XMLHttpRequest) {
       req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
       req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // Ajusta os segundos
    var segundos = 60;

    // Arquivo PHP juntamente com o valor digitado no campo (método GET).
    var url = "PesquisaRomaneio.php";

    // Adiciona ? se não tiver query string. Caso contrário adiciona &.
    url += url.indexOf("?") === -1 ? "?" : "&";

    // Adiciona o sufixo para evitar cache.
    url += "_=" + (new Date().getTime());

    // Chamada do método open para processar a requisição.
    req.open("GET", url, true);

    document.getElementById('resultado').innerHTML = 'Buscando Romaneios...';

    req.onreadystatechange = function() {

        // Verifica se o Ajax realizou todas as operações corretamente
        if (req.readyState == 4) {
            if (req.status == 200) {
                // Resposta retornada pelo PesquisaRomaneio.php
                var resposta = req.responseText;

                // Abaixo colocamos a(s) resposta(s) na div resultado.
                document.getElementById('resultado').innerHTML = resposta;
            } else {
                document.getElementById('resultado').innerHTML = "Erro: " + req.status;
            }

            setTimeout(buscarRomaneio, segundos * 1000);
        }
    };

    req.send(null);
}

// Inicia a função
buscarRomaneio();

Isso irá fazer o disparo sem precisar na primeira vez esperar os 60 segundos. Todavia, se quiser essa espera então troque por:
    req.send(null);
}

// Inicia a função.
setTimeout(buscarRomaneio, 60000);

Comment: @Diego adicionei uma sugestão na resposta
Comment: Ótima dica, vou trocar. Obrigado!!
Comment: Obrigado Guilherme, usei a segunda opção e funcionou! Muito obrigado!


Hidding a form element before printing

Question: I want to print only bits of a very big form, my first approach was as follow:
function THEME_preprocess_user_profile(&$variables) {
    global $user;
    $account = user_load($user ->uid);
    $variables['user_edit']  = drupal_get_form('user_profile_form', $account);
    $variables['user_edit']['field_about_me'] = 'invisible';
    .....
    $variables['user_edit']['field_some_filed'] = 'invisible';

}

This does work to hide certain element, the problem is that there is way more elements i want to hide than elements i want to show, so this process can be tedious..
Would anyone think of a better way to do so ?
UPDATE : Ideally i'd like to have a function similar to drupal_get_form, but that instead only return a targeted element.
Thanks a lot
Answer: if you want to hide elements the appropiate way is to set the #access attribute on each element to FALSE, using a hook_form_alter()

'#access'
Used by: All elements and forms
Description: Whether the element is
  accessible or not; when FALSE, the
  element is not rendered and the user
  submitted value is not taken into
  consideration.
Values: TRUE or FALSE.

Source: http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#access
Comment: +1, see  http://drupal.stackexchange.com/questions/7199/how-to-hide-and-or-prevent-access-to-fields-in-a-form-such-as-group-audience-fo for an example of how the code should be written
Answer: Remember #access will not consider the particular elements in submit process.
we can set #access to false if we want to totally ignore the fields.
In case you want to hide the field with a default value. just pass attribute in form alter:
$form[fldname]['#attributes']['style'][] = 'display:none;';

Answer: Either save the elements you wish to print in temporary var, hide all (or unset them), then reassign the saved elements to $vairables array, or use DS module.

Hidding a form element before printing


If a variable is coded as yes/no/unknown, is it categorical or ordinal?

Question: The dataset has ten variables, and I am trying to conduct a cluster analysis. The ten variables are coded yes, no, or unknown. And I converted the character values ('yes', 'no', 'unknown') to numeric values ('1', '0', '(blank)').

If the variable is coded in 'yes', 'no', or 'unknown', can I leave the 'unknown' value as blank or do I need to re-code the values to 1, 2, and 3 in ordinal way? (e.g., 3 = yes, 2 = no, 1 = unknown)

If the variable is coded in 'yes', 'no', or 'unknown', do I need to set the variable as categorical (using as.factor) or as ordinal (using as.ordinal)?

If the total proportion of 'unknown' is about 60% in my dataset, would it be appropriate to conduct the cluster analysis?

I first coded the values in 1 = yes, 0 = no, blank = unknown. And I used 'EGAnet' package to conduct the cluster analysis. And I tried two ways. One is setting the variables as categorical variable with 2-level. Another one is replacing the missing ('unknown) values using this code:
data <- replace(data, is.na(data), "")

and setting the variables as ordinal variable (3-level: "" < 0 < 1).
Finally, I run the EGAnet EGAglasso <- EGA(data = data, model = "glasso") to see the clusters and correlations among the variables.
However, I got different results depending on whether I set the variables as categorical or ordinal.
Comment: Define unknown, is it really missing data or does it mean indecisive or no opinion or does the one refuted to answer any question (thinking of a survey). It makes a big difference and if it has a meaning (other than truly missing) it gives value in your analysis and should be treated as a third category. For example, are young people more likely not to answer my question... etc.
Comment: re: your question - ordinal data is data that has an order - an example would be very bad, bad, good, very good. Unknown doesn't have a place within the order within yes or no. You could potentially use TRUE, FALSE, and NA, if you don't know, but maybe you want to reserve NA for missing data (as opposed to things you know you don't know)
Comment: @Mark yes and no already doesn't have an order.
Comment: @Mark it can work very poorly to put 'unknown' as a separate category.  It completely changes the meaning of the variable and can sometimes steal information from Y.  See
 [this](https://hbiostat.org/rmsc/missing.html#problems-with-simple-alternatives-to-imputation).  This is much more of a place for multiple imputation of the 'unknowns'.
Comment: It can be a valid aproach to model "unknown" as a separate category. Important questions are why are they unknown and if you only have one type of unknown. It looks like you have data from a survey and you should read some literatur regarding how to analyze such data or talk to an expert.
Comment: @Roland fair! In so far that two items order is kinda irrelevant, and they don't have a meaningful order ♂ brain fade my apologies
Comment: Thank you so much, @Roland! I understand your comments. Then it would be appropriate to set the variables as categorical with two levels. One of my concern is about 60% of data are coded as unknown so I think there are too many missing data..
Comment: Thank you for your comment @Mark! I understand that 'unknown' does not have a place. The problem is I have too many unknown values in my dataset :(
Comment: @user21531215 do you have any NAs in your dataset?
Comment: for the statistical stuff, you're much better off asking on Cross Validated
Comment: @Mark if the 'unknown' values are coded NA, they will be the missing values.
Comment: I mean outside of those
Comment: @Roland thank you for your advise. I will try to figure out the solutions!
Comment: in that case, you could turn the column into a logical, with yes = TRUE, no = FALSE, unknown = NA. But I'd check on Cross Validated about the statistical stuff first because that's not my area of expertise
Comment: @Mark No, there is no other NAs in the dataset.
Comment: Related: https://stats.stackexchange.com/a/623151/69508
Comment: @FrankHarrell thanks for sharing! I'll give it a read
Answer: This cannot be answered without knowing exactly what 'unknown' means in your dataset.
If 'unknown' refers to missing data, then it's likely best to replace them with 'NA' and analyse the variables as categorical (i.e. nominal, see Nick Cox's comment below).
But imagine that yes/no/unknown were the answers to a question about preference of object A vs. object B. In this case, 'unknown' could mean 'no preference' and if so, there would be a clear sequence: yes > unknown > no. The reverse (no > unknown > yes) is equivalent; the point is that 'unknown' is in the middle. In this situation, it would be reasonable to treat the variables as ordinal.
I would say the first case is more likely but you would know your data better than us.
EDIT: I won't recapitulate them here, but do see the excellent comments below for valuable additional points and caveats.
Comment: _nominal_ just means that categories have distinct labels or names, but that is the only information. _interval_ means that intervals can be compared but any zero point is arbitrary so ratios don't make sense. Yet the difference between interval and ratio only bites for procedures based on ratios, which means only sometimes.  On the whole (prejudices coming up fast) the scheme nominal-ordinal-interval-ratio is oversold in many people's views and even dangerous if tied up with outdated or dubious dogma about what you must/must not or should/should not do.
Comment: Some extra points: Sometimes unknown values are just missing values and reluctantly best left out of analyses; the opposite strategy is to use some kind of imputation to try replacing unknown with either Yes or No. More positively Yes and No can be coded as 1 or 0 and treated quantitatively: Means make sense.  Modelling in terms of probability (logit, probit, etc.) can make sense if Yes/No encodes an outcome. Using the variable as an indicator or dummy predictor can make sense. Such 0, 1 variables can be called binary, dichotomous, Boolean, logical, quantal and likely other names too.
Comment: Readers watch out: _categorical_ narrow sense means (roughly) nominal scale in a widely used if problematic terminology, while _categorical_ wide sense includes ordinal as well. In my reading the wide sense is more common; your reading may differ.
Comment: I don't read anyone here as suggesting that unknown is safely taken as  intermediate between yes and no unless there is context that justifies such a tactic. .
Comment: We agree then: at most mkt was saying that it might make sense.
Comment: I think most of this is saying basically the same thing: it _might_ be ordinal based on the question itself, we really don't know. @NickCox, `the point is that 'unknown' would be in the middle` is what I was going off of. Perhaps I'm just leaning a bit more towards saying "it depends", and it could go in either direction, varying per-question. (I think it's important (for me) to remember that ordinal does not have to mean increasing "goodness".) Sorry mkt, not an attack.
Comment: Thus I disagree with the definition and advice at the tag `categorical`. See for example Agresti's books which use the wider meaning. If you want categorical to mean nominal, why not just say nominal?
Comment: (+1). Just build on your example (and nitpick a bit), it may be difficult to interpret the meaning of "unknown" if it's really an option a respondent can pick. It could mean that the respondent doesn't have an experience of A or B (so she cannot really answer), or that she prefers A but only in specific circumstances, or that she doesn't want us to know her real preference because it's a sensitive topic, etc. So it might be tricky to draw conclusions from it. But I agree with the substance of your answer, in particular as you mention it's important to know what "unknown" means exactly.
Comment: I disagree with the assumption that `yes > unknown > no` as an ordinal value is safe lacking context. For instance, if the question is "are you a criminal", then certainly "yes" has a distinct and comparable value to "no"; if the question is "do you like brussel sprouts with your meal", who is to say that one value is greater than another? The "unknown" might be "it depends", which might be interpreted as better than yes, because "yes" suggests sprouts+cereal is as good as sprouts+chicken. I suggest the best answer, lacking more context, is either **nominal** or just **it depends**.
Comment: @r2evans What part of "**But imagine that yes/no/unknown were the answers to a question about preference of object A vs. object B.**" makes you think this answer advocates a decision of 'ordinal' without any context?
Comment: @r2evans No worries, and I appreciate the clarification.
Comment: I realize here we are considering three elements, but I thought I would share a small mathematical fact that any binary relation (order or otherwise) on only two elements [vacuously](https://en.wikipedia.org/wiki/Vacuous_truth) satisfies being a [transitive relation](https://en.wikipedia.org/wiki/Transitive_relation). And transitivity occurs in most, possibly all, notions of order that I have seen.
Comment: Thanks, excellent points. @NickCox I have to say that I find the terminology around data types frustratingly non-standard and opaque ('interval' and 'nominal' are rather unintuitive to me, for example). I personally find the narrow sense of categorical to be a more useful definition but I mainly wish we had one agreed-upon standard.
Answer: Reading the very interesting discussion here, I'd like to make a rather philosophical point that may be controversial, but is in my view well illustrated by how the discussion goes.
The point is this. There is a decision to be made here on how to treat the "unknown" values, and whether the resulting variable is treated as nominal ("categorical") or ordinal. This is a matter of judgment and not a matter of truth. We just can't say "you have to do this or that".
Furthermore, this decision concerns the meaning of the response categories rather than the data, so in general it cannot be decided in a data based way. This however doesn't mean that the data cannot be used. For example, one could imagine that there are other variables in the study and one could see that the other variables are related to the variable in question (let's say V1) in such a way that values of the other variables for the cases where V1=unknown tend to be in between the values for V1=yes and V1=no. This would constitute some evidence that "unknown" is located between yes and no, even though the evidence wouldn't be conclusive (other variables might be related to V1 in a non-monotonic way).
The user may also be tempted to run different versions of further analyses treating "unknown" in different ways, and decide which of the outcomes "looks best"/most plausible. This is problematic, because it will induce a bias in the sense that the user influences the analysis in the direction of what they want to see. So I advise against it.
It however illustrates that the decision of how to deal with the variable will also need to take into account what analyses are later done with the variable, as it depends on the later analysis what the impact of the decision actually is. And in fact running different analyses using different potentially valid versions of the variable can be used in a better way as a means to sensitivity analysis; i.e., in order to explore how analysis results are affected by the decision. If results are pretty much the same, the good news is that they can be seen as unaffected by this decision. Note that multiple imputation techniques for missing values do something similar.
I'm saying that the decision is not about "finding out what the variable truly is" but rather about judgment. But of course arguments can be made. As mentioned in other answers, other than looking at the data, it is important to consider background knowledge and the meaning of measurements. There may be knowledge (question wording, context) that indeed would support seeing "unknown" as an intermediate option between "yes" and "no"; there may be knowledge that could suggest that "unknown" is essentially different from both of these and should actually be treated as a third nominal category (note that there may even be cultural changes over time regarding such judgments, e.g., gender questions), and it may be that the idea is that we have a missing value here that really should be "yes" or "no" and nothing else, but we don't know, in which case a multiple imputation technique for missing values may be most appropriate.
One could even imagine investigating this issue in particular by asking follow-up questions to respondents who said "unknown" regarding which of these seems to be best for describing where they stand (obviously one needs to think carefully about how to word this). I suspect that in many real situations there may be a mix, unfortunately, i.e., some people think yes or no but won't tell you, some are somewhere in between, and some would argue that the question doesn't apply to them or similar. (In fact one can also critically revise the question because there may be reasons such as misleading or imprecise wording so that it produced many "unknown"s.)
Keeping further in mind that statistical models are different from reality and whatever we do is a simplification, particularly when dealing with missing values, insisting on a certain "overperfectionism" is not helpful. So I'd consider it legitimate to treat the variable as ordinal with "unknown" between "yes" or "no" if there are fairly good arguments to believe that many of the respondents have treated it in this way, even though one can still argue that chances are there is a good number of further respondents for which something else applies. Of course there needs to be caution with any interpretation, and one can add sensitivity analysis and further research, but ultimately the issue with missing values always is that we can't really know what's behind them, and whatever we do might be seen as "wrong" with a different interpretation in mind. Ultimately it will not normally be identifiable from observations which way of treating them is "correct", so that the idea that there is a single "correct" treatment is in my view wrong. So I say, it's a matter of judgment. (Note that any multiple imputation mechanism will be based on a model that of course may be wrong, see also https://www.jstor.org/stable/20203830 .)
Regarding the distinction between nominal, ordinal, interval, ratio scales I'd like to say something similar to the problem of missing values imputation. This classical distinction has been often criticised, (a) regarding whether it "correctly" classifies all relevant types of measurement and (b) what are the implications of this, such as "don't compute means of ordinal variables". Much of this criticism is in my view justified if the classical scheme is taken as a general prescription. However, I also think that it is very useful and enlightening to at least start thinking about scale types in a systematic manner. Much better and thoughtful analyses will happen if people have in mind that scale types are something to be considered, even though they may at some point disagree with certain "general recipes" and do something different in their specific problem, hopefully for good reasons. This is in my view the "true value" of the scale types concept, not that it were "the generally correct way to classify scales". Similarly, there is no single correct way to deal with missing values, but it is much better to start thinking about these in terms such as "missing at random", or "can we interpret them as their own category or not, and if so is the resulting variable ordinal" than just mindlessly imputing them somehow or deleting missing cases.
Answer: An interesting take on this:
If you encode "unknown" as some value between the level of "yes" and the level of "no" you are actually performing an imputation (a bad one, but an imputation nonetheless). The variable is still binary. If handling it categorically, then the missing data strategy is the use of a missingness indicator. Imputation is an analysis decision and doesn't affect the variable's nature. On the other hand, you often receive code books documenting the data and they might describe the variable as "variable: dietary restriction (binary): no=0, yes=1, unknown=-9" or something of the sort. Encoding is an analysis decision and doesn't affect the variable's nature.
I contend that nary an R or SAS user would disagree that the following list : {0, 1, 0, 1, 1, NA, 0} or [0, 1, 0, 1, 1, ., 0] is consistent with a binary variable.
Comment: @Galen not really. Suppose for instance in my analysis, "unknown" is treated as missing, so I perform mean imputation. That is, if 30% of the sample reports "no" and has x=0, "unknowns" are imputed to 0.3. I actually can't claim no < unknown < yes because the value is unobserved, the imputation is purely pragmatic. I don't mean a "variable's nature" in any precise way except that the value of "unknown" reflects a limitation of my design rather than a tangible quantity.
Comment: *Variable's nature* sounds like [level of measurement](https://en.wikipedia.org/wiki/Level_of_measurement). Are they synonyms in this case?
Answer: Visualizations
mkt's answer is correct in my opinion, but I thought I would briefly illustrate some of the choices that are possible. Let us suppose that $\text{yes} \geq \text{no}$, leaving what to decide about $\text{unknown}$.
$\text{unknown}$ can be connected to $\text{yes}$, or not, and connected to $\text{no}$, or not. This might make it seem like there are four options, but we should also consider the order of pairs. That is $\text{yes} \geq \text{unknown}$ is not in general the same thing as $\text{yes} \leq \text{unknown}$, and likewise for the pairings with $\text{no}$.
First option is that unknown is greater than both, which is fine as a partial order.

Another option is this cycle, which cannot be a partial order (although it can be a "cyclic total order" if you allow that notion):

Next option is that unknown is less than yes but greater than no, which is a valid partial order.

And the last option is that unknown is less than both, which is also a valid partial order.

Here is the code I used to generate the strings which I threw into the mermaid live editor (I was in too much of a hurry to write code to plot the network diagrams nicely):
from itertools import product

no = [
    ('unknown', 'no'),
    ('no', 'unknown')
    ]

yes = [
    ('unknown', 'yes'),
    ('yes', 'unknown')
    ]

default = (('yes', 'no'),)

relations = [r  + default for r in product(yes, no)]

for j, relation in enumerate(relations):
    print(f'relation {j}')
    mermaid_string = '\n'.join([' --> '.join(i) for i in relation])
    print(mermaid_string, '\n')

I left out some cases where the graph is not fully connected (in a weak sense). In those cases we don't have a partial order because the transitivity property (of a partial order) will not hold. I left the cycle in b/c of laziness/expedience. ¯\_(ツ)_/¯

Ordinal Regression (And Rank-Based Statistics For That Matter)
While it wasn't my original goal in this post, some may wonder how this get's us back to doing things like ordinal regression. One straightforward approach is to grade the partial order. That effectively gives us a sort of rank even if we started with elements of a set that were not objects normally thought of as having numbers. Order is about how things pair together, and for ordinal regression you can actually skip grading the elements and compute the eCDF cumulatively in topological order of the graph.
Quick Hack To Check Pairs For Partial Order
While I didn't use it here, you can think of a partial order in a rather indirect way which happens to be handy for checking if collection of pairs form a partial order. You can think of a partial order as the edge set of a directed acyclic graph that is equal to its own transitive closure.
So with a tool like Networkx, you can use these checks on a nx.DiGraph object instance d:

nx.is_directed_acyclic_graph(d)
nx.transitive_closure_dag(d) == d
Comment: Related: https://stats.stackexchange.com/questions/605349/what-is-a-rank
Answer: If these are three levels of the actual measurement, it may be ordinal, and may be possible to do correlation and regression treating these as -1, 0, 1 (do you like sweets - no, do not know what to say, yes).
But if "unknown" is the state of genuinely missing data, this depends on the proportion between "yes" and "no" cases. If the actual data set seems strongly biased to one of the sides (say only 0.05 % respond "yes") yet 30 % of data is missing, assuming "unknown" as "half yes, half no" may produce the wrong bias towards the "yes" case.


Probability that at least 3 of the 5 randomly selected questions can be solved

Question: As my friend my studying for her final for her Philosophy class, she asked me a question.
The professor assigned a list of 10 essay questions, and would be picking 5 to put on the exam. Of the 5 that he put on the exam, you only needed to answer 3. If she only knew how to answer 4 of the essay questions, what is the probability that she would be able to be solve at least 3 out of the 5 questions given to her? How does this probability change if she knew how to answer 5 of them? 6?
Thanks so much for the help!
Comment: edit the post to include what have you tried? also use the self-study tag.
Comment: Use hypergeometric distribution:  An urn contains 4 green balls and 6 red balls. Five balls are selected at random without replacement. What is the probability that at least 3 green balls are selected? In R, `sum(dhyper(3:4, 4,6, 5))` returns 0.2619048. Your friend needs to work a little harder.
Answer: Since your friend is a philosophy major, here is a little philosophical brain-teaser for her:

Exam Question: Suppose that one of the 10 practice questions for your exam (which is one of the five questions on this exam paper) is the question you are reading right now.  For the purposes of answering this question, assume that you have not seen the other questions on this exam.
(1) Your professor assigned a list of 10 practice questions, and has randomly picked five of them to put on this exam.  When you attempted the practice questions, you got 4 correct and 6 incorrect.  Assuming you answer the questions on this exam the same way you answered them in your practice attempts, what is the probability you will get at least three of the questions correct on this exam?  (Give a probabilistic solution using the hypergeometric distribution.)
(2) There is a nasty little logical paradox that can arise in answering Part (1) of this question.  Explain.  (Hint: Think about what happens if you answered this question wrong in your practice attempts.)

And here is the solution:

! (1) From this description there are $N=10$ practice questions and I answered $K=4$ of them correctly in my practice attempts.  There are $n=5$ random questions assigned to the exam, so the probability I answer at least three of the exam questions correctly is:$$\begin{equation} \begin{aligned}
\mathbb{P}(\text{Answer at least } 3 \text{ correctly})
&= \sum_{k=3}^5 \text{Hypergeom}(k|N=10 ,K=4, n=5) \\[6pt]
&= \sum_{k=3}^5 \frac{{4 \choose k} {6 \choose 5-k}}{{10 \choose 5}} \\[6pt]
&= \frac{{4 \choose 3} {6 \choose 2}}{{10 \choose 5}} + \frac{{4 \choose 4} {6 \choose 1}}{{10 \choose 5}} + 0 \\[6pt]
&= \frac{4 \cdot 15}{252} + \frac{1 \cdot 6}{252} \\[6pt]
&= \frac{66}{252} = 0.2619048. \\[6pt]
\end{aligned} \end{equation}$$ (2) In answering Part (1) we treated all the assigned exam questions as random.  However, suppose instead that having read this question, I know that it was one of the ones I got wrong in the practice attempt.  (Note that the question assumes I have not read the other questions on the exam, but I have to read this one in order to answer it!)  In that case there would be $N=9$ remaining practice questions and I answered $K=4$ of them correctly in my practice attempts.  There are $n=4$ random questions assigned to the exam (setting aside this one), so the probability I answer at least three of the exam questions correctly is:$$\begin{equation} \begin{aligned}
\mathbb{P}(\text{Answer at least } 3 \text{ correctly})
&= \sum_{k=3}^5 \text{Hypergeom}(k|N=9 ,K=4, n=4) \\[6pt]
&= \sum_{k=3}^5 \frac{{4 \choose k} {5 \choose 4-k}}{{9 \choose 4}} \\[6pt]
&= \frac{{4 \choose 3} {5 \choose 1}}{{9 \choose 4}} + \frac{{4 \choose 4} {5 \choose 0}}{{9 \choose 4}} + 0 \\[6pt]
&= \frac{4 \cdot 5}{126} + \frac{1 \cdot 1}{126} \\[6pt]
&= \frac{21}{126} = 0.1666667. \\[6pt]
\end{aligned} \end{equation}$$ Now, looking at this answer a logical paradox arises.  If the answer is correct then the assumption that it is answered incorrectly is wrong, and so we should not have conditioned on this, and so the answer is actually incorrect.  On the other hand, if this answer is incorrect (as assumed) then the above calculations are correct, so the answer is actually correct.  Thus, we obtain a situation in which the answer is correct if it is incorrect, and incorrect if it is correct.  This is somewhat similar to Russell's paradox.


Unit tests for simple REST client

Question: Let's assumed that i've got simple method which gets some data from REST service. Method looks like:
public string GetDataFromRest(string uri) {
 string result = String.Empty;

 using(WebClient web = new WebClient()) {
  result = web.DownloadString(uri);
 }

 return result;
}

So, now i want to create unit test for this method. I don't want to use external REST service but i want fake response from any URI without real conecting to service. Something like every execute of GetDataFromRest(uri) in Unit Test -> always returns some XML.
Answer: As the posted answer goes into some detail, part of your problem is you have a dependency on the WebClient class.
A sample wrapper for WebClient could look like:
public interface IWebClient
{
    string DownloadString(string address);
}

public class WebClientWrapper : IWebClient
{
    public string DownloadString(string address)
    {
        using(WebClient web = new WebClient()) {
            return result = web.DownloadString(uri);
        }
    }
}

public class MyClass
{

    private readonly IWebClient _webClient;

    public MyClass(IWebClient webClient)
    {
        _webClient = webClient;
    }

    public string GetDataFromRest(string uri)
    {
        return _webClient.DownloadString(uri);
    }
}

Now of course going this route means WebClientWrapper can be unit tested with a "less real" URI or what that you specifically control. I've only implemented one method of the WebClient, but this externalizes the dependency within GetDataFromRest from a real URI, as you can now mock the return data. This also helps in that anything else you need a WebClient for, you can now use the wrapper class, and easily mock the returned data, as you are now programming to an interface, rather than a concretion.
Comment: Thanks a lot! It'll be lot of changes for other POST, PUT etc. in my code, but will work like a charm :).

Unit tests for simple REST client


Procurar conteúdo dentro de duas tags html - Regex

Question: Tenho uma página HTML em uma variável string. Preciso procurar dentro das tags h2 de todo documento se existe a palavra "Blog". Estou usando o pregmatch mas não consigo criar a expressão pra encontrar.
Podem me ajudar mais uma vez?
Obrigado!
Answer: Você pode usar o DOMDocument para filtrar por H2.
Você não informou o HTML, portanto imagine isto:

Blog

Isto é um blog

Index

Isto é um Index

No PHP use algo similar a isso:
  $seu_html =  '

Blog

Isto é um blog

Index

Isto é um Index

';

  $doc = new DOMDocument();
  $doc->loadHTML($seu_html);

  // Todos os H2
  $h2 = $doc->getElementsByTagName("h2");

  // Loop de todos os H2
  foreach($h2 as $item){

      // Echo se encontrar a palavra Blog
      echo strpos(strtolower($item->textContent), 'blog') !== false ? 'Achamos um H2  blog' : '';

  }

Você pode testar isso clicando aqui.
A documentação do DOMDocument é extremamente ampla (por mim acredito que não muito amigável!) e possui muitas funções, talvez até alguma que remova a necessidade do foreach! Veja isso clicando aqui e aqui.

IMPORTANTE: O strpos foi usado para que possa "conter" mas não necessariamente ser "igual" ou "idêntico". Por essa razão se o H2 for "Blog do Zé", será VÁLIDO! O strtolower foi usado para tornar o texto em minusculo, dessa forma removendo o erro de "Blog" ser diferente de "blog", por exemplo.

Se quiser ainda usar REGEX....
Utilize o /
(.*?)<\/h2>/, por exemplo:
  $seu_html =  '

Blog

Isto é um blog

Index

Isto é um Index

';

  preg_match_all ("/
(.*?)<\/h2>/", $seu_html, $h2);

  // Loop de todos os H2
  foreach($h2[1] as $item){

      // Echo se encontrar a palavra Blog
      echo strpos(strtolower($item), 'blog') !== false ? 'Achamos um H2  blog' : '';

  }

Você pode testar isso clicando aqui.


Are the only $b$ such that $b^2 + 4c$ and $b^2 - 4c$ are both perfect squares primes of the form $4k + 1$?

Question: And of course, multiples of primes of the form $4k + 1$
$b, c, k$ are positive integers.
Ran into a math problem essentially involving this, just curious. I observed it to hold for the first $50$ integers, but not sure past that nor how to prove it.
Does it have to do with Fermat's "Christmas" theorem ($p = x^2 + y^2$ iff $p \equiv 1 \pmod 4$)?
Answer: The number $b$ need not be prime. We have $65^2+3696=89^2$ and $65^2-3696=23^2$.
A boring kind of example is $10^2-96=4$, $10^2+96=14^2$.
Remark: One can generate arbitrarily many non-boring  examples using $(r,s,b)$ such that $(r,s,b)$ is a primitive Pythagorean triple and $b$ is not prime. Any such example requires $b$ to have at least two not necessarily distinct prime divisors of the form $4k+1$.
Comment: Yes, you are. To keep my notation, you are looking for $x^2+y^2=2b^2$. Take $r$ and $s$ such that $r^2+s^2=b^2$. Then let $x=r+s$ and $y=r-s$. We get $x^2+y^2=2b^2$.
Comment: I was asking why, not just for examples. But I actually figured it out on my own (I think).
Comment: Addressing your remark, I'm not looking for $r^2 + s^2 = b^2$, rather $r^2 + s^2 = 2b^2$.


Almost surely convergence of a random variable with bounded expectation

Question: I am working on the following problem: Let $(X_n),n\geq1$ be a non-decreasing sequence of non-negative random variables. Assume that $\sup_{n\geq1}E(X_n)<\infty$. Prove the following:
a) $(X_n)_{n\geq1}$ converges almost surely
b) Denote the limit with $X$. Show that $E(X)<\infty$
c) $E(X|\mathcal{G})=\lim_{n\to\infty}E(X_n|\mathcal{G})$
I think b) and c) can be proven trivially with Fatou's lemma, e.g.:
$E(X)=E(\liminf X_n) \leq \liminf E(X_n)< \infty$. Does that also imply the existence of $X$? I think it doesn't, but I can't find a theorem that would guarantee the existence. Any ideas for a)?
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: $(X_n)$ is non-negative and non-decreasing. This implies that $X=\lim X_n$ exists (but it may take the value $\infty$). Fatou's Lemma gives $EX <\infty$ and this implies that $X$ is almost surely finite valued.
Now $Z=\lim_n E(X_n|\mathcal G)$ exists for the same reason. To prove that $Z=E(X|\mathcal G)$ note that $Z$ is $\mathcal G-$ measurable and prove that $\int_A Z dP=\int_A XdP$ for all $A \in \mathcal G$. For this apply Monotone Convergence Theorem.


should I nest when ICC and number of units is low?

Question: Let's say that I have 10 regions and 50 schools in each region.
I run two models (region <- DV ~ 1 + (1|region) and school <- DV ~ 1 + (1|school)) against the null model and find that the ICC for the region model is 0.08, whereas for the school model is 0.34.
Clearly variance among schools is more important than among regions.
However schools are nested within regions, and there are arguably a sufficient number of them to warrant a mixed model.
Would you still nest school within region? I often read that it's more important to have a large number of Level 2 units as Level 1 units. However region has way fewer units than schools...
Answer: Yes, I would fit the model:
DV ~ 1 + (1 | region / school)

It is not unusual to find much lower variation at higher geo-spatial levels. It is always good to have as many groups as possible (within reason) but you can only work with what you have, and 10 is sufficient in my opinion.
Comment: Yes, it would be "better" to ensure that you have more regions. It would be "better" still to conduct a controlled experiment / trial. As I mentioned, you can only work with what you have. If you have the possibility to sample vastly more regions, then by all means do so. As for the ICC, first it's not clear how you detemined the ICC is 0.08. Usually you fit the 3-level model and compare the variation at each level to the total. Anyway, it *may* be debatable whether 0.08 is meaningful. But what is meaningful ? 0.1 ? 0.15 ? If it's 0.15, then why ? And what if it's 0.14999 ?
Comment: Thanks for your answer @Robert Long. But wouldn't it be better to ensure that the highest level has the greatest number of units to make estimates more reliable? After all, the ICC is much larger for school than region, and it's debatable whether an ICC of 0.08 is actually meaningful. Also, why is it that we usually find lower variation at the higher levels? Has it something to do with `n`, or some other mixed-model peculiarity?


Em MySQL agrupar por semana não lista corretamente

Question: Tenho em MySQL a tabela acesso, que grava todos os acessos do cliente a um sistema, ela salva o id do usuário (id_usuario) e o dia (dia) do acesso. Estou fazendo uma consulta para checar os acessos semanais, assim:
SELECT COUNT(id_usuario) AS total, dia FROM acesso
GROUP BY WEEK(dia, 1)
ORDER BY dia ASC

O problema é que ele me retorna dias estranhos, alguns começam na segunda, outros na terça e muitas vezes alguns dias se repetem, veja um exemplo de um retorno:
02/01/2019 - 08/01/2019 - 130 acessos (02/01 = quarta | 08/01 = terça)
07/01/2019 - 13/01/2019 - 165 acessos (07/01 = segunda | 13/01 = domingo)
14/01/2019 - 20/01/2019 - 163 acessos (14/01 = segunda | 20/01 = domingo)

Reparem que no segundo resultado está até voltando um dia.
Como fazer essa consulta listar certinho as semanas? Pois precisaria de um resultado assim (intervalo entre domingo a sábado):
domingo - sábado = x acessos
domingo - sábado = x acessos
domingo - sábado = x acessos

A mudança de ano ou mês não importa. Acredito que em muitos dias não teria nenhum acesso, isso pode ser um problema para gerar dessa forma?
Comment: @AugustoVasques ainda assim ele terá problema agrupando coisas de anos diferentes, e dependendo de onde cairá o fim do ano, vai "separar" a virada do ano indevidamente. O parâmetro "modo" é um pouco mais complexo do que só ajuste do dia inicial.
Comment: @Bacco eu iria recomendar ao usuário sua resposta neste momento. Pois concordo integralmente com você sobre os problemas com os casos de uso da função `WEEK()` e a maneira que abordou resolve o problema do usuário sem criar efeitos colaterais.
Comment: Da forma que agrupou é normal que não comecem e terminem sempre no mesmo dia. Tem certeza que é a função WEEK mesmo que precisa? E tem certeza que é o Modo 1 o melhor para o seu caso (atenção à "virada de ano" neste caso) - Seria bom [edit] a pergunta e por um exemplo do que esperava como saída.
Comment: @Bacco então, existe outra forma de agrupar que não seja por WEEK?
Comment: Depende do resultado que quer obter. Falta deixar claro na pergunta o critério desejado. Exemplos ajudam. Por exemplo, dividir o número sequencial do dia por 7, agrupa por semanas. TALVEZ o WEEK seja bom, mas ai depende do critério da virada do ano. Se o ano começa numa terça, o que faz? (que provavelmente vai confundir seus resultados com WEEK)
Comment: Editei! Mas realmente não me importa a mudança de ano ou mês, preciso só pegar o intervalo de domingo a sábado.
Comment: O segundo parâmetro de função `WEEK(dia, 1)` está informando que as semanas pesquisadas na consulta começam sempre na segunda-feira. Faça `WEEK(dia, 0)` para que as semanas consultadas tenham domingo como dia inicial.
Answer: Se quer juntar apenas pela semana, de segunda a sexta, provavelmente este é um melhor caminho:
SELECT COUNT(id_usuario) AS total, dia FROM acesso
GROUP BY FLOOR(TO_DAYS(dia)/7)
ORDER BY dia

Se precisar mudar o dia de início da semana, pode usar um offset:
GROUP BY FLOOR((TO_DAYS(dia)+2)/7)

no lugar do 2 do exemplo você pode ajustar conforme desejado.
O TO_DAYS converte as datas em dias corridos desde o "Ano zero", e ao dividirmos por 7 fazemos com que os dias da mesma semana retornem o mesmo valor.
Foi evitado o uso do WEEK() por dois motivos:

O tratamento dos dias na virada do ano pode ser um pouco confuso, visto que o WEEK tem modos de operação não tão claros para quem não está acostumado com o conceito de "semana do ano", comum em lugares como os EUA, por exemplo, mas não no Brasil;
como ele "reseta" na virada do ano, agruparia coisas de anos diferentes, o que não seria desejável neste caso. Ainda, separaria de maneira indevida ocorrências entre um ano e outro que seriam da mesma semana.
Comment: @Tiago implorar ajuda não faz parte do escopo do site. Se você tem um dúvida específica nova faça uma que pode ser respondida em nova pergunta, caso contrário se já tem uma resposta ela é duplicata e não pode mais ser feita. Se só quer uma ajuda geral e não específica não faz parte do escopo do site. Fazer um código para pessoas quem não sabem fazer não faz parte do escopo do site. Você precisa entender minimamente o que faz. Você deve aprender a programar, fazer, e se tiver uma dúvida específica postar em pergunta. O que está fazendo aqui é errado e pode ser considerado comportamento abusivo.
Comment: @Tiago a solução é o que está nesta resposta: https://pt.stackoverflow.com/a/259973/70 - basicamente você está misturando colunas com e sem agregação, e isto não é aceito por padrão em versões mais novas do DB.
Comment: Foi o que eu falei e o que está na resposta, se não fizer agregação em todas as colunas ou mudar a configuração do DB, vai continuar com erro.
Comment: Fucnionou! Mas agora tive outro problema, que talvez seja legal abrir outro post. Em semans que não tenho acesso, eu teria que receber 0, mas ele simplesmente ignora. Isso muda muito a situação, certo?
Comment: Isso é um problema clássico de SQL que tem dezenas de perguntas no site. O SQL só retorna o que existe, ele não tem um conceito de "grupo vazio" (afinal, só você é que sabe o conceito do grupo, não o SQL). Provavelmente o que seria melhor no seu caso seria tratar isso na exibição, numa linguagem cliente. Simplificando: o problema acontece mesmo sem o GROUP, imagine uma tabela simples com 2 colunas, uma sendo o numero do mes e a outra sendo "quantidade de vendas", sendo que o valor zero nao é lançado, somente de 1 pra cima, e vc precisa de um SELECT dos 12 meses.
Comment: Entendi, só levei isso em consideração no final do projeto, vou estudar isso e se realmente não conseguir volto aqui. Muito obrigado, aprendi bastante!
Comment: Para solucionar, tem N maneiras, e qual a melhor, só depende do caso. Quase sempre um loop mes a mes mostrando os resultados fora do SQL é melhor, mas se precisar mesmo resolver em SQL puro, precisa "gerar" os grupos de uma forma, mas é algo meio "feio" em MySQL (que não tem generators). Algo como SELECT 1 UNION 2 UNION 3 UNION 4 ... UNION 12 AS meses LEFT JOIN (sua query)
Comment: @Bacco por favor preciso muito de sua ajuda, da uma olhada POR FAVOR https://pt.stackoverflow.com/questions/392025/erro-no-sql-group-by-clause-and-contains-nonaggregated-column-this-is-incompat
Comment: Olá @Bacco, o problema é que não foi eu quem fez esse select, foi um amigo que não esta mais presente. Esse select esta acima do meu conhecimento. Veja como ele funcionava http://sqlfiddle.com/#!9/28638/9
Comment: @Bacco se eu soubesse como fazer não estaria implorando ajuda. Já desativo o `ONLY_FULL_GROUP_BY` não retorna nenhum valor https://prnt.sc/o3wmip
Comment: @Bacco Me ajuda, por favor, https://pt.stackoverflow.com/questions/392025/left-join-group-by-this-is-incompatible-with-sql-mode-only-full-group-by


non-split real Lie algebra

Question: What are some examples of simple or semisimple non-split real Lie algebras? By non-split, I mean that no Cartan subalgebra $\mathfrak{h}$ is such that $\mathrm{ad}(X)$ is diagonalizable for each $X \in \mathfrak{h}$.
Is there a list somewhere? Or how can non-splitness be detected?
Comment: All compact real Lie algebras, like the SU(n).
Comment: $\mathbb R^3$ with the vector product is the canonical example.
Comment: OK. How about families (depending on $n$, or $(p,q)$, or whatever) of non-split Lie algebras? I am specifically thinking of matrix Lie algebras. And is there a way to detect non-splitness, if you catch my drift?
Answer: Simple Lie algebras over $\mathbb{R}$ are classified up to isomorphism by their Satake diagrams. The absolutely simple ones (i.e. those which are not scalar restrictions of complex ones -- these can easily be amended) are listed, for example, here: Onishchik, Vinberg p. 229 et seqq.
(With the exception of the anisotropic = compact ones mentioned in the comments, for which by a classical result by E. Cartan there is exactly one for each type (i.e. irreducible root system); for example the $\mathfrak{su}(n+1)$ are the compact forms of type $A_n$).
In that classification, the split ones are exactly the ones where the Satake diagram is the classical Dynkin diagram, i.e. has only white nodes and no arrows. The others (plus, as mentioned, 1) the scalar restrictions of the simple complex ones and 2) the compact ones) are all the non-split simple ones you are looking for.

non-split real Lie algebra


The Outward Unit Normal Vectors $\mathbf{n} = \mathbf{k} \times \mathbf{T}$ and $\mathbf{n} = \mathbf{T} \times \mathbf{k}$: Why?

Question: The following diagram is from chapter 16.2 of Thomas's Calculus, 14th Edition:

I've studied and understand the concept of the cross-product, but I don't understand why $\mathbf{n} = \mathbf{k} \times \mathbf{T}$ is the outward unit normal vector if the curve $C$ is parameterised clockwise and $\mathbf{n} = \mathbf{T} \times \mathbf{k}$ is the outward unit normal vector if the curve $C$ is parameterised anti-clockwise?
At the moment, I have to either memorise this fact or refer to my textbook for the information. However, in my experience with mathematics, this necessity is usually a sign of a lack of understanding of why something is the way it is. Therefore, I'm assuming that if I understood why this is the case, I would be able to remember which equation to use ($\mathbf{n} = \mathbf{k} \times \mathbf{T}$ or $\mathbf{n} = \mathbf{T} \times \mathbf{k}$) without needing to rely on rote memorisation or my textbook.
I would greatly appreciate it if people could please take the time to clearly explain why $\mathbf{n} = \mathbf{k} \times \mathbf{T}$ is the outward unit normal vector if the curve $C$ is parameterised clockwise and $\mathbf{n} = \mathbf{T} \times \mathbf{k}$ is the outward unit normal vector if the curve $C$ is parameterised anti-clockwise, so that I can mentally derive these facts, rather then needing to rely on rote memorisation or my textbook.
Answer: Vector cross products follow the right-hand rule, by convention. This is the reason $\mathbf{k} \times \mathbf{T}$ points outward for a clockwise parametrised circle. The right-hand rule is arbitrary (there is no objective mathematical reason to use that instead of the opposite, left-hand rule), but it's a choice that the mathematical community at large has come to agree on, as not choosing one way as standard is worse than having an arbitrary standard.
Using that rule (whatever incarnation you have learned), you can tell which way $\mathbf{k} \times \mathbf{T}$ points for your circle. If it points inwards, reverse the product to get a vector pointing in the opposite direction.
Comment: @ThePointer Knowing which vector to assign to each finger is an essential part of the right-hand rule. You should practice that.
Comment: you're right, I was confusing myself with it. I understand now. Thanks for the clarification.
Answer: It is simply a consequence of the convention of right-handed orientation for the three unit vectors $\mathbf {i,j,k}$  in the 3-D space where, by convention, we have: $\mathbf k= \mathbf i \times \mathbf j$


Unbounded mean implies convergence in probability to infinity.

Question: Let $X_1,X_2,...X_n,...$ are random variables satisfying $0\leq\dfrac{X_n}{n}\leq C,$ and $Var(X_n)\leq C'n$ for some constants $C, C'>0.$ Furthermore, $X_n(\omega)$ is non-decreasing i.e. $X_n(\omega)\leq X_{n+1}(\omega).$ Then, how do I show that $X_n\longrightarrow\infty$ in probability, provided that $EX_n\longrightarrow\infty?$
For given $a>0$,I have tried bounding: $$P(X_n\leq a) = P(X_n-EX_n\leq a- EX_n) = P((X_n-EX_n)^2\geq (a-EX_n)^2)\leq\dfrac{VarX_n}{(a-EX_n)^2},$$
for large enough $n$. But this is not enough to conclude that $P(X_n\leq a)\longrightarrow 0$, as there is no information about the how fast $EX_n$ converges to infinity.
Are there smarter ways to use Chebyshev's inequality?
Answer: I think the statement is false as written.
Counterexample: Let $X_n$ be $0$ or $\sqrt n$, each with probability $1/2$. Then $0 \leq X_n / n \leq 1$ holds; also, $Var(X_n) = \frac 1 4 \cdot n$. Further, $\mathbb{E}[X_n] = \sqrt n / 2$, so this expectation goes to infinity, and yet $\mathbb{P}(X_n = 0) = 1/2$ for all $n$, so $X_n \not \rightarrow \infty$.
Comment: There was a small typo, he means that $a$ is always the preimage of $0$ and $b$ is always the preimage of $\sqrt n$. That is, for all $n$,
$$
X_n(a) = 0 \\
X_n(b) = \sqrt n
$$
Comment: Sorry, I left out an extra assumptions on the $X_n.$ please see edited.
Comment: The example I provided can still satisfy this extra condition. Suppose that the sample space for each variable is $\{a, b\}$, where $a$ is always the preimage of $0$ and $b$ is always the preimage of $b$ under $X_n$.
Comment: I am not sure what that means


Error: [$injector:unpr] Unknown provider: routeParamsProvider <- routeParams using LazyLoad

Question: I'm using LazyLoad to make a on-demand load of the angular controllers, and trying to build all the paths at the moment, but always getting the error:
Error: [$injector:unpr] Unknown provider: routeParamsProvider <- routeParams

Below it's the routeProvider snippet
 $routeProvider
            .when("/", {templateUrl: "principal/index"})
            .when('/:controller/:action', {
                templateUrl: function(routeParams){
                    return routeParams.controller+"/"+ routeParams.action;
                },
                resolve: function(routeParams){
                    lazyLoad('assets/controller/'+routeParams.controlador+'/'+routeParams.controller+'Controller.js');
                    return lazyload;
                },
                controller: function(routeParams){
                    return routeParams.action;
                }
            })
            $httpProvider.interceptors.push('authHttpResponseInterceptor');
            $httpProvider.defaults.transformRequest.push(spinnerFunction);
      }]);

I can't even get a console.log about the path that the lazyLoad function it's receiving.
Any suggestion about what I'm doing wrong??
Thanks in advance.
Answer: "routeParams" does not work inside resolve. Use "$route.current.params" instead.
Try this:

$routeProvider
            .when("/", {templateUrl: "principal/index"})
            .when('/:controller/:action', {
                templateUrl: function($route){
                    return $route.current.params.controller+"/"+ $route.current.params.action;
                },
                resolve: function($route){
                    lazyLoad('assets/controller/'+$route.current.params.controlador+'/'+$route.current.params.controller+'Controller.js');
                    return lazyload;
                },
                controller: function($route){
                    return $route.current.params.action;
                }
            })
            $httpProvider.interceptors.push('authHttpResponseInterceptor');
            $httpProvider.defaults.transformRequest.push(spinnerFunction);
      }]);

Cheers


JButton toggle disable and enable ItemListener

Question: I'm trying to make a button that will enable or disable another button. I'm not sure why it's not entering the ItemListener or is ItemListener only used for toggle events? Here's my code.
This is in the main method:
        resumePause = new JButton ("Pause/Resume") ;
        leftPanel.add(resumePause) ;
        deleteObj = new JButton ("Delete");
        leftPanel.add(deleteObj);

        //sets delete button to disabled and resume to enable
        resumePause.setEnabled(true);
        deleteObj.setEnabled(false);
        // register the frame as a listener for Item events
        resumePause.addItemListener(this);

This is the ItemEvent method:
public void itemStateChanged (ItemEvent e) {
        System.out.println("In ItemStateChanged");
        if (playPause.isSelected()) {
            System.out.println("Delete enabled");
            deleteObj.setEnabled(true);
        }
        else{
            System.out.println("Delete disabled");
            deleteObj.setEnabled(false);
        }
    }

I added those println() to check if it ever enters itemStateChanged but it never does.
Comment: JButton's don't use ItemListener's they use ActionListener's
Comment: Ok, thought I could use it with ItemListener but I'll change it to ActionListener instead. What would be the equivalent action listener's method to `setEnable` `isSelected` ?
Answer: Just use a JToggleButton and then use the original listener, an ItemListener on it.
Comment: Perfect, that was the easier and simpler fix. thanks!


How to check if a password reset token is still valid?

Question: Is there a way to hook into the user_pass_reset form to detect if the provided hash is valid? Currently it seems to just throw a 403 error when submitting the form if the hash has already been used to change the password.
Using hook_form_alter(), I can retrieve the hash itself with explode("/",$form['#action'])[5], but am unsure how to check if it's already been used or not, or if it's expired. I see that this information might be part of the UserController class, but I'm not sure how to retrieve that.
Answer: Welp, I probably should have gotten the idea to follow where the form action actually takes you and see what its controller does. I pulled the timestamp and hash from the form action with the explode function, loaded the user object from the currentUser id, and used Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp));.


Como dar a uma lista de imagens o comportamento de um RadioGroup?

Question: Tenho 2 vetores de imagens, um para a imagem normal e outro para quando ela for selecionada.
Quando selecionar uma imagem no ListView preciso que as outras não fiquem selecionadas.
Já tentei de várias formas e essa foi minha última tentativa:
Activity.java:
Integer vetor1[] = {R.drawable.imagem1, R.drawable.imagem2,R.drawable.imagem.3, R.drawable.imagem4, R.drawable.imagem5};
Integer vetor2[] = {R.drawable.imagemselecionada1, R.drawable.imagemselecionada2,R.drawable.imagemselecionada3, R.drawable.imagemselecionada4, R.drawable.imagemselecionada5};

protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
        Adapter adaptader =  new Adapter(EscolhaAvatar.this,vetor1,vetor2);
        ListView listaImagens = (ListView) findViewById(R.id.list);
        listaImagens.setAdapter(adapter);
        listaImagens.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

listaImagens.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                desabilitaImagem(view, position);
            }
        });
    }

public void desabilitaImagem(View v, int posicao) {
        ImageView img = (ImageView) v.findViewById(R.id.img);
        listaImagens.setAdapter(adapter);
        img.setImageResource(vetor2[posicao]);
    }

Minha ideia era recriar o ListView e deixar como selecionada apenas a imagem em position
Comment: Eu tiraria essa logica da sua view e colocaria no seu adapter. Você pode usar a lógica de troca de imagem dentro do adapter que vc criou. Crie um listener (implemente OnCLick) do ImageView.
Comment: Eu já tentei fazer isso no adapter de vários jeitos mas não da certo, pq preciso mudar todas as outras imagens e no adapter n tem como percorrer uma a uma pq ele cria um item de cada vez. O problema é a referência das outras imagens que eu não tenho
Comment: Então ai vc chama o método notifyDataSetChanged do adapter ele atualiza a lista.
Comment: vocẽ precisa bolar uma forma para saber qual imagem está selecionada para poder mudar a imagem das outras no getView
Comment: da pra vc criar uma variavel int que guarda a posição da imagem que está selecionada. ai toda vez que o getView é chamado vc verifica se o primeiro parametro (position) é igual o valor da sua variavel. se for igual ele usa a imagem selecionada, se não ele usa a imagem normal
Answer: Com a ajuda de duas classes é simples implementar o que pretende.
Uma classe para encapsular uma ImageView com os estados seleccionada/não seleccionada.
Ela é responsável por guardar o estado e os resources ids das imagens de cada um dos estados:
SelectableImage.java
public class SelectableImage {

    private final int selectedImageResource;
    private final int unSelectedImageResource;
    private boolean isSelected;

    public SelectableImage(int selectedImageResource, int unSelectedImageResource){

        this.selectedImageResource = selectedImageResource;
        this.unSelectedImageResource = unSelectedImageResource;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }

    public int getImageResource(){
        return isSelected ? selectedImageResource : unSelectedImageResource;
    }
}

Como, num conjunto(lista) de imagens, apenas pode haver uma imagem seleccionada, criamos um classe para gerir essa situação.
Ela é responsável por guardar a lista de SelectableImage e garantir que, quando uma é seleccionada, a anterior é desseleccionada:
SelectableImageGroup.java
public class SelectableImageGroup {

    private ArrayList<SelectableImage> list;
    private SelectableImage selectedImage;

    public SelectableImageGroup(){
        list = new ArrayList<>();
    }

    public void add(SelectableImage selectableImage){
        list.add(selectableImage);
    }

    public void setSelectedImage(SelectableImage selectedImage){
        if(this.selectedImage == selectedImage)return;
        if(!list.contains(selectedImage))throw new IndexOutOfBoundsException();
        if (this.selectedImage != null) {
            this.selectedImage.setSelected(false);
        }
        selectedImage.setSelected(true);
        this.selectedImage = selectedImage;
    }

    public void setSelectedPosition(int position){
        SelectableImage selectedImage = list.get(position);
        setSelectedImage(selectedImage);
    }

    public ArrayList<SelectableImage> getArray(){
        return list;
    }
}

Agora é só implementar a ListView da forma habitual.
Adapter: SelectableImageGroupAdapter.java
public class SelectableImageGroupAdapter extends ArrayAdapter<SelectableImage> {

    private final LayoutInflater layoutInflater;
    private final Context context;
    private final int listItemResource;
    private final SelectableImageGroup selectableImageGroup;

    public SelectableImageGroupAdapter(Context context, int listItemResource,
                                       SelectableImageGroup selectableImageGroup) {
        super(context, listItemResource, selectableImageGroup.getArray());

        this.context = context;
        this.listItemResource = listItemResource;
        this.selectableImageGroup = selectableImageGroup;
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = convertView;
        if(view == null){
            view = layoutInflater.inflate(listItemResource, parent, false);
        }

        final SelectableImage selectableImage = getItem(position);
        ImageView imageView = (ImageView)view.findViewById(R.id.image);
        imageView.setImageResource(selectableImage.getImageResource());

        //Ver nota
        /*imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectableImageGroup.setSelectedImage(selectableImage);
                notifyDataSetChanged();
            }
        });*/

        return view;
    }
}

Layout da Activity: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

Cada item da ListView tem de ter uma ImageView
Layout do item: list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Para usar:
public class MainActivity extends AppCompatActivity {

    private SelectableImageGroup selectableImageGroup;
    private SelectableImageGroupAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        selectableImageGroup = new SelectableImageGroup();
        selectableImageGroup.add(new SelectableImage(R.drawable.imagem1,
                                                     R.drawable.imagemselecionada1));
        selectableImageGroup.add(new SelectableImage(R.drawable.imagem2,
                                                     R.drawable.imagemselecionada2));
        selectableImageGroup.add(new SelectableImage(R.drawable.imagem3,
                                                     R.drawable.imagemselecionada3));
        selectableImageGroup.add(new SelectableImage(R.drawable.imagem4,
                                                     R.drawable.imagemselecionada4));
        selectableImageGroup.add(new SelectableImage(R.drawable.imagem5,
                                                     R.drawable.imagemselecionada5));

        ListView listView = (ListView)findViewById(R.id.listView);

        adapter = new SelectableImageGroupAdapter(this,
                R.layout.list_item, selectableImageGroup);

        listView.setAdapter(adapter);

    //****  Ver nota ******
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectableImageGroup.setSelectedPosition(position);
                adapter.notifyDataSetChanged();
            }
        });
    //*********************
    }
}

Nota:
Da forma como está o código o que faz alternar entre o estado seleccionada e desseleccionado é um clique na linha da ListView.
Se quiser que essa alternância seja apenas efectuada ao clicar na ImageView,  "comente" o código indicado na Activity e "descomente" o código indicado no adapter
Comment: Deu certo! Muito obrigada!


Improving (piano) aural transcription

Question: Every once in a while I try to figure out how to play a song on piano. I can get the melody, rhythm, and I can usually figure out the chords, but I have a hard time figuring out which chord notes are present.
To be a little more concrete, maybe I can tell that the top note is an E and that it's an A minor chord, but sometimes I can't even tell how many of the chord notes are being played (let alone which notes they are). It's even harder if the recorded piano doesn't have the same sound as my own piano
Is this just something that improves with practice, or are there a few tips to improve my transcription accuracy?
Answer: Aural transcription is a good way to improve your ear! You can also try to play along to easy pop songs, but I can give you some other tips:

if you play, study and sing intervals, chord theory, and chord progression, the knowledge of chords will improve your ear training, as we hear what we know.

Sing and play e.g. the  cadence I-IV-V-I as arpeggio, also all triads and tetrads in relation to their solution, the same with circles of V7 chords or ii7-V7 chains.
2 other helps will:

be play along to  midifiles, you can slow down the tempo and you can see the keyboard or the the sheet transcription.
play along to songs on youtube e.g. with piano roll or videos where they show the keys of the keyboard or the sheetmusic. You can first play by ear and then control by looking at the video and compare your solution with the original music. You can also control the speed by slowing down to 25%.
Answer: If you know it is an a minor chord, then you should know that the notes are a-c-e.
You mentioned that you sometimes hear that the E is the top note. Being able to tell what notes are present will come with practice. The period of time the music was written in may also help you determine if there might be a 7th in the chord. Remember that the 7th in a chord will add a bit of dissonance between it and the 8th (a.k.a. the root). Composers during the 16th and 17th centuries avoided dissonance as much as possible. So, the likelihood of having a chord with a 7th is lower in music of the aforementioned periods.
A good way to practice listening for the chordal notes would be to play an 'A' and then play the note 'C'. Next, play them together. Get accustomed to the various intervals and how the two notes sound together. Now play the 'A' and play the 'E'. They make a Perfect 5th. Play them together. Memorize what they sound like together.  The more you do this, the easier it will be to hear the notes of the chord. When you start playing on the piano, after a bit you should be able to pick them out. The internet most likely has interactive exercises for practice use. Try googling "interactive pitch identification".

Improving (piano) aural transcription


Allow FAPI checkboxes to specify some options as disabled

Question: I want to disable a single checkbox in a checkboxes FAPI element.
<?php

namespace Drupal\fapi_example\Form;

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

class SimpleForm extends FormBase {

  /**
   * Build the simple form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['checboxes'] = [
      '#type' => 'checkboxes',
      '#options' => [
        'A' => $this->t('A'),
        'B' => $this->t('B'),
        //I want C allway check and disable.
        'C' => $this->t('C'),
        'D' => $this->t('D'),
      ],
      '#default_value' => array('C'),
      //Follow topic https://www.drupal.org/node/284917. But don't work
      //'#disabled_values' => array('C'),
      '#title' => $this->t('Title Checkboxes'),
    ];

    return $form;
  }

  /**
   * Getter method for Form ID.
   */
  public function getFormId() {
    return 'form_checkboxes';
  }

  /**
   * Implements a form submit handler.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

}

I try to follow this topic but its not working (8.1.x), and tried to search in google but it just
solve in Drupal 7. So How can I disable a single checkbox in a 'checkboxes' FAPI element?
Comment: Please provide the code you've come up with that isn't working. That will help others answer your question.
Answer: I find a way. Add option process in define form type.
<?php

namespace Drupal\fapi_example\Form;

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

class SimpleForm extends FormBase {

  /**
   * Build the simple form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['checboxes'] = [
      '#type' => 'checkboxes',
      '#options' => [
        'A' => $this->t('A'),
        'B' => $this->t('B'),
        //I want C allways check and disable.
        'C' => $this->t('C'),
        'D' => $this->t('D'),
      ],
      //Add options process
      '#process' => [
        array($this, 'processCheckboxes'),
      ],
      '#default_value' => array('C'),
      //Follow topic https://www.drupal.org/node/284917. But don't work
      //'#disabled_values' => array('C'),
      '#title' => $this->t('Title Checkboxes'),
    ];

    return $form;
  }

  /**
   * Process checkboxes
   */
  public static function processCheckboxes(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = is_array($element['#value']) ? $element['#value'] : array();
    $element['#tree'] = TRUE;
    if (count($element['#options']) > 0) {
      if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
        $element['#default_value'] = array();
      }
      $weight = 0;
      foreach ($element['#options'] as $key => $choice) {
        if ($key === 0) {
          $key = '0';
        }
        $weight += 0.001;

        $element += array($key => array());
        $element[$key] += array(
          '#type' => 'checkbox',
          '#title' => $choice,
          '#return_value' => $key,
          '#default_value' => isset($value[$key]) ? $key : NULL,
          '#attributes' => $element['#attributes'],
          '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
          '#error_no_message' => TRUE,
          '#weight' => $weight,
        );

        if ($key == 'C') {
          $element[$key]['#disabled'] = TRUE;
          $element[$key]['#default_value'] = $key;
        }
      }
    }
    return $element;
  }

  /**
   * Getter method for Form ID.
   */
  public function getFormId() {
    return 'form_checkboxes';
  }

  /**
   * Implements a form submit handler.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

}

It's working but i think FAPI allow options disable some value is better.


SOLR: What does an autoSoftCommit maxtime of -1 mean?

Question: Here's the default setting from my solrconfig.xml file:
 <autoSoftCommit>
   <maxTime>${solr.autoSoftCommit.maxTime:-1}</maxTime>
 </autoSoftCommit>

Does the maxTime of '-1' mean that automatic soft commits are off? If so, would I get the same result if I deleted the tag altogether? And if I have to manually do the soft commits, can that be done with 'commitWithin' (I googled this but got conflicting answers)?
Oh, and I'm using Solr 4.5.0
Answer: First off, you can see the expression ${solr.autoSoftCommit.maxTime:-1} within the tag. This allows you to make use of Solr's variable substitution. That feature is described in detail here in the reference. If that variable has not been substituted by any of those means -1 is taken as value for that configuration.
Turning commitMaxTime  to -1 effectively turns autocommit off. If you have a look at the relevant code below, you can see that commitMaxTime overrules any value of maxDocs, as the scheduleCommitWithin method returns immediately. I have not found this behaviour documented, so I looked up the code.
private void _scheduleCommitWithin(long commitMaxTime) {
    if (commitMaxTime <= 0) return;
    synchronized (this) {
      if (pending != null && pending.getDelay(TimeUnit.MILLISECONDS) <= commitMaxTime) {
        // There is already a pending commit that will happen first, so
        // nothing else to do here.
        // log.info("###returning since getDelay()==" + pending.getDelay(TimeUnit.MILLISECONDS) + " less than " + commitMaxTime);

        return;
      }

      if (pending != null) {
        // we need to schedule a commit to happen sooner than the existing one,
        // so lets try to cancel the existing one first.
        boolean canceled = pending.cancel(false);
        if (!canceled) {
          // It looks like we can't cancel... it must have just started running!
          // this is possible due to thread scheduling delays and a low commitMaxTime.
          // Nothing else to do since we obviously can't schedule our commit *before*
          // the one that just started running (or has just completed).
          // log.info("###returning since cancel failed");
          return;
        }
      }

      // log.info("###scheduling for " + commitMaxTime);

      // schedule our new commit
      pending = scheduler.schedule(this, commitMaxTime, TimeUnit.MILLISECONDS);
    }
}

Taken from https://github.com/apache/lucene-solr/blob/lucene_solr_4_5/solr/core/src/java/org/apache/solr/update/CommitTracker.java
To the second part of your question, if you remove the tag all together this will have the same result as setting the value to -1. As you can see below, if the xpath expression returns null, you will get -1 as default value.
But removing the whole expression from the configuration will also remove the option to override that configuration via Solr's variable substitution.
protected UpdateHandlerInfo loadUpdatehandlerInfo() {
  return new UpdateHandlerInfo(get("updateHandler/@class",null),
    getInt("updateHandler/autoCommit/maxDocs",-1),
    getInt("updateHandler/autoCommit/maxTime",-1),
    getBool("updateHandler/autoCommit/openSearcher",true),
    getInt("updateHandler/commitIntervalLowerBound",-1),
    getInt("updateHandler/autoSoftCommit/maxDocs",-1),
    getInt("updateHandler/autoSoftCommit/maxTime",-1),
    getBool("updateHandler/commitWithin/softCommit",true));
}

Taken from https://github.com/apache/lucene-solr/blob/lucene_solr_4_5/solr/core/src/java/org/apache/solr/core/SolrConfig.java


How do I use Mod-rewrite to clean URLs?

Question: I've been playing with Mod-Rewrite to try clean up my url's but haven't had much luck with any code I've found.
My current url looks like this:
http://www.mysite.com/id?u=1&id=wwo4955838_1917151587_n.jpg

But I am trying to achieve this:
http://www.mysite.com/id/wwo4955838_1917151587_n.jpg

I've not managed to achieve it so far my current code is
 RewriteRule  ^id$ index.php?load_page=id [NC,L,QSA]

Does anyone have any suggestions?
HTACCESS- so far
# 1 ---- Establish a custom 404 File not Found page ----

ErrorDocument 404 /filenotfound.php

# 2 ---- Prevent directory file listing in all of your folders ----

IndexIgnore *

# 1 ---- Rewrites Pages And Content----

 RewriteEngine On

 RewriteRule  ^home$ index.php?load_page=home [L]
 RewriteRule  ^meme$ index.php?load_page=meme [NC,L,QSA]
 RewriteRule  ^memesingle$ index.php?load_page=memesingle [NC,L,QSA]
 RewriteRule  ^id$ index.php?load_page=id [NC,L,QSA]

Comment: This is the only code you have in your htaccess file?
Comment: Hi- Ive made an edit now- I apolgise, I should have been clearer!
Comment: The other rules are working for you?
Comment: Yerp they seem to working just fine.
Answer: Try this:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^id/([^/]+)/?$ /id?u=1&id=$1 [L,NC,QSA]

You should enter your url like this:
http://www.mysite.com/id/wwo4955838_1917151587_n.jpg

Comment: Hey I had ago adding the new Rewrite rule- but I'm just getting Not Found

The requested URL /id was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Comment: Your current url in your question is already rewrite with some rule?
Comment: Nope- I replaced "RewriteRule  ^id$ index.php?load_page=id [NC,L,QSA]" with your new code.   I will keep trying and let you know if I figure it out?
Comment: Okay so I've managed to get it to work using this - "RewriteRule  ^id/([^/]+)/?$ index.php?load_page=id [NC,L,QSA]"   But now none of my CSS or images work because it see /id/ as a directory. If you have any advice on this it would be much appreciated! ?
Comment: correct Id isn't a directory - for some reason your code dosnt work for me. The only code that has worked is- RewriteRule  ^id(/|$)([^/]+)/?$ index.php?load_page=id [NC,L,QSA] and this still has the problem of ID/ being read a directory
Comment: I've managed to get it all working now- I've added a a / on my css links which has synced everything. thankyou for your help Rahil much appreciated.

How do I use Mod-rewrite to clean URLs?


Problemas com join laravel ORM

Question: Olá,
Estou tentando criar uma query avançada, mas estou tendo alguns problemas segue o código para análise!
Anuncio::join('users', function ($users) use ($request){
        $users->on('users.id' , '=', 'a.user');
    })->join('enderecos', function ($enderecos) use ($request){
        $enderecos->on('enderecos.id', '=', 'users.endereco');
    })->where('enderecos.uf_id', '=', $request['uf_id'])->get();

A query acima funciona perfeitamente, mas quando tento adaptar ela a um outro grupo de filtros ela não funciona e da erro!
Segue o outro grupo de filtros:
$anuncios = Anuncio::where(function($query) use ($request)
    {
        if(isset($request['uf_id'])){
            $query->join('users', function ($users) use ($request){
                $users->on('users.id' , '=', 'a.user');
            })->join('enderecos', function ($enderecos) use ($request){
                $enderecos->on('enderecos.id', '=', 'users.endereco');
            })->where('enderecos.uf_id', '=', $request['uf_id']);
        }
        if(isset($request['modelo'])){
            $query->where('modelo', $request['modelo']);
        }
        if(isset($request['marca']))
            $query->where('marca', $request['marca']);
    })->with('anuncio_dados')->with('adicionais')
        ->with('anuncio_imagens')->with('versaos')
        ->with('marcas')->with('modelos')->paginate(10);

Quando tento inserir ele nesta query, o filtro de uf_id não funciona. Alguém sabe me dizer o por que?
Comment: Primeira coisa os `joins` podem ser simplificados já visto que você não usa $request nem $users ( e outros) dentro pode ser somente a passagem de valores. Outro ponto: `quando tento inserir ele nesta query o filtro de uf_id não funciona. alguem sabe me dizer o por que?` porque, o erro aparece o que?
Comment: Existe a coluna `uf_id` dentro de enderecos?
Comment: Achei o problema, você não pode fazer where com `join` ... você precisa fazer tudo separado, utilizando sempre a última versão do builder coletada!
Comment: o erro que da é esse message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'enderecos.uf_id' in 'where clause' (SQL: select count(*) as aggregate from `anuncios` as `a` where (`enderecos`.`uf_id` = 15))"
Comment: sim, e como mencionei no post o que me deixou sem saber o que fazer, é que na primeira query o retorno é valido!
Comment: Gratidão pela sua ajuda, mas como seria isso? fiquei com duvida de como fazer!
Answer: Basicamente o código abaixo resolve, a observação é que dentro de where não pode fazer um join faça separado utilizando sempre a última versão da instância do builder fazendo as criticas e passando o novo valor para a mesma variável, exemplo:
$builderAnuncions = Anuncio::join('users', 'users.id', '=', 'anuncios.user')
                        ->join('enderecos', 'enderecos.id','=','users.endereco');

if(isset($request['uf_id']))
{
    $builderAnuncions = $builderAnuncions->where('enderecos.uf_id', '=', $request['uf_id']);
}
if(isset($request['modelo']))
{
    $builderAnuncions = $builderAnuncions->where('modelo', $request['modelo']);
}
if(isset($request['marca']))
{
    $builderAnuncions = $builderAnuncions->where('marca', $request['marca']);
}

$builderAnuncions
    ->with('anuncio_dados')
    ->with('adicionais')
    ->with('anuncio_imagens')->with('versaos')
    ->with('marcas')
    ->with('modelos')
    ->paginate(10);

Answer: Pelo que eu entendi, você está montando a query de forma incorreta.
Tente seguindo o exemplo abaixo onde eu seleciono anúncios com nome da marca começando com a letra F e incluindo a marca do veículo no resultado.
$query = Anuncio::join('marcas', 'marcas.id', '=', 'anuncio.marca_id')->where('marcas.nome', 'like', 'F%')->select(['anuncios.*', 'marcas.nome']);

Comment: Obrigado pela ajuda Junior, consegui resolver com o exemplo acima do Virgilio Novic!

Problemas com join laravel ORM


Determine which VIF interface belong to which Xen domain on SLES12.1

Question: As mentioned I have a list of Xen Domain as below:
Vm01
Vm02
Vm03
Vm04

And using bright network for communicating outside, After I launched 4 VM it automatically created 4 vif interface, but now I can not determine which interface is belong to which machine.
I am installing Xen hyper on Sles12.1 with kernel is: 3.12.62-60.62-xen
Could someone help me on this case, as I am a newbie in Xen :(.
Thank in advance...
Answer: Very simple that the vif interface name is the base on the domain id:
# virsh list --all
 Id    Name                        State
 0     Domain-0                    running
 12    xen_vm127                   running
 13    xen_vm126                   running
 14    xen_vm125                   running
 16    xen_vm123                   running
 17    xen_vm124                   running

:~ # ip a
23: vif12.0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master br1 state UNKNOWN group default qlen 512
link/ether fe:ff:ff:ff:ff:ff brd ff:ff:ff:ff:ff:ff
24: vif13.0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master br1 state UNKNOWN group default qlen 512
link/ether fe:ff:ff:ff:ff:ff brd ff:ff:ff:ff:ff:ff
25: vif14.0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master br1 state UNKNOWN group default qlen 512
link/ether fe:ff:ff:ff:ff:ff brd ff:ff:ff:ff:ff:ff
27: vif16.0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master br1 state UNKNOWN group default qlen 512
link/ether fe:ff:ff:ff:ff:ff brd ff:ff:ff:ff:ff:ff
28: vif17.0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master br1 state UNKNOWN group default qlen 512
link/ether fe:ff:ff:ff:ff:ff brd ff:ff:ff:ff:ff:ffenter code here


How can I determine odd time signature when listening to music?

Question: I try to understand odd time by listening to the underlying pulse and the duration of notes, but it doesn't always work when the rhythm gets complicated.
What I mean is visualising the pulse as the duration of an eighth note etc. and to make sure the beats I'm counting stop exactly as the bar stops and move on to the next bar.
Often times, it's not easy to decide whether the song is a 13/8 or 13/16 because sometimes the change on tempo counfuse me.
Comment: Why not track down the sheet music?
Comment: This has been well and truly Doktored! Hardly the same question, not sure if that's what the OP wanted?
Comment: At least after the edit, this question sounds more generic than trying to transcribe a specific song to me. Note generic-sounding phrases like "Often times, it's not easy to decide whether the song is a 13/8 or 13/16".
Comment: I have made further edits - I think this is now okay.
Comment: This is a lot easier to do with some software designed for transcribing music, like https://www.seventhstring.com/xscribe/overview.html. Just slow down the tempo, tap out the pulses on your mouse to put visual markers alongside the audio track, then count them up and mark the bars and beats at your leisure - and change your mind as often as you want, till your rhythm makes sense.
Comment: @alephzero - how have people managed for the last few hundred years before computers came along to do almost everything for them? Next, they'll be wiping our...
Answer: It's unusual for a whole song to be in 13/something - unless it's Greek, from experience. But x/8 and x/16 are rather different in that one is twice as fast, given the same bpm.
Do you mean there might be a 13/x bar somewhere in a piece? If so, it's pretty rare, bu if it is, it'll be counted something along the lines of 1231231231234. Even the humble 5/4 is split into 3+2, or 2+3. There will inevitably be divisions of 2,3 or 4, in a regular pattern.
As an aside, the piece you mentioned initially may be 4/4, 4/4, 7/4 from a brief hearing...
Answer: The distinction between 13/8 and 13/16 or 13/4 is probably not easy to distinguish, somewhat of a preference.  You should definitely be able to tell 12/8 from 13/8.  The song has to express the time signature in the melody, in the phrasing, if not in an obvious rhythmic pattern.
If you're trying to transcribe the piece what works for me is trying to find shortest division of time, fastest "beat" then try to count how many of that beat I tap before a phrase or riff repeats.  But whether you call that beat an 8th note or 16 note is really up to you, there is some room for choice here.  Different musicians may write the same piece in 8ths and some in 16ths.  Once you get the fast beat fitting try dividing in half and see if you still end on the end of a phrase.  With practice you learn to hear entire phrases.  If there is a tempo change then you need to divide the song in pieces (as if it were two songs) and apply the procedure to each piece then put it together.  I'm guessing my the 13/8 you are not looking at a simple waltz.  Keep in mind that the artist may be playing notes faster than the beat definition.  So you may tap 26 at first (which is an even number) but if you can track the phrases in 13 you have a measure if 13/something (you are free to call that something and 8th or a quarter note if you like).  Many time signatures like 5/4 and 7/8 are divided up into shorter groves (at Tim indicated in his answer).  If you listen to a lot of Rush you get good at identifying 7/8. And they will sometime toggle between 7 and 6 which adds to 13.