Upload fora do Lugar

Question:
Bom estou meio confuso aqui pois estou criando a pasta porem na hora de upar ela upa um nivel acima. onde esta o erro ?
<code> if (is_uploaded_file($_FILES["foto"]["tmp_name"])) {
mkdir("../img/$Npasta") or die("erro ao criar diretório $Npasta");
$foto = time() . '_' . $_FILES["foto"]["name"];
$diretorio = '../img/$Npasta';
$dirfoto = $diretorio.$foto;

if (!move_uploaded_file($_FILES["foto"]["tmp_name"], $dirfoto)) {
  $error = TRUE;
 }
}
</code>
Adendo: Estou criando as pastas dinamicamento pegando o ultimo id do banco somando + 1 e a pasta esta sendo criarda, so nao to entendendo é pq na hora de upar a variavel parece estar "perdida" pois como vcs veem o nome fica $Npasta.taltaltaltal.jpg onde que na verdade teria que ser img/4/nomedoarquivoupado.jpg
Comment: Cola o código normal aqui... porque dessa forma não dá nem pra ler o código
Comment: se clicar na imagem vai aumentar, coloquei imagem pq da pra ver o servidor e como esta sendo upado
Answer: Você pode fazer assim também:
<code>if(is_uploaded_file($_FILES["foto"]["tmp_name"])) {
    mkdir("../img/".$Npasta) or die("erro ao criar diretório $Npasta");
        $foto = time() . "_" . $_FILES["foto"]["name"];
        $diretorio = "../img/".$Npasta."/";
        $dirfoto = $diretorio.$foto;

    if (!move_uploaded_file($_FILES["foto"]["tmp_name"], $dirfoto)) {
        $error = TRUE;
        echo "Imagem não enviada!";
    }
}
</code>
Comment: no caso estou pegando a imagem via post, e tambem estou usando um subdominio para criacao creio que definir o diretorio assim pode causar algum problema futuro, pois se um dia resolver muda-lo para o dir raiz terei que alterar. de toda forma funcionou a criacao do diretorio , porem a imagem foi para a pasta nivel acima
Comment: deu certo andre, mais aqui me explica ai pq normal $Npasta nao estava pegando e ".$Npasta." assim ja pega?
Comment: Precisa concactenar as variaveis, quando voce for usar só com '', voce pode usar {$var} as chaves substituem o ''

Upload fora do Lugar


Mixed effect model with interaction

Question: I am trying to explore the effects of an intervention on different outcome measures over time. In this example I evaluate the differences in the log-transformed data of my response variable (named: measurement) over time (time1 [baseline], time2, time3) between groups (Group1, Group2, Group3).
This is my code:
t0<-lmer(measurement ~ Group * time  + (1|ID),gTUG)
And this is my output:

And the output from the anova(model) function:

(edited)(the total effect of the interaction is not significant; I think that it is due to lack of power and, additionally, my participants' data is quite variable and a bigger sample size could've improved the model)
(edited)Graph of the data:

How would you interpret the interaction properly? Would it be correct to say that only one level of the interaction is significant (i.e., Group2:timet2)?
(edited) Following the recommendations posted in the comments, I have checked whether adding an interaction significantly improves the model, and it does not significantly improve it. Output:

Therefore, would it be correct to focus on the differences between groups and across time points and report those?
I'd really appreciate your help!
Many thanks,
Anna
Answer: The effect estimators of interactions depend on the coding/contrasts. They are hard to interpret in the sense that they always compare a specific value to a baseline, interpretation depends on the baseline, and the contrast setting defines what it is. Probably from the code that you posted one could guess what the baseline is, but I'm frankly too lazy to look around and find it out (also it may depend on things that you have done before running the code that is posted above).
In any case what I recommend is this:

Test for the presence of the Group:timet interaction in total by fitting a model with it and another model without it and using the anova function to compare them.

Produce an interaction plot so that you can see what the most striking things are that cause the interaction as a whole to be significant (in case it is - I'd expect so based on the shown output, if maybe with p close to 0.05). Then interpret the plot.
Comment: I would add that you can use marginal means and pairwise comparisons to test on which specific pairs of conditions there are significant differences.
Comment: Many thanks for your answer! I have now amended  the question to provide more information about the model. I have also checked whether the model improved when adding the interaction term and it does not. Therefore, I assume I should delete the interaction and focus on the output from the model including only Group + time? Many thanks!
Comment: Personally I'd say you can use the model as it is, and say interactions are not significant so you won't interpret them. It is by no means mandatory to remove insignificant effects from a model, and there are good reasons against it (standard tests from a model that was constructed by data dependent selection are invalid). However there is a school of thought that would kick the interactions out in this case, so chances are if you do it it won't cause you trouble.
Comment: Hi @ChristianHennig, your answer helped me a lot to understand part of my model. Could you possibly have a look at this, please? https://stats.stackexchange.com/questions/566103/levels-in-a-mixed-effect-model-with-interaction-representation
Answer: My reaction is that you should see whether the time variable, including all of its interactions, adds anything significant to the model.
Interactions are tricky. The interaction coefficient for Group2:timet2 represents the difference of the estimated value from what you would predict solely from the individual Group2 and timet2 coefficients. (Recall that the timet2 coefficient itself represents the estimated difference between timet2 and timet1 only within Group1.) Your results show that is the only combination of Group and time whose effect can be distinguished statistically from those 2 sets of individual coefficients.
What makes me hesitate are the relatively small coefficients for either of timet2 or timet3 or for the other interaction coefficients, particularly when compared against the much larger coefficients for Group. I wonder whether a model without the interaction terms or maybe even without a time predictor at all might fit the data just as well.
Unless you had a pre-specified hypothesis about this particular interaction, I'd recommend comparing the full set of nested models overall: compare this model to one without the interaction, and compare the model without the interaction against one that just includes group as a predictor. Those are simple anova()-type comparisons.
If the overall test of the models with and without interaction show that the interaction model is significantly better than the one without the interaction, then go ahead and report this result. Otherwise, see whether time matters at all when added to a model that only contains Group. It might be that your data support no significant (or at least substantial) effect of time at all.
Added in response to updated information
As the overall interaction term isn't significant but the time term adds significantly to the Group-only model (p = 0.012 in anova(t0)), you should report the model with just the additive Group and time terms, no interaction.
Show something like the plot you have now added, which seems to summarize the data pretty well. The differences over time are significant, but they are much less than the difference between Group1 and the other 2 Groups. Group2 and Group3 don't seem to differ from each other.
You can then discuss whether the "statistically significant" effect of time is large enough to matter in practice, something that is based on your understanding of the subject matter rather than statistics per se.

As a separate note, consider whether it might be better to use a generalized linear model with a log link rather than to analyze the log-transformed data directly with lmer(). It's essentially a question of whether you wish to model the mean of the predictions on the log scale (as you are) or the log of the mean estimate from the linear predictor (generalized linear model with log link).
Comment: @AnnaFerrusolaPastrana I have added to the answer. Yes, a model with `Group` and `Time` but without their interaction seems to be the best way to proceed.
Comment: Thank you so much for your answer! I have now amended the question to include more information. In regard to the small coefficients of time, I understand your concerns about the small effect of time. However, my research aims to check whether there would be differences across timepoints for the outcome measure. Therefore, I think I cannot delete time since it is an important factor. Is this correct? Many thanks for all the helpful suggestions, I will take a look at those now!
Comment: This is very helpful, thank you very much!

Mixed effect model with interaction


How can I improve my picking speed and accuracy

Question: I've been playing acoustic guitar for almost 4 years and I just started electric. The way I see it there is a lot more picking involved in electric which I'm not so good at. Are there any exercises I can do to help me get faster and more accurate at my picking? (By accurate I mean not plucking the wrong strings - which is what I tend to do now!) Thanks
Answer: For speed picking, most electric guitarists use something called alternate picking, or variants of it. Learning it early would be a benefit for your hand/finger coordination. There are a lot of good easy-to-find free lessons online, i recommend Pebber Brown's videos on YouTube (stay away from his left hand videos, they don't explain good hand posture enough) but I'll provide a method below.
First of all, common alternate picking means strictly alternating between picking with an upwards pick stroke and a downwards one. That's down, up, down, up. Some variants allow for exceptions but this is the one to learn first before any others.
Start with a simple exercise on one string only, then quickly move on and incorporate changing strings. I recommend figuring out some mind-twisting (not fast) riff and playing it on the first few frets, like Iron Maiden's Aces High. But first some necessary basic mechanics to bore you to death.
For the pick to not "catch" on the strings, angle it downwards (upwards is sometimes useful but not as often), meaning it shouldn't be parallel to the string when hitting it. Grip the pick between your thumb and the side of the outermost joint of your first (index) finger. Point the tip perpendicular towards the strings. As for your other fingers, you can use them as a pivot point on the body of the guitar, if you find it very hard to hit the right string. Otherwise curl them up into something close to a fist, and use your forearm and/or palm for pivots.
The movement needed can be created in five (5) ways at least. The most common one is using wrist motion. As you move your wrist, the force should come mainly from a twisting forearm motion. The next three are finger motion, forearm motion and shoulder motion, out of which shoulder motion is probably useless. Finger motion consists of flexing the thumb and first (index) finger joints so that the pick moves in the direction of the edges. As for the other two you can probably guess. Now the first three mentioned have their respective uses, but if you strive for efficiency, you want to use two or more of them. If a muscle group only has to perform part of the motion, it is under less load and can perform better. So when you are confident in the basics, combine two types of motion (finger and wrist recommended) and reach for speed!
After you are confident in alternate picking, it's time to learn economy picking. This is a real virtuoso technique, and is more efficient for difficult string-crossing stuff. The basic rule is, instead of alternating up/downstrokes, you always pick towards the string where your next note is. For example: even if your previous stroke was a downstroke on string 4, you use a downstroke to move to string 3. Same techniques apply, you just have to think differently about it.
The rest is mainly diagnostic. For example, if you find your down strokes are louder than your up strokes, practice up strokes and try to normalize the volume between strokes. Articulation exercises are good for this, they make you listen to yourself, try emphasizing every third note so that it is not in sync with up/down strokes.
And finally, some additional considerations:

Using a thicker, stiffer pick with a sharper point can make speed picking easier, though strumming with such a pick requires a much more relaxed wrist.
Avoid tensing up in your forearm and wrist. Aim for a relaxed picking style.
A (competent) personal guitar teacher will be able to look at your technique and help you improve. If you happen to be living in a country where education is available (meaning affordable), what are you waiting for?

Write a comment if you find something you need explained further on this subject. Suggestions on clarification are welcome, i think it could be explained a lot better.
Answer: I bought this book to help with something similar.  It has good reviews.  However, I haven't used it much for my own playing.  I also saw some other similar books on Amazon when I searched for that one.
Answer: Practice alternate picking, but with a Metronome, increasing the speed gradually after each cycle


Error installing VSFTPd 3.0.2 on Ubuntu 12.04

Question: I'm following the official documentation to install the 3.0.2 version of VSFTPd.
Commands.
$ wget https://security.appspot.com/downloads/vsftpd-3.0.2.tar.gz
$ tar xvfz vsftpd-3.0.2.tar.gz
$ cd vsftpd-3.0.2/
$ make
$ mkdir /usr/share/empty/
$ mkdir /var/ftp/
$ useradd -d /var/ftp ftp
$ chown root.root /var/ftp
$ chmod og-w /var/ftp
$ cp vsftpd /usr/local/sbin/vsftpd
$ cp vsftpd.conf.5 /usr/local/man/man5
$ cp vsftpd.8 /usr/local/man/man8
$ make install

And I get this error after make install:
if [ -x /usr/local/sbin ]; then \
    install -m 755 vsftpd /usr/local/sbin/vsftpd; \
else \
    install -m 755 vsftpd /usr/sbin/vsftpd; fi
if [ -x /usr/local/man ]; then \
        install -m 644 vsftpd.8 /usr/local/man/man8/vsftpd.8; \
        install -m 644 vsftpd.conf.5 /usr/local/man/man5/vsftpd.conf.5; \
elif [ -x /usr/share/man ]; then \
        install -m 644 vsftpd.8 /usr/share/man/man8/vsftpd.8; \
        install -m 644 vsftpd.conf.5 /usr/share/man/man5/vsftpd.conf.5; \
else \
        install -m 644 vsftpd.8 /usr/man/man8/vsftpd.8; \
        install -m 644 vsftpd.conf.5 /usr/man/man5/vsftpd.conf.5; fi
install: accessing `/usr/local/man/man8/vsftpd.8': Not a directory
install: accessing `/usr/local/man/man5/vsftpd.conf.5': Not a directory
make: *** [install] Error 1

Can anyone help me to fix it?
Comment: Read the error message and make the needed directories.
Comment: While I am a big fan of using distro tools to install software, needing a newer version then the one shiped with your distro is one of the few exceptions I would make. Ubuntu ships 2.x, the poster wants 3.0.2
Comment: I just tried this on a ubuntu 12.04 system. I got the same error, but creating the missing directories fixed it. Maybe you forgot to use 'sudo' ? like 'sudo make install' ?
Comment: It tells you that the makefile does not define a "target" named "install-vsftpd". So there is not much you can do about it :) Where did you get the idea, that this target installs the bootscript? Maybe that ressource assumes a different makefile.
Comment: I do that, but doesn't install again!

`mkdir -p /usr/local/man/man8 /usr/local/man/man5`
Comment: Why don't you use `aptitude`? Installation from tarball lowers maintainability and stability of your system.
Comment: @Isaac : You are right re: lagging version in the distro.
Comment: I reinstall the Ubuntu and now probably works.
`whereis vsftpd` returns `vsftpd: /usr/local/sbin/vsftpd`. But I do `make install-vsftpd` to install the bootscript and returns this error: `make: *** No rule to make target 'install-vsftpd'.  Stop.`. Anyone know this error?
Answer: Try to create directories man5 and man8 by mkdir -p /usr/local/man/man8 and mkdir -p /usr/local/man/man5 if they aren't exist.


Understanding the application of Markov's inequality in a probability journal paper

Question:
I am trying to understand why the inequality (1) shown below holds. This is above (5.3) in page 28 of this paper. The explanation given in the paper is that it follows from the Markov's inequality, and I don't understand how.

Let $S$ be an event, $\mathcal{F}_{i-1}$ be a sigma algebra, $G_n^\star$ be a random graph. The precise definitions of $S,\mathcal{F}_{i-1}, G_n^\star$ are not needed for my question. In the paragraph above the inequality I am considering, it is mentioned that $\mathbb{P}(S\mid \mathcal{F}_{i-1})\geq 1-\varepsilon^2$. Then the paper considers the following set:
$$\mathcal{G} = \{G:\mathbb{P}(S\mid G_n^\star = G)\geq 1-\varepsilon\}$$

Then the paper says that by using the Markov's inequality, the following inequality holds (I am trying to understand why this is true): $$\mathbb{P}(G_n^\star\in \mathcal{G}\mid \mathcal{F}_{i-1})\geq 1-\varepsilon \tag{1}$$

My attempt at understanding this: I am thinking that:
\begin{align}
\mathbb{P}(G_n^\star\in \mathcal{G}\mid \mathcal{F}_{i-1}) &= \mathbb{P}(\mathbb{P}(S\mid G_n^\star)\geq 1-\varepsilon\mid \mathcal{F}_{i-1}) \\
&\leq \frac{\mathbb{E}[\mathbb{P}(S\mid G_n^\star)\mid \mathcal{F}_{i-1}]}{(1-\varepsilon)} \tag{2}\\
&= \frac{\mathbb{P}(S\mid \mathcal{F}_{i-1})}{(1-\varepsilon)}
\end{align}
where the inequality (2) follow from the Markov's inequality. So I am getting an upper bound for $\mathbb{P}(G_n^\star\in \mathcal{G}\mid \mathcal{F}_{i-1})$ using the Markov's inequality and not a lower bound as shown in (1). It'd be great to know what is wrong in my argument and/or why the inequality (1) is true. Thanks!
Answer: The trick is to go to the compliment (multiple times). When you want to show a lower bound, you can instead show an upper bound (for example by the Markov inequality) for the complement.
More precisely:
\begin{align*}
\mathbb P(G_n^*\not\in \mathcal G\vert \mathcal F_{i-1}) &= \mathbb P(\mathbb P (S\vert G_n^*) < 1 - \epsilon)\vert \mathcal F_{i-1})\\
&=\mathbb P(\mathbb P(S^c\vert G_n^*) \geq \epsilon\vert \mathcal F_{i-1})\\
&\leq \dfrac{\mathbb E[\mathbb P(S^c\vert G_n^*)\vert \mathcal F_{i-1}]}{\epsilon}\\
&= \dfrac{\mathbb P(S^c\vert \mathcal F_{i-1})}{\epsilon} \leq \dfrac{\epsilon^2}{\epsilon} = \epsilon,
\end{align*}
so that
$$
\mathbb P(G_n^*\in\mathcal G\vert\mathcal F_{i-1}) \geq 1 - \epsilon.
$$


Can we use cluster analysis in multiple regression

Question: I am quite new to Data Analytics. I was just wondering whether we can use cluster analysis in Multiple Regression. Let me give you a scenario so that it becomes easier to visualize.
I have a dataset of Property Transactions in the year 2013. The dataset has Property price, Region, Property Area in sq.m, Properties' locational attributes like is it close to bus stop, super market and so on.
Now if I use multiple regression model over here, I can use Price as my dependent variable and other variables as my independent variables and figure out what independent variables cause major influence on Price.
Instead of this approach if I use cluster analysis and figure out which regions have maximum prices and what are the locational attributes that are causing this increase, divide the dataset based on these clusters and then do multiple regression on these datasets to see what regression analysis results I get, will it make sense?
Comment: It's difficult to know what you're imagining here: "if I use cluster analysis and figure out which regions have maximum prices and what are the locational attributes that are causing this increase". You don't need cluster analysis to see where maximum prices are; in fact it is not clear that cluster analysis would help in that at all. How would the cluster analysis tell you anything about influences that the multiple regression won't? (Very generally, not much in statistics, including multiple regression, tells us about causes; your wording of influences is nearer the mark.)
Comment: I think you misunderstand the purpose of cluster analysis. It will look for properties that are similar across all the variables in your data set. This may tell you something useful about the properties, but  (as @NickCox said) you already know which properties have the highest price. Doing multiple regression _within_ each cluster might be useful but it's hard to say. It would be more typical to look at interactions or possibly a regression tree.
Comment: It's not easy to just "figure out...what are the locational attributes that are causing this increase." What your technique currently does is reduce price from a continuous variable to a categorical variable (ie a cluster label). you are proposing to first build a  classifier for price cluster and then use the features in that classifier to build a continuous prediction model for price. That might not be a bad route but it's probably not great and it's probably not what you really want to do
Answer: Since you have labeled data, a supervised approach will usually outdo any unsupervised approach.
I agree with Peter Flom, who in the comments noted that you "misunderstand the purpose of cluster analysis". Clusters are not meant to find regions with maximum prices.
Chances are that by partitioning your data into clusters without paying attention to price, your multiple regeression approach will be worse, because it only sees part of the data; and it may have discontinuities at the borders. But in other cases, exactly this can help.
Why not just give it a try and see for yourself? But beware of overfitting, don't increase the number of variables too much.
Comment: Thank you all for your inputs. I am surely going to try it out now.
Answer: Perhaps consider staying with the multiple regression first and determine which independent variables have significant impacts (low p-value) on the dependent(Price).
Then perform a hierarchical cluster (Ward's method) to understand and "type" your clusters. You might find similar Price clusters with completely different combinations of dependent variables. These would then expose the unique geographic and/or demographic conditions that drive the cluster creation.
If you are looking to perform or recommend actions towards the clusters, this approach would allow for that. $.02


Dúvidas sobre ID nos cadastros de um sistema retaguarda web

Question: Estou desenvolvendo um app web comercial e venho do mundo dos apps desktop. Percebi que na maioria dos sites de apps comerciais são ignorados os IDs ou códigos dos cadastros para os clientes. Claro que no banco de dados eles são fundamentais para os relacionamentos, mas tenho essa dúvida de deixá-los visíveis ou não nas grids e telas de cadastro.

Na empresa onde trabalho, usamos um sistema retaguarda desktop no qual todos os cadastros possuem a matrícula (ID ou Código) e eles são muito importantes para os clientes usarem para relacionarem um cadastro com o outro. Inclusive, quando migramos os dados de uma empresa concorrente para o nosso, os clientes fazem questão de preservarem os antigos códigos de clientes, produtos, grupos, fornecedores, etc.
O que é mais adequado fazer?
Comment: Talvez seria mais baseada em opinião, mas acho que dá pra salvar a questão sintetizando um pouco e mudando as tags que não tem a ver...
Comment: Acho que a tag adequada seria UX
Comment: Tranquilo, @LuizVieira, se desculpa não. Comunidade é pra ser assim mesmo, onde um erra o outro acerta e assim a gente mantém tudo nos conformes. Tinha me passado despercebido uma possível discussão acerca de UX e agora faz completo sentido. Me deixei levar pelo tom opinativo da publicação.
Comment: @RovannLinhalis concordo. Eu tive um pouco de dificuldade em compreender o que o OP deseja, e se há uma dúvida especifica.
Comment: Uma das vantagens de deixar visível é que pode facilitar numa busca. Muitos sistemas até hoje usam códigos como uma espécie de referencia há algo (geralmente é a chave primária), claro que hoje em dia as coisas estão mudando. Sendo assim, é melhor você pensar a respeito, e ver o que você tem a ganhar ou perder com isso. Você poderia consultar os usuários e ver se a ocultação do código na interface traz algum beneficio ou malefício.
Comment: Colega @LINQ, desculpe mas eu discordo. "Isso" cabe sim no escopo do site. Vide as discussões de escopo no meta e o tanto de perguntas e respostas de UX que já existem no site principal. Talvez a pergunta esteja de um jeito que pareça meramente opinativa (o "o que acham disso" denota bem o problema da pergunta), mas UX *sempre* teve (e sempre terá) essa discussão.
Comment: @LINQ Sem problemas. Obrigado. :)
Comment: Entendo a relação que os clientes utilizam com os códigos... muitos vendedores sabem os códigos dos produtos de cabeça, ou utilizam uma etiqueta com um "codigo interno" menor que o EAN pra ir adicionando os produtos com maior agilidade (nada que um leitor não resolva, mas não é assim que funciona em pequenos comércios do interior...) há também casos onde o cliente utiliza o código do sistema antigo, pra relacionar com um arquivo físico de fichas (sim, ainda vejo esse tipo de coisa por aqui...)... se fosse fazer algo hoje, certamente só mostraria o essencial, no máximo alguma função pra mostrar
Answer: O ponto-chave da sua pergunta é esse:

"[...] todos os cadastros possuem a matrícula (ID ou Código) e eles
  são muito importantes para os clientes usarem para relacionarem um
  cadastro com o outro [...]"

Sim, eles certamente são importantes... para a empresa que criou e usa o sistema. Primeiramente, é um incômodo para um usuário ter de lembrar um código, qualquer que seja e por mais curto que seja. Em segundo lugar, em termos de dados de identificação, nada é mais importante para o cliente do que seu próprio nome. Certamente os clientes desses cadastros que você menciona prefeririam usar seus nomes para se relacionar. Não acredita? Pergunte aos clientes. Ou faça um exercício de empatia e se coloque no lugar deles com algum serviço que você usa (telefonia, entretenimento, etc).
Se o código é algo realmente necessário ao negócio, facilite a vida do cliente colocando-o em um cartão. Isso não é nenhuma ideia brilhante: as locadoras de filmes já faziam isso há muito tempo (na época em que ainda persistiam). Se você precisa de um código, deixe o cliente defini-lo. Isso se chama login, e geralmente se usa e-mail não somente pelo contato, mas pela unicidade.
Bom, agora, considerando como usuário não o cliente, mas a pessoa que lida com o cliente e usa essa interface para algum relacionamento, o código é ainda menos necessário. O que esse usuário precisa realmente saber é o nome do cliente, talvez seu email e outros dados da identidade do usuário ou de sua situação no negócio, dependendo do domínio do problema. De fato, em um sistema bem feito, as linhas dessa tabela já demonstram a ação que o usuário precisa tomar em relação àquele cliente, e se bobear até fazem a ligação telefônica (um exemplo de telemarketing) mesmo exibindo o telefone. Por que então o ID seria necessário além de seu uso nas tabelas do banco, isto é, por que seria necessário na interação?
O que costuma ocorrer é que o tal ID é tão importante para a empresa que ela empurra goela abaixo do cliente e do usuário que atende este, mas quase nunca tal código é realmente necessário. Veja que fazer UX é justamente se colocar essas perguntas (difíceis e as vezes incômodas para quem já está acostumado com o tal do "mundo das apps desktop").
Comment: Eu trabalhei numa montadora onde se usava códigos para se referenciar a uma determinada peça, como eram muitas peças (milhares de modelos) e o nome delas eram longos e técnicos demais, o código ajudava, mas o código não era a chave primária do banco e sim para ajudar a identificar grupos de peças, como as peças de um caminhão que sempre iniciava pelos dígitos `509` ou outros grupos de modelos. Neste contexto, os códigos sem dúvida ajudavam, mas só os usuários do sistema, os clientes não precisavam saber o código que era usado internamente na fabrica.
Answer: Você é que precisa responder a questão, como toda questão de UX.
Você precisa mostrar esse ID por alguma razão? O usuário precisa estar ciente disto? Talvez para obter algum suporte? Pode mostrar opcionalmente?
Eu não colocaria nada que não seja muito necessário. E mesmo que seja por motivos secundários eu criaria uma forma opcional de mostrar a informação, sei lá, um modo avançado ou de suporte.
Seria diferente se isto for um código de cliente ou algo assim. Mesmo neste caso não sou fã da ideia. Prefiro deixar o usuário mais confortável lindando com uma informação que faça parte do domínio dele.
Não mostrar não quer dizer que não esteja presente em todo o sistema.
Acho a afirmação da última frase meio estranha, mas se isto é verdade pode ser um motivo para usar esse código. Porém esse código por vir de algo externo não parece ser uma chave primária, pelo menos não deveria ser. Aí o ID ainda se torna necessário e tem um motivo a mais para ele não ser mostrado. Mas o código natural seria. Não confunda ID de banco de dados (chave substituta) com chave natural que o usuário entende.
Veja mais em Surrogate Key e Natural Key.


Need to submit forms twice to be processed?

Question: Recently I notice that all action for submitting forms need to be executed twice to actually submit the values. Before this worked fine when I hard coded the resulting action path from my backing beans, but since I started to resolve all action path via the faces-config strange things has started to happen. One thing is that I need to press a submit button twice to fire the action, the browser fires the POST. I can see in firebug that two POST is fired and only the last one is processed by Glassfish.
Don know if this is side effect of the problem I experience. But many times when I do a forward the page losses CSS classes and things start to look ugly and some components (Richfaces - datatable) start to render badly. Actually I have to do redirect most of the time for things to render properly.

What can be the reason that I need to do two POST/submit before the Glassfish server will process the request ?
Why do I constantly need to redirect to make components (Richfaces) to render correctly ?

I use:

Glassfish 3.1
NetBeans 7.0.1
Richfaces 4.0-final

Sample of my Faces-config;
<navigation-rule>
    <from-view-id>*</from-view-id>
    <navigation-case>
        <from-outcome>CreateActivity</from-outcome>
        <to-view-id>/app_user/activity/Create.xhtml</to-view-id>
        <redirect />
    </navigation-case>
</navigation-rule>
<navigation-rule>
    <from-view-id>*</from-view-id>
    <navigation-case>
        <from-outcome>CreateActivityDetail</from-outcome>
        <to-view-id>/app_user/activity/UpdateDetail.xhtml</to-view-id>
    </navigation-case>
</navigation-rule>

Firebug log --
First POST (doesn't work when submitted)
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:6.0) Gecko/20100101 Firefox/6.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Faces-Request: partial/ajax
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:8080/humis/faces/app_user/activity/List.xhtml
Content-Length: 430
Cookie: JSESSIONID=cd70a069ad528b3923bd52f12b1c
        JSESSIONID=cbe0c977cf1c550f2a57cb4b334f;
        treeForm_tree-hi=treeForm:tree:resources:jmsResources:jmsDestinationResources
Pragma: no-cache
Cache-Control: no-cache

First Response
X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.1 Java/Sun Microsystems Inc./1.6), JSF/2.0
Server: GlassFish Server Open Source Edition 3.1.1
Cache-Control: no-cache
Content-Type: text/xml;charset=ISO-8859-1
Content-Length: 667
Date: Thu, 18 Aug 2011 13:30:22 GMT

Second POST (the one that works)
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:6.0) Gecko/20100101 Firefox/6.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Faces-Request: partial/ajax
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:8080/humis/faces/app_user/activity/List.xhtml
Content-Length: 494
Cookie: JSESSIONID=cd70a069ad528b3923bd52f12b1c;
        JSESSIONID=cbe0c977cf1c550f2a57cb4b334f;
        treeForm_tree-hi=treeForm:tree:resources:jmsResources:jmsDestinationResources
Pragma: no-cache
Cache-Control: no-cache

Second Response
X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.1 Java/Sun Microsystems Inc./1.6), JSF/2.0
Server: GlassFish Server Open Source Edition 3.1.1
Cache-Control: no-cache
Content-Type: text/xml;charset=UTF-8
Content-Length: 145
Date: Thu, 18 Aug 2011 13:30:44 GMT

Comment: Sometimes the POST is queued up that was supposed to happen previously, and the next action GET/POST will not be the current action until I press the button/commandlink again.
Answer: It sounds like that you've mapped the FacesServlet on multiple URL-patterns and that in some way all the autogenerated URLs to CSS and JS resources become invalid. Doing some basic debugging and investigation of the <link> and


Different vat rate per commerce shipping service

Question: I have a complex shipping price grid, with :

Different modes : tracked or not
Different zones : France, EU, World
Different prices per weight steps (<250g, <400g, etc.)

I started to implement that using Commerce shipping, Commerce flat rate and Commerce physical products, and a lot of rules, but now I need to apply a fixed VAT rate (20%) on shipping ONLY for tracked shipping in France.
Any idea of how I can do that? The VAT rate rule calculation seems to apply everytime, I don't know how to say "only for tracked shipping service".
Maybe it's time to make my own shipping module?
Comment: Ok, it seems it can be done with a condition on the VAT rate rule, if I use a PHP code condition, I can test the shipping line item.
Answer: As the author answered in a comment, this can be achieved by adding a rule condition to the rule that applies the VAT rate. Often pricing tables requires custom PHP code. Though, it's better to create a custom module and define your own rule condition in code.
You just have to implement one of the following hooks:
Custom Rules Action (not what you need, but good to know)
<code>/**
 * Implements hook_rules_action_info()
 */
function MODULE_rules_action_info() {
  return array(
    'machine_name' => array(
      'label' => 'Custom Action',
    ),
  );
}

/**
 * machine_name custom action
 */
function machine_name() {
  // do action
}
</code>
Custom Rules Condition (definitely what you need)
<code>/**
 * Implements hook_rules_condition_info()
 */
function MODULE_rules_condition_info() {
  return array(
    'machine_name_condition' => array(
      'label' => 'Custom Condition',
      'arguments' => array(
        'type' => 'user', // there are lots of types
        'label' => 'Fancy user',
      ),
    ),
  );
}

/**
 * machine_name_condition custom rules condition
 */
function machine_name_condition($user) {
  if ($user->uid == 1) return true;
  return false;
}
</code>


Using t-test for comparing Likert responses before and after intervention

Question: I am testing a hypothesis that states that participants after an intervention will be more likely to perceive themselves as being at risk for disease. Two questionnaires will be used.  One will consist of 5 questions and will measure perceived susceptibility and the the other will consist of 7 questions and will measure perceived disease severity.
I think the best way though uncertain to analyze these two questionnaires which are rated on 5-point Likert scales is to use a $t$-test but I am not sure of how or the best way to do it. I am looking for suggestions.
Comment: Now that I re-read the question and its title, it's not clear to me where the pre-post measurement process arises? Do you intend to use the two questionnaires twice (before and after intervention)?
Comment: The answer is yes. I will be using the same instruments pre and post the intervention.
Comment: Are these questionnaires considered validated in your study population? Are there standard ways to score each (e.g., arithmetic sum of responses, weighted sum, different subscales)?
Comment: I will have to do a pilot study initially. The
scores will be tabulated and separated by the overall number of participants who answer each question to determine the score rates for perceived severity and susceptibility and additonal demographic questions.
Answer: T-tests assess a difference in mean outcome between two groups. In this case, I assume you intend to use your 5 level ordinal response scale as such an outcome. This means that responses will be literally coded as such with the 1 indicating a response of "not at all at risk" and 5 indicating "at very high risk". This is generally considered a valid approach for the analysis of such data.
Your study design allows you to use a special paired t-test for which software is available to compute and test for differences in pre/post responses. In a 1 sample case, without a control group, you might test whether the estimated pre/post difference is consistent with having no difference (a difference of 0). It's generally bad practice to do an intervention study without a control group. This gives rise to the Hawthorne effect.
If you have a control group, then you can use a 2 sample paired t-test to compare pre/post differences between the intervention and control groups. In a future study, it might be useful to consider adjusting for certain variables, like family history, for greater precision. This would require a regression framework.
Comment: If I were to conduct this study using a regression framework what would you suggest ?  I do intend to look at the varialbes BMI, family history of disease, age , personal history of disease.
Comment: It depends on lots of factors, most notably the specific disease. Take a peek at Regression Modelling Strategies or Regression Methods in Biostatistics which give rich discussions about variable adjustment in such models.


Inserte a Contrasenha para continuar

Question: Observação: Não falo português. Este texto foi traduzido antes de ser postado e a tradução foi revisada por outros usuários.
Estou usando o Netbeans 8.0.1.
Faz dias que estou buscando uma solução pra isso. Já tentei usar JDialog e outras coisas, mas não deu certo.
Eu notei que depois que o usuário define as senhas e eu definir o fechadesalida = null, no meu banco de dados MySQL vai poupar todo o campo de texto, como espaços vazios.
quando a aplicação java começa accion = "insertar";
Primeiro de tudo eu preeencho os TextFields e clico nesse botão:
private void btnGuardarSalidaActionPerformed(java.awt.event.ActionEvent evt) {

    if (cboCamion.getSelectedItem() != null) {
        if (cboChofer.getSelectedItem() != null) {
            if (T_SalidaKm.getText().trim().length() != 0) {
                if (T_FechaSalida.getText().trim().length() != 0) {
                    ChoferLogin Chofer = new ChoferLogin();
                    Chofer.a = ((String) cboChofer.getSelectedItem());
                    Chofer.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "Inserte la Fecha");
                }
            } else {
                JOptionPane.showMessageDialog(null, "Seleccione el Km Salida");
            }
        } else {
            JOptionPane.showMessageDialog(null, "Seleccione el Chofer");
        }
    } else {
        JOptionPane.showMessageDialog(null, "Seleccione el Camion");
    }

}

Então, um outro JFrame aparece, e aqui o usuário insere a sua senha e o botão é clicado.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    ChoferLog();
}

Este é o metodo ChoferLog:
public void ChoferLog() {

    String sql4 = " Select * from choferes where chofer=? and Password=?";

    try {
        pst = con.prepareStatement(sql4);
        pst.setString(1, a);
        pst.setString(2, T_Password.getText());

        rs = pst.executeQuery();

        if (rs.next()) {
            JOptionPane.showMessageDialog(null, "Confirmado");
            viajes.GuardarSalida();
            this.dispose();

        } else {
            JOptionPane.showMessageDialog(null, "La Contrasena es incorrecto");
        }

    } catch (SQLException | HeadlessException e) {
        JOptionPane.showMessageDialog(null, "Error" + e);
    }

    dispose();
}

E este é o método GuadarSalida da class Viajes:
void GuardarSalida() {
    switch (accion) {
        case "insertar":
            sql = "insert into viajes(camion,chofer,kmsalida,acompanhante,"
                    + "viatico,destino,cargadediesel,litros,fechadesalida,"
                    + "bascula,peaje)"
                    + " values (?,?,?,?,?,?,?,?,?,?,?) ";
            break;
        case "modificar":
            sql = "Update viajes set "
                    + "camion= ?,"
                    + "chofer= ?,"
                    + "kmsalida= ?,"
                    + "acompanhante= ?,"
                    + "viatico= ?,"
                    + "destino= ?,"
                    + "cargadediesel= ?,"
                    + "litros= ?,"
                    + "fechadesalida= ? ,"
                    + "bascula= ?,"
                    + "peaje= ? "
                    + " where idviajes = " + id;
            break;
    }
    sql = "insert into viajes(camion,chofer,kmsalida,acompanhante,"
            + "viatico,destino,cargadediesel,litros,fechadesalida,"
            + "bascula,peaje)"
            + " values (?,?,?,?,?,?,?,?,?,?,?) ";

    try {

        day = T_FechaSalida.getText().substring(0, 2);
        month = T_FechaSalida.getText().substring(3, 5);
        year = T_FechaSalida.getText().substring(6);
        pst = con.prepareStatement(sql);
        pst.setString(1, (String) cboCamion.getSelectedItem());
        pst.setString(2, (String) cboChofer.getSelectedItem());
        pst.setString(3, T_SalidaKm.getText());
        pst.setString(4, (String) cboAcompanhante.getSelectedItem());
        pst.setString(5, T_Viatico.getText());
        pst.setString(6, T_Destino.getText());
        pst.setString(7, T_CargadeDiesel.getText());

        if (T_CantDiesel.getText().isEmpty()) {
            pst.setString(8, null);
        } else {
            pst.setString(8, T_CantDiesel.getText());
        }

        pst.setString(9, year + "-" + month + "_" + day);
        pst.setString(10, T_Bascula.getText());
        pst.setString(11, T_Peaje.getText());
        pst.executeUpdate();

        TablaDeEspera();
        LimpiarSalida();
        JOptionPane.showMessageDialog(null, "Se Cargo Con Exito !", "Guardar", JOptionPane.INFORMATION_MESSAGE);
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, "No Se Cargo Los Datos " + ex);
    }

}

E eu recebo esta exceção. Por favor me ajude, eu estou há dias procurando e não conseguimos encontrar a solução:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.substring(String.java:1950)
    at Viaje.Viajes.GuardarSalida(Viajes.java:353)
    at Viaje.ChoferLogin.ChoferLog(ChoferLogin.java:61)
    at Viaje.ChoferLogin.jButton1ActionPerformed(ChoferLogin.java:197)
    at Viaje.ChoferLogin.access$300(ChoferLogin.java:22)
    at Viaje.ChoferLogin$3.actionPerformed(ChoferLogin.java:116)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:289)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2739)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:719)
    at java.awt.EventQueue$4.run(EventQueue.java:717)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Comment: De acordo com a exceção gerada, o método substring não está encontrando o Index [1] provavelmente o campo T_FechaSalida não tem 2 caracteres, a leitura de substring(0, 2) seria (da posição 0, pegue até a posição 2 - 1), traduzindo, ele vai pegar a posição [0], [1]
Answer: Me parece que o seu erro vem daqui:
day = T_FechaSalida.getText().substring(0, 2);

Ou seja, o campo T_FechaSalida não foi preenchido de forma correta.
Você não está testando em lugar nenhum se os campos forma preenchidos corretamente.
Modifique o método btnGuardarSalidaActionPerformed para verificar se todos os campos estão preenchidos corretamente (ou coloque esta validação em outro lugar) antes de enviá-la ao banco de dados.

Inserte a Contrasenha para continuar


Isomorphic free groups $F(A),F(B)$ induce bijective sets $A \cong B$

Question: I need help trying to solve this problem.
Let $A, B$ be sets, and $F(A), F(B)$ the corresponding free groups. Assume $F(A) \cong F(B)$. If $A$ is finite, prove that so is $B$, and $A \cong B$ as sets.
Comment: The same question for *arbitrary set* (not necessarily *finite*) has been asked here: [free groups: $F_X\cong F_Y\Rightarrow|X|=|Y|$](http://math.stackexchange.com/questions/35229/free-groups-f-x-cong-f-y-rightarrowx-y)
Comment: Please explain the notation ~=.
Comment: it means it is an isomorphism.
Answer: Let $A$ and $B$ be any sets.  If the free groups $F(A)$ and $F(B)$ are isomorphic, so are their abelianizations.  The abelianizations are the free abelian groups on the sets $A$ and $B$.  It is much easier to see that if these are isomorphic, then $\# A \cong \# B$: for instance tensor with $\mathbb{Q}$ to reduce to the fact that bases of isomorphic vector spaces have the same cardinality.
Comment: Someone has to upvote this answer at some point, +1. Interestingly, [point 3 here](http://en.wikipedia.org/wiki/Free_group#Facts_and_theorems) claims that it follows readily from the definition.
Comment: I'm having trouble understanding the downvote here: what seems to be amiss?


Spivak's 'Calculus', 5-23(a$\land$b). How does $\frac{l}{\infty}=0$ make sense?

Question: Problem

(a) $\;\;\;$ Suppose that $\lim_{x\rightarrow0}f(x)$ exists and is $\neq 0$. Prove that if $\lim_{x\rightarrow 0}g(x)$ does not exist, then $\lim_{x\rightarrow 0}f(x)g(x)$ also does not exist.
(b) $\;\;\;$ Prove the same result if $\lim_{x\rightarrow 0}|f(x)|=\infty$.

Solutions from answer book

(a) $\;\;\;$ If $\lim_{x\rightarrow 0}f(x)g(x)$ existed, then $\lim_{x\rightarrow 0}g(x)=\lim_{x\rightarrow 0}\frac{f(x)g(x)}{f(x)}$ would also exist.
(b) $\;\;\;$ Cleary, if $\lim_{x\rightarrow 0}f(x)g(x)$ existed, then $\lim_{x\rightarrow 0}g(x)=0$.

Solution (a) is clear. Is there a more mathematical way of stating solution (b)?
The way I sort of make sense of solution (b) is through solution (a) since, if $\lim_{x\rightarrow 0}f(x)g(x)=l$ existed, then
$$\lim_{x\rightarrow 0}g(x)=\lim_{x\rightarrow 0}\frac{f(x)g(x)}{f(x)}=\lim_{x\rightarrow 0}f(x)g(x)\cdot\lim_{x\rightarrow 0}\frac{1}{f(x)}=l\cdot\frac{1}{\infty}=\frac{l}{\infty}=0$$
But since $\infty$ is not a number, how does this make sense? (it makes intuitive sense of course, but I want the maths behind the intuition).
Comment: $\frac{1}{\infty}$ gets closer to $0$ as the denominator approaches $\infty$ so they just say its zero
Comment: As you have confirmed that $\infty$ is not a number, you better say what it is... What is it?
Comment: Let $\lim_{x\rightarrow a}f(x)=\infty$ mean that, $\forall N$, $\exists \delta$ s.t., $\forall x$, if $0<|x-a|<\delta\
\Rightarrow f(x)>N$.
Answer: Just take the definitions:
If $\lim_{x \to 0} f(x) = C$ then for all $x \in (-\delta, \delta)$ we have $f(x) \in (C - 1, C + 1)$. Thus $|f(x)| < |C| + 1$.
If $\lim_{x \to 0} |g(x)| = \infty$ then for all $x \in (-\delta',\delta')$ we have $|g(x)| > M$.
Replacing $\delta$ with $\min\{\delta,\delta'\}$ we therefore have
$$ \frac{|f(x)|}{|g(x)|} < \frac{|f(x)|}{M} < \frac{|C|+1}{M}$$
Now choose $M$ appropriately and shrink $\delta$ accordingly, you can make this sum smaller than $\varepsilon$ for any $\varepsilon > 0$.


"live" mirror of HA VM cluster?

Question: I'm reading about HA techniques in virtualization but all solutions I see work more or less just like more specialized VRRP - when host gets down, VM is booted up on another virtualization host. If storage is shared (eg. iSCSI) then "the same" VM can be booted so to guest OS it looks like kind of power failure. But if there is some important data residing in RAM (for example in-memory database) then it's still lost.
It would be possible though to create snapshot of running VM with some interval (unfortunately it takes plenty of time to create such snapshot so it can't really be done every lets say 10 seconds). Then another virtualization host could load such snapshot and continue running VM "without interruption" (plus minus interval time).
So my question is - are there any solutions automatically "mirroring" VMs in such way that after virtualization host failure VM can be "resumed" on another host without noticeable interruption? Literally like RAID1 of VMs. Mirror that is fully synced on RAM level.
Answer: 1) Deploy a VMware vSphere cluster and use Fault Tolerance https://www.vmware.com/files/pdf/techpaper/VMware-vSphere6-FT-arch-perf.pdf feature on your virtual machines (as already mentioned above).
2) Deploy a XenServer cluster and use Remus https://wiki.xenproject.org/wiki/Remus.
Answer: Servers shouldn't "just fail" in the manner you're describing. Most people do not worry about this.
However, this is a use case for VMware Fault Tolerance (FT).
This will do what you're asking for.
If asynchronous replication is desired with a small delay (like 10 seconds), then a solution like Zerto would be apt.
Comment: Does Zerto actually save the memory state as well? Last I checked, they were only sending the changed disk bits over to the DR site
Comment: Oh, Zerto is just crash-consistent or application-consistent, depending on the VM. This is what most organizations use for DR with low RPT/RTO. VMware FT isn't widely used.
Answer: There are some solutions that can failover VMs without any downtime. At least I know about HPE VSA and Starwinds. They have free versions as well, so you can look at those.
However, I don't know exactly about the first one, ain't tested it by myself yet. About second one - there's an option where you can assign an amount of RAM on the HA device, and this RAM also is replicated on another node. And The VMs failover without reboot. Tested that with Hyper-V cluster.
Comment: HPE VSA and Starwind VSAN seem related to software-define storage - while the OP specifically ask about active memory (RAM) state synchronization
Answer: Unfortunately no, there is no way how to do it and you really don't need it at all. Even in-memory databases can make mirroring and HA on application level, there is no need for memory mirroring in this way. Just start multiple instances of your in-memory database and let mirroring begin! It is fault tolerant and you can even make any upgrades and maintenance without outage.
Answer: Unfortunately, the answer is no, at least for commercial/enterprise-grade hypervisors.
Ok, I stand corrected: I never used/read about Xen+Remus, and it seems quite interesting.
I know about VMWare FT, but it has such great limitations that I automatically discarded it. Fortunately, some of these restrictions were lifted with the last VMWare release. However, in network or I/O bond scenario the raw performance impact would be simply too great to tolerate.
Anyway, from what I can read, both are based on the concept of checkpoint: basically, the underlying VM is continuously live-migrated. True RAM lockstep/mirroring is way more expensive: some years ago, a project based around Qemu/KVM tried this very same thing - and it was abandoned due to the enormous performance degradation it commanded.
Comment: And the people who invented KVM pretty much did a RAM lockstep over WAN for Xen before creating KVM. Wasn't very useful due to network latencies and overheads, but a cool little demo to show folks 10 years ago
Comment: Xen is a commercial & enterprise-grade hypervisor, biggest pubic cloud AWS is run on a custom version of Xen.

"live" mirror of HA VM cluster?


Why doesn't my nested paragraph respect font-size styles?

Question: If I have this

.outer {
   font-size: 2em;
 }

    Some Outer Div Text

       Some Inner Div Text

Both texts are 32px (16px *2)
However with this HTML:

    Some Outer Div Text

       Some Inner Div Text

The outer text is 32px, while the inner text is 16px.
How come the paragraph tag doesn't respect the parent's font-size like the div tag? I thought they would both work the same since they are both block elements?
Here's a JSFiddle in case I'm not clear: https://jsfiddle.net/scottfwalter/2Lrd6tzm/
Answer: Simple answer is you can't nest p tags, if you open the console and inspect you will see the 2 p tags are siblings instead of parent/child, therefore there is no inheritance.
See this answer for more details Nesting
 won't work while nesting
 will?
Comment: Ooh you right.  I didn't realize if you nest paragraph tags they are not really nested.   This explains a lit.
Answer: That's because browsers have their's own predefined styles for basic typography. So for example chrome sets font-size: 16px for
 but says nothing about
.
That's why we use normilize.css or reset.css to avoid such missmatching.
Try setting * {font-size: 16px;} - this should do the trick
Comment: That does make sense.   I added * {font-size: 16px;} however it doesn't seem to help.   If outer paragraph has a font-size of 2em and the inner paragraph has a font-size of 1em shouldn't they both be 32px.   The div tag works with both the inner and outer as 32px as I expected.  Just curious why the paragraph tag doesn't seem to use the parent paragraph tag as expected.  FYI--I updated the fiddle.   You wouldn't normally nest paragraph tags.  Had someone ask me this the other day and I can't come up with a good answer.


Como caber todo conteúdo na tela? Borda no fim da página não aparece no visor ou navegador

Question: Estou tentando criar um layout responsivo ao máximo**, e tenho problemas com o fim da borda da div. Eu propositalmente coloco uma borda vermelha por volta da div, para se der algo errado eu identificar imediatamente. O objetivo é que eu tenha todo o conteúdo da página exibida no dispositivo (seja ele qual for), sem a barra de rolagem, porém exibindo 100 do conteúdo dela (sem necessidade real da rolagem). As duas bordas finais (canto direito e inferior) estão sumindo da tela do dispositivo. Segue o código usado

html,
body {
  margin: 0;
  height: 100%;
}
.um {
  background: #333;
  color: white;
  padding: 50px 20px;
  height: 100%;
  /* para falta de suporte */
  height: -webkit-calc(100% - 100px);
  /* para Chrome */
  height: -moz-calc(100% - 100px);
  /* para Firefox */
  height: calc(100% - 100px);
  /* para suporte nativo */
}
#containerGeral {
  position: relative;
  width: 100%;
  height: 100%;
  border-style: solid;
  border-color: red;
  background-color: yellow;
}
#caixaTeste {
  width: 15%;
  height: 15%;
  background-color: blue;
  position: absolute;
  top: 0%;
}
#caixaTeste2 {
  width: 15%;
  height: 15%;
  background-color: green;
  position: absolute;
  right: 0%;
  top: 0%;
}
#containerTeste {
  width: 40%;
  height: 40%;
  border-style: solid;
  border-color: red;
  background-color: green;
  bottom: 30%;
  position: absolute;
}
#containerFilho {
  position: absolute;
  right: 0%;
  width: 65%;
  height: 65%;
  background-color: #ccc;
}
#containerFilho2 {
  position: absolute;
  right: 0%;
  width: 65%;
  height: 65%;
  background-color: blue;
  bottom: 0%;
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, user-scalable=no">

RELATIVO: CONTAINER GERAL

ABSOLUTO

ABSOLUTO

NOVO CONTAINER

CONTEINER FILHO

CONTAINER FILHO - FILHO

** Não acredito que exista nada 100% responsivo.
Answer: O que ocorre é que a borda que #containerGeral possui está sendo adicionada ao height e ao width do elemento, então a medida será 100% + a borda.
Para resolver isso ou você retira a borda ou você muda o height e width 100% para height/width: calc(100% - (a borda)).
Lembrando que você deve definir a espessura da borda e fazer x2 no caso de haver tanto a borda direita quanto a esquerda e vale para a borda top e bottom também.
Outro detalhe é que você não está utilizando nenhum reset, então sua tag h1 e outros elementos podem se comportar diferente em diversos navegadores.
Para seu caso específico, você pode colocar :
html, body{margin:0; height:100%, padding:0;}

e
h1{margin:0;}

Meu reset é basicão :
*{margin:0; margin:0;padding:0}

Mas existem outros bem famosos que é o caso do Mayer.
Veja como fica:

<!DOCTYPE html>

     <meta name="viewport" content="width=device-width, user-scalable=no">

     <title></title>

RELATIVO: CONTAINER GERAL

ABSOLUTO

ABSOLUTO

NOVO CONTAINER

CONTEINER FILHO

CONTAINER FILHO - FILHO

Comment: Quando uso ...
   height: calc(100% - 100px);
   width: calc(100% - 100px);
fica um espaço em branco.
Quando uso somente...
   height: calc(100% - 100px);
na div tudo, fica a lateral perfeita, aparecendo a faixa vermelha que coloquei lá. Fica faltando somente a parte da bottom, aonde não aparece a borda vermelha, a tela fica praticamente perfeita.
Ainda estou curioso. Mas isso me ajuda demais mesmo!
Comment: Não entendi bem o que está acontecendo, em qual elemento vc es´ta colocando essas regras ? Fiz uma edição com um exemplo do seu código...@PauloSérgioDuff qualquer coisa comenta que agente ajusta
Answer: Adicione box-sizing: border-box; ao seu container externo, #containerGeral.
Da documentação da propriedade box-sizing:

A propriedade CSS box-sizing é utilizada para alterar a propriedade padrão da box model, usada para calcular larguras (widths) e alturas (heights) dos elementos. É possível de usar essa propriedade para emular o comportamento dos navegadores (browser) que não suportam corretamente a especificação da propriedade CSS box model.

Versão funcional a seguir:

<!DOCTYPE html>

     <meta name="viewport" content="width=device-width, user-scalable=no">

    <title></title>

RELATIVO: CONTAINER GERAL

ABSOLUTO

ABSOLUTO

NOVO CONTAINER

CONTEINER FILHO

CONTAINER FILHO - FILHO

Comment: fica bam assim tmb,, achei que se só manja assembly
Comment: Isso matou a pau! Valeu mesmo!
Essa única linha (box-sizing: border-box;)  mudou tudo
Comment: @PauloSérgioDuff Sempre um prazer ajudar!


Interpret neural network like the linear regression equation such as how much will Y change if we change X1 and keep the other variables fixed

Question: In linear regression, assume we get the following equation : Y = 0.8X1+1.9X2+2.4X3+4X4.
We can interpret the linear equation: Keep the other predictors fix, one unit change in X1 will increase 0.8 units in Y in average.
Now, I use the neuralnet package in R and built a neural network model. Then, make a plot like the following picture.

From my perspective, all variables start with W such as W11,W21,W31 are the weight that previous variable or neural. The blue line and letters starts with b such as b11,b21,b31 are the bias weight.
Ignore the other coefficients I did not notice, just focus on the X1, can I write the equation of this neural network plot like:
Y = W31*W21*W11*X1 + W31*W21*W12*X1 + W31*W21*W13*X1 + W32*W21*W11*X1 + W32*W21*W12*X1 + W32*W21*W13*X1 + W32*W22*W11*X1 + W32*W22*W12*X1 + W32*W22*W13*X1
It looks quite ugly, but what I am curious is can I interpret the formula like the previous linear model ? Such as how Y changes if X1 increases one unit.
Or are there any other ways to interpret neural network plot (neuralnet) like this?
Answer: This is a nice question, that touches on some interesting points in the history of neural networks (which I can only briefly mention here).
First, what you say is absolutely right if and only if the nodes in your network have linear activation functions, e.g. $b_{1,1} = x_1w_1 + x_2w_2 + x_3w_3$.
However, as explained here, if your network only has linear activation functions, you can simplify the equations so that your multilayer network can be replaced with a simple network with no hidden layers where the input nodes connect directly to the outputs, and this simple network is basically just a linear regression model, $y = x_1b_1 + x_2b_2 + \dots + x_nb_n$.
This is why most useful neural networks use non-linear activation functions, and adding making the model non-linear means the equation you want can no longer be calculated: the effect of changing the value of x1 will depend on the values of all the other inputs.
What you can do, however, is compute the average effect of changing x1 in your training data quite easily: by modifying the values of x1 in your data and calculating the average change in y.
Comment: Very very clear explanation ! If our activation functions are non-linear, how can identify the interaction terms ? Like we can identify the interaction terms in linear regression, `lm(Y~x1x2)`, if we know both `x1` and `x2` we can still make a decent interpretation. Is it possible in neural network plot ?
Comment: If I understand your question, then yes, you can write out the non-linear formula for the change in `y` as you increase `x1` from a given starting value, holding the other `x`s constant. This is what @Dave is talking about when he describes the *partial derivative*. As I've said, though, this is almost always too complicated to be usefully interpreted, so most people will instead explore changing the inputs to see what effect that has on the output.
Comment: @Eoin It might be beneficial to give an example of the "average effect of changing $X_1$".
Answer: One of the issues when you introduce nonlinearities and interactions is that the change resulting in a change in a variable of interest depends on the starting value of that variable of interest and of the other variables in the model.
For instance, consider a model like $\hat y = x_1-x_2+x_1^2x_2$. If you want to know by how much $y$ changes upon changing $x_1$ by one unit, take the derivative.
$$
\dfrac{
\partial \hat y
}{
\partial x_1
} = 1 + 2x_1x_2
$$
You cannot answer the question (with a single number) unless you know $x_1$ and $x_2$.
Neural networks are no different. We can take partial derivatives (making use of the chain rule) and interpret those derivatives as slopes just like normal. However, those slopes are likely to depend on the values of all variables (just like above), including the variable of interest.
Consequently, there is no simple interpretation like, "When $x_1$ increases one unit, our predicted $y$ increases by $\hat\beta_1$ units."
If $A$ is an activation function, a simple neural network with two features and two neurons (with activation function $A$) in the hidden layer is:
$$
\hat y = \hat b_{2,1} + \hat w_{2,1}A\bigg(\hat b_{1,1}+\hat w_{1,1}x_1 + \hat b_{1,3}x_2\bigg) + \hat w_{2,2} A\bigg(\hat b_{1,2} + \hat w_{1,2}x_1 + \hat w_{1,4}x_2\bigg)
$$
For a nonlinear activation function $A$, the partial derivatives with respect to $x_1$ and $x_2$ can involve both $x_1$ and $x_2$, meaning that you must know the point where you want to talk about changes in order to talk about changes.
Comment: That's exactly what you would do, yes.
Comment: @nobodyishere It might be worth calculating $\dfrac{\partial\hat y}{\partial x_1}$ in the neural net I gave in my answer.
Comment: @nobodyishere notice that Dave's answer is local (it's the best linear approximation to the neural network output), so you are measuring the direction of change per unit of the input through an infinitesimal perturbation. It does not have the same property of the linear regression model you presented in your question (without interactions, polynomial terms).
Comment: @Firebug @Dave Thanks. I understand that part now but I raise a new confusion. Go back to the neural network plot, are there any relationship between `W31` with other `W21,22,11,12,13`?  Or can we write the equation between`W31` and the other previous weights? I am so curious how the `neuralnet` package calculate the weights.
Comment: @nobodyishere I'm sure neural network parameter calculations are covered in existing questions on Cross Validated, but that really warrants a separate discussion in its own question. (I largely see it as an implementation detail and kind of a dull topic that only gets my attention when I have to pay attention, so I do not know any questions offhand, but they must exist. Good keyword for searches might be "backpropagation" and "gradient descent". I know 3Blue1Brown has a YouTube video that covers this, too, if you care to watch it.)
Comment: @Dave Thanks Dave. After watching some tut videos about neural network I completely know how to write such equations between Y and the predictors. One more question is that why the weights can be negative? Such as the orange and red `W` text in the plot are the weights, what does it mean if the number is negative? I don't find such explanations.
Comment: @nobodyishere That sounds like the beginning of an outstanding next question to post that I would expect to get upvotes (at least one from me) and good answers.
Comment: Nice to meet you again! I understand what you are talking about now. The default activation function of `neuralnet` is `1/(1 + exp(-x))`. What I am going to do is plug `1/(1 + exp(-x))` instead of `A` in your answer.
Comment: Hi Dave, I figure that my neural network model contains ten input variables and one hidden layers with 4 neurals in that layers. Can I conclude it is impossible to interpret the relationship directly between `Y` and `X1` ?  There are other variables such as `X2 to X10`.
Answer: You can interpret NN like that but it is pointless generally. The seeming utility in doing so for OLS is in decoupling of the partial derivative from other variables, I.e. $\partial/\partial x_1 f(x_1,\dots,x_2)=\beta_1$.
With a useful NN you won't get this decoupling and the partial ends up being a nonlinear function of all inputs $\beta(x_1,\dots,x_2) $ ,which you may have thousands of. So, the sensitivity to the variables is not the constant and as such not a simple intuitive concept to start with. Consider also that if you add interaction and polynomial terms to the OLS the sensitivity becomes more complicated and less intuitive for a linear regression too.
Note, that your example is NN with linear activation in inner layers, not a useful contraption as it turns out.


COM ownership with composition in interfaces

Question: Does a COM interface have to override AddRef and Release if it owns other interfaces?
At interface creation, members are created that maintain a refcount, so I have to override Release to not leak the owned interfaces when the own refcount reaches zero.
But what about AddRef? It seems like everything will be fine when just doing shallow copies of the owned interfaces. They might have a refcount below the owning interface, but can never reach zero when the owner has not reached zero.
An example of this scenario is IDirect3DTexture9 owning many IDirect3DSurface9 for each texture level.
Comment: What do you mean by "own" here? When a caller gets a pointer on an interface (using any method, QueryInterface or others), an AddRef has been made by the method callee. When the caller does not need the interface pointer anymore it calls Release. That's about all of COM. The caller does not use AddRef or Release return values.
Comment: @SimonMourier In my example there are child/owned interfaces created when a parent/owner is created. If the caller just Releases the created interface, the children/owned interfaces should be released aswell.
Comment: This depends on the design decision by the library author. Sometimes the "parent" owns (addrefs) the child sometimes the "child" addrefs the parent, sometimes both.
Comment: Example of "both", is old-fashioned DAO, parent owns child and child owns parent. Example of "parent owns" is ADO Recordset owns Fields. Example of "child addrefs" is ADO Recordset addrefs Connection.
Comment: @typ1232 whatever the *parent* does is the *parent's* responsibility. if it uses and allocates resources (of any kind, not just other COM objects), it should either delegate responsibility of these resources out, or release them once no longer needed, typically when released via `Release`.
Comment: If a "parent" class has a pointer to a "child" interface, than it also should have addref'd it implicitly (by calling a method) or explicitely (by calling AddRef). Same rule for everyone, there is no special "owner" behavior that would release a bunch of interface automatically.
Comment: COM object responds to external AddRef/Release calls in the way that when it gets the number of releases matching number of preceding addrefs, it self-deletes or otherwise handles this as termination of activity. That's it. It does not matter what it "owns" exactly.
Comment: Why are you talking about copies, shallow or otherwise? What is being copied where, and by whom? In what way is `AddRef` related to copying?
Answer: No.
The resources should be freed in the destructor, or automatically if you're using smart pointer fields.  I'm assuming you're using C++.
So, indeed, inner interface pointers may have a lower reference count than the outer interface pointer.
Other than the outer pointer counting 1 towards the inner pointer's reference count, the reference counts are otherwise totally independent.


How do I modify the HTML of my subtheme?

Question: I created a bootstrap subtheme ouf of CDN. Modifying the CSS works, but how do I do it with the HTML? Where do I put new HTML elements? For example: I'd like to add some elements to my footer, make it background color black and have it the width of the screen (it's not by default in Bootstrap)
This is my subtheme folder:
Comment: What's in the template folder?
Comment: What about placing blocks in the footer region?
Comment: The template folder is empty and placing blocks seems a hassle as I don't know how to place a navigation with links and email subscription option in the footer
Comment: Then simply copy your base theme's template folder over, flush cache and edit the templates inside there.
Comment: Although doing this on template level can make the page hard to maintain pretty fast. It's worth getting used to custom blocks instead.
Answer: A sub theme inherits its templates from the base theme. When you want to edit templates for your sub theme you simply copy over the desired template from the base theme's template folder into your sub theme's template folder, flush the cache and start editing it.
And then flush the cache again.
Comment: Thanks. This works. Just to compliment this: If I'd like to add my custom HTML, lets say something like this snippet here: http://bootsnipp.com/snippets/e3QvQ   - I create a html.twig file in my template folder and paste the html there, right?
Comment: @Vasmir - Sort of. In the bootstrap theme it's the page.html.twig you have to copy over and edit. Find the `` tag and alter it to your needs.


YAML parser from bash

Question: I am developing a pre-prod server for a Symfony2 app
I made a little hook script to update all of my git repositories which contain a Symfony app.
# ...

# Save old database
DATABASE_NAME=`YAML Parser Command` 'app/config/parameters.yml' database_name
TODAY=`date +"%Y-%m-%d-%H:%M:%S"`
logger -t "Update website Symfony2" "Save SQL in $TODAY.sql"
mysqldump $DATABASE_NAME > sqlSave/$TODAY.sql 2>&1 | logger -t "Update website Symfony2"
# Update database with doctrine
php app/console doctrine:schema:update --force  2>&1 | logger -t "Update website Symfony2"

# ...

How can I have access to the database name on this script ?
My server is on Debian. Is there a package to parse YAML?
Comment: Would you be alright with adding a dependency on a scripting language?  Many of them have YAML parsing libraries so you could call one of them and have it output the data you want from YAML.
Answer: You can parse yaml/json file directly in your shell/bash with niet.
Easy to install and easy to use:
$ pip install -U niet

Consider the following example:
$ cat dump.yaml
foo:
  bar:
    key: value
  baz:
    key: value
  tags:
    - one
    - two

You can parse this example file like this:
  $ niet dump.yaml foo.bar.key
  value
  $ for el in $(niet dump.yaml foo.tags); do echo ${el}; done
  one
  two

Niet have a good integration with shell and others bash like.
Niet yaml parser documentation, source code, and samples.
Comment: i couldnt find `yq` for centos and your suggestion about `niet` really helped.
Answer: Depending on the structure of your app/config/parameters.yml and the location of database_name within it, you might be able to use this parser. It will parse
foo:
  bar:
    key: value
  baz:
    key: value

into bash associative arrays. 100% Bash, but it needs to be Bash 4.x. If you can't stick to Bash 4.x then there are other answers on this question that may help you.

YAML parser from bash


How to get min and max from 2 tables in SQL

Question: I am Trying to get start date from min ID (ID=1) and end date from max ID (ID=3) but i am not sure how i can retrieve. Following is my data -

Table1 and Table2 are source table. I am trying to get output like 3rd table.
My requirement is get start date from first record of ID and End Date from last record of ID, we can recognize first and and last record with the help of ID field. If ID is min means first record and ID is max then last record
Please help me!
Answer: Here's one option; presuming you use Oracle (regarding you use Oracle SQL Developer), the x inline view selects

start_date which belongs to name with the lowest ID column value for that name (i.e. first_value partition by name order by id)
end_date which belongs to name with the highest ID column value for that name (i.e. first_value partition by name order by id DESC)

SQL> with
  2  -- sample data
  3  t1 (pid, name) as
  4    (select 123, 'xyz' from dual union all
  5     select 234, 'pqr' from dual
  6    ),
  7  t2 (id, name, start_date, end_date) as
  8    (select 1, 'xyz', date '2020-01-01', date '2020-07-20' from dual union all
  9     select 2, 'xyz', date '2020-02-01', date '2020-05-30' from dual union all
 10     select 3, 'xyz', date '2020-06-30', date '2020-07-30' from dual union all
 11     --
 12     select 1, 'pqr', date '2020-04-30', date '2020-09-30' from dual union all
 13     select 2, 'pqr', date '2020-05-30', date '2020-09-30' from dual union all
 14     select 3, 'pqr', date '2020-06-30', date '2020-07-01' from dual
 15    )
 16  select a.pid,
 17         x.name,
 18         max(x.start_date) start_date,
 19         max(x.end_date)   end_date
 20  from t1 a join
 21      (
 22        -- start_date: always for the lowest  T2.ID value row
 23        -- end_date  : always for the highest T2.ID value row
 24        select b.name,
 25               first_value(b.start_date) over (partition by b.name order by b.id     ) start_date,
 26               first_value(b.end_date)   over (partition by b.name order by b.id desc) end_date
 27        from t2 b
 28       ) x
 29       on a.name = x.name
 30  group by a.pid,
 31           x.name
 32  order by a.pid;

       PID NAME START_DATE END_DATE
---------- ---- ---------- ----------
       123 xyz  01/01/2020 07/30/2020
       234 pqr  04/30/2020 07/01/2020

SQL>

Comment: I am Trying to get `start date` from min ID (ID=1) and `end date` from max ID (ID=3)
Comment: OK, but why? Dates are in ascending order anyway, why do you need to involve IDs?
Comment: my requirement is get start date from first record of PID and End Date from last PID, so I can recognize first and and last record with the help of `ID`. If ID is min means first record and ID is max then last record
Comment: Aha, OK, I understand. I wrote a new query and edited my answer. Have a look, please.
Comment: thank you! this is what i was looking for...! Thank you so much for your time and help:)


@font-your-face don't work when 'Aggregate and compress CSS files' is enabled

Question: I added font using @font-your-face module and everything works just fine except when 'Aggregate and compress CSS files' is enabled. When I enable css aggregation and compression, whole website use some default font instead imported font in @font-your-face.
Does anyone have problem like this? Some suggestions how to resolve this?
Comment: This question appears to be off-topic because it is a bugreport for @font-your-face. You asked here, you got your answer, but are module maintainers notified? Have you made sure they know there is an issue? Seems not, so other people will still use this module with bug. Please don't divide bugfixing efforts - bugs belong to issue queue, because that's a way to make bugfixes available to as many people as possible, as fast as possible.
Comment: Try [AdvAgg](http://drupal.org/project/advagg/)
Comment: this is probably not bug, I'm using exactly the same version of @font-your-face on many other websites and there is not any problem like this...
Comment: I tried AdvAgg but without success...
Answer: After your compress the CSS using Aggregate option in Drupal, viewing the source code you'll find that there is an syntax error for @font-face.
Check for your syntax, there would be a break-age in that while aggregation.
Comment: Yes, you are right, I've checked it and found the issue in the same. Thanks for the solution it worked like charm!
Comment: I can't find any syntax error...
Comment: OK, remove everything except from CSS file except @font-face and then try aggregating the CSS and JS. Let me know if at that point your font-face works! Also, can you please share your CSS code here? If its too large then paste it somewhere on pastebin and then provide us the URL.
Comment: my CSS is on http://pastebin.com/wevqn0uw


Why are most microphones XLR and not USB?

Question: Wouldn't it be easier for the end users if all microphones were USB? Then why are most of them using XLR?
Comment: @Tim OP is asking us why the standard is XLR, not telling us to change it. For a non professional consumer, USB seems to be much more convenient and easier, so the question makes a lot of sense from that perspective. And again, downvotes for a perfectly fine question. This SE has severe issues with votes.
Comment: Millions of p.a. systems and other amps have only XLR sockets. (For various good reasons). It's worked that way for years - and years to come. If it ain't broke...
Comment: @foreyez has been around a long time and knows perfectly well that many of his questions are mischievously ingenuous.  He doesn't need your protection!
Comment: @Lyd same thing happens on stackoverflow. sometimes people downvote because the answer is "no". I don't take it personally. I appreciate your nice comments though!
Comment: @LaurencePayne I wrote this question right before I bought an xlr mic + audio interface. I was at a music store and all their mics were xlr so I was wondering. I never wanted an audio interface. I was always against it for years cause I thought that I could just record via usb so I never saw the point. so I asked this question to get "motivation" to buy one. I was recently having a lot of issues of random background static noise recording with usb so that's why I broke down and got it.
Comment: Yup.  A USB mic IS an 'audio interface', abeit a rudimentary one with only one, fixed input.   No reason the type should be particularly prone to static though.
Answer: Simple answer: because microphones are analog and USB is digital.
The only way you can make a "USB microphone" is to build an analog-to-digital converter into it. Of course you can buy the electronic components to do that with garbage sound quality for a few dollars, and for some applications (e.g. headsets with microphones) that is fine, because audio quality doesn't matter. For some Bluetooth wireless audio systems, the frequency bandwidth is no better than a 70-year-old telephone.
You can't power a standard design of mike that uses the standard 48 volt "phantom power" over a 5 volt USB cable either, except by adding yet more interface components.
Not to mention the fact that the maximum length of a USB cable is 5 meters which is completely inadequate for many recording situations. Professional audio recording often uses 100 meter cables in a large venue.
If you want professional results you use the right tools for the job, and a USB microphone is unlikely to be that tool.
Answer: A USB microphone is essentially a microphone, preamp, and audio interface in one. They're convenient when you're recording or streaming with a single microphone that can be placed within a short distance of the computer (the specification for USB has a maximum cable length of 5 meters). But they become almost unusable outside of that situation.
A live sound setup usually involves multiple microphones, perhaps run a very long way, and then plugged into a mixer, with signal routed to potentially many places. USB microphones have no use here.
A professional recording setup also usually involves multiple microphones. It's not impossible to use multiple USB microphones simultaneously, but it's a major headache, not the least of which is the additional strain on the computer to connect to multiple audio devices. And then there's also the issue of the maximum USB cable length.
Answer: No, for a few reasons.
1) USB isn't as transient and XLR isn't. What happens each time USB is upgraded?... buy new mics? The only major change to XLR was the introduction of 1986 phantom power in 1986 - gave mikes power without batteries ... the power supplied along cable.)
2) High-end mics are expensive, and sometimes older (pre-digital), better mics are sought out. The  studio that can spend $9k on a paired set of Neumann U-87's won't have a cost issue with a $1000 audio interface.
https://reverb.com/p/neumann-u-87-stereo-pair?gclid=Cj0KCQjwr-_tBRCMARIsAN413WTGenip_vGnZePkWYFbA9dRAnxa279Poo5Oe0BeT5zTi8KaVdH83ywaAp5UEALw_wcB&hfid=23213957&merchant_id=130263676&utm_campaign=6481936488&utm_medium=cpc&utm_source=google
Capitol Studios in Hollywood still has their #1 microphone, Neumann U47, $10k value, is still the featured microphone available to use.

3) USB has no fidelity advantages. (Mics could just as well be Ethernet or Bluetooth or USB Wireless.)
Answer: It might be more convenient for the casual computer user who just wants to record a podcast with a single mic.  And that market is catered for.  But that isn't what 'all microphones' are used for.
Also, latency.  The audio interface in a USB mic is a pretty basic one.  It won't have a low-latency ASIO driver like your Focusrite has.
Answer: Microphones with digital rather than analog interfaces work with a certain sampling rate and latency.  When working with more than a single signal source, sampling rates and latencies have to be synchronized.  D/A converters with reliable sample synchronization are way outside of the price league of what you can sensibly build into a microphone, and USB does not provide mechanisms for such synchronization: it would have to be done externally.
A typical drummer alone warrants using at least 4 microphones of at least 2 different types.


Annotations syntax

Question: Hello I was just wondering about the hints syntax.
PhpStorm automatically resolves parameters with:
@param ConfigFactoryInterface $config

But every ressources I find are using the full path:
@param \Drupal\Core\Config\ConfigFactoryInterface $config

How come?
Thanks you,
Mathias
Answer: Preface: annotations are something different, what you're talking about are called DocBlocks.

PhpStorm automatically resolves parameters

Not in my experience; if you're using the namespace at the top of that file
use Drupal\Core\Config\ConfigFactoryInterface;

then yes, just like in the rest of your PHP code in the same file, you don't need to use the fully qualified namespace when referring to that class.
Without that use statement at the top of the file, PhpStorm won't be able to resolve the class (without the differentiator of namespace, how would it distinguish between two identically named classes?). At that point you'll probably see a squiggly line under the class in the docblock, informing you that it couldn't be found.
Answer: According to drupal coding standard, you should write class full path in your phpdoc.
In phpstorm : File >> settings >> Editor >> Code style >> PHP >> PHPDoc tab, check "use fully-qualified class names" :

Annotations syntax


Combining data with differing dependent variables

Question: Suppose we have two feature matrices, $X_1$ and $X_2$, with response variables $Y_1$ and $Y_2.$ Where $X_1$ and $X_2$ have the same feature columns, but distinct observations. Furthermore, $Y_1$ and $Y_2$ are continuous responses measured on different scales (i.e. the underlying distribution of $Y_1$ is different than the underlying distribution of $Y_2$). Suppose there exists a function $f_Y$ such that $Y_1 \approx f_Y(Y_2)$.
Can we combine the datasets $(X_1, Y_1)$ and $(X_2, Y_2)$ to increase the number of observations we have for regression?
For example, for the mappings
$$
    \begin{matrix}
    X_1 & \underset{(1)}{\rightarrow} & Y_1 \\
     &  & \downarrow\tiny(Y) \\
    X_2 & \underset{(2)}{\rightarrow} & Y_2 \\
    \end{matrix}
$$
One could use $\underset{(1)}{\rightarrow}$ and $\underset{(2)}{\rightarrow}$ to learn $\downarrow\tiny(Y)$ and then regress using transformed $Y_2$ values to get:
$$
    \left(\begin{matrix}
    X_1 \\
    X_2 \\
    \end{matrix}\right) \rightarrow
    \left(\begin{matrix}
    Y_1 \\
    f_Y(Y_2) \\
    \end{matrix}\right).
$$
As an example of this problem in R, say we have the simulated data:
x1 = matrix(rnorm(500), nrow = 50)
x2 = matrix(rnorm(600), nrow = 60)
b1 = matrix(c(1,2,3, rep(0,7)), ncol = 1)
b2 = 2*(b1)^2
y1 = x1 %*% b1 + rnorm(50)
y2 = x2 %*% b2 + rnorm(60)

We can build simple linear regressions lm(y1~x1) and lm(y2~x2) to learn b1 and b2, but suppose we can learn a more powerful predictor if we combine the datasets.
How do we combine these data?
Comment: Maybe write another equation of Y1 = f(Y2) and then use SUR?
Comment: You haven't any information at all that could be used to estimate the mapping of dependent variables.  To get some, you will need to make some assumptions; that is, *create an explicit model* of the responses.  This is not a matter of combining data.
Comment: @whuber do you think we could learn something from the crossed predictions $X2 \underset{(1)}{\rightarrow}$ and $X1 \underset{(2)}{\rightarrow}$?
Comment: Yes, you might--but it is hard to see how you could improve either prediction using data from the other one without postulating some model about how they might be related.
Comment: @whuber I see, so it's probably best to scale the response variables in a reasonable fashion, say percent rank, as opposed to trying to learn the "true" mapping.
Answer: The introduction to this paper by Bastani gives some good references for solving this type of problem.

Multitask learning combines data from multiple related predictive tasks to train similar predictive models for each task. It does this by using a shared representation across tasks (Caruana 1997). Such representations typically include variable selection (i.e., enforce the same feature support for all tasks in linear or logistic regression, Jalali et al. 2010, Meier et al. 2008), kernel choice (i.e., use the same kernel for all tasks in kernel regression, Caruana 1997), or intermediate neural net representations (i.e., use the same weights for intermediate layers for all tasks in deep learning, Collobert and Weston 2008). Transfer learning specifically focuses on learning a single new task by transferring knowledge from a related task that has already been learned (see Pan et al. 2010 for a survey).


A particle moves along a curve so that its velocity is given by $v(t)= t^2 +1t −12$

Question: A particle moves along a curve so that its velocity (in meters per second) is given by
$$v(t)= t^2 +1t −12$$
$(a)$ Find the displacement over the time interval $[0,4]$
$(b)$ Find the distance over the time interval $[0,4]$
$(c)$ Find the average speed over the time interval
$[0,4]$
$(d)$ Find the avrage velocity over the time interval
$[0,4]$
I don't know how to do the last three, but for $(a)$, I used the antiderivative, and found the answer to be $-56/3$.
Could someone help with the process for the last three?
Comment: Umm, $v(0)=-12,$ I'm not sure how you get it is always positive. It is negative on $[0,3).$ @RaadShaikh
Comment: Average speed is total distance/total time. Average velocity is total displacement/total time. For (b), note that in this time interval, the velocity is always positive, so there's no 'turning around' that you need to worry about, and the displacement is equal to the distance.
Comment: Woops, yes, I did a dumb-dumb. Thanks and sorry
Answer: For b: The difference between distance and displacement is that when calculating distance, you account for moving in the negative direction, while displacement only takes the initial and final placement into account.
For example, if I walk forward 10 feet, then walk back 5 feet, my displacement is 5 feet, but my total distance is 15 feet.
This means we count every step as a positive velocity, or we take the absolute value of the velocity. Therefore: to calculate distance over a time interval [a,b], we take the integral of |v(t)|dt from a to b.
To take the integral of the absolute value of the function, first factor the function and find where the function is negative on the interval using the zeros. Then, you can split the integral at that zero, and multiply the interval where the function is negative by -1 to make it positive.
For c: Speed is the absolute value of velocity. Therefore, the average speed over [0,4] is 1/4 * the integral from 0 to 4 of |v(t)|dt. You can use your answer in part b to calculate this quickly.
For d: Same process as c, except without the absolute value.
Comment: thanks! for b)344/3 c)344/12 d)-14/3
Comment: oops, 79/3 and 79/12


older project loads on port 3000 despite i have deleted that project

Question: I have a problem since yesterday. I had a react project running on port 3000 (that project was run via Yarn)
I have deleted the project's folder as well as yarn, and since that when I try to run another react project, the server tries to run my deleted project and because it is not there so I got an error from Chrome that something went wrong while displaying the page.

I ran this command in order to terminate the process that occupied the port:
netstat  -ano  |  findstr  <Port Number>
taskkill  /F  /PID  <Process Id>
I even changed the port to another port but got exactly the same error from chrome.

I have no other solution to fix it. How can I fix the problem? :)
Comment: Well that cant really be simply answered. Try commenting out every function of your app and just display something like a 'Hello World' - if it works, you know something is wrong with your app (if not there must be another problem on your machine). Then you can either go on by continuing to activate feature by feature to see what causes it, or you use the developer tools to anaylze your app like described here: https://developers.google.com/web/tools/chrome-devtools/memory-problems/
Comment: I dont think this has to do with your previous react project. The error itself says "out of memory", so there might be a problem with a memory leak or something in your current project?
Comment: Thanks for your response. How can I solve the memory leak problem?
Answer: Steps to solve.

Run this code netstat -a -o -n

You should get some active connections.
Example

Search for the key word 3000. Example

Locate the one with local address 127.0.0.1:3000 that has it's state as ESTABLISHED. Example

Copy the PID and then enter this code taskkill /F /PID ENTER_THE_PID_NUMBER_HERE

Then you should get this response: Response


How to connect a socket with android using wifi direct

Question: I am trying to connect to a socket from the client to the server using wifi direct so I have this code on the server:
 ServerSocket serverSocket = new ServerSocket(2009);
 Socket client = serverSocket.accept();

and I have this code on the client
final WifiP2pDevice peer = wifiP2pDeviceList.get("aMacAddress");
          WifiP2pConfig config = new WifiP2pConfig();
                            config.deviceAddress=peer.deviceAddress;
                            mManager.connect(mChannel,config,new WifiP2pManager.ActionListener() {
                                @Override
                                public void onSuccess() {
                                    mManager.requestGroupInfo(mChannel,new WifiP2pManager.GroupInfoListener() {
                                        @Override
                                        public void onGroupInfoAvailable(WifiP2pGroup group) {

                                            try {
                                                Socket socket = new Socket();

                                                int port = 2009;

                                                int timeout = 5000;
                                                socket.bind(null);

                                                socket.connect((new InetSocketAddress(peer.deviceAddress, port)), SOCKET_TIMEOUT); // Error here
                                        }
                                            catch (IOException e){

                                                e.printStackTrace();
                                            }

Can I directly use the MAC address or what is my other solution ?
Comment: The MAC address of which device?
Answer: Socket communication needs InetAddress instead of deviceAddress string.
socket.connect((new InetSocketAddress(address, port)), SOCKET_TIMEOUT);

You can get the groupOwnerAddress (you can get only this IP address from WIFIP2P), after connection.
mManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() {
    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
        InetAddress address = wifiP2pInfo.groupOwnerAddress;
        //socket communication
    }
});

All devices can get this address. Send a message to this address, and groupOwner can get your IP, from the socket.


How to host multiple websites as sub domains on IIS?

Question: I'm trying to host two websites in IIS
https ://one.invalid.domain (port 44301) and
https ://two.invalid.domain (port 44302)
I have tried to add port and host name binding.
I did ipconfig /flashdns
However I am not able to navigate to the website from the browser. But if I put port number such as https ://one.domain.com:44301 then the browser loads the page,
How do I configure it so I don't have to put the port number in the browser.
There is just one public IP and A name records pointing to it.
Answer: If you don't specify the port number in the browser then the browser silently assumes port 443 for the HTTPS protocol. This means you need to setup the IIS binding on port 443 as well.
If you want to host multiple websites on the same port then make sure you include the host header in the binding and enable SNI (supported on IIS 8 and above).