Melhor forma de passar dados para todos os Controllers MVC

Question: Após fazer login pelo controller LOGIN, uma session é criada com o ID desse usuário no sistema, apartir desse ID posso dar um "fetch" com todas as suas informações, o grande problema é que, ao logar o usuário uma navbar fica no topo do site, ex:

Esse navbar fica no arquivo header.phtml, que não é uma "view", mas é chamada quando uma view é instanciada, para mostrar a navbar do usuário em todas as páginas eu tenho que passar um array com os dados desse usuário para todos os controllers através do controller principal no qual todos extendem, dessa forma eles irão "jogar" essas informações nesse header.phtml, qual seria a melhor forma de passar as informações do usuário logado para todos os controllers e exibi-lo nas views
Comment: Você quer saber em qual formato você passa os dados ou outra coisa?Realmente não entendi sua necessidade.
Comment: Você poderia passar pela session também e definir os dados no seu *controller* principal
Comment: Qual o framework você está utilizando?
Comment: Estou fazendo à mão, pensei em passar uma session com um array, mas se os dados forem atualizados? ficariam estáticos.
Comment: Insere uma regra na atualização dos dados em que se o usuário logado atualizar as próprias informações a sessão também é atualizada
Comment: Entendi, pode me dar uma luz sobre como seria essa regra? seria algo como AffectRows? e como eu passaria essa informação? vamos dizer que o usuário atualize seus dados no controller 'Minha Conta', como eu 'Avisaria' outro controller?
Comment: no método que você realiza a atualização do usuário você tem q fazer um `if($_SESSION["Usuario"]["id"]){$_SESSION["Usuario"]["username"] = $_POST["Usuario"]["username"]}` seria alguma coisa nesse sentido, mas sem ver seus códigos fica muito complicado ajudar mais.
Comment: Por hora eu vou indicar sua pergunta para fechar como "não é claro no que está perguntando", mas caso você a edite e deixe mais evidente sua necessidade eu removo meu voto.
Comment: Ok, Acho que isso já basta, obrigado pela ajuda!
Answer: Isso vai depender muito de como você está organizando a sua aplicação. Se você estivesse usando algum framework seria mais fácil sugerir uma solução. Seguem abaixo possíveis soluções.
Opção 1
Crie um objeto que represente o usuário e que possa ser acessado em qualquer parte da aplicação. Algo como SeuFramewok::$user. Em cada "page load", inicialize esse objeto a partir dos atributos que você gravou na sessão durante o login. Atualize os atributos da sessão quando o usuário atualizar suas informações. Essa solução é usada pelo YiiFramework (ele tem um objeto Yii::app()->user, acessível globalmente).
Opção 2
Coloque um objeto que representa o usuário no controlador pai (também carregando a partir da sessão), em uma propriedade de acesso publico. Acesse esse objeto no header.phtml através da referência que você tem ao controller.
De um forma ou de outra você precisa gravar os dados do usuário em uma sessão. O interessante é pensar em uma forma de disponibilizar isso facilmente para acesso na sua aplicação. Recomendo utilizar um framework, pois normalmente ele já implementa isso pra você e também lhe uma boa experiência caso deseje desenvolver o seu.
Answer: Eu criaria uma classe "usuário", com seus atributos e propriedades, e jogaria em uma session. Eu sobrescreveria a session sempre quando acontecesse alguma atualização.
Um problema desta minha solução seria o custo que estas "sessions" teriam para o servidor, pois imaginem uma aplicação com mais de dez mil acessos simultâneos onde cada usuário teria sua "session" alocada no servidor.
Comment: Vamos dizer que seja uma aplicação grande, então, qual seria a melhor opção?
Comment: Se o objeto não for complexo o custo não será grande. Se o objeto for complexo grave na sessão apenas uma parte dele (serialize apenas os atributos que precisam ser gravados) e carregue a partir dos dados da sessão.


A "systematic" part of a random time series component?

Question: I've seen at least 3 sources on time series* state that the component of a series that is variously called random, stochastic, or noise (something clearly separate from any deterministic, patterned component) itself consists of 2 parts, a systematic part and an unsystematic part.  I can't for the life of me figure out how the random part can in turn have a systematic part.  I can see how the series can have unsystematic and systematic parts, but not how the random component of the series could have both of these.
*For example, Burns and Grove, The Practice of Nursing Research (2005, p. 475-6).
Answer: The Burns reference that you are quoting seems to dividing the stochastic part into autocorrelation error, which is a byproduct of any time series analysis (and is systematic), vs. truly random error which is uncontrollable.
-Ralph Winters
Comment: @Ralph, +1 for looking up the reference. I should note however that if this is truly how the authors are dividing stochastic part it is a bit misleading. Suppose you have autoregressive model $Y_t=\rho Y_{t-1}+\varepsilon_t$. The division is that $\rho Y_{t-1}$ is systematic and $\varepsilon_t$ is non-systematic part. But if we substitute $Y_{t-1}=\rho Y_{t-2}+\varepsilon_{t-1}$ into the first equation and repeat the process indefinitely  we will get that $Y_t=\sum_{s=0}^{\infty} \rho^{s}\varepsilon_{t-s}$, so there is actually no systematic part according to the original definition.
Answer: "random" is often used as if it was a real property of the data under study, where it should be replaced with "uncertain".  To give an example, if I ask you what how much money you earned over the past month, and you don't tell me, it is not "random", but just uncertain.  However, treating the uncertainty as if it was random allows you to make some useful conclusions.
The noise is not "random" per se, but given that we usually have limited knowledge of how each particular piece of "noise" is generated, assuming that it is random can be useful.
Now whenever you fit a model to some data, you will have residuals from that model.  And if treating the "noise" as if it was random was a good idea, then the residuals from the model should be consistent with whatever definition of "randomness" you have used in fitting the model.  If they are not, then basically the time series is telling you that the "randomness" you assumed is not a good description of what it actually happening, and it gives you a clue as to what a better description might be.
For example, if I fit a linear relationship for the systematic part, but it is actually quadratic, then the so-called "random" noise will not look random at all, rather it will contain the squared component of the systemtatic part.
To make it even more concrete, suppose that your response $Y$ is a deterministic function of $X$, say $Y=3+2X+X^2$.  Now, because you don't know this function you suppose that $Y=\alpha+\beta X + error$, and because you have no reason to doubt the model prior to seeing the data, you assume that the error is just "random noise" (usually $N(0,\sigma^2)$).  However, once you actually fit your data and look at the residuals, they will all line up as an exact quadratic function of the residuals.  Thus there is a systematic component to the "noise" (in fact the "noise" is entirely systematic).  This is basically "Nature" telling "You" that you model is wrong, and gives a clue as to how it could be improved.
The same kind of thing is happening in the time series.  you could just replace the model above with $Y_{1}=1,Y_{2}=6,Y_{3}=0.5,Y_{4}=10,Y_{5}=3,Y_{6}=10$ and for $t\geq7$ have $Y_t=10+2 Y_{t-1} -5Y_{t-1}^3 + 2Y_{t-5}$  and the same kind of thing would happen.
Comment: +1 with the request for clarification: the "systematic" part of the residual should be nigh undetectible, otherwise it is an indication that the model is not satisfactory: a systematic effect -- whether real or an artifact of analysis -- has leaked out of the model, as it were, and the model needs to be modified to avoid this.
Comment: @wayne, this may or may not be the case.  If you have enough resources/time, you could probably find some justification for any part of the noise being "systematic".  This is basically an "over-fitting" problem, and also one of bias-variance trade off.  Taking account of a supposed systematic effect may lead to a better fit to the current data set, but could well lead to a worse fit in other data sets.
Answer: Systematic and unsystematic are rather ambiguous terms. One of the possible explanations is given by @probabilityislogic. Another may be given here. Since the context you gave is time series, I think this might be related to  Wold's theorem.  Unfortunately wikipedia text captures the essence, but does not go into the details of which part is systematic and non systematic.
I did not manage to find appropriate link to refer to, so I will try give some explanation based on the book I have. This subject is also discussed in this book. I will not give precise and rigorous definitions, since they involve Hilbert spaces and other graduate mathematics stuff, which I think is not really necessary to get the point across.
Each covariance-stationary process $\{X_t,t\in \mathbb{Z}\}$ can be uniquely decomposed into two stationary proceses: $X_t=M_t+N_t$, singular $M_t$ and regular $N_t$.
Singular and regular processes are defined via their prediction properties. In stationary process theory the prediction of process $X_t$ at time $t$ is formed from linear span of its history $(X_s,s<t)$. Singular processes are processes for which the prediction error:
$$E(\hat{X}_t-X_t)^2$$
is zero. Such processes sometimes are called deterministic, and in your context can be also called systematic. The most simple example of such process is $X_t=\eta$ for all $t$ and $\eta$ some random variable. Then the linear prediction of $X_t$ based on its history will always be $\eta$. The error of such prediction as defined above would be zero.
Regular stationary processes on the other hand cannot be predicted without error from their history. It can be shown that the stationary process $N_t$ is regular if and only if it admits  $MA(\infty)$ decomposition. This means that there exists white-noise sequence $(\varepsilon_t)$ such that
$$N_t=\sum_{t=0}^{\infty}c_n\varepsilon_{t-n}.$$
where coefficients $c_n$ are such, that the equality holds. These processes sometimes are called non-deterministic, or probably non-systematic in your case.
Comment: Don't the $c_t$ need to form an absolutely convergent sum? i.e. $\sum_{t=0}^{\infty}|c_t| < \infty$ as well
Comment: @probabilityislogic, I intentionaly wrote non-rigorous mathematical text, since strict definition of singular and regular processes involves Hilbert spaces, which I do not think are really necessary to get the point accros. I will update the answer to reflect that. Concerning $c_t$, it does not need to be summable. The equation must hold in $L^2$ sense, hence summability of $c_t^2$ is sufficient.


Find the most repeated value of a key in a dictionary

Question: I have the following  dictionary:
s_final = {
    a:[noun,adj,noun,noun,noun],
    b:[verb,verb,verb,noun]
}

I would like to retrieve the most repeated value of the keys such that my final output will be as follows:
s_final={a:[noun], b:[verb]}

Comment: So what did you try up to now?
Comment: Take care of your code. It's broken.
Answer: Use Counter.
>>> from collections import Counter
>>> s_final={'a':['noun','adj','noun','noun','noun'],'b':['verb','verb','verb','noun']}
>>> {i:[Counter(j).most_common(1)[0][0]] for i,j in s_final.items()}
{'a': ['noun'], 'b': ['verb']}


GMM weight matrix $W_n$ -- what does the index $n$ signify?

Question: The question is as in the title. The GMM estimator (in my Econometrics notes) is as follows:
$\hat \delta_{GMM}(W_n) = (S'_{xz} W_nS'_{xz})^{-1}(S'_{xz}W_ns_{xy})$
Comment: That $W_n$ is a function of the sample, and hence of the sample size, and so it will vary as sample size changes/increases.
Comment: Could you specify how it may be a function of the sample? An example would be great. My current (probably erroneous) understanding is that $W$ simply assigns relative weights to different moment conditions, so I don't see how it is a function of the sample. Thanks a bunch!
Comment: $W$ may be a constant matrix, may be not. When it is indexed by $n$ it means that it is constructed so as to be a function of the sample. The optimal choice of $W$ in terms of efficiency (estimator asymptotic variance) is a function of the sample, as a standard theorem proves which should also be  in your notes.
Comment: It is clear from the comments and an attempted answer that this question is inherently ambiguous and therefore unsuitable for this site.  If you can edit it to provide enough context to figure out the meaning of $n$, then we can vote to re-open.
Answer: The weight matrix $W$ is unknown in this sample and must be estimated iteratively. The notation you've supplied for its estimation is consistent with the Newton-Raphson method where the change in iterative estimates is denoted by $\delta$. You've put the $\hat$ (hat) over that $\delta$, but it should really be over the $W$. As a rule, anything that's estimated (as indicated with hat notation), is implicitly subscripted with $n$.
Comment: I am not sure that $W$ is unknown -- isn't it the case that $W$ can be chosen arbitrarily by the researcher? Unless you're referring to the $W$ that produces the most efficient GMM estimator. If that's what you meant, then the estimator in my question is not necessarily the efficient one.
Comment: The *structure* of $W$ is known. The actual values must be estimated. The structure behind a $W$ could be exchangeable, auto-regressive, etc.


What kind of bandoneon or concertina is appropriate for playing tango music?

Question: I really love the sound of tango and I'd like to buy a bandoneon.
With the relationship but seeming distinct existence from the Concertina, I don't know how to identify which kind of Concertina/Bandoneon would be able to give me that Tango sound.  Can a 20 key C/G do it?  a 30 key?  Is the 142-note bisoronal the only choice?  Which characteristics are required and acceptable?
Also, are these characteristics available in a non-professional instrument? I am an amateur player and can't justify a $3000+ purchase for an instrument I'll probably never be any good at.  Yet, I don't want to buy the wrong kind that has a more Irish sound.
Comment: This was running the risk of being closed as a shopping rec question. I've attempted to bring it on-topic without changing the original intent.
Answer: The term concertina has come to be used for two different families of instruments, both of which evolved out of earlier free-reed instruments.
By 20 (or 30) key C/G you refer to is an Anglo concertina; this style of concertina (along with English and Duet styles) are most closely associated with Irish traditional music (as well as other Northern European folk styles).  These instruments are not traditionally used for playing tangos, and it
may be difficult to achieve all of the expected stylistic features of tango music with this class of concertina.
The bandoneon, which is closely related to the chemnitzer concertina, are essentially  a completely different type of instrument.
ConcertinaMusic.com (a Chmnitzer site) has a nice timeline of free-reed instruments which gives the pedigree of these types of instruments.
Answer: i am an argentinian bandonion pleyer. for sound of tango you need a "Alfred Arnold" or "AA" type. another type you can buy is "Premier".  These both are from Germany but now, you can get those in Argentina too.
Answer: For argentine tango what is most important is to have the range necessary to perform the pieces with the tango sound which is characterized by the sound of two reeds played in octaves.   There are more bandoneons then 142 button layouts that have this characteristic.   There are bandoneons known as chromatic bandoneons ( a misnomer as all bandoneons are chromatic ) meaning in this context that it plays the same notes opening and closing.   These can be found in octaves and much cheaper then the 142 argentine layout.   Other alternatives are the much cheaper einheits bandoneon with 144 buttons.  Be careful though on this one as many come with reeds tuned in tremelo instead of octave.
Since a good one can be had for $1000 though you can afford to pay to have it tuned in octaves with the leftover cash.  I recently went this route and am very satisfied with the sound.


How can I get single keys in multi-item config objects using debug:config?

Question: For example, in drush I can run
drush cget search_api.server.iges_solr backend_config.connector_config.port
and get a useful answer.
('search_api.server.iges_solr:backend_config.connector_config.port': 8988)
In Drupal Console, I've tried the same formatting as in the drush command, I've tried a colon between the main config item, and the sub item
(drupal dc search_api.server.iges_solr:backend_config.connector_config.port)
I've tried a fair number of other things, and I've read the docs to no avail.  Is it possible to do without just grepping?
Answer: No, Drupal Console doesn't support selecting a key from a configuration object. This is clear from drupal help debug:config which even mention grepping.
Using grep isn't beautiful, but it works:
drupal debug:config system.date | grep -A1 timezone

does return the timezone with the first subkey. (Changing the value after A, you get more lines/the user subkey.)
I would of course prefer to get the configuration object as proper JSON and then pipe it to jq to select a key robustly, but Drupal Console doesn't support an output format option yet - see Github issue.
Comment: I disagree that it is clear from the docs which is why I asked the question.  There are plenty of reasons to use grep on that command besides getting the value for a single key.  For example, if you don't know the exact nomenclature of the key you are looking for.  Still, this does seem to be the right answer, and I appreciate the hint about grep options.  Cheers.


polar equation of the line y = x (in rectangular form) through the origin

Question: I'm using Mathematica and I'm trying to graph the polar equation
$$r = \frac k  {(\cos(\theta) + \sin(\theta))}$$
where k is an element of the integer and theta is the argument of the
function for which I let vary from 0 to 2pi.
If I assign any value to k except 0, I can definitively draw a line.
However whenever I'm trying to assign the value of 0 to k a cartesian plane appears with no graph in it whatsoever.
How come is this possible?
My goal is in fact to graph the equivalent of y = x (in rectangular form), but in a polar coordinate system.
Can someone is able to provide me the algebraic steps (if there is any) necessary to obtain such a graph in PolarPlot (the name of the command) using Mathematica?
Comment: Hey, but how to to it with the Mathematica command PolarPlot[{r = f(theta)},{theta, -2pi, 2pi}]?
Answer: $x=r\cos\theta$, $y=r\sin\theta$, hence the line $x=y$ is equivalent to $\cos\theta=\sin\theta$, which is same as the line $$\theta=\frac{\pi}4$$
Comment: Hey, but how to to it with the Mathematica command PolarPlot[{r = f(theta)},{theta, -2pi, 2pi}]?
Comment: It will just be a line parallel to the $r$-axis
Comment: @AbishankaSaha:  there is no $r$ axis in a polar plot.
Answer: Your equation $ r=k/(cos(\theta)+sin(\theta))$ is equivalent to $r(cos(\theta)+sin(\theta))=k.$ Substitute $ x=rcos(\theta)$ and  $y=rsin(\theta)$ in your equation and you will get $x+y=k$ which is the equation of a straight line. For $k=0$ we get $y=-x.$ Probably if you change the window for your graph you can see the graph.
Comment: But how to to it with the Mathematica command PolarPlot[{r = f(theta)},{theta, -2pi, 2pi}]?
Answer: If you just translate $y=x$ to polar you get $r \sin \theta=r \cos \theta$.  This is satisfied with $r=0$ and any $\theta$, which reflects the coordinate singularity at the origin.  Otherwise you can divide by $r$ and get $\cos \theta=\sin \theta$, which is satisfied when $\theta=\frac \pi 4$, \frac {5\pi}4$.  Plot that.
Comment: But how to to it with the Mathematica command PolarPlot[{r = f(theta)},{theta, -2pi, 2pi}]?
Comment: That is not possible.  This would give at most two values of $r$ because there is only two values of  $\theta$ that work.  The correct thing, as all the answers have shown, is $\theta = \frac \pi 4, \frac {5\pi}4$.  That lets $r$ be free, as it should be.


chain of compact subspaces must be nonempty

Question: Suppose $X$ is a compact space and suppose $\{ F_i \} $ is a collection of closed subsets of $X$ such that $F_{i+1} \subseteq F_i $ for all $i$. , then we must have $\bigcap_i F_i \neq \varnothing $.
MY try: Suppose $\bigcap_i F_i  = \varnothing $. We know the $\{ F_i \} $ must all be compact since they are closed sets living inside a compact space. Notice the collection $\mathcal{O} = \{ X \setminus F_i \} $ is definitely an open cover for $X$. Since $X$ is compact, $\mathcal{O} $ must have an finite open subcollection that covers $X$. How can I use my hypothesis that $F_{i+1} \subseteq F_i$ to get a contradiction. thanks.
Comment: I guess all the $F_i$ should be nonempty.
Answer: You went astray when you said that $\mathcal{O}$ is definitely an open cover of $X$. It's definitely a family of open subsets of $X$, but it doesn't necessarily cover $X$.

Show that $\mathcal{O}$ covers $X$ if and only if $\bigcap_{n\in\Bbb N}F_n=\varnothing$.

Now use that to get your contradiction: if $\bigcap_{n\in\Bbb N}F_n=\varnothing$, then something, and hence contradiction.
Comment: Brian: $\bigcup O = \bigcup ( X \setminus F_i ) = X \setminus \bigcap F_i = X $ is this correct ?
Comment: @DonAnselmo: That's a proof that if $\bigcap_nF_n=\varnothing$, then $\bigcup\mathcal{O}=X$. The converse is equally easy: if $\bigcup\mathcal{O}=X$, then $$\bigcap_nF_n=\bigcap_n(X\setminus F_n)=X\setminus\bigcup\mathcal{O}=\varnothing\;.$$
Comment: So, if $\bigcap F_i = \varnothing$, then $\mathcal{O}$ covers $X$.  How can we get contradiction from here?
Comment: @DonAnselmo: $X$ is compact, so $\mathcal{O}$ has a finite subcover, say $\{O_{n_1},\ldots,O_{n_k}\}$ for some finite set $\{n_1,\ldots,n_k\}$, where $O_m=X\setminus F_m$ for each $m\in\Bbb N$. What can you say about $F_{n_1}\cap\ldots\cap F_{n_k}$?
Comment: i mean the intersection must be empty
Comment: @DonAnselmo: Exactly — and there's your contradiction.
Comment: Brian, but we havent used the fact that $F_{i+1} \subseteq F_i $
Comment: @DonAnselmo: You use that to get your contradiction. If $n_1<\ldots<n_k$, the fact that the sets are nested means that $F_{n_1}\cap\ldots\cap F_{n_k}=F_{n_k}$. (Note: Your problem should include a hypothesis that the sets $F_i$ are non-empty.)
Comment: Got it! thanks very much Brian !! You are the topology genius of MSE!!
Comment: @DonAnselmo: You're welcome!
Answer: In fact something stronger exists. $X$ is compact iff for every family of sets {$F_{i}:i\in I$},$F_{i}$ closed subsets of $X$ that have the finite intersection property we have that $\cap${$ F_{i}:i\in I$}$\neq \emptyset$(the proof of this one is easy enough,but i don't write it because it needs many symbols.If you want it though i'll be happy to write it down:)). Here if we choose finite number of $F_{i}$ we have that their intersection is non-empty and because $X$ is compact we have the result


Como sair da listagem do git?

Question: Estou com um projeto baixado pelo repositório do GitHub.
Quando executo o comando git log dentro desse projeto, ele me lista todas as branches existentes no projeto, porém não consigo sair da listagem.
Já tentei de tudo, já fiz ESC em teclado, já tentei Ctrl+C, porém essas alternativas não funcionam, alguém teria uma sugestão?

Comment: Pressione `q` para sair.
Comment: @AndersonCarlosWoss muito obrigado funcionou, coloque como resposta para eu marcar como resposta.
Answer: Bem vindo ao less! Um paginador Unix que faz mais coisas que o more.
Você pode fazer muita coisa interessante com o less, como procurar por uma expressão regular com /. Mas, se seu interesse é apenas sair do programa, basta um q.
Esse é o mesmo paginador que você vê ao consultar o man de algum programa, como man less.

Detalhes extraídos dos comentários
Como bem lembrado pelo @Woss, é possível configurar o seu paginador. E essa configuração pode ser feita por repositório (não apenas global).
Conforme documentação que o @hkotsubo cavou, basta setar a propriedade core.pager para fazer a configuração. Leia a documentação oficial.
Como nota de humor de programadores:

You can set it [core.pager] to more or to your favorite pager (by default, it's less)

Em tradução livre (traduzindo até mesmo o nome dos programas):

Você pode configurá-lo [core.pager] para mais ou para o seu paginador favorito (por padrão, é menos)
Comment: Jefferson, ele sempre usa o Less ou isso é configurável? Estava pesquisando sobre isso antes de responder.
Comment: @AndersonCarlosWoss É configurável, basta setar o `core.pager` no `.git/config`: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration#_code_core_pager_code
Comment: @JeffersonQuesado Pois é. O simples fato do `less` ser uma "evolução" do `more` já mostra como programadores têm um senso de humor peculiar :-)
Comment: @hkotsubo, adorei o jogo de palavras na documentação: "You can set it to `more` or to your favorite pager (by default, it's `less`)"
Comment: @AndersonCarlosWoss é configurável, fica no `.git/config` na minha memória. Mas infelizmente eu perdi o link do SO internacional que falava sobre isso...
Answer: Olá!
CTRL+Z

Pode resolver o seu problema. Esse comando suspende os processos em questão, para encerra-los você pode apenas digitar q
Comment: `Ctrl+z` apenas suspende o processo, mas não o finaliza. Acredito que criar e manter múltiplos processos suspensos não será o desejado.
Comment: @AndersonCarlosWoss eita, não sabia disso! Obrigado Anderson, já fica a dica, será que deleto essa resposta?
Comment: Você pode editar e corrigir a informação, deixando claro isso. Provavelmente fazendo isso reverterá os votos na resposta.
Comment: @AndersonCarlosWoss eu corrigi até para não passar desinformação, obrigado.

Como sair da listagem do git?


How to set hostname if hosting multiple servers on the same machine?

Question: I'm learning about setting up my own web and mail servers, and I've been confused about this question for days, and articles online (including Server Fault) seems to be so inconsistent with their use of the term 'subdomain' and 'hostname'.
From my understanding:

A host name uniquely identifies a computer in a network
A domain and subdomain must have a DNS A record which points to one or more hosts

Let's say my web server is at 126.96.36.199, I have my host name set to development (confirmed by running hostname in bash shell), and I'm setting A records like so:
@   -> 22.214.171.124
www -> 126.96.36.199
mx  -> 22.214.171.124
mx  -> 22.214.171.124

Then I have the www and mx subdomains pointing to my web server whose hostname is development. The mx subdoman also points to two hosts (for redundancy).
Why do I need a hostname? My machine can already be identified using its IP address.
I read somewhere that says a hostname is important because it gets sent in some messages. But if my server is both a mail server, and a file server, and a database server, and etc, what should I set my hostname to be? I certainly don't want someone receiving my mail to see a from address of development. And a machine can only have one hostname right? Should I set my computer's hostname to abc.example.com or just abc?
Main Question
How to set hostname if hosting multiple servers on the same machine?
Comment: @c4f4t0r Are you saying my mail server can have one host name, my file server can have another host name?
Comment: try to find the different between dns and hostname
Comment: a server is a machine physical or virtual.
Answer: The hostname is a convenience for uniquely identifying the host on your network.  It's an entirely internal name that can be anything you want.  The hostname doesn't have to be related to any of its DNS names.
For example, your host named abc can have DNS records that point to it as www.example.com, mail.example.com, and so on.
If you run local DNS within your LAN, you can also give your host a local DNS name of abc or abc.localdomain, so you can type http://abc into your browser.  Again that just helps you to identify the host within your LAN.
Comment: because the email used hostname - do a small experiment: Try to resolve the fqdn and then try to resolve the hostname only.
Comment: But how come (if hostname has nothing to do with DNS records), one time I tried sending an email to myself from my server, and it arrived saying it's from `dayuloli@development`. `dayuloli` is my username on the server, and `development` is my machine's hostname
Comment: An example of why a unique identifier is needed is reverse DNS. RFCs state that `PTR` records should point at the unique canonical name of the device associated with a given IP address. A server could be providing numerous functions each with their own `A` record (www, mail, etc.), but those are all logical aliases. The uniquely identifying name for that device would be the hostname.
Answer: To answer your question - the hostname  should be whatever is meaningful to you or your organisation.
Hostname
The hostname is used only by the host. It's used by the system and services as a default (human-readable?) identity when no context-specific identity has been specified.
It might be used in a log file; it's probabaly used on your shell to give you an indication of which host you're administering; as you've pointed out, the default domain name for your mail server is your hostname, but this will need to be configured.
DNS
In your situation DNS is used by anything on the internet, trying to find its way to your server. That's all - a name referring to an IP address. You have multiple records pointing to the same server which can be used by applications and services to decide what to do with requests, which website to display for example, or which mailbox to deliver an email to. You need to tell the serveices what the domain names should mean to them, but they don't really mean anything to the host itself.
It would be wrong to say that the two are unrelated because often there will be a DNS infrastructure that is managed internally (on a LAN or WAN), or a de-centralised name discovery method like NetBIOS or MDNS. In these cases, the hostname would be used to identify or register the host within that naming service. However, from what you describe of your environment they seem to have no relation at present.
Answer: Hostname can be anything that you want and does not necessarily taken from the FQDN of your server like abc for abc.example.com though it is common to do that. It is not really a big deal except other server under example.com may easily recognized abc server.
However the issue may be if one want to set multiple FQDN for each server services hosted on the same machine as mentioned in the question like mail.example.com, db.example.com, web.example.com, ftp.example.com and dns.example.com which are all in the abc.example.com machine.
The reason may be are the server admin may not want the server services to communicate as abc.example.com and want, for example, mail.example.com to communicate on its own FQDN instead.
In furtherance to that, he or she, may want to secure each of the server services in their own FQDN, instead of just the server main FQDN abc.example.com.
If that is so, I think editing /etc/hosts and adding all the needed FQDN for the server services in the fixed ip line (whether 127.0.1.1 or 192.168.0.1 or static public ip) for the server may be the solution, for example:
abc.server.fixed.ip  abc.example.com  web.example.com  mail.example.com dns.example.com other-services.example.com abc-server-preferred-name


iscroll childbrowser maximum width

Question: just a questition related to Apple IOS6/IPad 2/IPad Mini and an iScroll 4.2.5 within a Childbrowser which is opened through an App build in Adobe Phonegap 2.3.0:
Horizontal Scroller with Images, scaled to 100% of the device height (width is dynamic):

...

one Image has a width of 1125px with some borders and spaces around the iscroller with 80 pages goes up to the estimated width of 111966
The iscroll works perfect for horizontal scrolling. But if there are more than 80 Images within the scroller, IPad 2 stopps displaying Images after the 42th Image, the IPad Mini stopps displaying after the 70th Image. It seems that the last Image is "cutted" of from top to bottom or the page's end has reached for the Images but not for the scroller.
It seems that there is a maximum width, but what now?
tnx
Answer: A solution would be to only show the number of allowed images and then refresh the iscroll with the next amount of allowable images.
Comment: Thanxs, i have used a paging for this

iscroll childbrowser maximum width


Exercise on Conditional probability

Question: I'm doing the following exercise:
You have 2 boxs filled with balls. In the first box you have 30% white, 30% black, 20% green and 20% blu balls. In the second box you have 25% white, 25% black, 25% green and 25% blu balls.(I assume that the quantity of balls are the same, for example 100 in the first one and 100 in the second one)
Calculate:

The probability of have extracted a blue ball, from a random box
if you extracted a blue ball, what is the probability that you extracted it from the first box?
If you take a random ball from the first box and a random ball from the second box, what is the probability that the ball are the same?

That's what I did:
1) $B=$probability of a blu ball, $A$=first box, $\neg A$= second box
$$P(B)=P(B|A)P(A)+P(B|\neg A)P(\neg A)=20\%*\frac{1}{2}+25\%*\frac{1}{2}=22.5\%$$
2) $B=$probability of a blu ball, $A=$first box
$$P(A|B)=\frac{P(B|A)P(A)}{P(B)}=\frac{20\%*\frac{1}{2}}{22.5\%}=0.88$$
I think that what I did until now is right. But know I dont know how to calculate the third point.
Can you give me some hits?
EDIT:
I just noticed that on the 2nd point if I switch the box A
with the box ¬A I get 0.55 (for the first) 0.88 (for the second). Isn't it strange? in the first box you have less of that kind of ball (20%) in the second you have more(25%). Shouldn't I get an highter probability if I use ¬A instead of A?
Answer: You will need to use weighted probabilities to solve this. Weighted probabilities work as follows. Suppose each event $A_i$ has probability $P(A_i)$ and $B$ has probability $P(B|A_i)$ for each $A_i$, (that is, $B$ is dependent on $A_i$) and only one of the $A_i$ can happen. Then the probability that $B$ happens is
$$P(A_1)P(B|A_1)+ P(A_2)P(B|A_2)+...+ P(A_n)P(B|A_n)$$
Thus, in this case, we have that $A_1$ is the event of getting a white ball from the first box, $A_2$ is for black balls, $A_3$ for green balls, and $A_4$ for blue ones. Then the probability of drawing a matching ball is
$$0.3P(B|A_1)+0.3P(B|A_2)+0.2P(B|A_3)+0.2P(B|A_4)$$
Given the ball percentages for box $2$, we can find each $P(B|A_i)$:
$$0.3(0.25)+0.3(0.25)+0.2(0.25)+0.2(0.25)$$
and that should be your answer, once you simplify it.
Comment: They seem fine, for all I can tell.
Comment: Oh it wasn't so hard. I should have spend more time on it. Are the other point correct?
Comment: @malloc If you found this helpful, don't forget to $\uparrow$! :)
Comment: I'll give you the "green mark", but I must wait some time before (math overflow policy)
Comment: Haha! Okay, no problem. XD
Comment: I just noticed that on the 2nd point if I switch the box $A$ with the box $\neg A$ I get 0.55 (for the first) 0.88 (for the second). Isn't it strange? in the first box you have less of that kind of ball (20%) in the second you have more(25%). Shouldn't I get an highter probability if I use $\neg A$ instead of $A$?
Comment: Ah, I see a better way to calculate it. Suppose you take $100$ balls from the first bin and $100$ from the second bin. Then $20$ should be blue from the first bin and $25$ should be from the second. That means that a total of $55$ blue balls are drawn, and $20$ are from the first box, so the probability should be $\frac{20}{55}=0.\overline{36}$.
Comment: @malloc Oh no! My "green mark" is gone!
Comment: I was hoping to new answer to my question, so I removed it to give some hope to the other xD.. Sorry it wasn't a good behaviour
Comment: :( Was my answer not good enough? If there's any way to improve it, please, let me know!
Answer: Part 1 looks alright. For part 2, there seems to be small mistake as $P(B|A)$ is $20\%$.
For part 3,
$P(balls\ of\ same\ color) = \sum P(C_1 \cap C_2) = \sum (P(C_1)*P(C_2)) \ \ \ \forall\  colors\ C$
$ \ \ \ \ \ \ \ \  = 0.30*0.25 + 0.30*0.25+0.20*0.25+0.20*0.25$
$ \ \ \ \ \ \ \ \ =0.25 = 25\%$
$C_1 \cap C_2$ means that ball is drawn of color $C$ from both bags. Since the balls are drawn independently, the probabilities for individual bags get multiplied.
Since the events of drawing balls of same color are mutually exclusive for different colors, these probabilities get added.
Comment: fixed..... Ty...
Answer: It will be $(.2)(.25)+(.2)(.25)+(.3)(.25)+(.3)(.25)=.25$. Or more simply, no matter what ball is taken out of the first box,  $\frac{1}{4}$ of the balls in the second box are a match.
Answer: For the third point, you can either pick
1)white and white(0.3*0.25)
2)black and black(0.3*0.25)
3)green and green(0.2*0.25)
4)blue and blue(0.2*0.25)
The answer is the sum of all these probabilities which is 0.25

Exercise on Conditional probability


Como conseguir carregar esses dados criados em uma tela de edição

Question: Seguinte, eu tenho essa tela de cadastro onde clicando no botão "+" vai adicionar inputs tipo texto (conforme codigo em anexo)
Meu problema é que essa criação é dinamica, a pessoa pode adicionar tanto 1, quando 2,3,4..ou seja N.
vou salvar esse dados e preciso que na hora de editar, consiga montar essa mesma estrutura. Ou seja, vai carregar todos os inputs de texto criados na tela de adição.
Eu não sei como fazer trazer essas informações de forma dinamica.
Estou aplicando angular v1 no projeto, estou usando para fazer a integração com o backend.
Então, gostaria de uma solução mais focada pro angular.
Exite uma forma de fazer?
Answer: Defina uma variável que vai guardar os valores no controller e um counter:
$scope.x = [];
$scope.counter = 0;

Agora você precisa de colocar ng-model nos inputs. Para isso, você precisa criar o html de forma dinâmica por ser um array que vai ter um counter dinêmico, e aí entra o $compile, documentação aqui: https://docs.angularjs.org/api/ng/service/$compile
Basicamente funciona assim:
// cria o input
var input = '

<input type="radio" disabled style="vertical-align: text-bottom;" value="teste" name="data"><input type="text" value="" class="form-control radio-alinha text" placeholder="Adicionar Alternativa" ng-model="x[' + $scope.counter + ']">

';
//compila e coloca no escopo
var compile = $compile(input)($scope);

Aí a var input fica renderizada. Não esquece de aumentar o counter no final: counter++


What is the null and alternative hypothesis of a chi square test whether a single matrix is an identity matrix?

Question: Say I had a correlation matrix:
$$
M =
\begin{bmatrix}
0.8 & 0.1 & 0.1\\
0.3 & 0.7 & 0.1 \\
-0.1 & -0.2 & 0.9
\end{bmatrix}
$$
I want to show that it is approximately an identity matrix $M = I$.
I was looking at the following R package: https://www.rdocumentation.org/packages/psych/versions/2.1.6/topics/cortest.mat
It uses a method derived from Steiger 1980, where he observed that

"the sum of the squared elements of a correlation matrix, or the Fisher z score equivalents, is distributed as chi square under the null hypothesis that the values are zero (i.e., elements of the identity matrix)"

I would translate this as:
$$
\sum^{N}_{i=1}\sum^{M}_{j=1}x_{i,j}^2 \sim \chi^{2}\; \mathrm{iff}\; \sum^{N}_{i=1}\sum^{M}_{j=1}x_{i,j}^2 = 0
$$
This doesn't make much sense to me. Using a simple identity matrix, I can easily show that this isn't true. I must be misunderstanding it.
E.g.
$$
I_{3} =
\begin{bmatrix}
1 & 0 & 0\\
0 & 1 & 0\\
0 & 0 & 1
\end{bmatrix}
\\
$$
$$
\sum^{N}_{i=1}\sum^{M}_{j=1}i_{i,j}^2 = 3
$$
When it comes to formulating the null and alternative hypothesis, the best I can get is:
H0: $\sum^{N}_{i=1}\sum^{M}_{j=1}x_{i,j}^2 = 0$
HA: $\sum^{N}_{i=1}\sum^{M}_{j=1}x_{i,j}^2 \neq 0$
Which somewhat makes sense. I want to prove that I have an identity matrix, and if it is true that summing the elements the identity matrix != 0, then this seems to check out. But the math I am coming here just feels inconsistent.
I ran the test on an identity matrix and found:
<code>> cortest(diag(10), cor=FALSE)
Tests of correlation matrices
Call:cortest(R1 = diag(10), cor = FALSE)
 Chi Square value Inf  with df =  100   with probability < 0
</code>
Looks great, assuming p val is "with probability", then that's what I want to see!
Then I ran the test again on a uniformly distributed correlation matrix
<code>> X <- matrix(runif(100,-1,1), ncol=10)
> cortest(X, cor=FALSE)
Tests of correlation matrices
Call:cortest(R1 = X, cor = FALSE)
 Chi Square value 7139.26  with df =  100   with probability < 0
</code>
this also has a very low p-value... maybe not so great afterall and I am not interpreting the results correctly
I checked out the original 1980 article on this, but it was too advanced for me to understand, and I cannot find any resources on this particular test online.
So my main question is:

What is the null and alternative hypothesis?
Answer: According to the paper, the test is the following. Denote $m$ as the number of features, then define $k = (m^2 - m)/2$, the number of unique off-diagonal element in the correlation matrix. Furthermore, define vector $p$ (length $k$) which contains all of these elements. Then (Eq. 16 in the paper),
$$H_0: p = p_0$$
or in your case $H_0: p = 0$, and the alternative $H_1: p \neq 0$.
The test statistic does not sum the diagonal element (see Eq. 22 in paper), only the off-diagonal. The test statistic is $\sum \sum_{i < j} z_{i,j}^2$, where $z_{i,j}$ is the fisher transformation of the $i,j$ element in the correlation matrix. It is distributed as $\chi^2_{k-q}$, where $q$ is the number of common correlations (in your case 1, since they are all 0).
Comment: makes much sense, thank you!


Unable to create indicator variables

Question: I am using the following code to create indicator variables
tab district, gen(dist_id)

However, I am getting error r(134) which says "too many values".
The number of distinct values in district are about 15000, and I have used the set maxvar 25000 command to accommodate the new variables. I am running Stata SE 12.1.
Could someone point out the mistake in the above command or an alternate method to construct the variables?
Comment: I am trying to include fixed effects at district level in my regression, and have 15000 districts, hence the indicator variables.
Comment: OK, but I hope you have a LOT of data.
Comment: Yes, I have more than 500,000 observations.
Comment: Welcome to the site. Right now, this looks like a pure Stata question, which is off topic here. But you may have a statistics question as well - why do you have 15000 distinct variables and need indicator variables for them?
Answer: It seems a loop with levelsof command works for this.
levelsof district, local(xxx)
foreach lev of local xxx {
    gen x_`lev'=0
    replace x_`lev'=1 if district==`lev'
    }

This solution is mentioned By Dan Palmer on the Statalist.org page linked here https://www.statalist.org/forums/forum/general-stata-discussion/general/1490495-use-a-for-loop-to-generate-dummy-variables
Comment: The thread you cite mentions a much better solution!
Comment: Do you mean tab, gen? My post mentions that this is not working for me.
Comment: You are correct. A fuller discussion would need to explore why you (think you) need so many extra variables. Factor variable notation usually makes them unnecessary.
Comment: I tried with factor variable notation too, but still got an error. I am using the variables to control for fixed effects, and my data is cross sectional.
Comment: I'd take your problem to Statalist.

Unable to create indicator variables


Choosing cost function for a neural network continuous forecast

Question: I´m using Octave to build a Neural Network regression (3 layers nn, using tanh as activation function, fmincg as optimizer and continuous output). The purpose of the model is to forecast demand for some products, based on multiple variables (past demand of the products, past stock levels, pendent orders, etc.). I'm normalizing all inputs and output.
The quality of the forecast is finally evalued with SFE (statistical forecast error), which I defined in Octave as:
    $$SFE=\frac{\sum_{i=1}^{m}abs(Y_m-Forecast_m)}{\sum_{i=1}^{m}Forecast_m}$$.
Despite this, I'm training the model as a "traditional" regression, using a sum of square errors as cost function (J):
    $$J=\frac{\sum_{i=1}^{m}(Y_m-Forecast_m)^2}{2m}$$.
I think this is not correct, as learning should be made towards the real objective (SFE) and J is over-estimating the impact of bigger deviations. But as abs() has no derivative, I don't realize how SFE function could work under a back-prop training for the nn.
How should the cost function (J) be defined so as to train the model towards SFE?
I'd like to use SFE itself, but I don't find it possible as I have to compute the gradient in order for the optimizer to work (fmincg for Octave) and abs() is not differentiable at 0. The answer should cover this aspect for the optimizer to work.
Answer: It would probably be best to use a loss function based on the absolute, rather than the squared errors.  This will give a model that computes the conditional median of the target distribution, rather than the conditional mean.  For details, see
M Saerens, "Building cost functions minimizing to some summary statistics", IEEE Transactions on Neural Networks, 11 (6), 1263-1271, 2000.
which is a very nice paper and ought to be much better known that it is.  It is probably not too doficult to use the SFE itself as the loss function, although it will involve more programming.
Comment: Thanks, Dikran! I agree with you, a function based on the absolute deviation should work better.

I've done many tests, and realized current loss function is not leading towards learning (tests with many training iterations and regularization testing perform even worse than tests with just a few iterations!).

I'd like to include SFE as cost function, but that doesn't seem feasible for me as I have to compute the gradient for learning. Do you have any clue on this?
Comment: I suspect the absolute deviation will be a very close approximation, as I suspect that the sum of the output will be more or less constant for models that are in the same ball park as the best.
Comment: The problem I have with using the absolute deviation is that it´s not differentiable at 0. Then, the gradient computation will not be possible for back-propagation to work. Am I correct?
Comment: It might be detrimental if you use non linear conjugate gradient. Stochastic gradient will have no problem with it. Instead of the absolute value, you can however use $\sqrt{x^2 + \epsilon}$ as an approximation, with a rather small $\epsilon$, e.g. 1e-4.
Comment: Thanks, that´s right, bayerj. In this case, we are using the fmincg package for Octave (which implements a nonlinear conjugant gradient). That´s why a replacement is needed for the partial derivatives vector to be calculated.

In case of using your propossed approximation, how would you mathematically compute a gradient?
Comment: I have implemented absolute error loss in my MLP library, which uses scaled conjugate gradient descent.  IIRC the lack of a derivative at zero doesn't actually cause much of a problem in practice as you know where the discontinuity is, and the error of the neural net is very rarely *exactly* zero.  I'd have to check my code when I get back to the office, but I don't think any special code is necessary.
Answer: The $L^2$ (or quadratic) error is defined as
$$J_2 = \frac{1}{m} \sum_{i=1}^m {(Y_i - F_i)^2}$$
whereas the $L^1$ (or absolute) error is defined as
$$J_1 = \frac{1}{m} \sum_{i=1}^m{ |Y_i - F_i|}$$
$J_1$ should have similar properties to $SFE$, though the gradients w.r. to $F_i$ will be easier to compute as there is no forecast dependent denominator.
The gradient of the $L^1$ norm $|x|$ w.r. to $x$ can be taken to be 1 for positive values and -1 for negative values. You will find that the special case $x=0$ does really not matter numerically, as it is unlikely you hit 0, so you can use -1, 1 or 0 for this value.
This suggests:
$$\partial_i J_1 = \frac{1}{m} (2 \cdot 1_{\{Y_i>F_i\}} - 1)$$
Comment: Being a highly intelligent internet person I realised I could just google "indicator function" and figure it out on my own :)  Thanks for mentioning its name in your last comment so I knew what to look for.
Comment: If it evaulates to either -1 or 1, why do 2 times 1{Yi>Fi} rather than just 2{Yi>Fi} for example?


webhosting php script

Question: I have purchased a cPanel/WHM web hosting reseller account and I want to set up a site for people to set up a hosting accounts. I also would like to have a domain name registration system on the site, so people can register the domain name they would like to host with me. How can I do this? Are there any ready-made scripts available or should I create my own script using the WHM API?
Comment: I assume you intend to run this service as a business? if so perhaps you should have figured out these answers before starting? It's also a remarkably open/unspecific "question" too - very hard to answer without either spending a lot of time discussing the setup with you or alternatively not bothering because you've invested about 2 minutes writing a detail-less question requiring very significantly more investment in answering.
Comment: I'd like to run my own car manufacturing empire, but first does anyone know what these round things with rubber on their edges are called???
Comment: sorry I didnt get you
Comment: Well said @Chopper3
Answer: You really have two questions here. The first is how to set up a site where people can purchase hosting and have the site automatically set up the hosting accounts in WebHost Manager. The second is how to create an online domain name registration system. I think these are both on topic here at ServerFault, but only barely... they both have to do with programming and might be more at home on StackOverflow.
In answer to your first question, you might want to look at software like phpHostBot which is an online signup solution for cPanel. There's a number of other scripts and resources out there, that was the first one I could find which looked like it might meet your needs. Read through the cPanel forums for more suggestions
As for domain name registrations, you'll need to start by choosing a registrar with a reseller program. I know they're somewhat unpopular but GoDaddy has cheap rates and a reseller plan however there are a lot of other domain name registrars out there. Many of them will also provide you with iFrameble interfaces or other helpful scripts.
Good luck!

webhosting php script


How can I simplify $\frac{\sin(1) + \sin(2) + \cdots + \sin(100)}{\cos(1) + \cos(2) + \cdots +\cos(100)}$

Question: So I was asked to simplify the expression
$$\frac{\sin(1) + \sin(2) + \cdots + \sin(100)}{\cos(1) + \cos(2) + \cdots + \cos(100)}.$$ I'm struggling to find a way of doing it.
I'd like just hints rather than a whole solution if possible.
Thanks in advance
Comment: @AdrianKeister Doesn't matter. All that will be used is that the arguments form an arithmetic progression.
Comment: Radians or degrees?
Answer: Hint:
$\sin(kt) = \mathbb{Im}(e^{ikt})$
and
$\cos(kt) = \mathbb{Re}(e^{ikt})$.
Answer: Another approach is to use the identities
$\sin A + \sin B = 2 \sin \frac{A+B}{2} \cos \frac{A-B}{2}$
and
$\cos A + \cos B = 2 \cos  \frac{A+B}{2} \cos \frac{A-B}{2}$
Start by rearranging the fraction as:
$$\frac{(\sin 100+\sin1)+(\sin 99+\sin2)+...+(\sin 51+\sin50)}{(\cos  100+\cos  1)+(\cos 99+\cos  2)+...+(\cos  51+\cos 50)}$$


Leetcode Single Number II Operator Solution Explanation

Question: The question is 'Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.' I came up with a simple solution but found this solution online and was confused. Can someone explain this code and probably can explain whats the use of these operators and when should we use them while coming up with a solution of a coding problem.
class Solution:
def singleNumber(self, nums: List[int]) -> int:
    seen_once = seen_twice = 0
    for num in nums:
        seen_once = ~seen_twice & (seen_once ^ num)
        seen_twice = ~seen_once & (seen_twice ^ num)
    return seen_once

Comment: A rough idea of this approach is as follow: if you pass an integer several times to the function, `(seen_once, seen_twice)` will have the following states of value: `(0,0) -> (n,0) -> (0,n) -> (0,0) -> ...`. Thus, any integer processed to the third times will "reset" the variables to its initial state, which is `(0,0)`. The only integer `k` which appears once will move the state of `(seen_once, seen_twice)` to `(k,0)`. The explanation of how  `(seen_once, seen_twice)` can be transformed as described above is just mathematics, with `~,&,^` are bitwise flip, and, xor operators, respectively.
Comment: An important observation to make it easier to understand is that you can look at each bit independently from all other. So if you can show that e.g. the least significant bit will be returned correctly you can use the same reasoning for all other bits - proving that the whole result is correct.
Answer: A rough idea of the approach is mentioned in one of the comments by Hung Thai but I would like to elaborate it further.
Variables seen_once and seen_twice are being used to store the value of elements that are being occurred as we traverse through the array. If the element occurs once then it's value is stored in seen_once, if it occurs twice then it is stored in seen_twice variable. If it occurs three times it won't be stored in any of the variables because if we pass an integer several times to the function, (seen_once, seen_twice) will have the following states of value: (0,0) -> (n,0) -> (0,n) -> (0,0) -> .... Thus, any integer processed to the third time will reset the variables to its initial state, which is (0,0).  So, the value that we get in the seen_once element after traversing through the whole array will be our answer.
Let's take an array: {2, 2, 2, 3}
seen_once = 00, seen_twice == 00

When we are at first element i.e. 2 its binary representation will be 10.
Now the value of seen_once will be (~00)&(00^10) = 10 which is 2.
And the value of seen_twice will be (~10)&(10^10) = 00.
So, seen_once stores 2 because it has occurred only once till now and seen_twice is 0.
As we traverse further, we again get 2, so the value of seen_twice will become 2 as it has occurred twice till now and value of seen_once will become 0.
Then we get 2 for the third time. Now the values of both variables will become 0.
And at last, we get 3, which has occurred only once so it will be stored in seen_once.
After the loop ends, we get our answer as seen_once = 3.


Relation between $|z^x|$ and $|z|^x$

Question: In the answers given to this question, the following relation is often used:
$$\left| z^x \right| = \left| z \right|^x$$
with $z \in \mathbb{C}$, $z = \alpha + i \beta$.

How to prove it?
Can $x$ be a complex number itself, or should $x$ only be a rational number?
Comment: $i^i \neq 1^i$ so $x$ has to be real
Comment: @ArchisWelankar please, read the comment I wrote in the corindo answer.
Comment: Someting seems to be wrong
Comment: @ArchisWelankar tried to fix it.
Answer: You can write $z$ in the form $z = re^{i\theta}$ with $r \in \mathbb{R}_+, \theta \in \mathbb{R}$.
$$ \forall x \in\mathbb{R}, \,\, |z^x| = r^x = |z|^x.$$
As noticed @Archis Welankar, when $x$ is complex the relation is not always true.
Comment: Thank you. But for $x \in \mathbb{C}$ I can't see it. If $x = u + iv$,
$$(z)^x = (z)^{u + iv} = (r e^{i \theta})^{u + iv} = r^u r^{iv} e^{i \theta u} e^{i \theta iv} = r^u r^{iv} e^{i \theta u} e^{- \theta v}$$ and...?

Relation between $|z^x|$ and $|z|^x$


Factor Analysis - multiple answers from same respondents

Question: i am conducting an Exploratory Factor Analysis. I asked 100 subjects to rate the credibility of 4 marketing tactics. I examined 8 tactics in total and 4 tactics were allocated randomly to every subject to answer.
Now I want to conduct a factor analysis to find the number and nature of constructs underlying the eight items.

Is it even ok to have multiple answers by the same respondents? (I have 100 x 4 answers -> translate to 400 rows of data in my SPSS output) Because one assumption of FA is, that "the answers are independent to each other", isn't it?

If it is ok, do I use the dataset with 400 rows or do I have to reduce the dataset with mean averages of some kind? What would be the advantage?

Thank you so much, I really need the help for my finals!
Answer: Factor analysis (FA) is a statistical method to describe variability among observed, correlated variables in terms of a potentially lower number of underlying, unobserved variables. The FA does not assume that the answers are independent - quite the opposite, FA assumes that the responses are dependent because a few (sometimes, a single) latent factors are assumed to generate the observed variation in your responses. You could say that, given the latent factors, the responses are assumed to be independent. This is just a way of saying that there is some shared variation (latent factors) and some unique variation (independent residual errors).
If your question is really about whether one or few factor(s) underlie the ratings (it's hard to tell from your question), then FA is the right approach. Since you have eight ratings but randomly assessed only four per person, you have used a planned missing data design. That is, the shape of your data is really 100 x 8 with half of the values being missing. Since the pattern of missing data is missing completely at random_ by design, there should be no bias in your estimates with modern missing data approaches (such as full-information maximum likelihood or multiple imputation).


Como adicionar um LI em uma UL através de Javascript?

Question: estou querendo adicionar uma LI entre duas LI de uma UL. Eu não tenho acesso ao codigo CSS/HTML do template do site, se não criaria facilmente, então to pensando em adicionar via html e javascript.
Já tentei de tudo e não consegui, alguem teria uma ideia de como poderia realizar isso?
queria inserir essa LI

Segue o codigo...

        <button type="button" class="navbar-toggle" data-toggle="slide-collapse" data-target="#slide-collapse" aria-expanded="false">
            <svg class="icone-menu" style="fill: rgb(255, 213, 65);">
                <use xlink:href="#icone-menu"></use>
            </svg>
        </button>

    **//////////// QUERIA COLOCAR A LI AQUI ////////////////////////////**

            <svg class="icone-home" style="fill: rgb(255, 255, 255);">
                <use xlink:href="#icone-home"></use>
            </svg>

Answer: JavaScript não têm um método para inserir "depois de", mas tem "antes de". Então o código que faria o que precisas é
elementoAnterior.parentNode.insertBefore(novoElemento, elementoAnterior.nextSibling);

Exemplo:

const menuMobile = document.querySelector('.menu-mobile-botao');
const li = document.createElement('li');
li.innerHTML = 'Aqui estou eu!';
menuMobile.parentNode.insertBefore(li, menuMobile.nextSibling);

<button type="button" class="navbar-toggle" data-toggle="slide-collapse" data-target="#slide-collapse" aria-expanded="false"><svg class="icone-menu" style="fill: rgb(255, 213, 65);"><use xlink:href="#icone-menu"></use></svg></button>

       <svg class="icone-home" style="fill: rgb(255, 255, 255);"><use xlink:href="#icone-home"></use></svg>

Comment: coloquei aqui, mas não funcionou. Mas obrigado por responder, sigo tentando alternativas. Vou ver se copio o codigo dessse elemento, dar um display none neste e criar uma nova div com o mesmo codigo já com a LI da maneira que desejo.
Comment: @WilliamApocalypse cria um jsFiddle com o código que tens sem funcionar que posso dar uma olhada e corrigir.
Comment: Obg amigo pela ajuda, coloquei aqui jsfiddle.net/#&togetherjs=OGEnEbclbu Na verdade, eu queria colocar a LOGO deste site, na BARRA inicial entre o botão e o icone de carrinho, iria eliminar o icone home e icone de mensagens. Para ficar o botão, logo e icone do carrinho, e eliminar essa logo abaixo da barra que ta muito fora dos padroes do e-commerce. Mas não encontrei como fazer isso pq nao tenho acesso ao codigo do tema/template, posso adicionar css, html e javascript. mas não to conseguindo pensar em um jeito. eu comentei da LI, pq vi que esses elementos na barra estao dentro de uma LI


WSO2 configuration Passthrough Proxy

Question: Hi i want to build a proxy definition in a use case in which:
1)i have a client
2) WSO2 ESB 4.7.0
3) 2 REST services: R1 and R2
i want this to happen:
1) Client sends a request to an ESB proxy
2) proxy forwards the request to R1
3) if the R1's response rises no any error, the same response should be sent the client and to R2, otherwhise a fault message should be sent back to che client.
Could anyone help me to write this condifuration?
Thanks a lot
Answer: Yes you can do this with service chaining. http://wso2.com/library/articles/2011/01/wso2-esb-by-example-service-chaining/ and http://docs.wso2.org/display/ESB470/Service+Chaining+Example explains service chaining in soap, but it is similar to rest.
Comment: thanks for the help... in my use case, i cannot import the two REST services R1 and R2 inside the ESB. They have to be in separate Application container, like Tomcat. So, maybe could it be solved by using Mediator?
Comment: Of course. Where the services are deployed is irrelevant here. Configure the endpoint to call those services correctly.
Comment: i followed your suggestion. It seems to be the right way...but now im facing up to this:client sends a REST request to the R1service. R1 answers with a JSON/XML object from which i have to get a "Code" element and a "DocID".If Code == ok i have to send a REST request to the R2Service appending the DocID to it. (i.e. localhost:8080/service/MyR2service/DocID).I used the Switch mediator to get the Code(only xml, not json?) and DocID.How can i build a RESTRequest to R2Service appending this param to the query url?I thought about Callout mediator but i have no idea how to use it with rest Request

WSO2 configuration Passthrough Proxy


Azure functions: Use Apollo Azure handler in async function

Question: I want to wrap my apollo handler into an async function, to perform some checks before the handler function is executed. Everything works fine, when I don't use an async function but exporting the function as async returns always an empty response.
functions.json
{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    }
  ],
  "scriptFile": "../dist/graphql/index.js"
}

The setup:
    import { buildSchema } from 'type-graphql';
    import { ApolloServer } from 'apollo-server-azure-functions';
    import { Context, HttpRequest } from '@azure/functions';

    import { resolvers } from '../src/graphql';
    import { authChecker } from '../src/auth';

    const schema = buildSchema({
      resolvers,
      authChecker,
    });

    const server = new ApolloServer({
      schema,
      context: ({ context }) => context, // directly use azure Context as Apollo context,
    });

    const handler = server.createHandler();

This works
export default (context: Context, request: HttpRequest) => {
  handler(context, request);
};

this returns always 204, empty response
export default async (context: Context, request: HttpRequest) => {
  // do async stuff: await ...

  handler(context, request);
};

Answer: There are 2 ways to return data from a Node.js Azure function:

returning data from an async function
passing data to the context.done() method

In your code, handler is a method from apollo-server-azure-functions package. Internally it calls context.done() to send the response back to Azure runtime.
But because handler(context, request) itself is a regular function call, your exported top-level async function resolves without waiting for it to finish.
You may want to return a Promise from your async function which will resolve when the underlying apollo server is ready to send the response. Here's an example implementation.


An Application using Arzela-Ascoli Theorem

Question: I am looking for a good application for undergraduates (Analysis I) that uses the AA-theorem. Perhaps, a proof of some surprising result that is not so easy to prove otherwise? I do realize that AA-theorem is usually used as a theoretical tool in other proofs. But I was wondering if anyone has any insightful examples that may make the students appreciate it?
Answer: I suppose it's probably too difficult to introduce compact operators and the Schauder fixed point theorem at this stage. But if you are willing to use them as black boxes, then you can do a trivial application of Schauder FPT: define the operator $T:C[0,1]\to C[0,1]$ by
$$
Tf(x) = \int_0^x f(t)~dt + 1.
$$
You can prove that the image of the unit ball of $C[0,1]$ under $T$ is pointwise bounded and equicontinuous, so $T$ is a compact operator. Therefore $T$ has a fixed point, which is the solution to the integral equation
$$
f(x) = \int_0^x f(t)~dt + 1,
$$
which is a way to recast the first-order ODE/IVP
$$
f'(x) = f(x), ~f(0) = 1.
$$
This is, of course, the exponential function. While it's a trivial ODE, the idea generalizes easily and it should give some insight into how Ascoli-Arzela is used in practice, as well as the historical development of the subject.
If you don't want to rely on compact operators, you should still be able to solve the ODE using the approach of the Peano existence theorem, which concerns the existence of short-time solutions to the ODE
$$
y'(t) = f(t,y(t))
$$
where $f$ satisfies a Lipshitz condition in $y$. While the full proof of Peano is a bit laborious, adapting the proof to our special case should be enough to illustrate the main ideas: (1) convert to the integral equation, (2) form piecewise linear approximations to the solution, (3) apply Ascoli-Arzela on the set of approximations to extract a convergent subsequence which should be the solution.
If you intend to or have already discussed the contraction mapping principle, this might also be a nice way to tie that discussion together, because the proof of the Picard existence theorem also converts the ODE to an integral equation, this time to obtain a contraction mapping. Again, this should serve to provide historical insights and motivations for these tools, which are used in much the same way even now.


Persistent variable (`variable_set()`) name restrictions

Question: Are there any restrictions, conventions, etc. for the names of persistent variables created with variable_set()?
Aside from project name prefix, I haven't found anything in the documentation. However, I notice that most modules restrict themselves to the same rules that apply to PHP variables.
Answer: Until Drupal 7, the main storage for the variables is the variable table in the same database Drupal uses.
The name column is a varchar(128) so that requires the variable names to have equal or fewer characters than 128.
Prefixing the variable names is purely by convention. Drupal Form API can handle spaces in machine names too, but you will almost never see a form array item key with spaces in it.
There are workarounds, but it's easier if there are no spaces, for example when you use drush, export settings, etc.
Comment: What characters does the Drupal Form API have trouble with?
Comment: None. You can even use a hash itself, which is used to differentiate form properties from child elements. But it's much harder to scan by eyes and must put extra effort to wrap the strings with quotes or something when using.


Mobius Inversion Formula IV

Question: I want to prove that for every $n \in \mathbb{N}$ : $$$$
$f(n)=\sum_{d|n} g(d) \quad$ $ \Leftrightarrow$  $\quad g(n)=\sum_{d|n} \mu(d)f(n/d)$
$$$$
I proved the first direction and for the second one I tried the following:$$$$IC
Let
$$ g(n)=\sum_{d|n}\mu(d)f(n/d) $$
$$ g(n)=\sum_{d|n}\mu(n/d)f(d) $$
Now applying the first direction yields
$$\mu(n/n)f(n)=\sum_{d|n}\mu(d)g(n/d) $$
$$\mu(1)f(n)=\sum_{d|n}\mu(n/d)g(d) $$
$$f(n)=\sum_{d|n}\mu(n/d)g(d) $$
Now letting $n=2$ then $f(2) = g(2)-g(1)$ not $f(2) = g(2)+g(1)$.
$$$$
Where did I go wrong?
Thanks in advance.
Comment: Come on... Yes it is wrong. Do you realize $\sum_{d |n} \mu(d) s(d)$ is not the same as $\sum_{d |n} \mu(n/d) s(d)$ ?
Comment: $\mu(n/n)f(n)=\sum_{d|n}\mu(d)g(n/d)$ is not correct, it is $\mu(n/n)f(n)=f(n) =\sum_{d|n}g(n/d)$
Comment: This is not what applying the first direction yields. Or is it?
Comment: What do you mean ?
Comment: If $f(n)=\sum_{d|n} g(d), \quad$then $\quad g(n)=\sum_{d|n} \mu(d)f(n/d)$, applying this to  $r(n)=\sum_{d|n}\mu(n/d)s(d)$ yields $\mu(n/n)s(n)=\sum_{d|n}\mu(d)r(n/d)$
Comment: No. it yields $s(n) = \sum_{d | n} r(d) = \sum_{d | n}r(n/d)$
Comment: I'm sorry... but how? Is my substitution wrong?
Comment: I see it now, thanks!
Answer: As you know $\sum_{d | n} \mu(d)= 1_{n = 1}$ so that
$$\sum_{d | n} \mu(d) f(\frac{n}{d}) = \sum_{d | n} \mu(d) \sum_{m | \frac{n}{d}} g(m)= \sum_{d | n}\sum_{m | \frac{n}{d}} \mu(d)  g(m)$$ $$= \sum_{m | n } \sum_{d | \frac{n}{m}}g(m)  \mu(d)=\sum_{m | n } g(m)1_{\frac{n}{m}=1} = g(n) $$

Mobius Inversion Formula IV


Largest/Smallest eigenvalue of a hessian

Question: Currently I am trying to prove the lower boundary of a certain quantity. To be more specific, the denominator of the Zouterdijk equation.
$\cos \left(\theta_k\right)=\frac{-\nabla f\left(\boldsymbol{x}_k\right)^{\top} \boldsymbol{p}_k}{\left\|\nabla f\left(\boldsymbol{x}_k\right)\right\|\left\|\boldsymbol{p}_k\right\|}=\frac{\nabla f\left(\boldsymbol{x}_k\right)^{\top}\left[\nabla^2 f\left(\boldsymbol{x}_k\right)+\tau_k\right]^{-1} \nabla f\left(\boldsymbol{x}_k\right)}{\left\|\nabla f\left(\boldsymbol{x}_k\right)\right\|\left\|\boldsymbol{p}_k\right\|}$
$\cos \left(\theta_k\right) \geq \frac{\frac{1}{8.1}\left\|\nabla f\left(\boldsymbol{x}_k\right)\right\|^2}{\left\|\nabla f\left(\boldsymbol{x}_k\right)\right\|\left\|\boldsymbol{p}_k\right\|}=\frac{\left\|\nabla f\left(\boldsymbol{x}_k\right)\right\|}{8.1\left\|\boldsymbol{p}_k\right\|}$
My question is about this term:
$\left[\nabla^2 f\left(\boldsymbol{x}_k\right)+\tau_k\right]^{-1}$
I do not understand how that term can be interchanged with an eigenvalue of the matrix.
For the proof the following relations need to be used:
$\lambda_1=\min _{\boldsymbol{x} \in \mathbb{R}^n:\|\boldsymbol{x}\|^2=1} \boldsymbol{x}^{\top} A \boldsymbol{x} \quad$ and $\quad \lambda_n=\max _{\boldsymbol{x} \in \mathbb{R}^n:\|\boldsymbol{x}\|^2=1} \boldsymbol{x}^{\top} A \boldsymbol{x}$.
Question:

Can somebody clarify why it is allowed to interchange a matrix with an eigenvalue
How do I need to interprete  the last relations? (In more basic language?)
Comment: There are several details missing here. What is $\mathbf{p}_k$? Is it $(\nabla^2f(\mathbf{x}_k)+\tau_k)^{-1}\nabla f(\mathbf{x}_k)$? Also, is $\tau_k$ a scalar (and a stand-in for $\tau_kI$, where $I$ is the identity matrix), or is it a matrix itself? Also, where does $\frac{1}{8.1}$ come from? Is it the eigenvalue that you're referring to? What does it have to do with $(\nabla^2f(\mathbf{x}_k)+\tau_k)^{-1}$? Which step, in particular, are you asking us about? Without this knowledge, it's difficult to to answer definitively.
Answer: You can show that the smallest eigenvalue $\lambda_1$ of a symmetric matrix $A$ satisfies $\lambda_1 = \min_{u : \|u\|^2 = 1} u^\top A u$. In particular, this means that for any nonzero vector $v$, we have
$$v^\top A v = \|v\|^2 \left((v/\|v\|)^\top A (v/\|v\|)\right)
\ge \lambda_1 \|v\|^2.$$
The inequality in your post is the above for $v=\nabla f(x_k)$ and $A=[\nabla^2 f(x_k) + \tau_k I]^{-1}$ (assuming the smallest eigenvalue of $A$ is $\ge 1/8.1$).
Note also that if $\mu_1, \ldots, \mu_n$ are the eigenvalues of $H:=\nabla^2 f(x_k)$, then $(\mu_1 + \tau_k)^{-1}, \ldots, (\mu_n + \tau_k)^{-1}$ are the eigenvalues of $A = (H+\tau_k I)^{-1}$.


Is my work about vectors correct?

Question: I have a question that involves vectors here:
$ O $ is the origin and the position vectors of three points $ P $, $ Q $ and $ R $ are $ \vec{p}, \vec{q} $ and $ 5\vec{p} $ respectively. $ M $ is a point on line $ \vec{PQ} $ such that $ \frac{\vec{PM}}{\vec{PQ}} = \frac{1}{4} $.
My diagram showing the points based on the question, some points are added because they are included in the sub questions.
My information:
$$
\begin{aligned}
\vec{OP} &= \vec{p} \\
\vec{OQ} &= \vec{q} \\
\vec{OR} &= 5\cdot\vec{p} \\
\vec{OR} &= 5\cdot\vec{OP}
\end{aligned}$$
a) Express $ \vec{OM} $ in terms of $ \vec{p} $ and $ \vec{q} $.
This one is pretty easy.
$ \vec{OM} = \vec{OP} + \vec{PM} $
But before I start solving, I first find the vector $ \vec{PM} $.
From the question, I can see that
$$
\begin{aligned}
&4 \cdot \vec{PM} \!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!&=& \; \vec{PQ} \\
\Leftrightarrow &\vec{PM} &=& \; \frac{1}{4} \cdot \vec{PQ}
\end{aligned}$$
To find $ \vec{PQ} $:
$$
\begin{aligned}
\vec{PQ} &= \vec{PO} + \vec{OQ} \\
&= -\vec{OP} + \vec{OQ} \\
&= -\vec{p} + \vec{q}
\end{aligned}
$$
From here,
$$ \vec{PM} = -\frac{1}{4}\vec{p} + \frac{1}{4}\vec{q} $$
With these information:
$$
\begin{aligned}
\vec{OM} &= \vec{OP} + \vec{PM} \\
&= \vec{p} -\frac{1}{4}\vec{p} + \frac{1}{4}\vec{q} \\
&= \frac{3}{4}\vec{p} + \frac{1}{4}\vec{q}, \text{final answer}
\end{aligned}
$$
b) $ K $ is a point such that $ \vec{OK} = h \cdot \vec{OM} $, where $ h \gt 1 $. Express $ \vec{OK} $ and $ \vec{QK} $ in terms of $ \vec{p}, \vec{q} $ and $ \vec{h} $.
I am going to solve for $ \vec{OK} $ first. From the question, it says that vector $ \vec{OK} $ is vector $ \vec{OM} $ multiplied by a constant, $ h $. And since the question asks me to express $ \vec{OK} $ in terms of $ \vec{p}, \vec{q} $ and $ h $, I don't need to find the actual value of $ h $. So my answer would be:
$$ \vec{OK} = \left(\frac{3}{4} \cdot h\right)\vec{p} + \left(\frac{1}{4} \cdot h\right)\vec{q} $$
Now onto solving $ \vec{QK} $.
$$
\begin{aligned}
\vec{QK} &= \vec{QO} + \vec{OK} \\
&= -\vec{OQ} + \vec{OK} \\
&= \frac{3h}{4}\vec{p} + \left(-\frac{3h}{4}\right)\vec{q}
\end{aligned}
$$
c) If $ \vec{QK} = \lambda x \cdot \vec{QR} $, find the value of $ \lambda $ and then constant $ h $.
This is where I got stuck. My working starts with finding $ \vec{QR} $.
$$
\begin{aligned}
\vec{QR} &= \vec{QO} + \vec{OR} \\
&= -\vec{OQ} + \vec{OR} \\
&= -\vec{q} + 5\vec{p} \\
&= 5\vec{p} - \vec{q}
\end{aligned}
$$
Then I equate them.
$$
\begin{aligned}
\text{Let} \; \lambda &= y\\
\vec{QK} &= y \cdot \vec{QR} \\
\frac{3h}{4}\vec{p} + \left(-\frac{3h}{4}\right)\vec{q} &= y \cdot \left(5\vec{p} - \vec{q}\right)
\end{aligned}
$$
Then I compare the like terms. I start with comparing the terms with $ \vec{p} $.
$$
\begin{aligned}
\frac{3h}{4}\vec{p} &= \left(5 \cdot y\right)\vec{p} \\
\frac{3h}{4} &= 5\cdot y \\
\frac{3h}{20} &= y
\end{aligned}
$$
Then terms with $ \vec{q} $.
$$
\begin{aligned}
-\frac{3h}{4} &= -y \\
-\frac{3h}{4} &= -\frac{3h}{20} \\
60h &= 12h \;\text{[THIS IS MY PROBLEM]}
\end{aligned}
$$
I don't understand which part of my working is wrong, I've made sure that all of my working steps are correct. I hope someone could come and lend a helping hand to help me find my mistakes. Thanks!
Answer: Found my mistake!
It's located at the subquestion b). I made a mistake about finding vector $ \vec{QK} $.
$$
-\vec{q} + \left(\frac{3h}{4}\vec{p} + \frac{h}{4}\vec{q}\right)
$$
This is where I calculated wrong. I subtract $ 1 $ from $ -\frac{3h}{4} $ which is impossible because $ -1 $ doesn't have constant $ h $. Hence, the correct vector for $ \vec{QK} $ is:
$$
\frac{3h}{4}\vec{p} + \left(\frac{h}{4} - 1\right)\vec{q}
$$
With this, let's try solving c) again:
From comparing the like terms of $ \vec{p} $:
$$
\begin{aligned}
    \frac{3h}{4} &= 5y \\
    h &= \frac{20}{3}y
\end{aligned}
$$
Now comparing the like terms of $ \vec{q} $:
$$    \frac{h}{4} - 1 = -y $$
Sub $ h $ into this equation.
$$
\begin{aligned}
    \frac{5y}{3} -1 &= -y \\
    \frac{8y}{3} &= 1 \\
    \frac{y}{\lambda} &= \frac{3}{8} \\
    h &= \frac{5}{2}
\end{aligned}
$$
Voila.

Is my work about vectors correct?


From Marginal Exp-Norm Distributions to What Conditionals and Joint?

Question: I have (trivariate: multivariate with three variables) data that appears to be good empirical and reasonable theoretical fit for a (univariate) convolution of an exponential and a normal distribution (some times called exp-norm or exGauss distributions).
My data are samples from the joint distribution:  J(R,G,B)
It appears that the marginals of R,G,B follow:
$R=R_N+R_E$ with $R_N \sim N(\mu_R,\sigma^2_R)$ and $R_E \sim Exp(\lambda_R)$
(and likewise for G,B).
I would like to effectively summarize the marginal, conditional, and joint distributions.  The main purpose of the summary is to compare these distributions (marginal, conditional, and joint) with other distributions generated in a like manner.  My difficulty is that (1) I don't know a form for the joint (or the conditional) distribution and (2) following from that, I have no parameters to estimate.
Thus, I need either a distribution free (non-parametric) approach to working with this data or I need to figure out a multivariate distribution that matches the data and the form of the marginals.  Or should I think about other options?
Comment: What do you mean by 'trivariate'? It would also help if you could to the extent possible use equations to illustrate your situation. Do you mean that you observe $Y$ where $Y = X + Z$, $X \sim Exp(\lambda)$ and $Z \sim N(\mu,\sigma^2)$?
Comment: It would also help if you clarify a bit more what you mean by "understand this data". Is there a specific question(s) you are trying to answer or is this just exploratory data analysis? I would suggest editing the question to incorporate your comment and make the question as precise as possible so that useful answers can be given.
Comment: Sorry to use a non-standard term.  The data are multivariate with three variables: R,G,B.  I have the joint J(R,G,B) and I can compute the marginals.  The form of the (univariate) marginals is the Y you defined.
Comment: I will try improve the question.  I need to give it a bit of thought.  -If- the data were multivariate normal (and, as follows, normal in the marginals), I would compute r and be done with it.  So, maybe I have two options:  (1) transform the data so they are normal or (2) compute r (via resampling) to assess its validity.  As far as "understanding the data":  ideally, I would want to characterize the conditional distributions (not necessarily by closed form equations) ... that is, I'd like to know how the variables affect each other.
Answer: Would copulas be any use here? I don't know enough about them, or your problem, to be sure.
Comment: @Mark In light of the revised question, I agree that looking at a copula-based description is a good suggestion.  There's nothing terribly difficult about copulas: because you have the marginals, you can apply the probability integral transform to make the three variables (R, G, B) uniform on [0,1].  A copula merely describes their multivariate distribution in these terms.  In effect, it eliminates the parameters from the marginals to allow you to focus on describing their multivariate dependencies.  It affords the non-parametric approach you're asking for.
Comment: I know that copulas capture advanced correlation structures; I don't know much else about them.  Unfortunately, I don't think they would be useful to me (for understanding the relationships in the data), nor to scientific colleagues (who would have to have some intuition/experience with copulas to understand my conclusions).
Comment: Thanks for sticking with it through the reformulation.  I will look into copulas.  Will copulas allow me to compare marginals and conditionals from different Js:  $J_1$, $J_2$, ...  I might also wish to compare $R_1|G_1$ (from $J_1$) and $R_2|G_2$ in some way.  The different joints are measurements on individuals in experimental conditions.  Some of the measurements are repeated measurements of the same individual).
Comment: @Mark Copulas will be useful for identifying, creating, and comparing models of joint distribution, but I don't think they will help in formal tests of hypothesis concerning those models.  Consider asking another question in which you reveal more about the nature of the data and how they are collected, because that ought to play an important role in the modeling and choice of analytical techniques.
Comment: Will do.  It's always difficult to get the right abstraction of a problem.  These two questions also seem to get at distribution free, multivariate analysis:  http://stats.stackexchange.com/questions/4/assessing-the-significance-of-differences-in-distributions and http://stats.stackexchange.com/questions/1927/is-there-an-accepted-definition-for-the-median-of-a-sample-on-the-plane-or-highe
Comment: I'm reading over some of the terminology regarding copulas.  I'm missing a "process".  For example:  with an empirical joint and empirical marginals and a distribution for the marginals, what do I do?  It seems that I need a transformation function to take my marginals to uniform distributions and then a "copula function" (term?) to combine those to for a distribution which (hopefully?) models the joint.  It may turn out that I'm more interested in the pairwise marginals (RG, RB, GB) than I am in the full joint.


Pimple dependency injection static or object

Question: Pimple help re-use the same object across application, and manage dependecy.
but how to manage Pimple itself?
Should I create a global object? Or make it static class? Or use a function?
I would like to access on Pimple methods from anywhere, controllers, models, plugins, etc...
Thanks!!
Comment: If you want to acces pimple methods from anywhere you are falling in service locator antipatern
Comment: thanks for your reply. What you mean? I add new object to Pimple on one place, then I re-use the object on other place. Example I need to have access on Database Object from a Model, but also from a Library or from a plugin hook. So I need access to Pimple. Can you explain a bit more. Thanks!!
Comment: @jlvaquero can you tell me alternative?
Answer: A lot of folk consider ServiceLocator to be an anti-pattern, but if you use it sparingly, there's little harm done.
<code><?php

namespace Acme;

class ServiceLocator
{
    static protected $container;

    public static function setContainer(\Pimple $container)
    {
        static::$container = $container;
    }

    public static function get($id)
    {
        return static::$container[$id];
    }
}
</code>
Comment: What I mean is that ABUSE of SL is antipattern. Using DI container everywhere is abuse. DI should build your dependency chain in the top layer. Then, use the layer and forguet about DI or SL.
Comment: You said: "Then, use the layer and forguet about DI or SL." My reply: "What you mean with "layer" ? Can you provide an example how I can set database object and re-use him on hole application? thanks!!"


What would be a reason to use the Root Mean Square Error (RMSE) to combine data?

Question: In this machine learning tutorial by Google they use the Root Mean Square to create a similarity measure between two shoes.
They first calculate the difference between the size of two shoes and then do the same for their price. Finally with those two values they compute Root Mean Square Error (RMSE) however they don't explain why it's appropriate to do so.
Could someone explain why would you use RMSE or in what case does it apply?
Comment: RMSE is euclidean distance.  For distance in shoe sizes, it is literally the most physically appropriate measure of difference.  I personally think absolute difference is better for cash value.  Better to ask the author for their justification.
Comment: They first normalize then apply RMSE. In any case the tutorial is one HOW to create similarity measure, and NOT WHY it has to be RMSE. They are not combining data. That's notwhatsimilarity for.
Comment: RMSE is the mean of the euclidean distance then?
Comment: @EngrStudent would you mind also explain why in your opinion the absolute difference is better for cash value?
Answer: As far as I see, this tutorial is mostly interested in presenting how to do clustering with a manually created similarity measure, and use RMSE as a natural choice for coming up with a similarity measure. So, it's not because the Euclidean distance (a scaled version of it to be precise) is the best choice for shoe + price feature pair. They also finish with saying

In general, your similarity measure must directly correspond to the actual similarity.

Noting that the choice of similarity which suits best to your data and problem's needs is left to you.
Comment: Could you expand on why RMSE is a natural choice for coming up with a similarity measure? This will help me decide what to do on my own data.
Comment: Because both features are numeric and the Euclidean distance between two points is the most natural one that comes to one's mind. Not saying it should be the choice. Most libraries measure Euclidean distance by default in their dist functions.
Answer: RMSE is a widely applicable and often used error function, but it is certainly not the only one or the best one for all circumstances. It has the sometimes-desired feature that bigger differences count for more, so a difference of two shoe sizes will more than double the feature-wise error compared to a difference of just one shoe size. Under this measure, two shoes that have a standardized size difference of 0.1 and a standardized price difference of 0.1 are more similar than two shoes of identical size but with a standardized price difference of 0.2.  You can contrast this with the mean absolute error (MAE), for example, which simply sums up the magnitude of differences - here, all differences count for the same weight, larger differences do not count for exponentially more error. With MAE, the previously mentioned pairs of shoes (0.1 and 0.1 difference vs. 0 and 0.2 difference) are identically "different" from one another.
The choice of error function will be domain dependent. The RMSE is a reasonable choice for many applications, and seems to be chosen in this example for convenience. Other error measures would also be justifiable for this problem, and there's nothing particularly special about this case to suggest that RMSE is inherently the best error measure to use here.
Comment: @WindBreeze Not sure what you mean by "granularity" for that to be true. RMSE simply puts more weight on larger errors, but it doesn't draw any more fine-grained distinctions in the difference measure for arbitrary samples. 100 pairs of samples may yield 100 different similarity measures by either RMSE or MAE, but there's no reason to expect that RMSE will allow you more "resolution" to determine the most similar pairs - it's just a different measure.
Comment: @WindBreeze The misunderstanding may have come from my particular example of RMSE vs. MAE, but it's not the case that one will always have differences where the other does not. My example showed two pairs of samples that had identical MAE but different RMSE, but you could also have two pairs with identical RMSE but different MAE (e.g. a pair with a price difference of 1.41 and a size difference of 1.41 has the same RMSE as a pair with a price difference of 0 and a size difference of 2, but different MAE). Either measure may find differences where the other does not.
Comment: If I understand correctly RMSE has more granularity when it comes to similarity then MAE.


Look up nodes that reference a given node

Question: I'm using the references module (not grounded to it, but it seems to work well enough) however I don't know how in a custom PHP block/etc I would be able to do a query that can look up all the nodes of a given type that reference the current node.
What sort of query would accomplish this?
For just looking up by type I've used this previously:
<?php
    foreach(node_load_multiple(array(), array('type' => 'homepage_image')) as $node){
    //code
    }
 ?>

Answer: Well, you know, this is one of the problems that gave birth to relation. Nonetheless, an EntityFieldQuery with a fieldCondition('name_of_the_reference_field', 'nid', $nid) is what you want.
Comment: I'm not necessarily against using Relation if it's a better module for this sort of thing; I'm still early in development. I may give it a shot to see if it works better. Do you have an example of how to accomplish it in Relations?
Comment: I would like to thank you for fieldCondition('name_of_the_reference_field', 'nid', $nid). In my case, using user reference via entityreference. Been googling around for 2 hours and finally ended up here. As you know entityreference do not support views filtering yet. And your clue is a god send. Thanks a lot.


Pattern matching in Scala

Question: scala> (1,5) == BigInt(12) /% 7
res3: Boolean = true

scala> BigInt(12) /% 7 match {
 | case (1,5) => true
 | }

<console>:9: error: type mismatch;
found   : Int(1)
required: scala.math.BigInt
          case (1,5) => true
                ^

Can someone perhaps explain me how to pattern match here?
Answer: match is more specific than equality; you can't just be equal, you must also have the same type.
In this case, BigInt is not a case class and does not have an unapply method in its companion object, so you can't match on it directly.  The best you could do is
  BigInt(12) /% 7 match {
    case (a: BigInt,b: BigInt) if (a==1 && b==5) => true
    case _ => false
  }

or some variant thereof (e.g. case ab if (ab == (1,5)) =>).
Alternatively, you could create an object with an unapply method of appropriate type:
object IntBig { def unapply(b: BigInt) = Option(b.toInt) }

scala> BigInt(12) /% 7 match { case (IntBig(1), IntBig(5)) => true; case _ => false }
res1: Boolean = true

Comment: Binding to variables and a guard is what I did. I just thaught it could perhaps be done a little better. Thank you.
Answer: 1 and 5 are Int types. The pattern match is expecting a scala.math.BigInt. So, give it that by declaring a couple of vals for one and five.
scala> val OneBig = BigInt(1)
oneBig: scala.math.BigInt = 1

scala> val FiveBig = BigInt(5)
fiveBig: scala.math.BigInt = 5

scala> BigInt(12) /% 7 match {
     | case (OneBig, FiveBig) => true
     | }
res0: Boolean = true

Comment: This doesn't work! `oneBig` and `fiveBig` in the pattern are new variables unrelated to the ones defined before. This can be changed by naming them with a capital letter (`OneBig` and `FiveBig`) or by surrounding the names in backticks.
Comment: Thanks. Forgot about that. For those interested see http://stackoverflow.com/questions/4479474/scala-pattern-matching-with-lowercase-variable-name or page 317 of the stairway book.
Answer: The problem is that 1 and 5 returned by /% are BigInts and so don't match literal Ints even though equals method (called by ==) returns true. This works but is a bit inelegant:
scala> BigInt(12) /% 7 match { case (x, y) if x == 1 && y == 5 => true }
res3: Boolean = true

Pattern matching in Scala


Kivy: how to retrieve ids or active states of checkbox (or other widgets) created within python

Question: My app follows 3 steps:

In step 1, the users enter a number (all widgets are in a .kv file -cf the code below).
In step 2, as many labels and checkboxes as the number entered in step 1 are generated. Then the user select some checkboxes and click on the button "OK 2".(Because the number of widgets of the second step can vary,they are created in the .py ―it may not be the best way to do it but I haven't found a better idea).
In step 3, I get the active state of the checkboxes generated in step 2 and according to which one is active or not, I do some more steps.

My question is how can I get the state of the checkboxes? When they are "created", each has an id but these ids don't appear when I print self.ids. Also I get an error if I pass any argument to the getcheckboxes_active def. (None is not callable).
The .py:

import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.checkbox import CheckBox
from kivy.uix.button import Button
from kivy.properties import StringProperty

class MyWidget(BoxLayout):
    input_text = StringProperty("10")

    def show(self, number):
        layout = BoxLayout(padding=10, orientation="vertical")
        for each in range(int(number)):
            layout2 = BoxLayout(padding=10, orientation="horizontal")
            l=Label(bold= True,font_size=20, text='Hello', markup = True)
            c= CheckBox(id = "CheckBox"+str(each))
            layout2.add_widget(l)
            layout2.add_widget(c)
            layout.add_widget(layout2)
        button = Button(text="OK 2")
        button.bind(on_press=self.getcheckboxes_active)  # self.getcheckboxes_active(self, "test") give an error None is not callable
        layout.add_widget(button)
        self.add_widget(layout)

        self.input_text = "Done"

    def getcheckboxes_active(self, *arg):
        '''how to get the active state of all checkboxed created in def show'''
        print(self.ids)  # CheckBoxes id aren't displayed
        print(*arg)
        print("State of all checkboxes")

class MyApp_auto(App):
    def build(self):
        return MyWidget()
MyApp_auto().run()

The .kv: I need to have a .kv because the "step 1 real app" is way more complex than an TextInput and a Button.
<MyWidget>
    orientation: "horizontal"
    TextInput:
        text: root.input_text
        id:input
    Button:
        text:'OK 1'
        on_press: root.show(input.text)

Answer: The issue here is that the ids dictionary is only populated with id values that were defined in the .kv file, not in python.
However, you can create you own dictionary that contains the references to the CheckBox widgets. Instead of providing the id property upon the creation of the widget, you could populate a dictionary attribute of MyWidget (let's call it check_ref) that links your id with each CheckBox instance:
class MyWidget(BoxLayout):
    input_text = StringProperty("10")

    check_ref = {}

    def show(self, number):
        layout = BoxLayout(padding=10, orientation="vertical")
        for each in range(int(number)):
            layout2 = BoxLayout(padding=10, orientation="horizontal")
            l=Label(bold= True,font_size=20, text='Hello', markup = True)
            c = CheckBox()

            # Stores a reference to the CheckBox instance
            self.check_ref["CheckBox"+str(each)] = c

            layout2.add_widget(l)
            layout2.add_widget(c)
            layout.add_widget(layout2)
        button = Button(text="OK 2")
        button.bind(on_press=self.getcheckboxes_active)  # self.getcheckboxes_active(self, "test") give an error None is not callable
        layout.add_widget(button)
        self.add_widget(layout)

        self.input_text = "Done"

    def getcheckboxes_active(self, *arg):
        '''how to get the active state of all checkboxed created in def show'''
        # Iterate over the dictionary storing the CheckBox widgets
        for idx, wgt in self.check_ref.items():
             print(wgt.active)

        # You can also get a specific CheckBox
        # print(self.check_ref[--my id--].active)

Comment: You can, but you'll have to use either `partial` or an anonymous function. In your example you could do something like: `button.bind(on_press=lambda x: self.getcheckboxes_active("teste"))`. This may also help: https://blog.kivy.org/2014/03/kivy%E2%80%99s-bind%C2%A0method/
Comment: Thanks a lot! I just have troubles with the last commented print : `self.check_ref[CheckBox0].state`, I get the error `name 'CheckBox0' is not defined`, even though `print(self.check_ref)` doesn't print a `CheckBox0` id.
Comment: `CheckBox0` should be a string yes?
Comment: Sorry for that! One last question. Why is the attribute is `state` with the two vales  `normal` and `down` whereas for a checkbox from a `.kv`, the attribute is `active` and the values are `True` and `False`?
Comment: Oops, my bad! You're right, it should be the `active` attribute and not `state`. I'll correct it.
Comment: Well, I posted before checking and with `active` and it's giving me `True` and `False`. so I posted my comment a bit to quickly, sorry!
Comment: I still have another question, why can't I pass any argument to the def in the line `button.bind(on_press=self.getcheckboxes_active)`? Why can't I write `button.bind(on_press=self.getcheckboxes_active (self, "test")`?
Comment: Super! Thanks a lot for this!
Answer: Possibly a common scenario: From a list of strings, make labels and their corresponding checkbox, using the previously mentioned idea of a dictionary, then show the selected checkbox label as the text of another label.
class BuildRequester(BoxLayout):
    chkref = {}
    def on_checkbox_active(self,chkbox,value):
        self.ids.label2.text = 'Selected ' + self.chkref[chkbox]
    def __init__(self, **kwargs):
        super(BuildRequester,self).__init__(**kwargs)
        prods = [' B_0003',' B_0007',' B_0008', ' B_0200']

        for i in range(4):
            self.add_widget(Label(text=prods[i],italic=True,bold=True))
            chkbox = CheckBox(group='1',color=[0.1,1,0,4])
            chkbox.bind(active=self.on_checkbox_active)
            self.add_widget( chkbox)
            self.chkref[chkbox]= prods[i]