Proper analysis for vernal pool study data

Question: I am trying to analyze a dataset consisting of counts of amphibian egg masses (3 different species) in nine vernal pools over a four-year period (consecutive years, 2014 to 2017). During each count (one per year), data were also collected on pool area, pool depth, pH, and conductivity. Initially, I did a standard ANOVA to determine whether pool (9 of them), year, area, depth, pH or conductivity were predictors of egg mass numbers in the pools. I was told (by journal manuscript reviewers) that ANOVA was not an appropriate analysis (because of the single value for each combination of factors, which I agree with), and they suggested two alternatives:

Multiple linear regression or similar model that allows for continuous and categorical variables (new variables could be added, such as percent surrounding forest, distance to nearest pool, any surrounding development, or low/high development pressure), both to be included as opposed to univariate correlations that can mask complex relationships among independent variables.
Because the same ponds were sampled repeatedly, samples from the same pond in multiple years are not independent replicates.  Recommend a repeated measure ANOVA, averaging all the years for each pool and just analyze the data for pool averages.

Please note that sample sizes are small (9 pools, 4 years), so any analysis may not have much statistical power. But even a finding of no effect would have meaning for the study.
Any thoughts on appropriate tests/approaches (these suggested ones or others) would be appreciated.

Additional Update:
Thanks for the responses. The Bayesian approach is probably the proper one, but I don't think I'm willing to put in the background work to understand/apply it, at least for this project. I'll likely take a crack at the multilevel (mixed?) model, with one IV (independent variable?) for each model, as Peter Flom suggests. I assume that this means running multiple separate models? Some clarification (and maybe appropriate routine/package in R) would be helpful.
The "hypothesis" here is that at least one of the independent variables affects total egg mass counts for a pool. From some preliminary analyses, I already know there is a significant correlation (Spearman) of pool size (area) with counts (the bigger the pool, the more egg masses), so that's one. I'm just looking to verify that with a model (or models, multilevel/hierarchical or otherwise) with which I can also analyze other variables. Perhaps a single model is not appropriate for these data, as mkt points out.
Basic visualization of the data may be all that's needed, but I've found that most journals these days find that insufficient and want hard stats to back it up.
Comment: Isn't the sample 3 species $\times$ 9 pools $\times$ 4 years? Do you plan to fit a separate model for each species? Are you also considering one "grand" model for the three species at once, in which case they might share at least the "year" component and more generally some/all of the environmental variables.
Comment: I *didn't* say that a single model is not appropriate - merely that a complex model is unlikely to tell you much when the data is so limited.
Answer: While I 100% agree with Peter Flom's answer (+1), I personally think you should drop the null hypothesis testing approach for this project. This advice is notwithstanding what you can convince your editor is reasonable.
Instead, I would develop a Bayesian mixed effects model. With a Bayesian analysis you will/should spend substantial amounts of time considering your choice of prior and likelihood, but there are no hard constraints on sample size per se. However, with small sample size you should expect that with weak priors you will have large standard errors. That's fine provided that you are okay with being imprecise if that is all your background knowledge (encoded into priors) and the data can support.
If you have insufficient clarity about what I just suggested due to Bayesian inference being unfamiliar to you, I recommend watching Richard McElreath's Statistical Rethinking lectures and then reading Gelman et al 2020.

(I am not retired and sometimes take small modelling projects on the side. I can be found if you look hard enough.)
Answer: Another approach is Bayesian canonical polyadic decomposition (BCPD), which is generally considered to be an exploratory method. You would start with the notion that your data array $\mathcal{A}$ can be decomposed as a linear combination of tensor products:
$\mathcal{A} = \sum_{k=1}^r \lambda_k \bigotimes_{j=1}^h \vec X_{k,j}$
See Tamara G. Kolda: "Tensor Decomposition"
 for a (non-Bayesian) explanation of canonical polyadic decomposition and some of the visualization techniques. For a Bayesian version of those decomposition plots you can either plot the MAP values or make a contour or surface plot of the posterior. For a more detailed review of tensor decomposition, I suggest the landmark paper Kolda & Bader 2009.
The gist of CPD is signal separation according to different combinations of levels of factors. Why I like BCPD is for encoding background information and imputing missing values.
Offhand I don't know of a package that does this, especially with customizable priors. But it can be readily built using probabilistic programming packages (PyMC, Stan, etc). At some point I should package my own code to share.
Comment: +1 for the lecture link.
Answer: Your journal reviewers seem ... confused.
Multiple linear regression will not solve the problem of having a single value for each set of factors. In fact, linear regression and ANOVA are mathematically the same. In matrix form, both are given by $Y = XB + e$.
If you average all the years for each pool, then you no longer have repeated measures, and this lowers your N to 9 (the number of pools).  Either you do RM-ANOVA or you average for each pool, but you can't do both.
In addition, RM-ANOVA makes unrealistic assumptions, including sphericity. A multilevel model would be better. Also, you have five independent variables. That's too many for the amount of data.
Finally, your last paragraph is troubling. If you have low power, then a finding of a non-significant effect is not very meaningful, because only a very large effect would be significant. HOWEVER, if you find small effects, then that may be meaningful. Small sample size does not bias the estimates, it just makes them imprecise.
I think what I would do in your situation is  multilevel models with one IV for each model. But you may need to hire a statistical consultant to help you with this. (Not me, I'm retired).
Answer: The multilevel/hierarchical models suggested by Peter Flom and Galen are the best solution, in the technical sense. But given your small sample size (9 points, 4 years, 6-10 predictors), and your apparent lack of a specific goal (such as a parameter to estimate or a  hypothesis to evaluate), I'd consider instead a simple descriptive/exploratory analysis.
It's not obvious that the hierarchical model will tell you a whole lot more than some basic visualisation. And the hierarchical models will be much more complex to execute and to interpret if you and your audience are unfamiliar with them.
UPDATE based on the addition to the question:
About journals wanting 'hard stats to back it up': you may be right, but statistics doesn't solve the basic problem here. Any model you could feasibly come up with is going to be a vast oversimplification of the true causal network. Among other things, there's plenty of important unmeasured variables - predation pressure perhaps being the most important. And the weak observational design will not allow a model to provide strong evidence for any causal claims. Some evidence of association based on a model may be useful, but there aren't going to be any 'hard stats' you can point to with confidence. This is why I think a descriptive analysis is a good option - it's simple and the limitations aren't buried under model complexity.
Answer: Not my area of expertise (limnology, amphibians, or statistical models), but I seem to recall a friend having a similar problem (except with kidney transplant survival data) and he basically fed his data into a few different machine learning frameworks and then pried the lid off the top of the black box and was able to pick out predictors and levels of significance. Depending on the ML framework, e.g. a Bayesian classifier, might have similar results.  I will leave it to others to comment on the post-hoc extraction of measures of association and prediction from ML libraries.
I think there is another, probably totally off-topic for a stats forum, perspective that I am surprised the reviewer didn't mention.
Others commented on the problems w/ having a data set of non-independent (see below) measurements w/ only 9 sites × 4 years, where there are likely significant unmeasured differences, e.g.  temperature in the weeks leading up to the sample time, rainfall--and timing is key here, changes in predator species (which may be highly localized), spread of pathogens, or even a change in what brand of pesticide the local farmer is using, etc. would all have potential to confound the crap out of the data.
So I think the first thing would be to back up a bit and just look at the data and see if there is a story to tell.  You didn't mention what the data actually showed.
I don't think you can use year as a separate variable either, as I don't recall frogs living all that long...so while it is a separate sample w/ a different set of variables, it is only a rough proxy of comparable conditions between your sites, assuming they are in the same general area and elevation.  If they are ponds up in the mountains at different elevations, then they very well could have markedly different temperature and precipitation profiles.
Most ponds in areas w/ sedimentary rock underlying a decent layer of soil are roughly a spherical cap (or a spherical segment if the sediment has truncated the water column to a frustum) has a volume $\mathrm V = \frac{1}{6}\pi h (3a^2 + h^2)$.  a=area, h=depth
Since both pH and conductivity (which you didn't mention the range) depend on the volume of water in the pond (as well as runoff) these variables are inherently linked--not just by chance, but intrinsically so.
Finally, you didn't mention the year-to-year, pond-to-pond variability. Obviously, your stochastic noise level is pretty high to begin with.  One thing you didn't mention, but what you can actually get your hands on is the actual weather data which you might want to try and figure into your analysis as the temperature, rainfall, and to a lesser extent, wind and cloud cover, will impact the water balance which frogs are rather particular about.
If you know the location of the ponds, you can probably pull up enough GIS data to get an idea of land use--but it won't tell you how much organochlorine and other hormonal disruptive pesticides were used year to year (although it should be less in each, we hope).
I know that isn't the answer to the "what statistical model do I use" question, but might help you answer the "how do I make sense of this data" question.
Comment: "*he basically fed his data into a few different machine learning frameworks and then [...] was able to pick out predictors and levels of significance.*" Leaving aside the problematic phrase "levels of significance", you will not obtain inferences of statistical significance without distributional assumptions. At that point, you might as well go back to classic statistical models since the [change of variables](https://en.wikipedia.org/wiki/Probability_density_function#Function_of_random_variables_and_change_of_variables_in_the_probability_density_function) for most ML models [...]
Comment: [...] becomes infeasible to work out. And since we do not have IID assumptions, you cannot just bootstrap a p-value from retraining your ML model on resamplings of the data. Furthermore, ML models often have parameters which cannot be readily coupled to human-understandable hypothesis.
Comment: I think the key is that ML models are not totally obscure.  The value was the ability to pick out, from the mess of data that is a transplant patient's record, what was _important_ and _non-random._  Again, it was about 12 years ago when he presented his work, so I am hoping that someone who works w/ various ML models--again, generalizations about "often" but rather looking for a particular ML--I want to say he was using a Bayesian network with kernel density estimation, but, as I mentioned, I was hoping to prompt someone who might be able to comment on the specifics, rather than just "most".
Comment: That doesn't have anything to do with the underlying problem when dealing with a small amount of information which is not independent and I don't have quite the statistical intuition to make any sort of recommendation without knowing what the data actually looks like.
Comment: A Bayesian network is explicitly a probability distribution, representing a factorization of a joint distribution using the chain rule of probability, which relates to what I was saying about distributional assumptions being required to make inferences of statistical significance. Used in conjunction with KDE this makes the inference a nonparametric statistical procedure. There are no specifics to comment on unless they are provided, and without them there are too many possibilities to consider or discuss.
Comment: Since you mentioned Bayesian networks, they *can* be used to model some forms of non-independence among observations.
Comment: I think what we know is there is an outcome variable of interest ( 4×9×3 measures of nascent tadpoles) and a data set which is thought to be predictive, but which really has two known variable (we don't know if the ponds are so similar as to make the between pond difference unimportant, I suspect the year to year variability may be much greater than between if they are separate ponds in a connected wetland ecosystem) but the measurements of pH and conductivity (which may, or may not be corrected to account for [H⁺]) both are numerators over the volume of water in the pond.
Comment: I think the biggest problem in making any recommendation about what direction to go is that we have no idea what happened.  While I am asked to do so on a regular basis, I find making bold decisions w/ no idea of what the results of the tests show best left to politicians, as they don't seem to suffer from the same lack of certainty in the face of a paucity of evidence.  Hopefully, we will find out what happened to the frogs in another installment.
Comment: Obviously, if pH/conductivity is just reflective of how much water is in the pond, or the frogs do different things in identical ponds the math gets easier.


Stargazer mudando a posição da variavel dependente

Question: Considerando as regressões quantílicas.
library(quantreg)

> x=rnorm(100,12,2)
> y=rnorm(100,0,4)

a<-rq(y~x,tau = .10)
b<-rq(y~x,tau = .15)
c<-rq(y~x,tau = .20)
d<-rq(y~x,tau = .25)

Como eu só tenho uma constante e uma variável explicativa eu gostaria de colocar como colunas X e a constante, ou seja, "transpor" o resultado que o pacote stargazer me oferece, que é o oposto desse aqui:
stargazer(a,b,c,d,title="Regression Results",align=TRUE, dep.var.caption="",model.numbers=TRUE,intercept.bottom=FALSE,font.size="scriptsize",keep.stat="aic",dep.var.labels="",multicolumn=TRUE,ci=TRUE,ci.level=0.90,dep.var.labels.include=TRUE)

O stargazer gera uma tabela assim:

O que eu quero é que cada tau esteja nas linhas, tendo, assim, uma tabela com tau´s linhas e 2 colunas.
Há como?
Comment: Olá Diogo. Dica importante pra facilitar que você tenha ajuda mais rapidamente/facilmente: construa e disponibilize um [mcve].
Answer: Difícil deixatr tão completa quanto a tabela produzida pelo stargazer, se você puder simplificá-la, pode fazer assim:
modelos <- list(a,b,c,d)
param <- plyr::ldply(modelos, function(x) coef(x))
param <- cbind(data.frame(tau = seq(0.1, 0.25, by = 0.05)),
               param)

xtable::xtable(param)

Ele produzirá o seguinte Latex
% latex table generated in R 3.2.1 by xtable 1.8-2 package
% Mon May 23 15:34:54 2016
\begin{table}[ht]
\centering
\begin{tabular}{rrrr}
  \hline
 & tau & (Intercept) & x \\
  \hline
1 & 0.10 & -12.75 & 0.61 \\
  2 & 0.15 & -9.13 & 0.41 \\
  3 & 0.20 & -7.15 & 0.29 \\
  4 & 0.25 & -5.52 & 0.19 \\
   \hline
\end{tabular}
\end{table}

Que compilado dá essa tabela:

Lembre-se de ter instalado os pacotes plyr e xtable, usando install.packages("nome_do_pacote").
O xtable possui diversas opções de configuração da tabela, você pode dar uma olhada neste link para saber mais.


Erro ao copiar arquivos entre servidores

Question: Estou copiando arquivos via rsync entre dois servidores linux, o comando que estou utilizando é:
rsync -Cravzpt --remove-source-files --exclude 'script.sh' --exclude 'index.php' /var/www/html/bkpserver/tarefario email@example.com:/var/www/html/

Mas quando executo esse comando, ele pede senha do root e após alguns segundos, apresenta o seguinte erro:
ssh: connect to host xxx.xxx.xxx.xxx port 22: Connection refused
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(226) [sender=3.1.1]

Eu não faço a mínima ideia do por que está tendo esse erro, pois tenho exatamente o mesmo comando em mais 3 servidores diferentes e copiando para o mesmo servidor de destino e todos funcionam.
Comment: Essa pergunta não é sobre programação. Deve ter outra comunidade do SO que lá com isso.
Comment: @ThiagoLunardi  A pergunta não é de programação.
Comment: @ThiagoLunardi Dei o enter antes da hora, A pergutna não é especificamente de programação mas é sobre servidores ubuntu. Acho que está no escopo.
Comment: Existe o Server fault Stack Exchange
Comment: @ThiagoLunardi Então me diga, que tipo de pergunta pode ser feito nessas tags que ele assinalou? Ubuntu e Servidor. Ora, Ora. :-)
Answer: A mensagem de erro diz que o servidor recusou a conexao, pode ser um firewall bloqueando, um roteador no meio da conexao ou a porta 22 do ssh fechada. Tente o seguinte (exemplos aqui pressupõe o debian ou ubuntu):
1) Veja se o serviço ssh esta ativo
$ sudo /etc/init.d/ssh status
[sudo] senha para sidon:
● ssh.service - OpenBSD Secure Shell server
   Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
   Active: active (running) since Qui 2017-07-20 08:27:25 BRT; 4h 36min ago
  Process: 1896 ExecReload=/bin/kill -HUP $MAINPID (code=exited, status=0/SUCCESS)
 Main PID: 1145 (sshd)
    Tasks: 1
   Memory: 1.4M
      CPU: 23ms
   CGroup: /system.slice/ssh.service
           └─1145 /usr/sbin/sshd -D

Observe a linha Active: active (running)...
2) Se estiver rodando, verifique em que porta:
~$ sudo cat /etc/ssh/sshd_config | grep Port
Port 22

3) Veja se a porta esta aberta:
sudo netstat -pln | grep '22'
tcp        0      0 0.0.0.0:22          0.0.0.0:*           OUÇA   1145/sshd
tcp6       0      0 :::22               :::*                OUÇA   1145/sshd

Faça isso no lado servidor que não está aceitando a conexão.
Se tudo isso estiver ok (SSH ativo na porta 22 aberta, sem firewall bloqueando) veja se o servidor esta conectado a um roteador, nesse caso o roteador funciona como, digamos... um intermediário ou mesmo um "firewall", então voce precisa fazer um redirecionamento NAT, ou seja qdo o comando rsync requisita a porta 22, a requisição "bate" no roteador e ele não sabe o que fazer, então vc tem redirecionar a 22 para o ip do servidor.
Comment: Olá, @Sidon, desculpe não lhe dar um retorno antes. Efetuei os testes que você passou nessa resposta, os 3 itens estão ok. Ambos os servidores (o de origem e o de destino) estão hospedados na DigitalOcean e não tem nenhuma configuração de Firewall além das padrões da própria D.O.
Comment: Consegui fazer o rsync rodar via comando direto no putty, mas pela tarefa cron continua o mesmo problema.
Answer: Não estava conseguindo me conectar ao servidor de destino pois o servidor de origem não tinha uma chave RSA. Segui o tutorial "Gerando as chaves SSH e automatizando o acesso" que é encontrado no link:
Backups remotos com rSync e chaves SSH e o backup começou a funcionar normalmente.


In the musical texture "monody", can the underlying harmony be provided with a single voice?

Question: According to these wiki pages
(https://en.wikipedia.org/wiki/Monody
https://en.wikipedia.org/wiki/Homophony),
in Monody, "one solo voice sings a melodic part, usually with considerable ornamentation, over a rhythmically independent bass line."
It is also said on the wiki pages that there is melody dominated homophony where "accompanying voices provide chordal support for the lead voice, which assumes the melody and that Monody is similar to melody-dominated homophony in that one voice becomes the melody, while another voice assumes the underlying harmony."
So, does creating the underlying harmony for a melodic voice require chords (3 voices) or is a single voice enough?
At the bottom, are a couple of monody examples from these two videos:
Comment: Enough for what? Are you not already aware of large amounts of music that is only two voices?
Comment: @ToddWilcox I am trying to learn how a singular voice can be used to shape the harmony for the lead voice. I'm not sure what the term for that would be called within "two part writing" and the closest thing I came by was monody.
Comment: @Lecifer Given your underlying goal, it sounds like my post doesn't answer your "real" question. Is that the case? If yes, please edit your question to include the motivation explicitly, and I'll update my post accordingly.
Comment: @Aaron is it ok to add that to this question or would it be better to try and post it as a completely different question. I know people usually tell me not to ask more than one question, and even with this one I did something wrong to warrant a close vote.
Comment: @Lecifer I suppose in this case it would be better to open a separate post. Perhaps the answer(s) here will inform how you understand and address the underlying issue(s).
Comment: @Aaron The thing is, i'm trying to dissect how playing notes in succession in a first voice (the implied harmony, and the timing of the notes) helps/controls what you can do melodically in a second voice. Would asking something like that be too broad of a question?
Comment: @Lecifer Yeah, that's pretty broad. Here's a way you might start answering your own question: find a lead sheet (melody + chord symbols) and write out the melody plus an accompaniment made up of only chord roots. After doing this a few times, try the same exercise where the accompaniment is only chordal thirds, then only chordal fifths. Finally try writing the accompaniment using the nearest chord tone, regardless which part of the chord it is.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/150561/discussion-between-aaron-and-lecifer).
Answer: The concepts of monody and homophony are describing two different things. Monody is a musical style; whereas, homophony is a musical texture.
Musical textures
There are

Monophony: every voice is in unison or octaves.
Polyphony: multiple voices are independent of each other but of equal value within the music.
Homophony: a single melody with an essentially choral accompaniment, which is to say, the "voices" in the accompaniment need not operate independently of each other, and they play a subordinate role.
Heterophony: multiple voices simultaneously perform variations of the same melody.

Musical style
Monody is a specific style that arose in the early 17th century. It is essentially homophonic. There was a clearly dominant melodic part, as in homophony (and counter to polyphony), and the accompaniment was largely chordal (though it might contain polyphonic elements within itself).
The core innovation of monody was that the accompaniment played a clearly subordinate role to the melody and was often played on a single instrument.
The creation of harmony
The question of how many voices are required to create harmony is again a somewhat separate issue. Harmony can be created (rather, implied) by a single voice. Bach's cello suites are a canonical example of this.
Thus, if one voice can suggest harmony, then a melody with single-voice accompaniment can do so as well. Monody the style would have had a chordal accompaniment (i.e., multi-voiced, but not independent voices), but jazz, for example, might be performed with "just" bass and saxophone, say — an essentially two voice texture (leaving aside chords on the bass or multiphonics on the sax) yet able to express clear harmony.

In the musical texture “monody”, can the underlying harmony be provided with a single voice?


Python: return uma list em formato 2D

Question: Quero usar o __str__ para receber uma list e retorna-la em forma de uma matriz.
Exemplo:
list_exemplo = [[0,1], [2,3]]retornaria como:
[[0, 1],
[2, 3]]

Como faço isso no método __str__?
Comment: Poderia detalhar melhor? Você está implementando alguma classe para poder utilizar a `__str__`?
Answer: como o Anderson ja apontou nos comentarios, vc deve implementar a função __str__, porem oq da a intender na sua duvia é que vc quer um feedback na hora da criação da lista, isso vc ja deve implementar o construtor __init__
class Lista(list):
    def __init__(self, *args):
        super().__init__(*args)
        print(self.__str__())

    def __str__(self):
        return super().__str__().replace('],', ']\n')

a = Lista([[1,2],[3,4]])

esse exemplo ñ é final, acredito que ha formas melhores de se fazer isso
Answer: Se você só quer formatar uma lista de listas na forma de matriz, não precisa criar uma classe pra isso - e aí não precisa de um método __str__ - uma função que receba a sua estrutura de dados é o suficiente.
Agora, implementar uma classe tem outras vantagens: ela permite de fato tratar sua estrutura como uma matriz, e até implementar operações como são definidas para matrizes. Mas não vamos colocar o carro na frente dos bois.
PAra a formatação de impressão, um método fundamental de se entender é o  .join das strings - ele permite que strings que sejam parte de uma lista sejam coladas numa única string, usando a parte que chama o .join como elemento de cola entre elas.
Nesse caso, o elemento de "cola" desejado é uma mudança de linha - para isso usamo so caracter especial \n (line feed). Se quiser apresentar os colchetes iniciais e uma vírgula no final de cada linha, de forma que a saída seja Python válido, pode fazer:
def formata_matriz(matriz):
    return "[{}]".format(",\n".join(str(linha) for linha in matriz))

(Lembre-se que tem que usar um print(...) no resultado dela para que o \n seja expandido para uma mudança de linha:
In [617]: print(formata_matriz([[1,2],[3, 4]]))
[[1, 2],
[3, 4]]

Se quiser algo mais com cara de "matriz" pode deixar de lado os colchetes de fora, as vírgulas no final, usar caracteres de formatação e tabulação da formatação, e o caracter | para delimitar a matriz:
def formata_matriz(matriz):
    return "\n".join("|{}|".format(", ".join(
        f"{elemento:>5.2f}" for elemento in linha)) for linha in matriz)

Nesse caso uso uma f-string, eu faço uso da mini-linguagem de formatação do .format depois do : para garantir alinhamento a direita para os números, com espaço para 5 dígitos, sendo dois depois do . decimal:
In [630]: print(formata_matriz([[1.45,2.3],[23, 4.0]]))
| 1.45,  2.30|
|23.00,  4.00|

Python: return uma list em formato 2D


Serial connection is opening all ports?

Question: I'm creating UART Interface with MFC, the interface include open connection, send message and receive message.
I thought I had opened the port fine, after checking, my D9 connector is sitting over COM5, which opened successfully.
The issue is that even changing the connection from COM5 to the unreasonable COM535, I still didn't received any errors
I've tried several COM port, some reasonable and some not.
This is how I initialize the connection to the bad COM:
<code>Serial::Serial(CString &commPortName, int bitRate)
{
    commHandle = CreateFile(L"\\\\.\\COM535", GENERIC_READ|GENERIC_WRITE, 0,NULL, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED , NULL);

    if(commHandle == INVALID_HANDLE_VALUE)
    {
        throw("ERROR: Could not open com port");
    }
    else
    {
        // set timeouts
        COMMTIMEOUTS cto = { MAXDWORD, 0, 0, 0, 0};
        DCB dcb;
        if(!SetCommTimeouts(commHandle,&cto))
        {
            Serial::~Serial();
            throw("ERROR: Could not set com port time-outs");
        }

        // set DCB
        memset(&dcb,0,sizeof(dcb));
        dcb.DCBlength = sizeof(dcb);
        dcb.BaudRate = bitRate;
        dcb.fBinary = 1;
        dcb.fDtrControl = DTR_CONTROL_ENABLE;
        dcb.fRtsControl = RTS_CONTROL_ENABLE;

        dcb.Parity = NOPARITY;
        dcb.StopBits = ONESTOPBIT;
        dcb.ByteSize = 8;

        if(!SetCommState(commHandle,&dcb))
        {
            Serial::~Serial();
            throw("ERROR: Could not set com port parameters");
        }
    }
}
</code>
When I connect to COM5 it's all good, but I expect to have an issue connecting to COM535 which I dont, and that's not how it should be.
Comment: Since you are using MFC, I'm assuming you are using Windows Operating System.  This is not a C++ issue and more of an issue with Windows API.  You'll have to look up the function and find out what errors are generated when an invalid COM number is supplied.
Comment: Already have checked it, I set Serial data member at the constructor of CUARTDlg, when I use one of the method of the Serial class, the connection is established, the complier will return comHandle=0xfffffffff for bad attempt in connecting, which it does not
Answer: The "issue" was my own workplace issue, restarted my PC and I started to get the errors for bad COM port

Serial connection is opening all ports?


Post form only after submit using Entity Framework controller

Question: I have this view that I created so that a user can fill out this form, hit submit, and it will post to a controller that schedules the game. The controller will then return the results of the request.
But I think I may have something missing.  Because when I navigate to the page, via this link:

Create Game Schedule

I think it's trying to post right away, and everything is null or empty and throws errors stating such.
But I don't want it to post until after the user hits submit.
Is there a way to get the form/controller to not try and post until the user is done filling out the form?
Here is the view:
@model GameScheduler.Models.gameSchedulingEvent

@{
    ViewData["Title"] = "CreateGamingEvent";
}

CreateGamingEvent

gameSchedulingEvent

        <form asp-action="CreateGamingEvent">

                <input asp-for="GameName" />

                <input asp-for="GameStart" />

                <input asp-for="GameEnd" />

                <input type="submit" value="Create" />

        </form>

And here is the controller method:
public async Task<IActionResult> CreateGamingEvent(
            [Bind("GameName, GameStart, GameEnd")]
    GameSchedulingEvent gameSchedulingEvent)
{
    result = await client.ScheduleAsync(
                gameSchedulingEvent.Name,
                gameSchedulingEvent.Start,
                gameSchedulingEvent.End);

    return View(result);
}

Any help/suggestions would be greatly appreciated.
Thanks!
Comment: Have you declared the form's action `[HttpPost]`? If not, the default GET will execute when the action link is clicked.
Comment: Then you need to split the action so there is a `[HttpGet]` and a `[HttpPost]`.
Comment: Yes, when I had [HttpPost] in there, it could not find the page whenever I would try and navigate to it.
Comment: You mean I need an HttpGet and HttpPost with the same method name?  thanks
Comment: The name will need to match the request. But yes, the action name can be the same.
Comment: But it's just a form the user fills out, then it should hit the controller when the user hits the submit button.  Why would I need an HttpGet? thanks
Answer: The action link will send a GET request. You can handle both verbs with two separate actions.
The GET to render the initial form
[HttpGet]
public IActionResult CreateGamingEvent()
{
    return View();
}

And POST to accept the form submission
[HttpPost]
public async Task<IActionResult> CreateGamingEvent(
        [Bind("GameName, GameStart, GameEnd")]
GameSchedulingEvent)
{
    ...
}

Comment: EF does not affect this issue. The form submission will send a POST request (unless you specify otherwise) -- so you need the POST action to accept the submission. The returned response from the POST action would depend on your application behavior and if you're using AJAX. See https://www.stevefenton.co.uk/2011/04/asp-net-mvc-post-redirect-get-pattern/ for a standard response that doesn't involve AJAX.
Comment: I should also clarify: the default form method will be GET if not specified. You ought to use POST if you are changing state i.e. saving a database record.
Comment: thanks.  how does this work with .net core entity framework?  Because for each controller method, I need to add a different view.  With HttpGet, would I send them to the form view?  Then what would the HttpPost be for? Thanks again


How to hide a field based on a specific condition?

Question: I have a website for ads, which are either of those:

Regular ads.
VIP ads.

The Regular ads have an additional field "field_adding_make_vip". If the user decides to change a Regular ad to a VIP ad, the user will use the description from that field and send a SMS to a specific number and that ad will become automatically a VIP ad.
The filter in Views to show the VIP content is a additional field "field_vip_date" that uses a date filter. That mechanism is created with a custom PHP file.
So only left to do is: when the Regular ad becomes a VIP ad, the field "field_adding_make_vip" will be automatically hidden and the VIP ad will have additional field "field_adding_vip_image" that will show a VIP image, so every user will know that the selected ad is a VIP ad.
How can I hide that field and show the VIP image when the ad becomes a VIP ad?
The Regular ad and VIP ad are the same content type (adding). I'm using the field "field_vip_date" as a filter in views by date. Let's say when the date field of a specific node is set to 25 October, that node will be displayed in a VIP block position in the website until 25 of October and the next day it will be automatically removed from that position. That's for a block view position.
In every page node the field "field_adding_make_vip" has a description with the node id how to send the SMS, to be used to make it a VIP ad. The whole idea is when the user sends an SMS with the number ID, the field "field_adding_make_vip" will disappear, because the regular node has become a VIP ad and that node will have an additional field "field_adding_vip_image" that will display an image with a text "VIP".
Somehow the field "field_vip_date" (which is a date field) will have to control the field "field_adding_make_vip". For an example if "node/120" has "field_vip_date" set to 25 October, the field "field_adding_make_vip" will be hidden until 26 October and the field "field_adding_vip_image" will be displayed until 26 October.
Note: I've tried the code from @harshal, but it has errors. The name of my custom module is "custom_alter" and here's the full code:
<?php
function custom_alter_form_alter (&$form, &$form_state, $form_id) {

 $node = node_load($nid);
 $date = date('d/m/Y');
 $todaysdate = strtotime($date);
 $field_date_vip = $node->field_date_vip['und'][0]['value'];
 $date = date('d/m/y',  $field_date_vip);
 $expirydate = strtotime($date);

If ( $todaysdate <  $expirydate )) {
  //Hide the field adding_make_vip using css
  drupal_add_css(drupal_get_path('module', 'custom') . '/css/hide_field_adding_make_vip.css');
             }
else {
// hide field adding_make_vip using css
  drupal_add_css(drupal_get_path('module', 'custom') . '/css/hide_field_adding_vip_image.css');

}

}

Answer: I'm not sure I completely understand what you need. But if I'm correct and you just need to show / hide specific fields in a node based on some other field in that node the hook_field_access should help you.
 /**
 * Implements hook_field_access().
 */
function YOUR_MODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  switch ($field['field_name']) {
    case 'field_adding_make_vip':
      if ($node['isVIP'][value]) {  //Is the node VIP?
        return false;  //Show the field_adding_make_vip
      }
      else {
        return true; //Hide the field_adding_make_vip
      }
      break;
  }
    case 'field_adding_vip_image':
      if ($node['isVIP'][value]) {
        return true;
      }
      else {
        return false;
      }
      break;

}

Comment: @Petroll Thank you for your answer. I'll post more details in the main thread.
Comment: Please check my updated thread, 'cos I cannot find a way to open a chat with you.
Answer:
Somehow the field "field_vip_date" which is a date field will have to
  control the field "field_adding_make_vip". For an example if
  "node/120" has "field_vip_date" set to 25 October, the field
  "field_adding_make_vip" will be hidden until 26 October and the field
  "field_adding_vip_image" will be displayed until 26 October.
For the part to disppear the vip image fields after expiry the code is as follows : This is just for a single node.

function module_name_form_alter($form,&$form_state, $form_id) {
    if ($form_id == 'adding_node_form') {
       $nid = $form['nid'] ;
       $node = $node_load($nid);
$form['#submit'][] = 'adding_node_form_after_submit';
    //insert the code here

    }
}

function adding_node_form_after_submit ($form, &$form_state) {
$field_vip_date = $form['field_vip_date']['und'][0]['date'];
$expiry_date = strtotime($form['field_vip_date']['und'][0]['date']);
$date = date('d/m/Y');
$current_date = strtotime($date);
if ($current_date > $expiry_date) {
drupal_add_js( drupal_get_path('module', 'your_module_name') . '/' . custom.js);
}
}

Now add a js file in your custom module folder.
In your custom.js the code goes as follows:
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
   // add your code here
$('.field-name-field-adding-vip-image').hide();
      });
    }
  };

})(jQuery);

Comment: I cannot understand where to put this code.
Comment: u should use it inside hook_form_alter()
Comment: I've edited my first post. Please check it.
Comment: check for the form_id and set the condition as given above in edited answer
Comment: can you send me your email, so I can send you the link of the website, because I think that we are going in a wrong direction. I didn't find a way to chat with you here.


How to loop over OG group members from comment

Question: I'm trying to set up a Rule to send a privatemsg to all group members when someone posts a comment on the group node itself.
One approach I've tried using existing options provided by the OG module:

**Events**
After saving a new comment

**Conditions**
Entity is a group
  Parameter: Entity: [comment:node]

**Actions**
Get group members from group audience
  Parameter: Group content: [comment:node]
  Provides variables: List of group members (group_members)
Loop
  Parameter: List: [group_members]
  List item: Current member (member)
    **Loop actions**

This method fails to find any members. I'm guessing this is because the "Get group members from group audience" function expects its parameter to be a node posted on the group rather than the node representing the group itself.
Another method I've tried is to define a new Rules action in a custom module:

/**
 * Implements hook_rules_action_info
 */
function mymodule_rules_action_info()
{
    return array(
        'mymodule_get_og_members' => array(
            'label' => t( 'Get OG members from group node' ),
            'group' => t( 'Custom' ),
            'parameter' => array(
                'nid' => array(
                    'label' => t( 'Group node NID' ),
                    'type' => 'integer',
                ),
            ),
            'provides' => array(
                'group_members' => array(
                    'label' => 'List of group members',
                    'type' => 'list',
                ),
            ),
        ),
    );
}

/**
 *
 */
function mymodule_get_og_members( $nid )
{
    $node = node_load( $nid );
    $uids = og_get_group_members_properties( $node, array(), 'members__' . OG_STATE_ACTIVE, 'node' );
    $members = user_load_multiple( $uids );
    // user_load_multiple indexes by UID which might be confusing the Rules loop. Reindex!
    $members = array_values( $members );
    dpm( $members ); // This works!
    return $members;
}

In Rules UI I've added this custom action followed by a loop. The loop suggests the provided members-list variable to iterate over and everything looks fine, yet when the Rule is run I get errors like this:
Unable to get variable group_members, it is not defined.
Unable to evaluate loop.
I've asked an overlapping question here: https://www.drupal.org/node/905632#comment-10893894
Similar posts that I've read:
How to loop over a list of Organic Group users using Rules
I can't access a provided variable in rule action
https://drupal.stackexchange.com/a/170922/58279
Answer: I found a work-around by implementing all of the desired functions in the custom action provided by my custom module:

/**
 * Implements hook_rules_action_info
 */
function mymodule_rules_action_info()
{
    return array(
        'mymodule_comment_notify_og_members' => array(
            'label' => t( 'Notify OG members of comment' ),
            'group' => t( 'Custom' ),
            'parameter' => array(
                'comment' => array(
                    'label' => t( 'Comment entity' ),
                    'type'  => 'entity',
                ),
            ),
        ),
    );
}

/**
 * Notify relevant OG group members of a new group comment
 *
 * @param   object (entity metadata wrapper)    $comment
 */
function mymodule_comment_notify_og_members( $comment )
{
    //~ dpm( $comment->getPropertyInfo() );

    // Get the nodes we need from the comment entity metadata wrapper
    $node = $comment->node->value();
    $author = $comment->author->value();

    // Get all active group members
    $uids = og_get_group_members_properties( $node, array(), 'members__' . OG_STATE_ACTIVE, 'node' );
    $members = user_load_multiple( $uids );
    foreach( $members as $member )
    {
        if( $member->uid !== $author->uid )
        {
            // We're not notifying the author of his own comment

            $subject = format_username( $author ) . ' commented on ' . check_plain( $node->title );
            $body = '';
            $body .= 'Hi ' . format_username( $member ) . ',';
            $body .= '' . l( format_username( $author ), 'user/' . $author->uid ) . ' just commented on the ' . l( $node->title, 'node/' . $node->nid ) . ' group.';
            $body .= '' . l( 'View the comment', 'node/' . $node->nid, array( 'fragment' => 'comment-' . $comment->cid->value() ) ) ;

            privatemsg_new_thread( array( $member ), $subject, $body, array( 'author' => $author ) );
        }
    }
}

Answer: Would "fetch entity by property" be an option?
Type: user / property: og_user_node / value: comment node nid
That action gives a list to loop over.
Comment: Thanks for your response. I've found another way of achieving what I needed but I thought I'd give your answer a go out of curiosity.
I don't see og_user_node as an option under Property (The property by which the entity is to be selected). I see:
'Group membership',
'OG memberships',
'[Active/Pending/Blocked OG membership' ,
'OG embership from field Group membership',
'[Active/Pending/Blocked OG memberships from field Group membership'.

Which of these were you referring to?
Answer: Ben, you were a huge help to me.
"I'm guessing this is because the "Get group members from group audience" function expects its parameter to be a node posted on the group rather than the node representing the group itself."
^^^ this is exactly right. Using "Get group members from group audience" when using node A that is an organic group does not work.
When node A contains node B, use "Get group members from group audience" using node B.
Thank you!


Inconsistent result from isnumeric

Question: I have the following queries.
<code>    select ISNUMERIC(result+ 'E0'), from t1
    select ISNUMERIC('7' + 'E0')
    select ISNUMERIC('7' + '.E0')
</code>
The data type of result column is varchar(50).The first query yields 0 even when result is  like 2,3 and returns 1 for float only ...Whereas second and third query works fine for both integer and float.Am I missing anything? My requirement is to check whether result column is number(integer,float) or not.I know isnumeric returns 1 for type like money,small money,real etc but this is not the case here as i don't have such type in my result and i am only receiving 0.
Comment: have a look in here: http://www.tek-tips.com/faqs.cfm?fid=6423
Comment: I am using MS SQL 2014.
Answer: The reason for the seemingly inconsistent result might be, that there is a space in your result column value. Try timming text and feed the trimmed text to ISNUMERIC:
<code>select ISNUMERIC(ltrim(rtrim(result))+ 'E0') from t1
</code>
Comment: Thanks.You are right it's because of space. It works but when I tried to copy the cell data and paste in notepad and other editor  I could not find space.

Inconsistent result from isnumeric


From the perspective of the multiverse theory, would maths "work the same" in every possible Universe?

Question: I've had an interesting discussion with a friend recently and I was arguing that in every possible Universe, mathematics would always have to work the same, i.e. $1 + 1 = 2$ would have to be true for every possible Universe, regardless of the laws of physics, number of physical dimensions etc. because in every Universe if you have one thing, and then another, you have two things in total. Another example: every possible Universe would have the same prime numbers and therefore the Ulam spiral would look the same in every possible Universe (with at least 2 dimensions).
Is this true? Is there an example that would prove this false?
Comment: The math should be the same, but not the same theories may be applicable to the same phenomena. Even in our home universe we may have that $1$ drop of water plus $1$ drop of water is still just $1$ (bigger) drop of water. This doesn't show that $1+1=1$ instead of $=2$, it shows that for *this* phenomenon, addition of natural numbers is not a suitable model.
Comment: Is mathematics not a part of the way in which we (humans) think? I mean, it is not like '$1+1 = 2$' has any meaning except in our heads (in fact, nothing really does...). But when we think of mathematics as something solely in our heads then it does not matter if we think about one universe or the other, the way we think about it won't change and so mathematics wouldn't either.
Comment: Yes, I agree that in alternative universes we might use alternative models to describe certain phenomena. This is the only part I can see changing. To give some more context, we were having a discussion involving cosmology and I was trying to show that there are things that would stay the same across all possible universes. I then hypothesised that e.g. if the Ulam spiral looks the same in every Universe and it's impossible for it to look different then perhaps the initial state of the Universe could not have been different. I know that's a bit farfetched and I digress...
Comment: IMHO, it is possible different universe has different math. The fundamental issue is the foundation we build modern math on, the logic system we have right now doesn't seem to describe the reality well once we get to sufficiently small length scale. In a universe when classical logic doesn't work, there are issues what the math should become. Maybe i should consult Living Tribunal for advice...
Answer: AFAIK, there's no reason to think that mathematics would be different in any other universe, nor that it could be different.
Answer: Like every statement in natural language, every mathematical statement does not occur isolated but in a certain context. There are also undefinable concepts in any language, whether natural or not. "$1+1=2$" is only meaningful in a context where "$1$" and "$2$" and "$+$" and "$=$" are meaningful. If their meanings are completely determined, then that statement would be true no matter what. So it depends a lot on what exactly you define them to mean! What really is a "thing"?
To give a bit of detail, we could for example say that expressions that have the same value are equal, in which case we can write them down with an "$=$" in between. We could also define "$2$" to be a short-form for "$1+1$", and so both have the same value. Thus we get "$1+1=2$" as long as "$1$" and "$+$" are defined. Notice that I did not define what "value of an expression" means. That again is up to you to decide, but for most reasonable definitions what I said holds.
Also, there is little use for a multiverse theory because there must still be a single over-arching framework that governs what universes are allowed and how they interact. And hence we might as well consider that one single framework as the true universe.


LDAP Module - Notice: Trying to get property of non-object in ldap_authentication_init() appears

Question: I have a site with Drupal 7.41 and LDAP module version 7.x-2.0-beta8. My goal is to connect my drupal site with an Active Directory account.
After I installed LDAP module i saw a error message: Notice: Trying to get property of non-object in ldap_authentication_init() (line 223 of  [... ] ldap/ldap_authentication/ldap_authentication.module)
But i thought that was a part of Module. When i configure and test my module, this error message still appears. The stack of test is:
<code>            sid = empresa.cl
            numeric_sid = 1
            name = empresa.cl
            status = 1
            ldap_type = default
            address = XX.XXX.X.XXX
            port = 389
            tls = 0
            followrefs = 0
            bind_method = 2
            basedn = Array ( [0] => ou=chile,dc=empresa,dc=cl )
            binddn =
            user_dn_expression = empresa//%username
            user_attr = samaccountname
            account_name_attr =
            mail_attr = mail
            mail_template =
            picture_attr =
            unique_persistent_attr =
            unique_persistent_attr_binary = 0
            ldap_to_drupal_user =
            testing_drupal_username = nombre
            testing_drupal_user_dn = CN=nombre, OU=chile, DC=empresa, DC=cl
            grp_unused = 0
            grp_object_cat =
            grp_nested = 0
            grp_user_memb_attr_exists = 0
            grp_user_memb_attr =
            grp_memb_attr =
            grp_memb_attr_match_user_attr =
            grp_derive_from_dn = 0
            grp_derive_from_dn_attr =
            grp_test_grp_dn =
            grp_test_grp_dn_writeable =
            search_pagination = 0
            search_page_size = 1000
</code>
Any possible suggestion or advice for this problem?
Answer: This message disapears when i add data in a 'Authorization Tab' In a email section and I select a "LDAP Server Type" (This option belongs to LDAP server's configuration from Server tab) such as Active Directory.
Thank, you Anyway


Rails 3 - translating of routes with I18n

Question: I want simple thing. Translate routes with I18n like this
get I18n.t('routes.login') => "devise/sessions#new", :as => :new_user_session

I made file initilizers/locale.rb with
I18n.default_locale = :cz

It works perfectly when i run 'rake routes', but when i run server it ignore default locale and throw 'translation missing message'
Any suggestion what is happening and why ?
Answer: I believe, that normally routes are loaded once, even before locale are set, so you simply can't use the logic you have here. You need more advanced stuff to get it to work. Take a look at i18n_routing: http://github.com/kwi/i18n_routing
Comment: gem is a good suggestion for rails 2 and 3.  It apparently handles all urls shown in each locale you handle.  It does not touch in any way the database, so if you query in SQL you maintain the table name.


Find general solution of ODE $(1+t^2)x''+(x')^2+1=0$

Question: I want to solve following ODE:
$$
(1+t^2)x''+(x')^2+1=0
$$
substitute $y = x'$
$$(1+t^2)y' + y^2 + 1 = 0\\
\frac{dy}{dt}=\frac{-(1+y^2)}{1+t^2}\\
\frac{dy}{1+y^2} = \frac{-dt}{1+t^2}
$$
integrating both sides leaves me with
$$
\arctan y = - \arctan t + c
$$
taking $\tan$ from both sides
$$
y = \tan ( - \arctan t + c)\\
\frac{dx}{dt} = \tan ( - \arctan t + c)\\
dx = dt \tan ( - \arctan t + c)
$$
I surely can't integrate that - I must have done mistake somewhere. Could somebody point me where and how to fix it?
Comment: let $c = \arctan(c)$ and then use tangent subtraction formula to get an easily integrable closed form.
Comment: @NinadMunshi which tangent substraction formula you're speaking of?
Comment: The trig identity
Answer: By reassigning the constant
$$\arctan y = \arctan C_1 - \arctan t = \arctan\left(\frac{C_1-t}{1+C_1t}\right)$$
one can take tangent on both sides and integrate getting the solution
$$x = \left(1+\frac{1}{C_1^2}\right)\log\left(1+C_1t\right) - \frac{1}{C_1^2}t + C_2$$
or in the case $C_1 \to \infty$ and $C_1 = 0$ we have
$$x = \log t+C_2$$
$$x = -\frac{1}{2}t^2+C_2$$
respectively.
Answer: Hint:
$$\arctan y + \arctan t = c$$
You can use the arctan addition formula:
$$\arctan y + \arctan t = \arctan \dfrac {y+t}{1-yt}$$


What is the probability that you identify correctly each painter and her painting?

Question:
At an art gallery, you enter a room where $6$ paintings are hung on its walls.  Four people are in the room. If you know that one of these people is not a painter and the other three are the painters of three of the works exhibited, what is the probability that you identify correctly each painter and her painting?

My analysis:
First there is only one correct way of identifying each painter with her painting.  I know that only $3$ are painters and one is not, so I should identify $3$ distinct persons with $6$ distinct paintings. I assume there should be a permutation of $6P3=120$ and the probability must be $1/120$, but according to the mcq the correct answer is:$1/480$.
How should I proceed?
Comment: The wording of the question could be improved.  Evidently, the author meant that you know that three of the four people present are among the six painters, but that you do not know which three of the four people are the painters.  To get the desired answer, you need to multiply by the probability that you correctly identify all three painters among the $\binom{4}{3}$ ways of selecting three of the four people in the room.
Answer: Can be done by matching the painters up with their paintings, one after the other, probability-tree style.
First, you have to pick one of the $3$ painters out of the $4$ people $\frac{3}{4}$. Then, you have to pick the 1 painting they painted out of $6$.
Probability of doing this is $\frac{3}{4}\times\frac{1}{6}$.
Next, there are $2$ painters left out of $3$ people, and $5$ paintings left.
Probability of getting both the first pick correct, and the second is $\frac{3}{4}\times\frac{1}{6}\times\frac{2}{3}\times\frac{1}{5}$.
Therefore, the probability of getting all 3 correct is $\frac{3}{4}\times\frac{1}{6}\times\frac{2}{3}\times\frac{1}{5}\times\frac{1}{2}\times\frac{1}{4} = \frac{1}{480}$
Comment: Why is the probability of picking one painter out of 4 people 3 over 4 instead of 1/4?
Comment: When first choosing a painter, it doesn't matter which painter you get, because you haven't picked a painting yet. All that matters is you don't get the person who isn't a painter.


What makes this music calm?

Question: The Girl from Ipanema by Stan Gets & João Gilberto in the album Getz/Gilberto https://music.youtube.com/watch?v=N-TKOh0zsvU
Why does this song sound very calm, chill, non-attention-grabbing, non-energizing before the sax starts playing? I feel like I could sleep to it. How can I make music like this?
Comment: I actually get a bit stressed out from not understanding the lyrics, feels like I only heard other versions of this song.
Comment: @Emil The female vocals are in English.
Answer: Although this question is somewhat subjective there are objective elements that can be used to explain why it has that calm mellow feeling to it.
Style: This is Bossa Nova, a Brazilian style of music whose general characteristics are slow to medium tempos, fairly sparse rhythms with some syncopation, smooth jazzy harmony and consonant melodies.
Instrumentation: The piano is played very sparsely, the nylon string guitar provides rhythm, harmony and syncopation, the acoustic bass and drums play simple steady accompaniment. The saxophone plays a mellow jazzy solo and background lines. Although all of these instruments are capable of producing a bright harsh sound they are played here with a very soft, warm sound.
Vocals: Both the female and make male singers (Astrid Gilberto and Antonio Carlos Jobim) are singing smoothly in a low register so there is no harshness to their voices.
If you want to create music in this style, study and listen to Bossa Nova. There are many other styles of music that have a similar relaxing and calming effect on the listener as well but that would be for another question.
Comment: @Emil Your comment is not related to music. This is not about someone sneaking up on you. Most vocalists have a mellower sound in their low register.
Comment: @Emil the word "calm" was used by the OP in his question, it was not my choice,
Comment: @Emil You liking or not liking his delivery and using a word like "creepy" is subjective and irrelevant. This question is about the calm feeling of this music which I answered  objectively, not based on whether I like it or not. I included a section about vocals so where do you get the idea that I don't consider singing a part of the music?
Comment: @John Belzaguy: Yes. Also, the singers and the sax are close to the microphone, which makes them sound intimate. Even the piano is close-miked. (And it sounds as if there's an unusual damper being used.) There's very little vibrato in either the voices or the sax. They aren't trying to impress. There's no showiness or glitter. (I thought the question absurd: 'How can I make music I can sleep to?')
Comment: I am not entirely sure that low register necessarily means calm- I got the feeling of a burly man coming up behind me and whispering things in my ear, which I don't want. Interesting otherwise.
Comment: His singing voice is basically so soft it is whispering. I do not like his delivery. If he had actually sang it would be less creepy. Not sure why you do not consider the singing a part of the music? I do not think you are correct, my comment is about how the music is perceived, and I challenged your position that low register means calm.
Comment: I think calm is the wrong word. Nature is calm, but it has high frequency components, and are not this smooth. I think a more apt word is intimate. The whole question is subjective (can it get more subjective than calm?).
Comment: Fine, maybe some people like songs that feel like strange men whisper softly in their ears, but it certainly does not make me calm.
Comment: @OldBrixtonian Music can be used to create or enhance many different types of moods including getting to a very relaxed state (which could potentially lead to sleeping) so I didn't find the question absurd.

What makes this music calm?


Volume of Region Bounded by $y = \sqrt{x}$ and $y = 18-x^2$

Question: I haven't a clue why I'm having so much issues solving this problem. The two curves are $y=\sqrt{x}$ and $y=18-x^2, x \ge 1$, and rotated about the $y$-axis.
If I'm not mistaken, I need to use the shell method. In that case, the volume integration formula is $\int 2\pi x f(x)dx$.
So my thickness is $dx$, my height is $f(x)$, I believe my range is from $1$ to $\sqrt{18}$ ($1$ because $x \ge 1$ and $\sqrt{18}$ because $0 = 18-x^2$).
So I integrate $2\pi \cdot x \cdot x^{1/2} dx$ and get $(2/5)x^{5/2}$ from $1$ to $\sqrt{18}$, but that isn't even close to the answer.
I've been working on this problem far too long and am getting brain fog.
Comment: Yes, sorry. Rotated about the y-axis.
Answer: Note that the graph of $y = \sqrt{x}$ and $y = 18-x^2$ shows that these two curves meet at $x = 4$ and $y = 18-4^2 = \sqrt{4} = 2$.  Write out explicitly $f$ in the question body.
$$f(x) = 18-x^2-\sqrt{x} \quad \forall\,x \in [1,4]$$
\begin{align}
\text{Required volume of revolution}
&= 2\pi \int_1^4 x f(x) dx \\
&= 2\pi \int_1^4 (18x - x^{3/2} - x^3) dx \\
&= 2\pi \left[9x^2 - \frac{x^{5/2}}{5/2} - \frac{x^4}{4} \right]^4_1 \\
&= 2\pi \left[ 9(4^2 - 1^2) - \frac{64}{5} + \frac25 - \frac{4^4 - 1^4}{4} \right] \\
&= \frac{1177\pi}{10}
\end{align}
Comment: My book gives an answer of $1177pi/10$, so perhaps my bounds are wrong?
Comment: @awbasham (1) *Which* book?  (2) Use `\pi` instead of `pi` to input $\pi$.  (3) If you have new bounds, you're welcome to start a new question.
Answer: You will be adding "a lot of" silinders of height $dy$ with radius $r(y)$. It is of the form $$V = \int _0^2 S_1(y)dy + \int _2^{18} S_2(y)dy  $$
The two curves meet at $y=2$ (for $x=4$) so for $y\in [0,2)$ the radius of the circle is determined by $y=\sqrt{x}$, therefore $r_1(y) = y^2, y\in [0,2)$.
The radius is determined by $y=18-x^2$ for $y\in [2,18]$ hence $r_2(y) = \sqrt{18-y}, y\in [2,18]$.
Our volume is therefore
$$\pi\int_0^2 y^4dy + \pi\int_2^{18} (18-y)dy\tag{1} $$
If $x\geq 1$ is assumed, then we need to subtract some volume. To picture this, draw a vertical axis at $x=1$ and subtract the volume which is obtained by revolution of the piece to the left of $x=1$. We compute  the volume similarly so obtain
$$\pi\int_0^1 y^4dy + \pi\int_1^{17} dy + \pi\int_{17}^{18}(18-y)dy \tag{2}$$
Volume of interest is obtained by subtracting $(2)$ from $(1)$.
Comment: It makes sense to me now that I see the solution. I suppose I was too close minded, as all previous problems were simple volumes of areas under two curves. The text even says for this specific problem "bounded by the graphs of the given equations". Maybe I just misinterpreted the question. Thanks!
Comment: I just calculated a correct answer using your logic. I'm just quite confused how such hoops are required to jump through. This chaining of volumes doesn't really fit with the chapter material. It was my understanding that the volume being calculated was only from x range 1 to sqrt(18), and only the region under both curves. My head hurts.
Comment: I am making the assumption the piece rotating around the y axis is the one bounded by $x=0$, $y_1,y_2$. Augmented with the extra condition that $x\geq 1$. I merely apply the additivity property of the integral.
Comment: When you write $dx$ it may be that you are rotating around the $x$ axis. You must pay attention around which axis the piece is being rotated. Results will be very different, indeed.
Should you have rotated around the $x$ axis, the radii of the circles will be $y$-values (the 'height' of the graph).
Answer: Look at the region and set up the integral as below:

$$V = 2\pi\int_{1}^{4} (18-x^2-\sqrt{x})xdx$$
$$V = 2\pi \int_1^4 x (18-x^2) dx - 2\pi \int_1^4 x \sqrt{x} dx $$
$$== 2\pi \left[ 9(4^2-1) - \frac{4^4-1}{4} -\frac{64}{5} +\frac25  \right]$$
$$ V = \frac{1177\pi}{10}$$


Failed to transfer data between view controllers in iOS

Question: I am a newbie to Objective-c and stackOverflow. :)
I have created 2 view controllers which are connected by a segue called "showDetailSegue".
In the LPLviewcontroller1, I have a sentence property, which I use to set the text in the textview in LPLviewcontroller1, and I want to use segue to set the value of sentence property in LPLviewcontroller. Moreover, I have a button on the LPLviewcontroller which can perform the "showDetailSegue".
However, the program stops at
    int main(int argc, char * argv[])
    {
        @autoreleasepool {
            return UIApplicationMain(argc, argv, nil, NSStringFromClass([LPLAppDelegate      class]));
            (program breaks here)
        }
    }

The System log is
2014-06-25 16:49:43.199 test[6322:60b] -[LPLViewController button:]: unrecognized selector sent to instance 0x8d43f30
2014-06-25 16:49:43.204 test[6322:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[LPLViewController button:]: unrecognized selector sent to instance 0x8d43f30'

Here is LPLviewController.m
#import "LPLViewController.h"
#import "LPLViewController1.h"

@interface LPLViewController ()

@end

@implementation LPLViewController

- (IBAction)press:(id)sender {
    [self performSegueWithIdentifier:@"showDetailSegue" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"showDetailSegue"]){
        LPLViewController1 *controller = (LPLViewController1 *)segue.destinationViewController;
        controller.sentence = @"dfjlasdkfjlskdfjlksdjflkadsjf";
    }
}
@end

Here is LPLviewController1.m
#import "LPLViewController1.h"

@implementation LPLViewController1

-(void) viewDidLoad
{
    _text.text = _sentence;
}
@end

Comment: how you are defining the event of the button?
Answer: Not 100% sure without seeing the header files, but from the exception, it sounds like you did not define the property "sentence".
Answer: You need this in the LPLViewController1.h header file:
@property (nonatomic, strong) NSString *sentence

Then use self.sentence in your LPLViewController1 implementation to access the value. The prepareForSegue:sender method is fine. But this is pretty basic Objective C stuff...


Generating data from meshgrid data (Numpy)

Question: I'd like to ask how to generate corresponding values from a meshgrid. I have a function "foo" that takes one 1D array with the length of 2, and returns some real number.
import numpy as np

def foo(X):
    #this function takes a vector, e.g., np.array([2,3]), and returns a real number.
    return sum(X)**np.sin( sum(X) );

x = np.arange(-2, 1, 1)          # points in the x axis
y = np.arange( 3, 8, 1)          # points in the y axis
X, Y = np.meshgrid(x, y)         # X, Y : grid

I generate X and Y grids using meshgrid.
Then, how can I generate corresponding Z values using "foo" function, in order to plot them in 3D, e.g., plotting using plot_surface function with X,Y,Z values?
Here the question is how to generate Z values, which has the same shape to X and Y, using "foo" function. Since my "foo" function only takes an 1D array, I do not know how I can uses this function with X and Y to generate corresponding Z values.
Comment: Do you want `z = foo([x, y])` for each point `(x, y)` in the meshgrid?
Answer: Stack your two numpy arrays in "depth" using np.dstack, and then modify your foo function, so that it operates on only the last axis of your stacked array. This is easily done using np.sum with parameter axis=-1, instead of using the builtin sum:
import numpy as np

def foo(xy):
    return np.sum(xy, axis=-1) ** np.sin(np.sum(xy, axis=-1))

x = np.arange(-2, 1, 1)          # points in the x axis
y = np.arange( 3, 8, 1)          # points in the y axis
X, Y = np.meshgrid(x, y)         # X, Y : grid
XY = np.dstack((X, Y))

And now, you should get:
>>> XY.shape
(5, 3, 2)
>>> foo(XY)
array([[ 1.        ,  1.87813065,  1.1677002 ],
       [ 1.87813065,  1.1677002 ,  0.35023496],
       [ 1.1677002 ,  0.35023496,  0.2136686 ],
       [ 0.35023496,  0.2136686 ,  0.60613935],
       [ 0.2136686 ,  0.60613935,  3.59102217]])

If you want to achieve the same effect, but without modifying foo, then you can use np.apply_along_axis, which should do exactly what you need:
>>> np.apply_along_axis(foo, -1, XY)
array([[ 1.        ,  1.87813065,  1.1677002 ],
       [ 1.87813065,  1.1677002 ,  0.35023496],
       [ 1.1677002 ,  0.35023496,  0.2136686 ],
       [ 0.35023496,  0.2136686 ,  0.60613935],
       [ 0.2136686 ,  0.60613935,  3.59102217]])

Comment: Thanks for the wonderful solution. This is exactly what I wanted to do. However, I have some problems to apply this approach to my code bock. I actually posted another question regarding this matter [link](http://stackoverflow.com/questions/39715227/making-a-function-that-can-take-arguments-in-various-shapes). My actual foo function is actually something like `return X[0] + X[1];`, so it cannot perform an iterative operation on a nested array, and can only take the shape of (2,). Thus, if I put XY into my actual foo function, it spits our error. In this case, how can generate Z as you did?
Comment: Oops, sorry, I forgot it!
Comment: By the way, can you let me know how I should change your ode if I just want to use my current foo function, which can only take (2,) shape?
Comment: @AnnDescomp I've posted an answer on your other question. See if that works for you...
Comment: I am now looking at "..." indexing. In addition, I'd want to know if there is a way to generate Z with my current foo function, which can explicitly take only one (2,) shape Numpy array as an argument.
Comment: @AnnDescomp You _don't_ want to modify your foo function, but you still want to achieve the same result?
Comment: @AnnDescomp See the edit I've made to my answer. Hopefully that should solve your issue. Again, don't forget to upvote! :-)


Difference between four random effects structure

Question: What is the difference between the following four random effect structures in R?
m1 = lmer(dv ~ pred1 + (time|id), data = df, REML = FALSE)
m2 = lmer(dv ~ pred1 + time + (time|id), data = df, REML = FALSE)
m3 = lmer(dv ~ pred1 + (1|id) + (1|time:id), data = df, REML = FALSE)
m4 = lmer(dv ~ pred1 + time + (1|id) + (1|time:id), data = df, REML = FALSE)

Is there any reason for using one over the other? Do they offer different advantages?
Comment: What type of variable is `time`?
Comment: This might help: https://stats.stackexchange.com/questions/13166/rs-lmer-cheat-sheet
Comment: @AlexJ - time is year ranging from 2005-20. Some users have records for all years and others for select years. Not all users start at same time. So time could be a factor variable or discrete variable. Not sure if that complicates the differences b/w four models further.
Answer: in general, terms shouldn't be in RE if they're missing from FE
(By "terms" here I mean "terms that vary among groups", not "grouping variables"; in formula notation, that means having a term like (f|g) where f is not in the fixed effects)
Because random effects are mean-centered, having f vary among groups but not be included in the fixed effects specifies that it has an effect of exactly zero in the population but nevertheless varies among groups.  This is usually not sensible, although it does apply in some cases (e.g., if the response variable itself has been standardized so that its population-level mean is zero, then you could have the intercept vary across groups ((1|group)) but drop the intercept from the fixed effects (+0 or -1).
(Therefore, models 1 and 3 are not generally a good idea.)
is time a numeric variable or a factor?
If time is numeric, the linear model corresponding to ~time (we'll see why this is important in a minute)  consists of an intercept and a slope with respect to time. If it's a factor, then the linear model consists of an intercept and a set of contrasts — i.e., one parameter per distinct time value — or (if we use ~0+x) an indicator/dummy variable for each time value.  Thus there are three ways that time could show up in a RE:

(time is numeric): (time|id) denotes a random-slope model, with among-group variances for the intercepts and slopes and an among-group covariance between intercepts and slopes: the random-effects component is $b_{i,0} + b_{i,1}(t)$ (where $i$ is a group index), $b \sim \textrm{MVN}(0, \Sigma)$, $\Sigma$ is $2 \times 2$
(time is a factor/categorical): (time|id) denotes a model where the variability across groups is different at every time step, and where there are different correlations between every pair of times (an $n \times n$ covariance matrix if there are $n$ distinct times): RE component $b_{i,j}$ ($i$ = group, $j$ = time), $b \sim \textrm{MVN}(0, \Sigma)$, $\Sigma$ is $n \times n$. The latter model (which I'll call 'unstructured' time variation) tends to be data-hungry ($n(n+1)/2$ covariance parameters to estimate)
(1|time): here time is treated as a grouping variable rather than an effect (automatically converted to a factor). RE component $b_j$, $b_j \sim N(0, \sigma^2)$

nested random effects
: is an interaction operator, so (1|time:id) corresponds to variation in the intercept across subject-by-time combinations. Thus (1|id) + (1|time:id) (which can also be abbreviated as (1|id/time) corresponds to variation in the intercept (denoted by the 1 to the left of the bar) across subjects and across times within subjects. The RE is $b_{1,i} + b_{2,ij}$, $b_1 \sim N(0, \sigma^2_1)$, $b_2 \sim N(0,\sigma^2_{2})$. This nested model is also called a (homogeneous) compound symmetric covariance structure because it corresponds to a model where variation among herds is the same at every time point and correlation across herds is the same for every pair of time points    (e.g. see here, search for "compound symmetry")
With all those concepts, we can say (leaving out everything inessential, including pred1:

~(time|id): no time effect at the population/fixed-effect level (probably silly), random slopes or unstructured time variation depending on whether time is numeric or categorical
~ time + (time|id): as above, but with a time effect at the population level
~ (1|id) + (1|time:id): no time effect at the population level. Variation among subjects and among times within subjects
 ~ time + (1|id) + (1|time:id): ditto, but with a population-level effect of time

Recommendations

For a moderate-sized data set with many (more than 3 or 4) distinct time points, where the within-group trends are not obviously nonlinear, I would generally recommend the random-slopes model (model 2 with numeric times)
For a moderate to large data set with lots of times and nonlinear patterns, I would recommend a low-order polynomial model in time (if that's adequate), or a hierarchical GAM (e.g. see the excellent paper by Pedersen et al. 2019)
With a small number of distinct time points I would suggest the unstructured-time model for a large data set, falling back to the compound-symmetry model if necessary for parsimony

Pedersen, Eric J., David L. Miller, Gavin L. Simpson, and Noam Ross. 2019. "Hierarchical Generalized Additive Models in Ecology: An Introduction with Mgcv." PeerJ 7 (May): e6876. https://doi.org/10.7717/peerj.6876.


jQuery :has(.something:contains()) unsupported?

Question: Given the HTML below, I am trying to use jQuery to match all the list items that have a span with the class "foo" and that span should contain the text "relevant".

Some text relevant

Some more text not relevant

Even more not so either

Blablabla relevant blabla

No foo here relevant

Note that there are also a few span's with the class "bar", and that also has the text "relevant", that should not be included.
My attempts at a selector:
ul li:has(.foo:contains('relevant"))

This does not work. The next example selects something, but does not take into account that there are multiple span's inside the list:
ul li:has(span:contains('relevant"))

Here is a live example that you can play with. In a working version, only the first and fourth elements of that list should be selected.
Comment: +1 for using jsbin in the question, saving us all work time.
Comment: @Kobi - +1 for admitting you SO at work :)
Answer: Check this out:
$(document).ready(function(){
    $('span.foo:contains(relevant)').parents('li').each(function() {
       alert($(this).text());
    });
});

Comment: That selects the span.foo, not the list item.
Answer: Beaten to it...  But if you want a pure selector you were darn close
ul li:has(span[class='foo']:contains('relevant'))

Answer: I tried to reverse the order of the selectors:
$("ul li:has(:contains('relevant').foo)").css('background-color', 'red');

This seems to work well, can't say why though: http://jsbin.com/asoma
Answer: I know this may not be as elegant, but at least it'll work:
$("ul li .foo:contains('relevant')").parent("li");

I couldn't get your version to work either...
Answer: Not sure why you're having that problem with the selector, confirmed this does work though:
$("ul li").filter(":has(span.foo:contains('relevant'))").css('background-color', 'green');


How to exclude product variations from product teaser display?

Question: I am developing an online shopping website using Drupal Commerce.
In my products teaser display all my products variations are also shown. I want only the main product to be displayed and not its variations on teaser display. Right now I am using in-build taxonomy term view to display my product teaser.
Any suggestions?
Answer: Fortunately I got the answer, by looking at the solution described in a comment to View of products with multi-value product reference field show multiple rows per product node. Here is a summary of it:

I created a view of product display nodes. Added the relationship to products. Added two fields "Content: Title" and "Commerce Product: Image".
  Got a row for every display node and product (so a node that references two products gets two rows). This is what I expect to happen.
Possible solution A:
I click on "Query settings" in the third column, and in query settings enable "Distinct" (it's a checkbox).
  That kills the duplicates.
However, DISTINCT is usually a bit stupid, so it might not work in all cases. In those cases, you can try the next possible solution.
Possible solution B:
I enable Aggregation (again, it's in the third column). I make sure to have a "Content: Nid" field added at the top of the fields list, so that it groups by that first. Might need to apply "MIN' to the title (by setting: Aggregation type to "Minimum" in "Aggregation settings" for that field).
Note that once you do that, the image will stop displaying. The solution for that is to go into "Aggregation settings" for the image field, and change the "Group column" from "fid" to "Entity ID". That makes it display again.
Answer: You may want to try what's below, based on what I found in a comment to "View of products with multi-value product reference field show multiple rows per product node".
Create a view of product display nodes. Add the relationship to products. Add two fields "Content: Title" and "Commerce Product: Image".
So that you get a row for every display node and product (so a node that references two products gets two rows). Here are possible solutions for it:

Click on Query settings (in the 3rd column), and in query settings enable "Distinct" (it's a checkbox). That removes the duplicates.
However, DISTINCT is usually a bit stupid, so it might not work in all cases. In those cases, you can try another possible solution, as detailed below.

Enable Aggregation (in the 3rd column). Make sure to have a "Content: Nid" field added at the top of the fields list, so that it groups by that first. You may need to apply 'MIN' to the title (by setting Aggregation type to Minimum in "Aggregation settings" for that field).
Note that once you do that, the image will stop displaying. The solution for that is to go into "Aggregation settings" for the image field, and change the "Group column" from "fid" to "Entity ID". That makes it display again.


Visual Studio Code remote: Invalid username or password fatal: Authentication failed

Question: I'm using Visual Studio code editor issue is it is not asking for password when i run
git push origin branchname
remote: Invalid username or password
fatal: Authentication failed for 'https://bitbucket.org/..../.....git/'

but it was working properly before.
I tried these commands also
git config --unset user.password

git config credential.helper ""

now when i try to push code it is giving me following errors :
fatal: credential-cache unavailable; no unix socket support
remote: Invalid username or password
fatal: Authentication failed for 'https://bitbucket.org/..../.....git/'

but from command prompt i'm able to push code. Is there any way i can enable password dialog to appear when i push the code.
Thanks
Comment: `user.password` is meaningless: you might as well `git config --unset aardvark.purple`. Nothing cares about it, nobody uses it, so don't set or unset it. The `credential.helper`, on the other hand, does matter, but you'll need a VSCode expert to tell you what it *should* be set to here.
Comment: What is your OS and Git version? What does `git config --global credential.helper` return?
Comment: @VonC: I'm working on windows 10, git config --global credential.helper returns `cache`, `git version 2.32.0.windows.2`
Answer: Make sure you have generated a BitBucket HTTP access token first.
And use that as password.
I would try, from command-line:
git config --global credential.helper manager-core

git ls-remote https://bitbucket.org/..../.....git
# enter your bitbucket username/token
# check it does return the remote branch names

# Then, again:
git ls-remote https://bitbucket.org/..../.....git
# check it does return the remote branch names /without/ asking for your credentials

Once the git ls-remote is working (meaning it does no longer ask for your credentials, which are now successfully cached), close and restart VSCode.
See if the issue persists then.
Answer: Try to set app password for bitbucket, you are trying to use account password as app password which is wrong as per bitbucket April update.
Go to bitbucket -> personal setting page -> app password -> create a app password
Now use this app password to push and pull the code from bitbucket !


proving limit of sequence when related limit is known

Question: Suppose I have the sequence $\{x_n\}$, where $ x_n >0$ for all $n\ge1$.
The sequence satisfies:
$$\lim_{n\rightarrow\infty}{x_n^{x_n}} = 4$$
I am trying to prove that
$$\lim_{n\rightarrow\infty}{x_n} = 2$$
I have tried logarithms and the definition of the limit, but to no avail...
Any hints?
Answer: Hint: You could e.g. show and use that $f(x)=x^x$ is continuous and strictly increasing for $x\geq 1$ (and $f(x)\leq 1$ for $x\leq 1$).


Remove one of the two "Apply to selected items" submit buttons with Node Bulk Operations

Question: If you make a view and add the Node operations bulk form, two "Apply to selected items" boxes are automatically generated like this:

How do I get rid of one of these?
I turned on twig debugging, but the template that is outputting the button is core/modules/system/templates/container.html.twig, which is not something that I can easily customize to remove one of the buttons.
How I created the view:

Create a new view of content showing fields.
Add Node operations bulk form under Fields.
Save the view.
Answer: This is intentional functionality for some workflows (for long lists of results).
If you wanted to get rid of the button, you could hook_form_alter it away. Form IDs and array structure are dynamic based on your view so you'll have to adjust accordingly based on the view & action button to remove (this can be found in the Views UI, if not known).
/**
 * Implements hook_form_alter().
 */
function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // @TODO: Determine view_id / display_id / field_id for a specific VBO form:
  if ($form_id == 'views_form_' . $view_id . '_' . $display_id) {
    // HEADER ACTION BUTTON:
    //unset($form['header'][$field_id]['actions']);
    // FOOTER ACTION BUTTON:
    //unset($form['actions']['submit']);
  }

Comment: For the node operatiosn bulk form, the *$field_id* is `node_bulk_form`.


Is the typical use of the N6 Neapolitan chord to lead to a perfect cadence rather than a half cadence?

Question: The basic N6 description is that it leads to the dominant chord, but this doesn't fully explain its use in cadences.
A survey of my harmony texts - Piston, Seigmeister, and Kostka - show N6 going to dominant harmony as part of a perfect cadence. Or, the examples are too short to show how the phrases end cadence-wise.
I am mostly concerned with Baroque and Classical styles. Also, I'm not concerned with N6 in modulation or other non-cadence aspects.
Theoretically I suppose N6 could be used as part of a half-cadence, but I'm interested in its actual occurrence in scores. I lack the deep knowledge of the literature.
Comment: Related: https://music.stackexchange.com/questions/85955/ii6-i-cadence-plagal-or-authentic
Answer: Interesting question; it's definitely less common! In my experience, the most common half cadences that use a Neapolitan have an intervening applied chord to the dominant, like in this example from Schubert's "Der Müller und der Bach" from his Die schöne Müllerin:

I'm not sure if this "counts" for what you're looking for, but I thought I'd share it. And this might violate your Baroque/Classical stipulation, but 1823 isn't too late, right? :-)
Comment: Perfect! It has *both* simple PAC (4,5,1) and half (4,#4,5) cadences. The half cadence fits perfectly with Gjerdingen's 'converging cadence' it just has a Neapolitan/phrygian inflection. Thanks.


Comparing weights versus time graphically using reshape, vioplot, and ggplot2

Question: I have a group of 200 children who came to clinic at months 0, 1, 2, 3, 6, 9, and 12 this year. At each clinic visit the children were weighed.
# Set seed to create reproducible example data
set.seed(50)

# Create patient ID numbers, genders, and ages
control <- NULL
control$Age_0 = round(runif(200,1,10), digits = 1)
control$Gender <- sample(c("Male","Female"),200,T)

# Create monthly weights
control$Weight_0  = ((control$Age_0 + 4) * 2)
control$Weight_1  = (control$Weight_0 * 1.1)
control$Weight_2  = (control$Weight_0 * 1.2)
control$Weight_3  = (control$Weight_0 * 1.3)
control$Weight_6  = (control$Weight_0 * 1.4)
control$Weight_9  = (control$Weight_0 * 1.6)
control$Weight_12 = (control$Weight_0 * 1.8)

# Store as data frame
control <- as.data.frame(control)

This gives me data that looks like:
head(control)
  Age_0 Gender Weight_0 Weight_1 Weight_2 Weight_3 Weight_6 Weight_9 Weight_12
1   7.4   Male     22.8    25.08    27.36    29.64    31.92    36.48     41.04
2   4.9 Female     17.8    19.58    21.36    23.14    24.92    28.48     32.04
3   2.8 Female     13.6    14.96    16.32    17.68    19.04    21.76     24.48
4   7.9   Male     23.8    26.18    28.56    30.94    33.32    38.08     42.84
5   5.6 Female     19.2    21.12    23.04    24.96    26.88    30.72     34.56
6   1.4   Male     10.8    11.88    12.96    14.04    15.12    17.28     19.44

I asked for help on analyzing this data set previously here: Comparing weights versus time graphically with error bars. Spacedman suggested that I try making a violin plot of the data. I figured out how to do this, like so:
library(vioplot)
vioplot(control$Weight_0, control$Weight_1, control$Weight_2, control$Weight_3, control$Weight_6, control$Weight_9, control$Weight_12, col = "gold", names = c("0", "1", "2", "3", "6", "9", "12"))

Spacedman suggested that I make plots by age group. Apparently this would be easier if I were to put the data in long format. I think I figured out how to do this, like so:
long <- reshape(control, idvar = "ID", ids = row.names(control), times = names(control)[3:9], timevar = "Characteristic", varying = list(names(control)[3:9]), direction = "long")

head(long)
           Age_0 Gender Characteristic Weight_0 ID
1.Weight_0   7.4   Male       Weight_0     22.8  1
2.Weight_0   4.9 Female       Weight_0     17.8  2
3.Weight_0   2.8 Female       Weight_0     13.6  3
4.Weight_0   7.9   Male       Weight_0     23.8  4
5.Weight_0   5.6 Female       Weight_0     19.2  5
6.Weight_0   1.4   Male       Weight_0     10.8  6

My question is:
Now that I have the data in long format, can anyone suggest how to use either vioplot or ggplot2 to create graphics that are stratified in this manner? And any other suggestions on how to analyze these data graphically? And in particular how else to take advantage of this "long" format?
Answer: Not sure exactly what you're trying to do but here are some starters.  They don't do well at showing the longitudinal nature of the data but they do illustrate how easy it is to do things once you have the data in long format.  Like B. Williams I have renamed your weight variables.

Some interesting options for dealing with the longitudinal nature of the data are in this question's answers.
library(reshape2)
library(ggplot2)
library(scales)

# Set seed to create reproducible example data
set.seed(50)

# Create patient ID numbers, genders, and ages
control <- NULL
control$Age_0 = round(runif(200,1,10), digits = 1)
control$Gender <- sample(c("Male","Female"),200,T)

# Create monthly weights
control$Weight_00  = ((control$Age_0 + 4) * 2)
control$Weight_01  = (control$Weight_00 * 1.1)
control$Weight_02  = (control$Weight_00 * 1.2)
control$Weight_03  = (control$Weight_00 * 1.3)
control$Weight_06  = (control$Weight_00 * 1.4)
control$Weight_09  = (control$Weight_00 * 1.6)
control$Weight_12 = (control$Weight_00 * 1.8)

# Store as data frame
control <- as.data.frame(control)

control.m <- melt(control, id.vars=c("Age_0", "Gender"))
head(control.m)

ggplot(control.m, aes(x=variable, y=value, color=Gender)) + geom_boxplot()
ggplot(control.m, aes(x=variable, y=value, color=Gender)) + geom_violin()
ggplot(control.m, aes(x=cut(Age_0, 5), y=value, color=Gender)) + geom_boxplot()

Answer: One option. Note that I renamed your weight names as they will otherwise not be ordered properly when read as factors.
# Create monthly weights

control$Weight_A  = ((control$Age_0 + 4) * 2)
control$Weight_B  = (control$Weight_A * 1.1)
control$Weight_C  = (control$Weight_A * 1.2)
control$Weight_D  = (control$Weight_A * 1.3)
control$Weight_E  = (control$Weight_A * 1.4)
control$Weight_F  = (control$Weight_A * 1.6)
control$Weight_G = (control$Weight_A * 1.8)

# Store as data frame
control <- as.data.frame(control)
long <- reshape(control, idvar = "ID", ids = row.names(control), times = names(control)[3:9], timevar = "Characteristic", varying = list(names(control)[3:9]), direction = "long")

library(ggplot2)
ggplot(long,aes(Age_0,Weight_A,group=interaction(Gender,Characteristic)))+geom_violin(aes(fill=Gender),alpha=.2)


Cochran's rules for contingency table

Question: I am proposing this question for a chi-squared test of association between party and voting. The following table is based on how (R)-Republican and (D)-Democrats voted on a specific bill
<code>     yes no
   R  99 11
   D   1 48
</code>
Since the (D, yes) cell is 1, could I be violating Cochran's rules for a chi-squared test?
Comment: Cochran's main point under this heading was that a rule such as all expected counts being at least 5 was over-cautious.
Comment: What is the *expected* count for D-yes?
Comment: 30.817 found from (100*49/159)
Comment: Isn't the rule that the $\chi^{2}$ contingency table test should not be used when *expected* counts in any cell are less than 5?
Comment: @Alexis I should have specified that the table listed here is the observed counts. None of the expected count cells are less than 5
Comment: @NickCox is spot on.
Answer: Answer: contingency table $\chi^{2}$ tests with expected counts less than 5 were deemed inappropriate by Cochran, but your example is of observed counts.

Cochran's rules for contingency table


Map a Filtered Array in PHP

Question: I am trying to map one array, array1, as key to another array, array2. Basically this:
[
    "array1_val1" => [
        "array2_val1"=> "creation_time",
        "array2_val2"=> "creation_time",
        ...
    ],
    ...,
]

This is not the problem, the problem is the method I am trying out. As follows:
$div = array_map(function ($value){
    global $files;
    global $value;
    return array_filter($files, function($k){
        // global $value;
        $ex = explode("_", $k);
        var_dump(substr($ex[0], 0, 5)."    ".$value."   ".__LINE__);
        return substr($ex[0], 0, 5) === $value;
    }, ARRAY_FILTER_USE_KEY);
}, $file_names_g);

Definitions:

$file_names_g - is an array that has all distinct values (first 5 letters of the file names of $files values)
$files - is an array with filename (key) and creation date (value). The filname starts with same 5 letters in $file_names_g and rest differ depending on date the files are created.

Filename example: ABC_24May2017.bak
Now I want the files that start with the same first 5 letters in $file_names_g with $file_names_g being a key and and array with file name as key and creation date as value, (this is the format of the $files array).
Now the problem is that I cannot figure out how to give $value variable access to the function in array_filter. Mentioning it global doesn't help, I get either an empty value or a null. How can I overcome that or is there any better method?
Regards
Comment: You can pass a value into a closure using [`use`](https://stackoverflow.com/questions/1065188/in-php-5-3-0-what-is-the-function-use-identifier)
Answer: You can use a variable defined in the outer scope inside a closure function with use:
$value = 'foo';
function($k) use ($value) {
     // you can now access the variable value
}

Comment: You learn something new everyday! Thanks! but now I have a new problem. Array is mapped to numeric keys, not like I wanted.
Comment: @echo_salik Ah ok then :) Just please try to avoid "solved it" comments, as that might come across as a bit insulting to someone having a similar issue as you. If the problem is not even a problem anymore, that's a valid point.
Comment: @echo_salik Please open a new question about that specific question and keep the question only to that one problem.
Comment: yeah... i though of that, during which I solved the question. Thanks!
Comment: @echo_salik you can also ask and answer your own question in one go. (There's a checkbox on the bottom for that.)
Comment: my solution was more like... well its ok like that i get what i need. So yeah... not much of a solution xD
Comment: Aye aye Captain! :)

Map a Filtered Array in PHP


How to find 5-year survival probability of newborns from a life table?

Question: I was trying to learn cohort component method for population projection from this link of the webpage of Measure Evaluation. To project the population forward using cohort component method, when the age groups are in 5-year intervals, we need 5-year survival probabilities (please see Table 8.1 of the above link).
Now, I can find out 5-year survival probabilities from the life table of my country. But how can I get something like the first entry of Column 4 of Table 8.1 (which is 0.9809) from a life table? As far I understand this quantity is the probability of surviving of newborns during the 5 year projection period.
Answer: This is calculated is as follows: (1L0 + 4L1)/(5*100,000).


How to install Pygame on Sublime Text on Mac

Question: I've been using python on my MacBook Pro (2018) for a couple months and it seems to be overheating like crazy. but only when I'm using IDLE. So I decided to switch to Sublime Text as an alternative.
Does anyone know how to get PyGame to work on sublime text on macOS?
I'm getting an error saying:
<code>ImportError: No module named pygame
</code>
even thought I do have PyGame installed correctly as I have been using it on python's IDLE. I've even deleted and reinstalled PyGame but still no hope.
Any tips??
Comment: How did you install `pygame`? With `pip install pygame` or with another command?
Comment: By default Sublime runs `python` to execute Python scripts, so if you're for example using Python 3, then that would be installed as `python3` and thus Sublime is using the wrong version to run your program.
Comment: @NinoFiliu yeah I used the pip install Pygame command
Comment: pip either install packages for Python3 or Python2.7 or both. Check that you installed the package with the right version.
Answer: It seems like Python does not know that Pygame is installed. Therefore, you have to reference it. Using Package Control that comes with Sublime Text 3 seems like the best idea for you. Here's a quick guide -
https://forum.sublimetext.com/t/sublime-will-not-import-pygame/12545