Erro de saída - Linguagem C

Question: Boa tarde,
Atualmente estudando Linguagem C e me deparo com uma situação que tem travado no andamento dos estudos,fiz uma estrutura que recebe cadastro e endereço. O compilador não acusa erros, porém quando roda se comporta de forma estranha não permitindo receber todos os dados, a saída esperada em cada linha deveria ser:
Nome->
Idade->
Rua->
Numero->
Onde cada linha aponta para o dado a ser preenchido após digitar e dar enter.O erro ocorre após informar idade:
Nome-> Jeferson
Idade-> 35
Rua-> Numero->
Na mesma linha de Rua-> logo em seguida aparece Numero->,tentei colocar o "\n" , mas ele pula também direto para Numero->.
Segue a baixo o código, e agradeço qualquer ajuda oferecida.
#include<stdio.h>
#include<stdlib.h>

struct endereco{
char rua[50];
int numero;
};
struct cadastro{
char nome[50];
int idade;
struct endereco ender;
};
int main(int argc, char const *argv[])
{
struct cadastro c;
//Lê do teclado uma string e armazena no campo nome
printf("Nome-> ");
gets(c.nome);

//Lê do teclado um valor inteiro e armazena no campo idade
printf("Idade-> ");
scanf("%d",&c.idade);

//Lê do teclado uma string
//e armazena no campo rua da variavel ender
printf("Rua-> \n ");
gets(c.ender.rua);

//Lê do teclado um valor inteiro
//e armazena no campo numero da variavel ender
printf("Numero-> ");
scanf("%d",&c.ender.numero);

system("pause");
return 0;
}

Comment: O seu erro é a saída sem quebra de linha?
Comment: É por causa do `gets`, q ñ purga de stdin o caractere de quebra d linha
Comment: Tambéḿ tentei o fgets(), aconteceu a mesma coisa...
Comment: Tenta usar `getline`
Answer: O problema tem a ver com o intercalar de gets e scanf, e no caso o gets está a ler apenas a quebra de linha que ficou da leitura da c.idade deixando o texto por ler, que é apanhado pelas leituras seguintes.
No entanto, antes de começar quero deixar aqui a mensagem dada pelo compilador, que é relevante:

main.c|18|warning: the `gets' function is dangerous and should not be used.

A função gets é perigosa e não deve ser usada! Para além disso é dificil de por a funcionar com outros tipos de leitura como o scanf. A alternativa mais segura seria passar para fgets, mas também pode resolver com scanf se utilizar o formatador apropriado.
Leitura com scanf
Para fazer a leitura com scanf até ao final da linha pode utilizar "%[^\n]", ou especificar o tamanho com "%50[^\n]".
Com isto as suas leituras ficariam assim:
printf("Nome-> ");
scanf("%50[^\n]",c.nome); //ler ate ao fim da linha

printf("Idade-> ");
scanf("%d",&c.idade);

printf("Rua-> ");
scanf(" %50[^\n]",c.ender.rua);
//     ^-----este espaço consome a quebra de linha da leitura anterior

printf("Numero-> ");
scanf("%d",&c.ender.numero);

Veja este exemplo a funcionar no ideone
Leitura com fgets
Para o fgets é preciso um pouco mais de tratamento, pois a quebra de linha é lida e armazenada na variável. Isto depois causa um efeito estranho de "Enters" a mais quando vai mostrar os seus valores.
A leitura é feita com:
fgets(string, tamanho, stdin);

A quebra de linha que ficou a mais é removida através strcspn que lhe dá a posição onde ela está ou o tamanho da string se não existir:
string[strcspn(string, "\n")] = 0;

Aplicando ao seu código ficaria assim:
printf("Nome-> ");
fgets(c.nome, 50, stdin); //leitura com fgets
c.nome[strcspn(c.nome, "\n")] = 0; //remoção do \n

printf("Idade-> ");
scanf("%d",&c.idade);

printf("Rua-> ");
fgetc(stdin); //ler a quebra de linha da leitura anterior
fgets(c.ender.rua, 50, stdin); //leitura com fgets
c.ender.rua[strcspn(c.ender.rua, "\n")] = 0; //remoção do \n

printf("Numero-> ");
scanf("%d",&c.ender.numero);

Veja este exemplo também no Ideone
Dcoumentação das funções utilizadas:

fgets
fgetc
scanf
strcspn
Comment: muitíssimo obrigado pela "aula", foi o suficiente para me fazer trocar de material de estudo, pelo jeito não é nem um pouco esclarecedor.
Obrigado pelos apontamentos.
Answer: Realmente oque estava complicando era a instrução gets, recomendo ler a explicação do colega abaixo, mas de qualquer forma aqui esta uma alternativa para seu código sem muitas alterações.
#include<stdio.h>
#include<stdlib.h>

struct endereco{
    char* rua[50];
    int numero;
};
typedef struct cadastro{
    char nome[50];
    int idade;
    struct endereco ender;
}cadastro;
int main(int argc, char const *argv[])
{
    cadastro c;
    //Lê do teclado uma string e armazena no campo nome
    printf("Nome-> ");
    scanf("%s", &c.nome);

    //Lê do teclado um valor inteiro e armazena no campo idade
    printf("Idade-> ");
    scanf("%d",&c.idade);

    //Lê do teclado uma string
    //e armazena no campo rua da variavel ender

    printf("Rua-> ");
    scanf("%s", &c.ender.rua);

    //Lê do teclado um valor inteiro
    //e armazena no campo numero da variavel ender
    printf("Numero-> ");
    scanf("%d",&c.ender.numero);
/*
    printf("%s", c.nome);
    printf("\n%d", c.idade);
    printf("\n%s", c.ender.rua);
    printf("\n%d\n", c.ender.numero);
*/
    system("pause");
    return 0;
}

Comment: Obrigado pelos apontamentos.

Erro de saída - Linguagem C


How to prove Legendre Polynomials' recurrence relation without using explicit formula?

Question: Assume there is an inner product on linear space $V = \{ \text{polynormials}\}$:
$$\langle f, g\rangle = \int_{-1}^1 w(t) f(t)g(t) dt$$ with $w(t) \ge 0$ and not identically zero.
Then we can construct general Legendre Polynomials with coefficient of highest degree = 1
$$p_0(x) = 1$$
$$p_i(x) = x^i - \sum_{j=0}^{i-1}\frac{\langle x^i, p_j\rangle}{\langle p_j, p_j\rangle} p_j$$
These are orthogonal basis for $V$.
Only by these conditions, how to prove there exist $a_i$ and $b_i$ such that
$$x p_{i-1}(x) = p_i(x) + a_i p_{i-1}(x) + b_i p_{i-2}(x)$$
similiar to recurrence relation of Legendre Polynomials.
I know for Legendre Polynomials, we use generating function to prove these relations. How to prove these for generic weight?
My attempt:
$$p_i(x) = x^i - \sum_{j=0}^{i-1}c^i_j p_j$$
with $c^i_j = \frac{\langle x^i, p_j\rangle}{\langle p_j, p_j\rangle}$
$$x p_{i-1}(x) = x^i - \sum_{j=0}^{i-2}c^{i-1}_j x p_j$$
$$ x p_{i-1} - p_i = \sum_{j=0}^{i-1}c^i_j p_j - \sum_{j=0}^{i-2}c^{i-1}_j (p_{j+1} + a_{j+1}p_j + b_{j+1} p_{j-1})$$
From coefficients of $p_{i-1}$ and $p_{i-2}$, we can get $a_i$ and $b_i$ formula. However, I cannot show coefficients of $p_j$ with $j < i - 2$ will cancel each other.
Answer: The following is an adapted translation of Wikipedia.fr, Suite_de_polynômes_orthogonaux#Relation_de_récurrence.
Let us prove that
$$p_{n+1}=(x+b_n)p_n-c_np_{n-1}$$
where
$$b_n=k_{n+1}-
k_n,\qquad c_n=\frac{h_n}{h_{n-1}},$$
$k_j,h_j$ being given by
$$p_j(x)=x^j+k_jx^{j-1}+\cdots,\quad h_j=\langle p_j,p_j \rangle.$$
(By convention, $c_0=p_{-1}=k_0=0.$)
The polynomial
$(x+b_n)p_n–p_{n+1}$ has a degree $<n$ hence may be written $\sum_{j=0}^{n-1}\mu_{n,j}p_j,$
with
$h_j\mu_{n,j}=\langle (x+b_n)p_n-p_{n+1},p_j\rangle=\langle xp_n,p_j\rangle$
(since for $j<n,$ $p_j$ is orthogonal to $p_n$ and to $p_{n+1}$).
Moreover,
$\langle xp_n,p_j\rangle=\langle p_n,xp_j\rangle.$

For $j<n-1,$ this inner product is $0$ because $\deg(x p_j)<n.$
For $j=n-1,$ it is equal to $h_n$ because (reasoning like previously) $x p_{n-1}–p_n$ has a degree $<n.$

We may conclude:
$(x+b_n)p_n-p_{n+1}= c_np_{n-1},$
where $c_n=\mu_{n,n-1}=\frac{h_n}{h_{n-1}}.$


Programmatically check an ag-grid checkbox

Question: I'm using browser automation software to run automated UI tests.  Our front end site uses Vue and ag-grid.  My browser automation software essentially allows us to use typical javascript/jquery selectors to interact w/ the UI automatically.
I'm trying to get our browser automation software to check boxes in an ag-grid checkbox, inside an ag-grid.

I am not a Vue developer, so I was trying the typical things I'd do.  Things like:
$('.ag-selection-checkbox').click();

But nothing I do actually clicks and selects to box.  Any advice would be greatly appreciated.
UPDATE For those in my situation.  I used the ag API like so:
document.querySelector('#myGrid').__vue__
   .gridOptions.api.forEachNode((row,index) => {
       document.querySelector('#myGrid').__vue__.
           gridOptions.api.getRowNode(row.id).selectThisNode(true);
       }
)

Answer: Try using the class that is directly associated with the checkbox, in this case it would be the class applied to the input element: ag-input-field-input ag-checkbox-input.
You can get the checkbox of the first row like this:
const checkbox = document.querySelector('.ag-center-cols-viewport .ag-row .ag-checkbox-input');
checkbox.click();

Please see this example showcasing a row selection via the DOM based on the button click.
Comment: Thank you!  I had to eventually use this instead, but I think it's because of the above instead, but I think it's because I'm loading from the server, and this would have worked otherwise.
Comment: No worries :) Glad you solved it.
The class .ag-selection-checkbox I think is the culprit here, if you inspect the DOM, you can see that has a margin of 12px. Perhaps the click event was focused on the margin and not the checkbox, hence using the .ag-checkbox-input ensured that the checkbox was directly selected.


C3 symmetry, chirality and polytopes

Question: Is there some analogy for the phenomenon of chirality related to enantiomorph polyhedrons, but where the family of enantiomorphs is more than two polyhedra, in three or more dimensions, and related through C3 symmetry instead of a mirror image ?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Not really. The existence of chirality comes abstractly from the fact that the orthogonal group $O(n)$ has exactly two connected components separated by the sign of the determinant, namely the rotations (determinant $1$) and the reflections (determinant $-1$). This means that if you take a shape in $\mathbb{R}^n$ and apply every element of $O(n)$ to it you generically get two disconnected families of shapes, each of which is the reflection of the other. If two shapes are related by a rotation then you can just move one of them until it exactly overlaps the other but you generally can't do that with a reflection.
So the $C_2$ is not something we impose, it's already there. Even if you want to consider more general linear transformations, $GL_n(\mathbb{R})$ also has exactly two connected components which are also separated by the sign of the determinant ("orientation-preserving" vs. "orientation-reversing"). I think the same phenomenon persists even if we go all the way up to the homeomorphism group $\text{Homeo}(\mathbb{R}^n)$ but I'm not sure.
Comment: Considering the short exact sequence $$SO(n)\hookrightarrow O(n)\overset{\det}\twoheadrightarrow C_2$$ I would guess that the OP wants something like $$G\hookrightarrow O(n)\twoheadrightarrow C_3$$ and a polyhedron whose symmetry group is a subgroup of $G$.
Comment: @mr_e_man: that's what I'm saying, there isn't such a thing. Any (continuous) homomorphism from $O(n)$ to a discrete group factors through $C_2$.
Comment: What about discontinuous homomorphisms?
Comment: Okay, suppose there's a homomorphism $h:O(n)\to C_3$. Any reflection $f\in O(n)$ has $f^2=1$, so $h(f)^2=1$ in $C_3$, which implies $h(f)=1$. Since anything in $O(n)$ is a composition of reflections, $h(f)=1$ for all $f$.
Answer: There is a gradual deformation of an icosahedron where the enantiomorph deformation on faces is C3 (and C5 on vertices and C2 on edges):

It is used to explain $Au_{60}$. Could the bond distribution in a chiral $C_{60}$ buckminsterfullerene be similar? Eventually but there are also chiral truncated pseudo tetrahedrons where the truncation area lacks mirror planes which might explain point symmetrical chirality. Such an arrangement can also be made from making four similar chiral selections of faces in an icosahedron. In flatted form:

"more than two polyhedra"? A polyhedral collection can of course be cut or joined further, like from the image above. I think the question would benefit by specifying cases that don't qualify as answers, if you mean so.

C3 symmetry, chirality and polytopes


Linux IP Forwarding for OpenVPN - correct firewall setup?

Question: I have OpenVPN running on a Linux machine. The VPN server has a public IP address (x.x.x.x) and the VPN clients are assigned addresses on the "tun" device in 10.8.0.0\24. I have an IPTables rule to NAT masquerade 10.8.0.0\24 onto the public IP address.
To get the VPN server running, I had to enable IP forwarding (so I set net.ipv4.conf.default.forwarding=1).
... In other words, it's exactly what the OpenVPN tutorial says to do, with no fancy tricks.
This all works, but I'm worried about the enabling forwarding part. I think the machine will now forward packets from any IP address to any IP address, which doesn't seem suitable. Since it has a publicly accessible IP, this is particularly bad.
Are there any firewall rule suggestions to restrict the unwanted forwarding behaviour? I think any answer will be one or more IPTables rules in the FORWARD chain, but this is where I've got stuck.
thanks!
Answer: If you use these rules for forwarding table, you should be fine.
<code>-A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -s 10.8.0.0/24 -j ACCEPT
-A FORWARD -j REJECT
</code>
You can put the rules in file /etc/sysconfig/iptables and restart firewall. For command line trial first do
<code> iptables -F
</code>
to remove the default rejection of forwarding traffic and add 'iptables ' before each of the above three rules.
Comment: Quick question: when using `/24` shouldn't we specify 3 octets? Something like `10.8.8.0/24`? Tx
Answer: Here's a subset of what I've got set up on my openvpn gateway:
<code>iptables -A FORWARD -i tun0 -o tun0 -j ACCEPT # vpn to vpn
iptables -A FORWARD -i tun0 -o eth0 -j ACCEPT # vpn to ethernet
iptables -A FORWARD -i eth0 -o tun0 -j ACCEPT # ethernet to vpn
</code>
Note that this is just a subset; the rest of the rule do standard NAT things.
Comment: I think this wont restrict unwanted forwarding behavior and connection from public IP address can be initiated towards towards hosts behind VPN. The machine with public IP address would have been configured with routing to send replies to internal machines. Now if someone sends packets to public interface with destination as intranet IP packets can go till hosts behind VPN tunnel. If this VPN tunnel is also default route for hosts so that they can send packets to Internet directly then even a connection can be established from outside to inside. Please review rules once.
Comment: Since you already have such setup it should not be that hard to test whether my suspicion is correct or not.


Core-Data complex countForFetchRequest

Question: Suppose i have a one to many relationship between two model entities Entity One and Entity Many, and Entity One has a name field,

Entity One (1) --- (m) Entity Many

I want to check if an Entity One exist with name equal to "one" and has associated Entity Many records. Can i perform this check using countForFetchRequest: method? How? I'm not very good very predicates.
Answer: Ended up doing this, and seems to be working:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = [NSEntityDescription entityForName:@"EntityA" inManagedObjectContext:context];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"name == %@ AND relationshipRecords.@count != 0", aName];

NSError *error = nil;
NSUInteger numberOfRecords = [context countForFetchRequest:fetchRequest error:&error];

[fetchRequest release];

Core-Data complex countForFetchRequest


Question on basic hypothesis testing

Question: I have a question about hypothesis testing.
How can I test a hypothesis like the following for example:
People prefer chicken to beef.
And for example, the data that I have is that I've asked from 1000 people "do they prefer beef or do they prefer chicken?" 80% said chicken, and 5% said beef and 15% indifferent.
In general, how can I test some hypothesis like that, without putting a limit on it (like more than 60% of the people prefer chicken to beef)?
Answer: "People prefer chicken to beef" is not quite precise, so we need to 'unpack' the concept a bit:
"The proportion of people who prefer chicken to beef is larger than the proportion of people who prefer beef to chicken"
If that's what you really mean, that's something we can work with.
You also have a sample which -- if it's a random sample from the population of interest -- yields a set of counts. Here's an example using your numbers:
<code>  Prefer                    Prefer  |
  Chicken    Indifferent    Beef    |   Total
                                    |
    800         150          50     |   1000
</code>
The statistical question then is: if there's no preference of chicken to beef in the population of interest, could we observe such a sample outcome by chance?
The obvious model here is a multinomial model. We could condition on the people who express a preference (so there's an implied but uncontroversial "among those who express a preference" inserted into our hypotheses), yielding the relevant subtable:
<code>  Prefer       Prefer  |   Total with
  Chicken      Beef    |   a preference
                       |
    800         50     |    850
</code>
This is now a straight binomial proportions test.
The original (bolded) research hypothesis in your question was framed as a one sided hypothesis (the two sided hypothesis would be "there's a preference for one or the other - they're not equally preferred").
However, you also need to ask yourself whether you really want to conduct the test using a one-sided hypothesis test or whether it's better to conduct a two-sided test and deal with the original one-sided hypothesis in the conclusion.
Since that's a different issue to the central one here (and addressed in other questions on site), I'll leave the issue aside for now -- and simply assume you do want a one-tailed test. Different authors present one-tailed tests somewhat differently but in this case because of the clean phrasing in your statement, I think the development is straightforward.
The null and alternative hypothesis in words is:
$H_0: \text{The proportion of people who prefer chicken to beef is not higher}\\ \qquad\text{than the proportion of people who prefer beef to chicken}$
$H_1: \text{The proportion of people who prefer chicken to beef is higher}\\
\qquad\text{than the proportion of people who prefer beef to chicken}$
and in terms of population parameters:
$H_0: \pi_C \leq \pi_B$
$H_1: \pi_C > \pi_B$
where $\pi_C$ and $\pi_B$ are the population proportions (among those expressing a preference) who prefer chicken and beef respectively.
But since we're conditioning on those expressing a preference (only considering two outcomes now), this is equivalent to:
$H_0: \pi_C \leq 0.5$
$H_1: \pi_C > 0.5$
And now this is a standard one-tailed binomial proportion test.
(Alternatively we could keep the original trinomial and formulate the hypothesis as a contrast. It would yield the same result.)
The sample size is such that we could just do a Z-test, but I'll go ahead and do it as a binomial test.
Under the null, the highest probability of observing a result as or more extreme (in the direction of the alternative) will be given by the equality case, so we work out our p-value by taking $\pi_C=0.5$. Let $X_C$ be the number in a sample of 850 (who express a preference) preferring chicken.
Then under that "best case", we have $X_C\sim\text{binomial}(850,0.5)$. The p-value is then $P(X_C\geq 800)$ (an astronomically tiny number which will lead you to reject the null hypothesis at any of the usual significance level choices; $p\approx 1.3 \times 10^{-256}$ -- however, the actual number is effectively meaningless, since even tiny deviations from the assumptions - which will certainly be the case (at least) - can change it by several orders of magnitude).
[Alternatively if you want to work strictly with a rejection rule, the 5% critical value for $X_C$ is $450$, and the 1% critical value is $460$, and you reject $H_0$ if you equal or exceed your critical value.]
If you did it using a Z-test, then with continuity correction your Z-statistic is $29.12$.
Comment: Thank you for the time and the help, really appreciate it.
Comment: @Glen_b Thanks! I was stuck reviewing a paper with a cohort of patients... Same group tried two drugs -> interview -> which drug was preferred by each patient -> two proportions (drug A vs drug B) -> Is drug B better than A. I think it fits well...
Answer: In hypothesis testing, you come up with...a hypothesis! So if the statement was

People prefer chicken to beef

Maybe you try to quantify it by saying, "hmmm, I think over 50% of people prefer chicken to beef". It doesn't actually matter if people say they are indifferent, after all you walk into the experiment with no prior knowledge.
In this situation you would perform a (binomial) hypothesis test which says $H_0:$ people are indifferent to chicken, whilst $H_1$: people would prefer chicken (one sided test). In this scenario you will have to have some kind of number that you're testing against.
Or maybe, the survey to be location orientated and we have change our hypothesis to:

More people in country A list their favourite food as chicken than any other country.

In this case we can have a hypothesis which does not have some notion of a predetermined number/proportion, (this can probably be framed as a chi-squared test).
So in general, asking or framing the question/hypothesis in the appropriate way can lead to different approaches and hence difference assumptions. There is no "one way" to do this, and learning to ask the best question is often the hardest part of statistics.
Comment: Thank you for the time and the help, really appreciate it.

Question on basic hypothesis testing


Explicit prior versus implicit prior

Question: I am reading a paper where they talk about keeping a prior explicit as opposed to an implicit prior. To be honest, I have never came across the terms explicit/implicit in context of priors and I was wondering if these are technical terms associated with prior distributions. Does an explicit prior simply means when the prior distribution is specified? How does one get an implicit prior from the problem specification?
Comment: I have never heard that too and it's hard to guess without the context. However, when you choose a prior on $\theta$, then you implicitly assign a prior on $\theta^2$ (for example). Perhaps this is the what the author means ?
Comment: I would have thought working with the likelihood function as if it were a probability distribution (up to proportionalty) was the equivalent of an implicit uniform prior.
Answer: In my understanding the probability density function is explicitly given for an explicit prior. If this is not possible, the prior can be still implicitly defined which I would then call an implicit prior. Consider estimation of a parameter $\theta$. Assume that because of some circumstances the prior distribution is not specified for $\theta$ directly but for a functional transform of $\theta$, i.e. $f(\theta)$ follows distribution $X$. In order to get back to the distribution of $\theta$ it would be necessary to find the inverse transform $f^{-1}$. Since this is sometimes computationally infeasible, it is not done. Yet, one can still use this implicitly defined distribution for $\theta$ to do i.e. parameter estimation.
Comment: Thanks for the answer guys. Unfortunately, the writing is very vague and does not say much other than keeping the prior explicit, which is confusing and frustrating.
Answer: I like to think of an implicit distribution as an algorithm able to produce samples. An explicit distribution on the other hand has an analytical expression for its density.

Explicit prior versus implicit prior


Finding distance using orthogonal projection

Question: I am not quite sure, I can use the orthogonal projection right. My question is, if there is a simple way, how to find a distance between two skew lines when given only a 2 points and directives of those lines, using the orthogonal projection.
For example: If I take two skew lines $p$ and $q$, where $p$ is determined by the point $[6, 3, - 3]$ and directive $(- 3, 2, 4)$, and the line $q$ is determined by the point $[- 4 - 4, 12]$ and directive $(- 3, 3, 8)$, what is their distance?
Comment: Note that although the asker of the "duplicate" question was expecting a different kind of answer than you are expecting, [this answer to that question](http://math.stackexchange.com/a/57969/139123) is based on ideas of orthogonal projection. Was it a useful answer?
Comment: what does it mean for lines to be oblique? i have heard of skew lines in $R^3$ meaning nonplanar lines that don't meet. like some of the edges of a cube. are you using oblique lines in the sense of skew lines?
Comment: possible duplicate of [distance between lines in the space (with calculus)](http://math.stackexchange.com/questions/56588/distance-between-lines-in-the-space-with-calculus)
Comment: Nice Q/A, but I need help specifically with othogonal projection ;)
Comment: [Here is another answer](http://math.stackexchange.com/a/1182349/139123) which is (implicitly) based on ideas of orthogonal projection. It describes a vector that performs an orthogonal projection of one of the oblique lines onto a plane containing the second line and parallel to both lines.
Answer: I will give you two solutions one involving orthogonal projection and one solving a linear equation - you may choose which one you like better.
Orthogonal Projection:
One point ($\vec{p}_1$) and the two directives define a plane if they are linearily independent i.e. $ \vec{v}_1\times a=\vec{v}_2$ can only be solved by $a=0$, otherwise they define a line. Anyways the shortest distance is the orthogonal projection of the other point ($\vec{p}_2$) to this plane/line. In the following I will assume that they are linearily independent as you said the lines were oblique.
For this one first needs to orthogonalize the two directives:
$$
\vec{v}_3 = \vec{v}_1-\dfrac{\vec{v}_2\left(\vec{v}_1\cdot\vec{v}_2\right)}{\vec{v}_2^2}
$$
Then the distance can then be calculated by the orthogonal projection to the plane:
$$
\vec{a} = \vec{p}_1-\vec{p}_2 \\
\vec{d} = \vec{a} - \dfrac{\vec{v}_3\left(\vec{v}_3\cdot\vec{a}\right)}{\vec{v}_3^2} - \dfrac{\vec{v}_2\left(\vec{a}\cdot\vec{v}_2\right)}{\vec{v}_2^2}\\
\text{distance}= \lvert\lvert \vec{d} \rvert\rvert
$$
Linear Equation
$x$ and $y$ are variables, the two lines are defined by the point $\vec{p}_1$ and the directive $\vec{v}_1$ and $\vec{p}_2$ and $\vec{v}_2$ respectively.
Therefore the distance between to points is:
$$
\lvert\lvert\left(\vec{p}_1+x\,\vec{v}_1\right) - \left(\vec{p}_2+y\,\vec{v}_2\right)\rvert\rvert
$$
The minimum distance is therefore:
$$
\mathrm{min}{\left(\lvert\lvert\left(\vec{p}_1+x\,\vec{v}_1\right) - \left(\vec{p}_2+y\,\vec{v}_2\right)\rvert\rvert\right)}
$$
The minimum in the absolute value is the same as the square root of the absolute squared:
$$
\sqrt{\mathrm{min}{\left(\left(\left(\vec{p}_1+x\,\vec{v}_1\right) - \left(\vec{p}_2+y\,\vec{v}_2\right)\right)^2\right)}}
$$
To find the minimum we can set the first derivative to 0.
Comment: I have doubts about the orthogonal projection. The vectors $\dfrac{\vec{v}_3\left(\vec{v}_3\cdot\vec{v}_2\right)}{\vec{v}_3^2}$ and $\dfrac{\vec{v}_2\left(\vec{v}_3\cdot\vec{v}_2\right)}{\vec{v}_2^2}$ are independent of the choice of $p_1$ and $p_2$, so depending on which values of $p_1$ or $p_2$ were chosen along the two lines, without changing the lines we can change $\vec a$ and therefore also change $\vec d$.
Comment: @DavidK Oh yes you are right I have an error there, I'll fix it.
Answer: Let your first line be defined by $p_0 + t \vec v$ and the second line
by $q_0 + t \vec w$.
Consider the vector $\vec v_\perp = \vec v \times \vec w$.
The vector $\vec v_\perp$ is perpendicular to both
$\vec v$ and $\vec w$.
Now consider a vector $\vec u$ defined by $p_0 + \vec u = q_0$
(that is, take the line segment from $p_0$ to $q_0$ and make a vector $u$ of the same
length as that segment parallel to that segment).
Project $\vec u$ orthogonally onto $\vec v_\perp$.
Call the resulting vector $\vec u_\perp$.
Confirm that the image of the line $p$ under a translation by the vector $\vec u_\perp$
is a line intersecting the line $q$.
Confirm that the translation is an orthogonal projection
onto the plane containing $q$ and the image of $p$.
What does that tell you about the distance between the closest points
on the lines $p$ and $q$?


Solving an equation for an ellipse

Question: It's some years since I did math and I can't, for the life of me remember how to solve equations.
I am trying to find the centre of an ellipse from the radii and $2$ points on the ellipse using : $$\frac{(x_A-C_x)^2}{a^2} + \frac{(y_A-C_y)^2}{b^2} = 1$$
where $(x_A,y_A)=A$ and $a$ and $b$ are the semi-major axis and the semi-minor axis. $(C_x,C_y)$ are the coordinates of the centre.
If $x_B$ and $y_B$ are the coordinates of another point on the ellipse, then I get the following: $$\frac{(x_A-C_x)^2}{a^2} + \frac{(y_A-C_y)^2}{b^2} = \frac{(x_B-C_x)^2}{a^2} + \frac{(y_B-C_y)^2}{b^2}$$
Which I can expand:
$b*b*(xa*xa+cx*cx-2*xa*cx)+a*a(ya*ya+cy*cy-2*ya*cy)=b*b*(xb*xb+cx*cx-2*xb*cx)+a*a(yb*yb+cy*cy-2*yb*cy)$
and from there:
$b*b*xa*xa+b*b*cx*cx-2*b*b*xa*cx+a*a*ya*ya+a*a*cy*cy-2*a*a*ya*cy=b*b*xb*xb+b*b*cx*cx-2*b*b*xb*cx+a*a*yb*yb+a*a*cy*cy-2*a*a*yb*cy$
And then
$b*b*xa*xa-2*b*b*xa*cx+a*a*ya*ya-2*a*a*ya*cy=b*b*xb*xb-2*b*b*xb*cx+a*a*yb*yb-2*a*a*yb*cy$
Now what?
I'm damned if I can remember what to do next.
[Edit]
I've got down to this:
$(a*a*ya*ya-2*a*a*ya*cy-b*b*xb*xb-a*a*yb*yb+2*a*a*yb*cy)/2*b*b*(xa-xb)=cx$, but as far as I can see, I still need to resolve cy before I can work out cx.[/Edit]
PS. This question was mistakenly posted on the Programming section: https://stackoverflow.com/questions/43468181/solving-equations-for-an-ellipse?
Comment: I have already answeared your question on stackoverflow :)
http://stackoverflow.com/questions/43468181/solving-equations-for-an-ellipse/43473049#43473049
Comment: Hi Arkdiusz, I saw your answer: thanks. I need to find the point cx,cy. I can plug in the values for the two points on the ellipse and can also use the semi- major and minor axis, but I don't have the centre point. I'm trying to use the equation to find it.
Comment: *Please* format your equations using MathJax. They're nigh unreadable right now.
Comment: Two points aren't enough to determine a unique center point, as you're discovering. Unless the center is on the chord joining those points, there are two possibilities.
Comment: Mathjax? Ok, I'll look into it. Thanks. I should have mentioned that I'm writing a little python converter to convert SVG files into DXF, so I have the Large Arc flag and the sweep flag to dictate which side of the chord the centre falls.
Answer: Note that centre $C=(X,Y)$ is either one of the intersection for
$$
\left \{
  \begin{array}{ccccc}
    \dfrac{(X-x_A)^2}{a^2}+\dfrac{(Y-y_A)^2}{b^2} & = & 1 & \cdots \cdots & (1) \\
    \dfrac{(X-x_B)^2}{a^2}+\dfrac{(Y-y_B)^2}{b^2} & = & 1 & \cdots \cdots & (2)
  \end{array}
\right.$$
The point $C$ also lies on the conjugate diameter w.r.t. chord $AB$ namely
$$
\frac{(X-x_A)^2}{a^2}+\frac{(Y-y_A)^2}{b^2}=
\frac{(X-x_B)^2}{a^2}+\frac{(Y-y_B)^2}{b^2}$$
$$
\frac{2(x_A-x_B)X}{a^2}+\frac{2(y_A-y_B)Y}{b^2}=
\frac{x_A^2-x_B^2}{a^2}+\frac{y_A^2-y_B^2}{b^2}$$
In principle, it is solvable
$$X=\frac{x_A+x_B}{2} \pm \frac{a(y_A-y_B)}{2b}
\sqrt{\frac{4}{\dfrac{(x_A-x_B)^2}{a^2}+\dfrac{(y_A-y_B)^2}{b^2}}-1}$$
$$Y=\frac{y_A+y_B}{2} \mp \frac{b(x_A-x_B)}{2a}
\sqrt{\frac{4}{\dfrac{(x_A-x_B)^2}{a^2}+\dfrac{(y_A-y_B)^2}{b^2}}-1}$$

Solving an equation for an ellipse


Xamarin.Android: Access to the path ******** is denied

Question: I'm getting the above error when trying to print a file with my Xamarin app through call to a web service method. When same method is called from browser it prints without problem. Write and read permissions for external storage are granted. The file I want to print is located in a shared network folder. What could be the reason that folder access is denied only for the app?
That's the part of the code where filepath is used:
<code>public static string SubstituteFileContent(string filePath, string substituteValues)
        {
            var rdr = new StreamReader(filePath);
            var fileContent = rdr.ReadToEnd();
            //textBoxSource.Text = fileContent;
            var index = fileContent.IndexOf("^XA");
            fileContent = fileContent.Remove(0, index);
            var start = fileContent.IndexOf("^DFE");
            var end = fileContent.IndexOf(".ZPL^");
            fileContent = fileContent.Remove(start, end - start + 4);

            rdr.Close();

            var substitutedContent = SubstituteFields(fileContent, substituteValues);
            return substitutedContent;
        }
</code>
Comment: please post the relevant code
Comment: It may be that you still don't have read/write permission because Depending on the version of Android you have to specifically prompt the user for it to be allowed. [Here's](https://stackoverflow.com/questions/46911486/xamarin-system-unauthorizedaccessexception-access-to-the-path-is-denied/46933816#46933816) an example of that.
Comment: `a shared network folder` ? Are you uploading it from your Android to the web server? Trying to access a shared network folder (SMB-based?) from Android? etc.. ?
Comment: @Nick this happens on API 19
Comment: @SushiHangover I'm trying to read a file from a shared folder on the server. No idea if SMB-based or not...
Comment: So, you can't access the path which is on your server from your app? I don't think it is your problem.
Comment: Yeah, if you're not copying the file to your device to then print it sounds like you don't have permission from the network folder
Comment: @Nick, but I gave full control to all users under folder sharing options. Moreover, when I copy the files on same machine where android emulator is running they print without issues.
Answer: Ok, solved it myself. I had to explicitly share the network folder with "Everyone" under Share settings.


What's the meaning of $C^1(R)$?

Question: Given the function $f(x)=(\max(-x,0))^2$ Show if $f(x)$ is in $C^1(R)$. I don't get what does $C^1(R)$.
Comment: [See this wikipedia page](https://en.wikipedia.org/wiki/Smoothness#Differentiability_classes)
Comment: Maybe it stands for $C^1$($\mathbb{R}$) and it's a typing error...
Comment: Why did you not ask this to the person that gave you this problem? :-|
Comment: @MarianoSuárez-Alvarez you're right I will send an email to Terry Tao, hope he answer me XD
Comment: Well, it is usually a good idea for people asking questions tot tell us where they got their problem from. Can you imagine why?
Comment: Not really, sorry...
Answer: It means "continuously differentiable on $\mathbb{R}$." $f \in C^1(\mathbb{R})$ if $f$ is differentiable, and its derivative is continuous (on $\mathbb{R}$).
See this link for more details, and the hierarchy of differentiability classes.
Answer: $C^1(\mathbb{R})$ consists of the functions which are one time continuously differentiable.
Answer: It means that $f$ is continuous, differentiable, and its derivative is continuous.
Comment: @ClementC. my mistake

What's the meaning of $C^1(R)$?


How can I get the source code for Komodo Edit?

Question: How do I get the source code for Komodo Edit?
Komodo Edit is an open source text editor. I want to
inspect and learn from the source code for Komodo Edit.
In the download location,
http://downloads.activestate.com/Komodo/releases/5.1.4/, I
can only see binaries. How do I get the full source code?
Comment: It seems that the URLs have been changed  [for browsing online](http://svn.openkomodo.com/openkomodo)
Answer: The source for Komodo Edit is available on the Open Komodo Project's Website.
Answer: Apparently the only way is to get the source code through Subversion. From the Open Komodo Development README:

The Open Komodo sources are kept in a Subversion repository
  hosted at the openkomodo.com site. Read-only public access
  is available via:
svn co http://svn.openkomodo.com/repos/openkomodo/trunk openkomodo

For Windows, using TortoiseSVN (see
Practical guide to subversion on Windows with TortoiseSVN
for installation, setup and use):
Right click on <folder to receive the source code>/SVN
Checkout/set "URL of repository" to
"http://svn.openkomodo.com/repos/openkomodo/trunk"
The result was 15164 files in 6120 folders, 138 MB transferred, 348 MB on disk.
Including 93 C files, 138 C++ files and 971 Python files.
The source code files can also be browsed online.
Answer: Start your search with Komodo Community.


service httpd status shows internal server error

Question: I have a dedicated server. No PHP files were running when i use my website so i tried looking into the apache and used service https status to check apache status and this is what i am getting
service httpd status
Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, root@mps-vm1 and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fipsmod_bwlimited/1.4 Server at localhost Port 80

Can someone please tell me what should i do?
Comment: You should do as it says and look in the error log.
Comment: I'm confused: this error is displayed by the browser, while "service httpd status" should be typed into a terminal (and the answer should be one of "httpd is running (pid xxxx)" or "httpd not running")
Comment: no this message is displayed in the SSH terminal(putty)
Comment: IMHO your configuration is messed up. Start examinig "/etc/init.d/httpd", to discover why the error 500 comes up asking the pid of httpd (that is what service httpd status does)
Comment: @AndrewQ, Start by looking the the logs - they should contain valuable information about the error, it's location etc
Answer: service httpd status will be retrieving Apache's /server-status/ page (provided by mod_status). It will be doing this via apachectl status (or apache2ctl if you're on Debian or Ubuntu)
This likely means that your configuration is not loadable. You can use apachectl configtest to test a configuration before reloading/restarting the webserver.
The error message, by default, will also be found in /var/log/httpd/error_log (or ssl_error_log, depending on how the request came in.) Those should be your first point of call in a situation such as this.
Comment: It could be a file called error.log (or something completely different too).
Answer: So I solved the issue by reinstalling APACHE. That seemed to be the only way. Maybe when I was making changes to the installation files, I did something terribly wrong and messed up Apache.


Views tagging question (bulk update tags)

Question: We have a few taxonomies and don't want users to spend time tagging content. Ideally, we would like to have a view where we could tag content without opening each node.
A module exists for exactly this purpose in D6 but nothing in D7.
http://drupal.org/files/images/views_tagger_screenshot.png
Is there any other way to accomplish this??
Answer: Found a solution, via the editablefields module!! Here is a quote about it (from the module's project page):

... allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).


Bug in Unity 2D gravity?

Question: I'm writing a script in C# in Unity that essentially functions as a switch to turn gravity on or off for a 2D Rigidbody. When the game starts, gravity should be 0 for the Rigidbody. Then when the user taps the space bar, gravity is supposed to increase to 3 (which is does). Then, however, when the player collides with a gameObject labeled 'InvisGoal', the player should teleport to another location and then gravity should be 0 again. However, the player always falls after coming in contact with InvisGoal and teleporting and I can't figure out why. This is my first project in C# so sorry for any obvious errors.. The script is here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BallLaunch : MonoBehaviour {

private Rigidbody2D myRigidBody;
public GameObject Ball;

// Use this for initialization
void Start ()
{
    myRigidBody = GetComponent<Rigidbody2D> ();
    GetComponent<Rigidbody2D>().gravityScale = 0f;
}

// Update is called once per frame
void Update ()
{
    if (Input.GetButtonDown ("Jump"))
    {
        GetComponent<Rigidbody2D> ().gravityScale = 3f;
    }
}
void OnTriggerEnter2D(Collider2D other){

    if (other.tag == "InvisGoal")
    {
        Ball.gameObject.GetComponent<Rigidbody2D>().gravityScale = 0f;
        transform.position = new Vector3 (0.61f, 1.18f, 0f);
        return;
    }
 }
}

Comment: should it just be `GetComponent()` instead of `Ball.gameObject.GetComponent()` when you set to 0?
Comment: Yeah I noticed that after I posted it... unfortunately I think it only simplified the code
Answer: Ball.gameObject.GetComponent<Rigidbody2D>().gravityScale = 0f;

This is likely what is causing the problem.
It sounds like the RigidBody2D you are referencing to in this line is not the same as the one you retrieved beforehand with GetComponent().
GetComponent returns the component of the GameObject you call it from. Therefore in the code I mentioned above,
Ball.gameObject.GetComponent<RigidBody2D>()

and
GetComponent<RigidBody2D>()

would give you an two different RigidBody2D component if the field Ball does not refer to the same GameObject your BallLaunch script is attached to.
[
Supposing BallLaunch script is attached to the Ball you want to set the gravity of (As picture above)
Simply change:
Ball.gameObject.GetComponent<Rigidbody2D>().gravityScale = 0f;

To
GetComponent<Rigidbody2D>().gravityScale = 0f;

Also, since you already referenced your RigidBody2D in your Start method to the field myRigidBody, you can replace all subsequent GetComponent with myRigidBody.
GetComponent<Rigidbody2D>().gravityScale = 0f;

To
myRigidBody.gravityScale = 0f;

Comment: In addition, there may be some built up momentum (gravity is an acceleration factor! If they're already moving, they'll continue to move!) Might not be important to the asker, or it might be. Worth mentioning.

Bug in Unity 2D gravity?


Sendmail problem

Question: I am trying to get my server to be able to send email from PHP. Currently it is using send mail, but whenever I try to send mail to a gmail address I get this sort of response:
<code>--o54Mqd5s008981.1275691959/ServerName
Content-Type: message/delivery-status

Reporting-MTA: dns; ServerName
Received-From-MTA: DNS; localhost
Arrival-Date: Fri, 4 Jun 2010 22:52:38 GMT

Final-Recipient: RFC822; firstname.lastname@example.com
Action: failed
Status: 5.7.1
Remote-MTA: DNS; gmail-smtp-in.l.google.com
Diagnostic-Code: SMTP; 550-5.7.1 [xxx.xxx.xxx.xxx] The IP you're using to send mail is not authorized
Last-Attempt-Date: Fri, 4 Jun 2010 22:52:39 GMT
</code>
How can I set this up to relay through a google account that I own? Is sendmail the best thing to use, or should I switch to Postfix or something? This is on an Ubuntu Server 9.10
Answer: Your server address may be listed as a dynamic address, which should never be sending email into the Internet  directly.  The standards provide of a layer of trust and require static addresses with correct rDNS configuration.  Almost all the spam I get comes from dynamic addresses.
You should setup your server to send outgoing emails via your ISPs SMTP server.  You can use Gmail as your relay, but you will need to enable SMTP services on your Gmail account.  Then you will need to configure Postfix to authenticate when connection to Gmail.
Answer: If I remember correctly, you can't relay through gmail, even using your own credentials.

Sendmail problem


SAN array storage not accessible

Question: Good morning peeps. I'm fairly new sys admin world and am working in my first systems engineer position (jr) and inherited a dual drive SAN array last week which was entirely unused without being touched since 2007. FUN!
Given our need of storage for backup data as BackupExec won't backup our Notes databases, I'm writing a powershell script to do a VSS copy of the databases on a set scheduled to backup them up to this array.
I've updated the firmware to the latest version, formatted it making a RAID50, and have 2 IP's for the internal web interface. However, while accessible via the web interface, the storage behind it is not accessible. I set an option to allow FTP connections but that isn't working either as an error message is received:
<code>An error occurred open the folder on the FTP server. Make sure you have permission to access this folder.

Details: 501 Directory non existent or syntax error
</code>
The controller is an MSA2012fc HP StorageWorks. Is there something I'm missing? I've tried multiple accounts with the FTP site and get the same error each time. This happened before the firmware update as well.
What needs to be installed so that I can manage what's been written to the SAN?
Comment: Gotcha. Putting the version information in your question would be beneficial to anyone else looking at this question.
Comment: `Given our need of storage for backup data as BackupExec won't backup our Notes databases` - Backup Exec most certainly can backup Notes databases. What is the issue you're having?
Comment: Backup Exec 14 does not support Notes 9.0.1. I worked with Veritas for 11 days of troubleshooting before they told me "We don't support this configuration"

http://planetlotus.org/profiles/daniel-nashed_140930

http://blog.nashcom.de/nashcomblog.nsf/dx/symantec-backup-exec-end-of-life.htm
Answer: The MSA 2012fc is fibre-channel, the 2012i was the iSCSI version and the 2012sa was the direct-connect SAS version.
If it is the fc version (it'll say on the controllers themselves) then you'll have to connect them via fibre-channel (or FCoE but that's way out of your picture I suggest) - and FC isn't the least-complex thing in the world, though I'm happy to help if you have specific questions.
Sam's right though that R5/50 is dead, has been for half a decade at least, please avoid for your data-health and sanity - 1/10 and 6/60 are the only games in town.

Edit - thanks for all your information so far, here's what you need to do.
Add a dual-port FC HBA PCIe card to your server - there are other manufacturers but I like Emulex (QLogic are very good I just don't have as much experience with them). There are different speeds you can get but as your 2012fc only runs at 4Gbps then there's no point spending money on 8 or 16Gbps card, but you may find that's all you can get - Emulex cards based on their '1105' chipset are very reliable. So you stuff that in the server, you then download and install the latest drivers and utilities from the manufacturer's site.
You also need to add in the 'multipath' feature in server 2012R2, this is important or your server will think the one LUN you've shared is actually two, one down each line!
Oh yes you need to cable it up - go from server FC port 1 to SAN controller 1 port 1 and server FC port 2 to SAN controller 2 port 1 - use 'OM3 LC-LC' fibres, that's all you need.
You then need to configure the array, once you're into the GUI you need to create an array of the disks using RAID 1/0 or 6/60, then create a LUN (logical drive) of whatever size you like, then you share that out onto the controller ports mentioned above as a particular LUN number (start with 1).
You can then go onto the server and go into the FC utilities and 'scan' the FC HBA, you should hopefully see the WWNs (world-wide-names, like MAC addresses for FC kit) listed, one controller per server port, and hopefully the WWN for the shared LUN. If this is the case you just go into windows disk manager and that LUN should be seen as a disk, so partition and format it - job done!
One caveat here, if you ever want to share a LUN between more than one client you have to jump through a lot more hoops, your setup is about as simple as it gets (hopefully).
Hope it goes well, let me know how you get on ok.
Comment: Yes, it is the fc. There were 6' fiber wires connecting them despite being 1' apart and we just replaced them on Friday.

Is there a program available to manage the storage array? Know why the error above is being returned after entering known good credentials? Same error here: An error occurred open the folder on the FTP server. Make sure you have permission to access this folder.

Details: 501 Directory non existent or syntax error
Comment: Thanks for confirming it's the FC model - I have to say that given your comparative lack of experience you could easily be in for a very long haul with this one. First of all do you know how you clients are going to talk to this SAN? Do they have FC HBAs? Do you need an FC switch between clients and array? If so do you know how to configure the switch? Will clients have to access the same LUN/s? If so what file system and locking manager will you use to allow this to work? You need to answer these basic questions before worrying about array configuration issues.
Comment: Oh and I may be wrong but have you connected the array to an ethernet switch? If so please disconnect it, unless it's a few very specific switches in the world that won't work.
Comment: Long haul is fine. :D This SAN isn't used for anything so it is just sitting there. The only client to be talking to the SAN will be our backup server via TCP/IP or via mapping as a network drive. Whichever is easiest for the powershell scripting.

We HAVE a fiber switch but won't be using it for that.

The controller is connected to ethernet, the individual storage devices are not.
Comment: Ok so it'll go [backup client]---IP over ethernet---[backup server]---FC---[SAN array] right? If so then you've saved yourself 98% of the crap. So you have an FC HBA in your backup server? What OS is your backup server running? Oh and the data will never be available via FTP, that's not how this works at all, you can only get at the disks via FC, the FTP is there for say management firmware updates and logs. btw I'm in the UK so knocking off soon, available tomorrow though.
Comment: Right. No FC HBA in backup server. What software do I need to get to the disks via FC? OS on backup server is 2012 R2.
Comment: Looks like our backup server (running 2012 R2) isn't capable of handling such old software, with the FC software released is for 2008 R2 and Server 2003. Awesome.

Already made the array and have the LUN with WWN ready.

Thank you for the info. I'll be installing the software this week hopefully to get the disk partition and formatted ready for use.
Comment: Sorry, bit confused, which FC software is only for 2008/3? if you get any current FC HBA PCIe card it'll come with 2012R2-capable drivers - I'm confused.
Comment: The FC software from the manufacturer, HPE.

    http://h20564.www2.hpe.com/hpsc/swd/public/readIndex?sp4ts.oid=3687120&swLangOid=8&swEnvOid=4064
Comment: Ah right - that's only the SAN array controller software - you don't NEED that, it just lets you bring them up to the latest version is all - and it should run just fine anyway, you only run it once so worst comes to worst spin up a VM or run it on a laptop if you have to - in fact if I recall correctly you can download that and then apply the actual firmware file inside via the CLI/SSH if you're really having problems. Either way it's just a controller patch/patching-mechanism and you don't need it as such.
Comment: I did get the firmware updated already via GUI of the FC controller.

Thanks!
Answer: How is the SAN interfaced into the network, iSCSI?
Also, while it's still blank, I would reformat the RAID/s as RAID 10 or at least RAID 6. RAID 50 is just as problem prone as RAID 5, you'd be wise to avoid it!
Comment: Just looked into it. I'll redo them as RAID10. Thanks.

I believe it is iSCSI.
Comment: Agreed with SamAndrew, RAID 10 is always better. About SAN, just ping all the paths, the connections to the SAN can be the bottleneck.
Comment: What do you mean by "RAID 50 is just as problem prone as RAID 5"?  Sure, if you don't know how to lay out, align, and partition a RAID 5 LUN, and don't size the RAID segment/stripe size correctly, you'll get crappy performance.
Comment: Yes, it is iSCSI.

The speed of read/write isn't an issue as of right now, but instead the management capacity of the SAN is my concern. Is there a management interface which needs to also be installed?
Comment: @AndrewHenle, it's not about performance, RAID 50 has all the same fault-tolerance shortcomings as RAID 5: https://community.spiceworks.com/topic/587968-why-not-raid-5

SAN array storage not accessible


Differentiation under integral sign proof question (special case)

Question: The theorem in my textbook says:

Suppose $f(s,x)$ and $f'_s(s,x)$ is continuous on $\alpha < s < \beta$, $a \leq x \leq b$. Then the function
  $$
 \varphi(s) = \int_a^b f(s,x)\,dx
$$
  is differentiable on $\alpha < s < \beta$ and
  $$
\frac{d}{ds}\int_a^b f(s,x) \, dx = \int_a^b \frac{\partial}{\partial s}f(s,x)\, dx
$$

The proof starts with the definition of the derivative, i.e.
$$
\frac{\varphi(s+h) - \varphi(s)}{h} = \int_a^b \frac{f(s+h,x) - f(s,x)}{h}\,dx
$$
Then they use the mean value theorem on the interval $[s, s+h]$, i.e. $f(s+h,x) - f(s,x) =
f'_s(s+\theta h, x)h$, for $\theta \in [0,1]$ and then
\begin{align*}
\int_a^b \frac{f(s+h,x) - f(s,x)}{h}\,dx =& \int_a^b f'_s(s+\theta h,x) \, dx
\\
=& \int_a^b f'_s(s,x) \, dx + \int_a^b f'_s(s+\theta h,x) - f'_x(s,x) \, dx
\end{align*}
so it suffices to show that the second integral, say $\rho(h) \to 0$ when
$h \to 0$. (And the proof continues with that...)
Why are we allowed to use MVT here? The interval of $s$ is open, but MVT demands that the function is continuous on a closed interval and differentiable on an open interval.
Suggest edits if needed.
Answer: For any $s \in (\alpha,\beta)$ and for $h$ small enough, the interval $[s,s+h]$ is strictly contained in $(\alpha,\beta)$. Therefore by the hypotheses, $f$ is continuous on $[s,s+h]$ and differentiable on $(s,s+h)$.
Comment: When you say this, I feel quite slow. Thanks.


Animar activity de forma circular

Question: Eu gostaria de fazer um efeito de transição ao chamar uma activity.
Quando a imagem, nesse caso uma circular, for pressionada a activity crescesse a partir de um circulo com mesmo raio da imagem até preencher toda a tela.
Answer: Pesquise sobre overridePendingTransition  tem uma questão aqui ensinando como fazer com modo circular (que acredito ser o que você gostaria de fazer).

Animar activity de forma circular


Is there a limit on the number of events that a track and field athlete may enter in one meet?

Question: At the high school level, my local district limited an athlete to four events in one track and field meet. Famous sprinters like Carl Lewis have won four gold medals in one meet and other track and field athletes often compete in multiple related events (shotput and discus, sprints and relays, sprints and various jumps, etc.).
Without considering scheduling and logistical conflicts, and the physical limitations of the athlete, is there rule that limits on the number of track and field events that an athlete may enter in one meet, assuming that this athlete had the requisite skill to compete in each entered event?
Comment: Logistically, though (once you've got around the physical toll of multiple events), there's only one swimming pool so it's a lot easier to do multiple events, with athletics unless you stick to just the track, the field events can (and often do) run simultaneously.
Comment: Don't think that there will be any, as swimmers usually take part in more than 4 events anyway.
Comment: True, but I believe that track and field is governed by a different group than the swimmers (the International Association of Athletics Federations).
Comment: oh, I had Olympics in mind.
Comment: @rest_day, even in the Olympics I've only heard of a max of 4 events - wasn't sure if there's some obscure rule or more practical reasons. For sure, swimmers (like Mark Spitz or Michael Phelps) enter many more events
Comment: @Unsliced, absolutely - I was wondering if there was a rule in place. Unless the event was spread out over a very long period, the logistics of having multiple qualifying heats would prevent many athletes from competing in overlapping events.
Answer: I looked through the IAAF Competition Rules [PDF]. The most relevant piece I saw was rule 142.3, Simultaneous Entries, which basically permits the referee to allow a participant to compete in the high jump or pole vault out-of-order. I didn't find anything from the IOC, but I doubt they'd impose an extra limit (especially considering the apparent lack of one in swimming). Plus, the rules are focused on preventing athletes from gaining an unfair advantage, I don't think more events are going to help an athlete gain an advantage.
There may be high-school athletic associations that limit event entries, IIRC my high school association had a limit of four, which couldn't all be the same area (Track|Field), e.g. 3 track and a field event.
Comment: Olympic sports are organized under the rules of the relevant international governing body, so you are correct that Olympic athletics competition is governed by World Athletics (formerly IAAF) rules.


Loading local project static assets from CDN with RequireJS

Question: I have a single page application with node serving up the backbone app along with all the marketing material. I would like to serve all assets (JS, html, images) from our Rackspace Cloudfiles CDN to reduce load times as gzip files will be delivered as well as reduce the load on my node server.
What is the best way to automate this?
I need would need to:

sync files after build to the CDN
reference the CDN for all static assets in production mode

I found solutions with both Grunt and Node Modules which are used in my project.
Grunt CDN
Grunt Cloud Files
Node Asset Rack
If I go with Grunt - which is my first choice,

How do I set the express application I am running on to serve from the CDN in production?
Is it better to use the asset manager for node since its serving all my assets anyway?
Comment: I'm not really sure what you are asking here. Grunt CDN explains how to setup the grunt task for your build/deploy step to replace your urls with CDN URLs, regardless of app. If the URLs for those assets are dynamically generated, then you need to manually set the URL template where appropriate.
Comment: @rdodev I mean with regards to serving assets not listed in my templates but instead served directly to requirejs
Comment: I see. well that extra layer does complicate things. I'll look into that and report back if I find anything interesting.
Answer:
How do I set the express application I am running on to serve from the CDN in production?

When you render your view you could pass it a flag to tell where to pick the assets from.
I've got an example here if you are interested. In my case I've got a flag on whether I am connected to the network or not (e.g. during a flight) to decide where to pick my JS files from:
<code><% if(isConnected) { %>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
      <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
      <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
      <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.min.js"></script>
      <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-cookies.min.js"></script>
    <% } else { %>
      <script src="/js/jquery.min.js"></script>
      <script src="/js/bootstrap.min.js"></script>
      <script src="/js/angular.min.js"></script>
      <script src="/js/angular-resource.min.js"></script>
      <script src="/js/angular-cookies.min.js"></script>
    <% } %>
</code>
https://github.com/hectorcorrea/hectorcorrea.com/blob/master/views/index.ejs#L136
In my example, the value is hard coded, but you could easily pass Express dev/prod value to the view to get the same thing done automatically.
Comment: a lot of my assets are loaded directly with requirejs - any ideas for those


How to set the price without decimals?

Question: in my store, I want to set the products price without decimals,
e.g. "$500.00" ==> "$500"
I put following codes in the template.php:
<code>function roomify_travel_commerce_currency_info_alter(&$currencies){
  $currencies['TWD']['format_callback'] = 'roomify_travel_commerce_currency_format';
}

function roomify_travel_commerce_currency_format($amount, $currency, $object = NULL, $convert = TRUE) {
  $price = number_format(commerce_currency_round(abs($amount), $currency), 0, $currency['decimal_separator'], $currency['thousands_separator']);

  $replacements = array(
    '@code_before' => $currency['code_placement'] == 'before' ? $currency['code'] : '',
    '@symbol_before' => $currency['symbol_placement'] == 'before' ? $currency['symbol'] : '',
    '@price' => $price,
    '@symbol_after' => $currency['symbol_placement'] == 'after' ? $currency['symbol'] : '',
    '@code_after' => $currency['code_placement'] == 'after' ? $currency['code'] : '',
    '@negative' => $amount < 0 ? '-' : '',
    '@symbol_spacer' => $currency['symbol_spacer'],
    '@code_spacer' => $currency['code_spacer'],
  );

    return trim(t('@code_before@code_spacer@negative@symbol_before@price@symbol_spacer@symbol_after@code_spacer@code_after', $replacements));
}
</code>
then the price became correct, but my admin page was broke!
and apache error log showed:
<code>[Thu Feb 09 07:20:41.168665 2017] [proxy_fcgi:error] [pid 25564:tid 139845024192256] [client **.**.**.**:40368] AH01071: Got error 'PHP message: PHP Fatal error:  Call to undefined function mytheme_currency_format() in /opt/bitnami/apps/drupal/htdocs/profiles/roomify/modules/contrib/commerce/commerce.module on line 641\n', referer: http://**.**.**.**/drupal/?q=admin
</code>
please tell me where I went wrong! thank you!!
Answer: Your callback function is in your theme's template.php file, which is only loaded when that theme is being used.
I'm assuming your admin backend uses a different theme, so it can't find your callback function on admin pages.
The best solution would be to move the logic into a custom module; it's not theme related functionality so best practice would be to move it there anyway, even if it wasn't causing a problem.

How to set the price without decimals?


Two games with collected statistics, how accurate is the data?

Question: Suppose one wants to test how many players still play the day after receiving the game, and two days after receiving it.
And that the results would be:
Game 1:

Total numbers of players = 120
Players playing the next day = 21,7%
Players playing two days after = 18,3%

Game 2:

Total numbers of players = 62
Players playing the next day = 16,1%
Players playing two days after = 8,1%

Is it possible to calculate how accurate the result is, particularly in game 2.
What is the +- percentage?
Could game 2 in fact be better than game 1?
Comment: If players decide to play independently of each other, the answer is [here](http://stats.stackexchange.com/questions/4756/confidence-interval-for-bernoulli-sampling).
Comment: @Scortchi The question also appears to be asking (in the final sentence) about the standard error of the difference of two such percentages
Comment: @Glen Good point: there's an answer for that [here](http://stats.stackexchange.com/questions/46847/what-is-the-standard-error-for-the-distribution-of-the-difference-in-proportions).
Answer:
Is it possible to calculate how accurate the result is, particularly in game 2. What is the +- percentage?

A common way to do this is to build a confidence interval (informally people look at this as a range of likely values even if this is not quite the right interpretation). There are many methods to do that, as detailed in the link provided by Scortchi (Confidence interval for Bernoulli sampling).

Could game 2 in fact be better than game 1?

Here, under the same assumptions (in particular that the players in each group are not the same and decide to continue to play independently of each other), you could use a $\chi^2$ test for independence. If the test allows you to reject the null hypothesis of independence, it means that the difference you observe is unlikely to have come about by chance. Since game 1 is better than game 2 in the sample, you would then conclude that it is indeed better than game 2 and, conversely, that game 2 is unlikely to be in fact better than game 1.
Even if the difference turns out not to be significant, it's still not evidence that there is no difference, let alone a difference in the other direction but that would at least mean that you cannot formally rule it out at the error level you picked. You could also compute a confidence interval for the difference (or for some other measure of the dependence like the odds ratio). Note that these methods (and others) can help you to gauge the strength of that evidence but no matter how you cut it, the data you have provide at least some evidence that game 1 is better and you can't wish that away.
Off the top of my head, I don't have any idea to use the data from both days together.


How do I programmatically create a webform from a newly created node?

Question: This is the code I am using.
function walk_handler_entity_presave(EntityInterface $entity) {
  if (method_exists($entity, 'getType') && $entity->getType() === 'walk') {
    $elements = [];

    $elements[] = [
      '#title' => 'This is a test',
      '#type' => 'textfield'
    ];

    $webform = Webform::create([
      'id' => 'walk_' . $entity->id(),
      'title' => 'Test',
      'elements' => Yaml::encode($elements),
      'settings' => Webform::getDefaultSettings()
    ]);

    $webform->save();
  }
}

Somehow, this hook will get triggered twice: once when the node is getting submitted, and another time when the webform is getting created. The result is that I'm getting an error about the Webform object not having a getType() method and this is why I'm using method_exists() in the condition.
I can't seem to find any hook that would only focus on nodes and not on webforms.
What other hook can I use to react to new nodes being created?
Answer: hook_entity_presave() is called for every entity being saved which means that, since that hook_entity_presave() implementation is saving an entity, it is being invoked twice.
Using method_exists() is generally wrong, as in PHP is generally preferable to check if the object is an instance of a class implementing an interface or a class extending another class.
In this case, it's also wrong because the code isn't supposed to run for every entity that has a getType() method, but just for nodes. (While nodes are the only Drupal core entities with that method, there could be entities implemented from third-party modules that define that method, possibly for different purposes.)
You should check the entity type as said from berramou or use hook_ENTITY_TYPE_presave() as said from No Sssweat.
Since the question is asking how to create a webform when a node is created, I would rather use hook_ENTITY_TYPE_insert() which is invoked:

Only when an entity is created, not when an entity is updated
After the entity has been saved in the storage

Using this hook has the benefit of not creating a new webform every time a node is edited. The implementation code is also simpler, as it doesn't require checking the webform is already created for that node.
Answer: If you want the hook_entity_presave() to only focus on nodes and not on webforms, you can check the entity type like in the following code.
 /**
 * Implements hook_entity_presave().
 */
function YourModule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'node') {
    // Do you webform creation code here
  }
}

Answer: hook_entity_presave() runs when any entity is inserted or saved; thus, it runs twice in your case, since you have a Node and a Webform entity being saved.
You would have to add a conditional to check the entity type as @berramou's answer suggests.
Alternatively, you could use hook_ENTITY_TYPE_presave() and target the node.
/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function MODULE_NAME_node_presave(Drupal\node\NodeInterface $node) {
  // your code goes here
}


discrete = countable and continuous = uncountable?

Question: I want to understand what a discrete random variable and a continuous one are.
Let $X: \Omega \rightarrow \mathbb{R}$ be a random variable (a function).  If $\text{Image} (X)$ is a countable set, then $X$ is a discrete random variable.
If $\text{Image} (X)$ is a uncountable set, then $X$ is a continuous random variable.  Right?
Are sets also called discrete/continuous?  Or just random variables are?  In the first case, discrete = countable and continuous = uncountable?
Comment: https://en.wikipedia.org/wiki/Image_(mathematics)
Comment: What do you mean by "lm(X)"?
Comment: Please explain or write out any abbreviations you might be using.  Although "$\mathcal{Im}$" is indeed commonplace in mathematics, it's far less common in statistics and in your case is easily confused with lower case "L" lower case "M."  BTW, "discrete" means many things, but isn't a standard characterization of a set.  It is the [finest topology](https://en.wikipedia.org/wiki/Comparison_of_topologies) that can be defined on a set, though, so sometimes through an abuse of language sets (especially subsets of topological spaces) are termed "discrete."
Answer: Say you toss a fair coin. If it is head then you wait until the first tail of a (different) fair coin tossed once per second (that is, a geometric distribution, and if it tail, then you wait for an event with an exponential distribbution (e.g., like a lightbulb failing). Then the nontrivial support set of your waiting is uncountable, but most would not characterize this as a continuous random variable.
Instead, one way of characterizing a continuous random variable is that
$$
\forall_x P(X = x) = 0
$$
(see here, for example, as well as an alternative definition in the footnote). Conversely, if there is a countable set $E$ for which
$$
\sum_{x \in E} \left[ P(X = x) \right] = 1,
$$
then it is discrete.
The above distribution, for example, would not be considered continuous or discrete - it is mixed.
Answer: Some preliminary issues: This issue is complicated slightly by the fact that random variables are only interesting up to how they behave on a set with probability measure one - or to put it another way, random variables are uninteresting on sets with probability measure zero.  For an arbitrary random variable $X: \Omega \rightarrow \mathbb{R}$ it is possible for $\text{Image}(X)$ to be uncountable, but for $X$ to still have a discrete distribution, since the uncountable part has probability measure zero.  This kind of thing complicates the discussion.
To simplify this matter, it is  common to categorise random variables by their probability measures, rather than by the image of the random variable in its functional mapping definition.  This approach is equivalent to treating random variables in equivalence classes defined by probability measure, with two different random variables (in a sense that they are different functions on the sample space) being considered equivalent if they differ only on a set with probability measure zero.

Categorising random variables by probability measure: The above explains why we caegorise random variables as "discrete" or "continuous" based on probability measure, rather than the image of their functional definition.  Even with this simplification, there is still a further complication.
The probability measure for any random variable can be written as a mixture of a continuous part and a discrete part (and in some nasty cases, a singular continuous part, which we will ignore).  For an arbitrary random variable $X: \Omega \rightarrow \mathbb{R}$ we can then write:
$$\mathbb{P}(X \in \mathcal{A}) = \alpha \int \limits_\mathcal{A} f(x) d\lambda(x) + (1-\alpha) \sum_{x \in \mathcal{A} \cap \mathcal{D}} p(x).$$
The first part is the continuous part of the measure, with density $f$ and $\lambda$ being Lebesgue measure.  The second part is the discrete part of the measure, with mass function $p$ and $\mathcal{D}$ being a countable set.  The value $0 \leqslant \alpha \leqslant 1$ is the parameter giving the mix of continuous and discrete parts.
Discrete random variables: A discrete random variables is one where the probability measure has the above form with $\alpha = 0$.  You are correct that this entails a countable set of values with probability one.  Remember that this does not mean that its image is countable; it is possible that it still has an uncountable image, but its probability measure is concentrated entirely on a countable set within that image.
Continuous random variables: A continuous random variable is one where the probability measure has the above form with $\alpha = 1$.  This necessitates an uncountable image, and it also means that the cumulative distribution function for the random variable will be continuous in the regular functional sense.
Mixture random variables: A mixture random variable is one where the probability measure has the above form with $0 < \alpha < 1$.  This necessitates an uncountable image, but it also means that the cumulative distribution function for the random variable will not be continuous in the regular functional sense.  It will have jumps at the points in the discrete part of the distribution.
Answer: It's also not about having transcendent numbers.
A variable that can take the two values 0 and pi is still discrete. It has just two levels.
It's not about infinitely many numbers in a finite interval, either.
Otherwise we would never have continuous variables, because our measurement resolution are discrete, and so are our numeric representations.
On discrete variables, the average of two values may not correspond to a real value. Say you have a binary value, less than 6 ft and over 6 ft tall, encoded as 0 and 1. If the average of two persons is 0.5, does that mean they are on average exactly 6 ft tall?
On continuous variables, it would be perfectly plausible to observe an interim value.
But even then, there is a gray area. If you consider the classic 'iris' data set. The variables are continuous. They are lengths of flower petals, so it is plausible for a flower to have any length in-between.
But for many analyses, you will get artifacts from the discrete resolution of the input data, which has 0.1 mm or so as step size. This causes problems e.g. with Single-Link clustering. But this is IMHO a different kis0nd of discreteness: the values in-between make sense, it is only our input data that has a bad resolution.


Hypergeometric distribution- problem with derivation

Question: A random variable $K$ has hypergeometric distribution with parameters $N, m, n$, with probability mass function:
$$
p_K(k)=\frac{\binom{m}{k}\binom{N-m}{n-k}}{\binom{N}{n}},\quad k\in\{\max(0,n+m-N),\ldots,\min(n,m)\}\quad,
$$
$N$ is a population size,  $m$ and $N-m$- sizes of two disjoint subsets of population (name them $A$ and $B$). The numerator  indicates the number of $n$-element subsets, which contain $k$ elements choosen from $A$, and $n-k$ elements from $B$. I know the deriviation  of this formula, however, i tried to do it in another way, and result is not correct. I would like to find out, where my reasoning fails. Suppose we firstly count a number of $n$-element sequences, in which we have on first $k$ places elements from $A$, and on the rest $n-k$ places elements of $B$. Then we divide this amount by a count of permutation to achieve figure of $n$-element subsets of population, with exactly $k$ elements from $A$ and $n-k$ elements of $B$:
$$
\frac{\underbrace{m\times(m-1)\times\ldots\times(m-k+1)}_{k\ elements}\underbrace{(N-m)\times(N-m-1)\times\ldots\times(N-m-(n-k)+1)}_{n-k\ elements}}{n!}\\=\frac{m!}{(m-k)!}\frac{(N-m)!}{(N-m-(n-k))!}\frac{1}{n!}=\frac{\binom{m}{k}k!\binom{N-m}{n-k}(n-k)!}{n!}\ne \binom{m}{k}\binom{N-m}{n-k}\quad.
$$
What is wrong with my derivation?
Answer: Your numerator $$\frac{m!}{(m-k)!}\frac{(N-m)!}{(N-m-(n-k))!}$$
is the number of $n$-element sequences, in which we have on first $k$ places elements from $A$, and on the rest $n−k$ places elements of $B$. And in which the order matters, i.e. $(a_1,a_2,a_3,b_1,b_2)$ and $(a_1,a_3,a_2,b_2,b_1)$ are distinct $k+(n-k)$-element sequences.
You can't divide by $n!$ "to achieve figure of n-element subsets of population, with exactly k elements from A and n−k elements of B", because your sequence is splitted into two distinct subsequences, and you have $k!$ permutations in the first subsequence and $(n-k)!$ permutations in the second one. To count the $n$-element subsets with exactly $k$ elements from $A$, followed by $(n-k)$ elements from $B$, you must divide by $k!(n-k)!$.
A simple example. Let's say that $n=4$ and $k=2$. A single sequence may be:
$$a_1,a_2,b_1,b_2$$
There are $n!=4!=24$ permutations, e.g.
$$a_1,a_2,b_1,b_2;\quad a_2,a_1,b_1,b_2;\quad a_1,a_2,b_2,b_1\quad a_2,a_1,b_2,b_1\tag{1}$$
but also:
$$b_1,a_2,b_2,a_1;\quad b_1,b_2,a_1,a_2;\quad etc.\tag{2}$$
In (2) you do not have $k=2$ elements of $A$ followed by $n-k=2$ elements of B, as you have in (1), and the number of permutations in (1) is just $k!(n-k)!=2\times 2=4$: the number of permutations of $k$ elements of $A$, multiplied by the number of permutations of the following $n-k$ elements of $B$.
When you divide by $k!(n-k)!$ you get the number of $n$-elements subsets where the order does not matter:
$$\frac{m!}{(m-k)!k!}\frac{(N-m)!}{(N-m-(n-k))!(n-k)!}=\binom{m}{k}\binom{N-m}{n-k}$$
But this is still the "number of favorable cases", where $k$ is fixed. To get its probability you have to divide it by the "number of all cases possibile", which is $\binom{N}{n}$.
Comment: Some problems with your answer, e.g., ${m\choose k}\ne m(m-1)\cdots (m-k+1)$.
Comment: Ops! I was a bit hasty :)
Comment: @DedekindCuts Thanks!
Comment: @Mentossinho Ok. I'll edit my answer.
Comment: Sorry: the amount of all kind of $n$-sequences is $N!/(N-n)!$ if the order matters.
Comment: @Mentossinho ... but not $n$-element subsets with $k$ elements from $A$ *followed by* $n-k$ elements from $B$.
Comment: @Sergio thank you for your time and answer! However, further i have a problem to understand, why it's wrong to divide by $n!$- an amout of permutations on "whole" sequcence. Could you clarify, why it fails, when i have "two distinct subsequences"? I think my misunderstanding is an effect of lack of knowledge about some elementary, combinatorics fact.
Comment: @Sergio so the key point here is that on starting point in this problem i'm interested in amount of sequences, which have on first $k$ places elements of A, and elements of B on the rest $n-k$. That's why we must divide by a figure of this particular class of sequences. If i would like to divide by $n!$, i should start from the amount of "all kinds" of sequences, which is $\binom{n}{k}\binom{m}{k}k!\binom{N-m}{n-k}(n-k)!$. Do i understand it correctly?
Comment: @Mentossinho The amount of "all kinds of $n$-sequences" is $\binom{N}{n}$ if the order doesn't matter, $n!$ if the order matters. Dividing by $k!(n-k)!$ is the same trick as computing "$n$-element sequences, in which we have on first $k$ places elements from $A$, and on the rest $n−k$ places elements of $B$" by $m(m-1)\dots$ [$k$ elements] times $(N-m)(N-m-1)\dots$ [$n-k$ elements].
Comment: @Sergio sorry, in my previous comment i meant all n-sequences with $k$ elements from A and $n-k$ elements from B, no matter where they are; then dividing by $n!$ give me $n$-element subsets with $k$ elements from A and $n-k$ elements from B.
Comment: @Sergio thank you for your help, i accept the solution :)
Comment: @Sergio i see it, if i am interested in particular kind of sequences, here these with first $k$ elements from A and rest from B, to achieve subsets (where order doesn't matter), i divide the amount of these sequences by the amount of their permutations ($k!(n-k)!$); but if would start from all sequences with $k$ elements from A and $n-k$ from B (the amount is $\binom{n}{k}\binom{m}{k}k!\binom{N-m}{n-k}(n-k)!$), then i should divide by its number of permutation ($n!$), to achieve amount of subsets (where order doesn't matter).


Permission Issues in Windows 10

Question: I have 2 machines, one is Windows 10 and the other is Windows 7, recently whenever I download a file on Windows 10 machine directly on my External Hard Disk and detach it from that machine and try to attach it to windows 7 machine, I have no access to any of the downloaded files it gives me access denied. I can access folders and see the files are present but cannot open them.
To solve this issue I have to manually assign permission to each files by first taking ownership of that file for "Everyone" account and then assigning "Everyone" full control.
I have tried to take the ownership of the folder but receives the error of access denied for each files when selecting the option of "Permission Inheritance for files and Sub Folder"
I have even tried to write a PowerShell to assign permission but the situation does not change it returns with an access denied error. FYI, PowerShell window is opened as Administrator by selecting Run as administrator.
Even if I run the intended application as Administrator it will still not work it will still give me Access Denied.
The only workaround I found was to perform the above actions of individual file ownership and permission assignment.
It would of great help is someone can provide a permanent solution to this issue.
BTW, The external hard drive which I use is WD drive and its with me for than 5 year now and never encounter this issue in the past.
And the files in questions are Photos, videos, documents and mp3.
Comment: When you take ownership of the folder, you should mark the option to take ownership of subfolders and files.
Comment: I have tried doing that but it still says access denied.
Answer: This is neither a PowerShell nor a programming issue, so the question would be more suitable for SuperUser.
Creating a file on removeable media on one system and then trying to access that same file on a different system will normally fail unless you took precautions to make the data accessible from other systems. That is because even though users and groups may have the same name on both systems they still have different SIDs (which is what the system actually uses to decide whether access is or isn't allowed).
To grant a user on a different system access to the file you have to take ownership and grant the user(s) on that system access.
<code>takeown /f x:\ /a /r /d y
icacls x:\ /reset /t /c
icacls x:\ /grant administrators:(oi)(ci)f username:(oi)(ci)rx
</code>
Note that adjusting ownership and permissions of a single file usually does not suffice. The user must be able to at least traverse the entire path to that file. Similarly taking ownership and adjusting permissions on a folder may not suffice unless the files in that folder inherit their permissions from the folder. If they don't you need to take ownership of the files and adjust their permissions as well.
The above 3 commands recursively take ownership of everything on drive X:, reset permissions to enable inheritance, and grant access to the Administrators group (full control) and the user "username" (read and execute).
With that said, you can prepare permissions so that files are accessible on different systems without the need to take ownership and adjusting permissions on the target system. There are a number of principals and groups that have the same well-known SID on all Windows systems, e.g.

Everyone (S-1-1-0)
Administrators (S-1-5-32-544)
Users (S-1-5-32-545)
Authenticated Users (S-1-5-11)

Granting access for instance to the group "Users" should make your data accessible across different systems.
Comment: Regarding direcrtory traversal, standard users have SeChangeNotifyPrivilege enabled by default, which bypasses traverse checking. This privilege may surprise someone who's used to Unix, which requires execute access to traverse a directory.
Comment: I thought I was quite familiar with Windows, but I wasn't aware of that. Thanks for mentioning.
Answer: Install a separate hard drive or prepare a separate partition for each operating system.
Install the operating systems. For example, if your PC has Windows 8.1, install Windows 10 onto the other hard drive or partition.
Reboot the PC. The boot menus should appear with both operating systems listed.
If both operating systems aren't listed:
Open a command line, either as an administrator from inside Windows, or by booting to a command line using the Windows installation disk and presssing Shift+F10, or by booting to Windows PE (WinPE: Create USB Bootable drive).
Add boot options for a Windows operating system.
Bcdboot D:\Windows
Reboot the PC. Now, the boot menu will show both menu options.
Comment: These are two different Computer and not partition.
Answer: Let's give permission to the file and check if that helps. Follow these steps to give permission to the drive.

Right-click on the file which you're unable to access and select Properties.
Click on the 'Security' tab and under 'Group or user names' click on 'Edit'.
Click on 'Add' and type 'everyone'.
Click on 'Check names' and then click 'OK'.
Select 'everyone' and under 'Allow' select 'Full control' and click
on 'Apply' and Click 'Ok'.

Hope this helps.

Permission Issues in Windows 10


Problem 12, chapter 1 of Walter Rudin's Functional Analysis

Question: The question is to prove that the metric , defined below, induces usual topology on R :. $d_2(x,y)=|\phi(x)-\phi(y)|$
Where $\phi(x)=\frac{x}{(1+|x|)}$ and $d_1$ is the usual metric.
The continuity of $\phi\times\phi$ and $d_1$ gives that $d_2$ is continuous when $\mathbb{R}$ is given usual metric, but I'm not able to do other way. Any help?
Comment: [Nothing new under the sun](https://math.stackexchange.com/questions/1272986/topologically-equivalent-metric/1273060#1273060) :)
Answer: As you observed, one direction follows from continuity of $\phi$. The other direction should therefore follow from continuity of the inverse function.
Observe that $\phi$, viewed as a function from $\mathbb{R}$ onto the open interval $(-1,1)$,  is invertible, and its inverse is given by: $\phi^{-1}(y)=\frac{y}{1-|y|}$. In particular, the inverse function is continuous on $(-1,1)$. As a result, if $\{x_n\}_{n=1}^{\infty}$ is a sequence in $\mathbb{R}$ converging to some $x\in\mathbb{R}$ in the $d_2$ metric, then
with $y_n=\phi(x_n)$ and $y=\phi(x)$ you have $y_n\to y$, and therefore, by continuity of the inverse, (note that $y_n,y\in (-1,1)$), we get:
$$x_n=\phi^{-1}(y_n)\to\phi^{-1}(y)=x\quad\hbox{as}\quad n\to\infty$$
hence $x_n\to x$ in the $d_1$ metric.


is there any solution to curses library problem?

Question: so I was programing a snake game with curses and it's already there but python tells me that it doesn't exist
import random
import curses

screen = curses.initscr()
sh, sw = screen.getmaxyx()
curses.curs_set(0)
window = curses.newwin(sh, sw, 0, 0)
window.keypad(1)
window.timeout(100)
snk_x = sw//4
snk_y= sh//2
snk=[[snk_y,snk_x],[snk_y,snk_x-1],[snk_y,snk_x-2]]
food = [sh//2,sw//2]

"D:\python projects\Scripts\python.exe" "D:/pythonProject/snake
game.py" Traceback (most recent call last):   File
"D:\pythonProject\snake game.py", line 2, in
import curses   File "C:\Users\yasse\AppData\Local\Programs\Python\Python310\lib\curses_init_.py",
line 13, in
from _curses import * ModuleNotFoundError: No module named '_curses'
Comment: Python's standard `curses` module doesn't support Windows.  There are replacement versions that do: `pip install windows-curses` for one.
Answer: Try entering this:
pip install windows-curses

into your terminal that should fix it


Is it inappropriate to call multiple regression analysis 'correlational'?

Question: I recently received a review back for a paper in which I referred to some previous studies as 'correlational' where they used multiple regression to analyze some population data and make biological conclusions (specifically a linear mixed effects regression). One reviewer made a very big deal about this, suggesting that I "completely mischaracterized" this work (I suspect he/she was an author) which was "far from correlational", "much more sophisticated", and provided "much stronger evidence than mere correlational methods". I suspect the reviewer was referring to the fact that multiple regression models control for other included variables. From my (current) point of view, they are all correlational, just of differing complexity and assumptions between independent and dependent relations. Our study was trying to give a more mechanistic account of the data, therefore I wanted to make a distinction between statistical and mechanistic relationships. So I used the term correlational in a very broad sense.
So my question: Is it inappropriate to describe linear regression models as 'correlational', and would you yourself do so? If not, why not?
I am familiar with the mathematical relationships between regression coefficients and the 'partial correlation coefficients' e.g. discussed here, and here. My question, rather, is about terminology and whether you folks find it too loose (in some sense) to refer to regression methodology as correlational, or if a more broad term like 'statistical' would be more appropriate in this case.
Much thanks.
Comment: Both you and the reviewer have a defensible case. The reviewer is treating the term narrowly and you are treating it very broadly. I have been on both sides of the relationship here, and a journal editor too, and advise treating this as needing clarification, not confrontation. But as you ask for specific advice: (1) I wouldn't use the term "correlational" for multiple regression; (2) I would make my point in other terms when one choice of terminology is clearly an irritant.
Comment: Thank you very much @NickCox, I appreciate the input. All is well taken :)
Answer: Correlation can be two things. Correlation is a mathematical construct on one hand, which is de facto Pearson correlation. Correlation is also a counterpart to causal on the other, meaning conditional dependence between an "exposure" and "outcome" that may be mediated by 100s of unmeasured factors. Calling work (i.e. the analyses/results of a study) "correlational" doesn't immediately suggest to me whether you mean they summarized several bivariate associations using partial correlations or whether the study was conducted from observational data.
I am strongly inclined to believe that you and the reviewer hold opposing ideas of what "correlational" means in this context. This is giving generous credit to the idea that other aspects of this communication did not denigrate anyone's research/findings.
As far as regression analyses are concerned, you can use regression models to analyze "quasiexperimental" data (or observational data) in which adjustment for confounding variables is used to infer what a hypothetically controlled (blocked/randomized) experiment would yield as a result. This leads to the distinction between correlation and causation. Only randomized controlled trials are worthy of discussing results in a causal context. Other results are not "correlational" but you may refer to findings as "associations".
The word correlation is confusing. In literature presented to a statistical audience, I am careful to avoid correlation altogether except in the context of Pearson's correlation. I would favor "empirical" or "epidemiological" or something of that ilk to refer to findings from observational studies.
Comment: I suppose it is the difference between 'mechanistic' and 'statistical' I am grappling with. What I meant in the paper was to say that previous studies found a statistical relationship, but the demonstration suggested no biological mechanism. I called this correlational in the sense that they observed a purely statistical dependency. We fitted a process-based model to the empirical data to suggest a biological mechanism, and therefore claimed that we provided a mechanism for previously correlational results. Regardless, the comments are clarifying my usage. So thanks.
Comment: @gregory_britten I guess I fell into my own trap there! It's all about avoiding words with ambiguous double entendres in mathematical statistics. "Empirical", alas, is victim of that. From the perspective of describing results, empirical is a good descriptor of *in vivo* (observational) studies whereas results from controlled experiments have *in vitro* applications. In summary, the word "correlational" should be dropped altogether. If findings are consistent with other literature and your own, then good. If the findings are inconsistent, then don't dismiss that research. Discuss it.
Comment: I'd differentiate between *empirical* & *mechanistic* models, the form of the latter being more heavily based on theory, though not necessarily implying a causal relationship from predictor to response; & between *observational* & *experimental* studies.
Comment: @Scortchi agreed, although there is a great deal of correspondence between the two distinctions: observational data, error prone and subject the infinite unmeasured mediation pathways, is carefully adjusted by measured confounders, but the results are important to interpret as "population averaged" which is why large public health data almost *necessitates* GEE (the empirical approach). On the other hand, experimental *in vitro* data are so carefully controlled, little wonder analysts favor measuring and fitting sophisticated probabilistic models for their data (the mechanistic approach).
Comment: very good points, but I raise the question: would you call the results of a designed experiment (for which there appears to be causal evidence) 'empirical'?
Comment: You're right, though it depends on the area too. When I worked for an engineering company I fitted empirical models to experimental data (response surface methodology) perhaps rather more than mechanistic models to experimental data; but I don't recall ever fitting a mechanistic model to observational data, only empirical models.
Answer: Knowing no more than what you've said, I agree with @NickCox, @AdamO, and with you for the most part. If you have discussed this "completely mischaracterized" work in further depth than you've said here, it may not be safe to assume the objection is mostly to your characterization of it as "correlational", unless the reviewer has made that really clear. His/her objections seem very emphatic, so you're right to suspect s/he is an author. Might you be able to talk to this reviewer more directly to seek consensus (or at least compromise) on how to describe the work? I suppose some review processes might rule out conferral outside the formal framework, but it seems counterproductive in this case if you can't work together with this person.
Of course, this isn't to say there's any certainty of whom you're dealing with beyond what you actually know; I only agree it seems likely, and echo the other Nick's suggestion to seek clarification from this person. It would seem to be in your mutual best interest to describe everything optimally from both perspectives. Hopefully all the initial bluster will die down as you communicate further. Sometimes people begin by making a bigger fuss than is really necessary just to ensure they get your attention and make an impression, despite the evident risk of that being a worse impression (e.g., biased, unreasonable, alarmist). It's easier for some to proceed with restraint and mutual respect once they've been reassured that the lines of communication are open and the other party is paying attention. It seems you've made the opposite first impression with what you've written, so an overblown reaction is understandable, if still unreasonable. Clarification should help greatly if s/he's willing to work with you.
Regression is indeed correlational in the broad sense, as has already been said here, but the strictest, most simplistic sense of correlational may appeal to those who have a less nuanced understanding of general linear models. The stricter usage may also appeal more to people who understand correlational analysis as a loaded term in causal research contexts, such as your problem reviewer, it seems. If your intention was to imply a weakness in causal evidence, then your usage was loaded intentionally, and some defensiveness is to be expected. You'd be right to say that multiple regression doesn't really provide more causal evidence than a bivariate correlation (the stricter sense of "correlational" that AdamO described) – it mostly makes relational evidence clearer regardless of whether these relationships are causal. Hence I doubt your reviewer is simply objecting to your characterization because the method involved multiple regression, not just bivariate correlations. Maybe the reviewer felt the original design had other, "more sophisticated" elements that provide "much stronger evidence". Maybe I give this person too much credit though; I've been led to think one should never underestimate the capacity of reviewers to overreact to issues that amount to nitpicking.
Generally, I wouldn't object to describing regression as correlational, and might have done so myself in your case initially, but given the apparent offense this has caused, I don't see any harm in backing off and rephrasing. If your intention was to imply critique of causal evidence, it would be better to state the critique clearly and delicately, not to just imply it. If your alternate phrasing of the "distinction between statistical and mechanistic relationships" captures your meaning just as well, maybe you can avoid the issue by replacing the "correlational" phrasing entirely, but again, if you can confer with your reviewer about this alternative, you'll stand a better chance of having the change received well, of course. AdamO has provided some other good alternatives, and your comment on his answer seems quite a bit clearer about the distinction you intended to make between your work and your reference. As for "empirical", I think you're encountering the same basic issue by using a single word with a variety of possible interpretations where several sentences that clarify your intention with context would be preferable.