Factorise $8wxyz+w²yz+w²xz+w²xy+x²yz+x²wz+x²wy+y²xz+y²wz+y²wx+z²xy+z²wy+z²wx+w²xyz+wx²yz+wxy²z+wxyz²+xyz+wyz+wxz+wxy=0.$

Question: I apologize for not having anything to show for an attempt. I've provided additional context, though, to keep it on topic. I hope it's enough.
The Question:

Factorise $$\begin{align}\, & 8wxyz \\
&+w^2yz+w^2xz+w^2xy \\
&+x^2yz+x^2wz+x^2wy \\
&+y^2xz+y^2wz+y^2wx \\
&+z^2xy+z^2wy+z^2wx \\
&+w^2xyz+wx^2yz+wxy^2z+wxyz^2 \\
&+xyz+wyz+wxz+wxy=0\tag{I}
\end{align}$$ over $\Bbb C$.

Context:
Here's a Q&A based on an answer from this meta question:

What are you studying?

A PhD in combinatorial group theory, first year.

What text is this drawn from, if any? If not, how did the question arise?

None. It arose as part of my research into the orders of abelianisations of certain cyclically presented groups.

What kind of approaches (to similar problems) are you familiar with?

Here's a related question about a system of equations generated by a smaller case:
The system $2XY+X^2+Y^2+X^2Y+Y+XY^2+X=0$, for distinct pairs $X, Y\in\{J, K, L\}$ for $n$th roots of unity $J, K, L$.

What kind of answer are you looking for? Basic approach, hint, explanation, something else?

A "simple" factorisation would suffice.

Is this question something you think should be able to answer? Why or why not?

No. I have little training in factorising polynomials in multiple variables.
Observation:
The equation $(I)$ has $w=x=y=z=0$ as a solution.
Please help :)

NB: I $\color{red}{\text{suspect}}$ due to the context of the question that some of the roots are $n$th roots of unity. It would be weird if they weren't.
Comment: If it were 5wxyz instead of 8wxyz, there would be the factor 1+w+x+y+z
Comment: @dxiv I'll probably ask a separate question about a system of equations based on this, similar to the one I linked to in the question.
Comment: Horner Form: $z (x (w (1 + w) + w x) + w x z) + y (x (w (1 + w) + w x) + y (w x + (w + (1 + w) x) z) + z (w (1 + w) + x (1 + w (8 + w) + (1 + w) x) + (w + (1 + w) x) z))$
Comment: There are numerous professional tools for factoring polynomials. Have you tried turning any of them loose on this?
Comment: It is not quite clear what field this is over, and whether there are maybe additional constraints. Taking the real case at face value, suppose that $\,x=y=z=a \ne 0\,$ for example, then the equation reduces to the quadratic $\,(a + 3) w^2 + (3 a^2 + 14 a + 3) w + 3 a^2 + a=0\,$, which can certainly have non-zero $\,w\,$ roots of magnitude other than $1\,$.
Comment: @dxiv All I know is that $w, x, y, z$ are probably $n$th roots of unity; if they're not, it'd be strange. I can't tell you much more but such is the nature of research, I guess.
Comment: I just gave you a family of examples where none of $w,x,y,z$ are roots of unity. Besides, you can't solve one equation for $4$ unknowns. If you want to see if it factors as a polynomial, instead, you could check that the discriminant of the quadratic in $w$ is not a perfect polynomial square, so there are no linear factors in $w$. Then repeat for the next variable. Other than that, sorry, but it is not clear to me what the question means to ask.
Comment: @dxiv The roots of unity thing is kind of like a boundary condition anyway. I know I can't solve it for four unknowns. I'll try to see if it factors as a polynomial. In the meantime, though, I should probably get some rest; it's 02:38 where I am.
Comment: Only Wolfram Alpha.
Comment: @Empty2: Good observation. And the cofactor would be the expansion of $wxyz(1+w^{-1}+x^{-1}+y^{-1}+z^{-1})$. Nice symmetry.
Answer: $$\begin{align}\, p_1(x, y, z, w)=\\
& 8wxyz \\
&+w^2yz+w^2xz+w^2xy \\
&+x^2yz+x^2wz+x^2wy \\
&+y^2xz+y^2wz+y^2wx \\
&+z^2xy+z^2wy+z^2wx \\
&+w^2xyz+wx^2yz+wxy^2z+wxyz^2 \\
&+xyz+wyz+wxz+wxy\tag{I}
\end{align}$$
is a polynomial from $\mathbb{C}[x, y, z, w]=\mathbb{C}[x][y][z][w]$. So it can be seen as polynomial $p_2$ of the variable $w$ with coefficients from the integral domain $\mathbb{C}[x][y][z]$.
So we have
$$\begin{align}\, p_2(w)=\\
&(yz+xz+xy +xyz)w^2\\
&+(x^2z+x^2y
+y^2z+y^2x
+z^2y+z^2x
+x^2yz+xy^2z+xyz^2
+yz+xz+xy+8xyz)w\\
&+(x^2yz
+y^2xz
+z^2xy
+xyz)
\end{align}$$
The coefficients are from $\mathbb C[x,y,z]$. The constant term can be split into the irreducible factors $$x y z (x+y+z+1).$$
The coefficient of $w^2$ is a polynomial of $\mathbb C[x,y][z]$:
$$(xy+x+y)z+xy$$
This is linear in $z$. So a factor can only be a common divisor of $xy+x+y$ and $xy$.
But
$$\gcd(xy+x+y,xy)=\gcd(x+y,xy)=\gcd(x^2,x+y)\\ \gcd(x,x+y)=\gcd(x,y)=1$$
So $$yz+xz+xy +xyz$$ is irreducible.
If $p_3(w)$ is a polynomial of degree $\gt 0$ that divides $p_2$, then $$p_2(w)=c_1w+c_0,$$ with $c_1, c_0 \in \mathbb C[x,y,z]$ and
$$c_1 \mid (yz+xz+xy +xyz)$$
and $$c_0 \mid x^2yz
+y^2xz
+z^2xy
+xyz.$$
So the possible values for $c_1$ are $$a, a(yz+xz+xy +xyz)$$ where $a \in \mathbb C$ and the possible values for $c_0$ are $$b, bx, bxy, bxyz,b(1+x+y+z), b(1+x+y+z)x, b(1+x+y+z)xy,b(1+x+y+z)xyz$$ where $b \in \mathbb C.$ Other divisors like $b y$ we will ignore here for symmetry reasons.
So if we check $$a(yz+xz+xy +xyz)w=b(1+x+y+z)$$ we multiply $(2)$ by $$(b(1+x+y+z))^2$$
and get
$$a(yz+xz+xy +xyz)w=b(1+x+y+z)$$
$$\begin{align}\, \\
(yz+xz+xy +xyz)(b(1+x+y+z))^2\\
+(x^2z+x^2y
+y^2z+y^2x
+z^2y+z^2x
+x^2yz+xy^2z+xyz^2
+yz+xz+xy+8xyz)\\a(yz+xz+xy +xyz)b(1+x+y+z)\\
+(x^2yz
+y^2xz
+z^2xy
+xyz)(a(yz+xz+xy +xyz))^2=0 \tag{3}
\end{align}$$
and we have to check if there are appropriate $a$ and  $b$ such that this equality holds.
This task is simpler if we substitute $x,y,z$ by numbers and solve the resulting equations. I did this using a CAS and found out that all possible combinations result in $$a=b=0$$
So there are no proper factors.
Comment: very nice answer+1


What is cov(X,Y), where X=min(U,V) and Y=max(U,V) for independent Normal(0,1) variables U and V?

Question: Let:

$U, V \overset{i.i.d.}{\sim} \mathcal{N}(0,1)$, i.e. independent standard Normal random variables.
$X=\min(U,V)$
$Y=\max(U,V)$

What is the covariance of $X$ and $Y$?

Related: What is cov(X,Y), where X=min(U,V) and Y=max(U,V) for independent uniform(0,1) variables U and V?
Answer: $\newcommand{\E}{\mathrm{E}}$ $\newcommand{\Var}{\mathrm{Var}}$ $\newcommand{\cov}{\mathrm{Cov}}$ $\newcommand{\Expect}{{\rm I\kern-.3em E}}$
As a direct consequence of the definition of covariance, $\cov (X,Y)= \E(XY)-\E(X)\E(Y)$.
Fact 1:
$U, V \overset{i.i.d.}{\sim} \mathcal{N}(0,1)$
$\Rightarrow  U - V \sim \mathcal{N}(0,2)$  (sum of normally distributed random variables)
$ \Rightarrow |U - V|$ is a half-normal random variable with parameter $\sigma = \sqrt2$
$ \Rightarrow \E (|U - V|) = \frac{\sigma\sqrt{2}}{\sqrt{\pi}} = \frac{\sqrt{2}\sqrt{2}}{\sqrt{\pi}} = \frac{2}{\sqrt{\pi}}$
Fact 2:
$\E(X)+\E(Y) = \E(X+Y)$ (linearity of the expectation).
We have $\E(X+Y) = \E (\min(U,V)+\max(U,V))= \E(U+V) = \E(U)+\E (V) = 0 + 0 = 0$. As a result,  $\E(Y) = -\E(X)$.
Fact 3:
Since $Y-X = |U - V|$:
$2\E(Y) = \E(Y)-\E(X) = \E(Y-X) = \E (|U - V|)= \frac{2}{\sqrt{\pi}}$, hence $\E(Y)= \frac{2}{2\sqrt{\pi}}= \frac{1}{\sqrt{\pi}}$
Fact 4:
Since $XY=UV$, we have $\E(XY)=\E(UV)=\E (U)\E (V)=0$
Using these facts: $\cov (X,Y)= \E(XY)-\E(X)\E(Y)= 0 + \E(Y)\E(Y) = \frac{1}{\sqrt{\pi}}\frac{1}{\sqrt{\pi}}=\frac{1}{\pi}$.
Comment: Should have a negative sign for $cov (X,Y) $ - you've used $E(Y)^2$ instead of $E (X)E (Y) $ in fact 4.  Good answer though.
Comment: E(X)E(Y) would be the same as E^2(Y).  The problem is that the sign changed from - to +.  It is a shame to give such a nice proof and make one careless mistake at the very end.  I overlooked it at first glance.
Comment: The sign changed as $\E(X) = -\E(Y)$ (fact 2). I posted the answer as I thought readers from [What is cov(X,Y), where X=min(U,V) and Y=max(U,V) for independent uniform(0,1) variables U and V?](http://stats.stackexchange.com/q/25965/12359) could be interested.
Comment: Sorry Franck somehow I got confused.  it looks like you had it right and we had it wrong.


How can I manage stored procedure rights of the role in SQL Server

Question: I want to create three SQL Server database roles.

That can CREATE, ALTER and EXECUTE all stored procedures in database
That can only EXECUTE all stored procedures in database
That have no access to any stored procedures in database

I have created the roles, but I'm facing issues while REVOKE their permissions.
I have executed
REVOKE CREATE PROCEDURE TO [ROLE NAME]

to revoke the permissions to create the procedure and it executed successfully.
But I got error while executing this statement:

Error: Incorrect syntax near 'ALTER'.

I am very new to SQL server role rights so I might be completely wrong with my approach.
Please guide me to achieve my goal in correct way.
Thanks
Comment: What did you use to give the `ROLE` the ability to `ALTER` Stored Procedures? `GRANT ALTER PROCEDURE TO YourRole;` would have given you the same error.
Answer: From the documentation Create a Stored Procedure:

Permissions
Requires CREATE PROCEDURE permission in the database and ALTER
  permission on the schema in which the procedure is being created.

Therefore just giving CREATE PROCEDURE on it's own won't allow you to create a procedure. In fact, giving a ROLE the CREATE PROCEDURE permission, and not ALTER on the schema will result in the below error:

The specified schema name "dbo" either does not exist or you do not have permission to use it.

There is no ALTER PROCEDURE permissions, therefore, for a member of a ROLE to be able to both CREATE and ALTER a PROCEDURE you would need to do:
GRANT CREATE PROCEDURE TO YourRole;
GRANT ALTER ON SCHEMA::dbo TO YourRole; --Replace with appropriate schema name

This, however, will also enable to user to ALTER anyprocedures on said schema. Ut also enable those in the role to ALTER other objects on the schema as well (such as tables) though.
If your ROLE has permissions to ALTER the procedures and you want to remove that, you would need to run the below:
REVOKE ALTER ON SCHEMA::dbo TO YourRole;

This will, as mentioned, also revoke their ability to ALTER any other objects on said schema.
Remember, REVOKE doesn't DENY, it simply means that the USER won't inherited that permission from that ROLE any more. If the USER has the permission from a different ROLE, or they have the permission themselves, they will be able to continue to use the permission. If you must stop a USER from performing an action, regardless of any other permissions, they must have the DENY permission.
Comment: So that means if I execute REVOKE ALTER ON SCHEMA::dbo TO [ROLE NAME]. Then it will not allow user to ALTER table, function, view anything?
Answer:
1) That can CREATE, ALTER and EXECUTE all stored procedures in
  database

That's the db_owner role, or the CONTROL permission on the database.  Anyone with all those permissions can escalate their own privileges to a database-level admin.  So don't try.

2) That can only EXECUTE all stored procedures in database

GRANT EXECUTE TO [SomeRole]

3) That have no access to any stored procedures in database

A user has no access to any stored procedure unless you grant permissisions or add them to a role that has permissions.


Apply resolution algorithm to check SAT for CNF

Question: I have a CNF:
$$(\neg p \lor \neg q \lor r) \land (\neg p \lor \neg r) \land p \land q$$
I need to check SAT for it using resolution algorithm, but i don't know how. I know how to check it with truth table, but not with resolution algorithm. I don't really see how to transform it further to find (or not find) a contradiction. How to apply resolution algorithm for this CNF and if its satisfiable find all satisfying assignments?
Comment: You two must be in the same course: https://math.stackexchange.com/questions/3861003/find-conjunctive-normal-form-of-propositional-formula
Answer: To apply the resolution method, from you formula in conjunctive normal form (CNF)
$$(\neg p \lor \neg q \lor r) \land (\neg p \lor \neg r) \land p \land q$$
you get the starting clauses
$$
\neg p \lor \neg q \lor r  \qquad \neg p \lor \neg r \qquad p \qquad q
$$
If there is a way to derive the empty clause $\bot$ by applying the resolution method (i.e. by applying iteratively the resolution rule to the starting clauses and to the clauses you get after a resolution), then the CNF is unsatisfiable.
In this case, there is a way to derive $\bot$ by applying the resolution method, and hence the initial CNF is unsatisfiable. Indeed,
\begin{align}
1. \qquad &\neg p \lor \neg q \lor r &\text{given} \\
2. \qquad &\neg p \lor \neg r &\text{given} \\
3. \qquad &p &\text{given} \\
4. \qquad &q &\text{given} \\
5. \qquad &\lnot r &\text{resolution from 2. and 3.} \\
6. \qquad &\lnot p \lor \lnot q &\text{resolution from 1. and 5.} \\
7. \qquad &\lnot q &\text{resolution from 6. and 3.} \\
8. \qquad &\bot &\text{resolution from 4. and 7.}
\end{align}


Firebase parando a iteração do forEach

Question: Objetivo:
Estou tentando fazer um array de objetos contendo 3 informações: id, title e imageUri. Porém ao pegar o valor de imageUri do firebase(uma URL de download), o forEach trava.
Erro:[Unhandled promise rejection: TypeError: JSON.stringify cannot serialize cyclic structures.]
observação: Quando eu retiro a parte do firebase(imageUri: firebase...), funciona como o esperado

a função:

    processData = ( data ) => {
        console.log('---------data recebida na processData(Main.js:70)--------\n', data)
        var localProcessedData = [];

        Object.entries(data).forEach( ([key, value]) => {
          var event = {
            id: key,
            title: Object.getOwnPropertyDescriptor(value, "eventTitle").value,
            imageUri: firebase.storage().ref('events/active/' + key + '/image').getDownloadURL()
          }
          localProcessedData.push(event);
        })

        this.setState({
          processedData: localProcessedData,
          eventsDataIsLoaded: true,
        })
      }

o tipo de dado que a função recebe como parâmetro:

     Object {
      "-M-I83aV9t1fezOsBn17": Object {
        "active": true,
        "created": "2020-02-05T02:18:30.772Z",
        "description": "Olimpiadas Inter Atletica",
        "eventTitle": "oia",
        "location": "Uberlandia",
        "owner": "p87xn6x8DZTwb6qyTadhkk3UxJV2",
        "price": "130",
        "startDate": "15",
        "time": "14",
        "updated": "2020-02-05T02:18:30.772Z",
      },
      "-M-KlUH-zQhnIhb6wMH8": Object {
        "active": true,
        "created": "2020-02-05T14:34:20.399Z",
        "description": "Cia 2020",
        "eventTitle": "Cia",
        "location": "Uberlandia",
        "owner": "p87xn6x8DZTwb6qyTadhkk3UxJV2",
        "price": "130340",
        "startDate": "15",
        "time": "14",
        "updated": "2020-02-05T14:34:20.399Z",
      }
    }

Meu objetivo é formatar esse dado e transforma-lo num array desse modo:

    Array [
      Object {
        "id": "-M-I83aV9t1fezOsBn17",
        "title": "oia",
        "imageUri": "url da imagem"
      },
      Object {
        "id": "-M-KlUH-zQhnIhb6wMH8",
        "title": "Cia",
        "imageUri": "url da imagem"
      }
    ]

Comment: Dá uma lha aqui https://stackoverflow.com/questions/42266462/react-native-json-stringify-cannot-serialize-cyclical-structures
Comment: @LeAndrade eu tinha lido isso mais cedo mas nao entendi muito bem
Comment: a função ```getDownloadUrl``` não retorna uma Promise? ou eu estou enganado?
Comment: @LeandroSimões sim
Comment: Então, nesse caso vc teria que executar essa função, obter o resultado dela, através do `.then` e só depois, com o resultado em mão, continua a função e cria o objeto `event`. Do jeito que está fazendo ali, a propriedade `imageUri` do objeto `event` não é a url em si, e sim uma Promise não "resolvida", não sei se deu pra entender?
Answer: Resolvi fazendo a função ficar async:
Object.entries(data).forEach( async ([key, value]) => {
  var event = {
     id: key,
     title: Object.getOwnPropertyDescriptor(value, "eventTitle").value,
     imageUri: await firebase.storage().ref('events/active/' + key + '/image').getDownloadURL()
  }
  localProcessedData.push(event);
})```

Firebase parando a iteração do forEach


webm / vp8 player for java

Question: does anyone know of a java library that plays vp8 or webm videos?
thanks!
Answer: VLC can play webm and vp8 videos since version 1.1.0, and there are Java bindings available for it. Have a look at:

jVLC: http://wiki.videolan.org/Java_bindings
VLCJ: http://code.google.com/p/vlcj/

I've used jVLC and it works, but it is not actively maintained anymore. VLCJ looks very good.
Comment: VLCJ is now the preferred Java VLC binding with the older JVLC now abandoned.
Answer: http://sourceforge.net/projects/javavp8decoder/
it's beta but maybe it's a start.
Comment: Like I see this is just for webp images so far.
Answer: I don't know of any native implementations (yet) but there are plugins for gstreamer and ffmpg , both have very good java-wrappers

webm / vp8 player for java


How to Pass argument from URL to field in Views

Question: I need some help about the follow case:
I have a json file from webservice that i extract all informacion and shows into a view. (I have a module that do it)
The json file is specify in a field into a views:
    Json_file: "http://[path]/event/4.json"
However, only show all informacion about the EVENT 4 ("event/4").
My question is: Is there any solution to pass an argument and change the url that is defined in the field of the route? (Only change the number after "event/")
For example:
Json_file: "http://[path]/event/4.json"
Json_file: "http://[path]/event/5.json"
Json_file: "http://[path]/event/3.json"
Note: The structure of the URL is static, always have the same structure.
Answer: This is done using contextual filters. The easiest way to do it is to set up a "page" display by clicking Add+ on the views page. Give the page the URL of http://[path]/event/% (you may also have to try %.json depending on the exact call you are trying to make, the json files are known to drupal right?). The % gives you the argument you are looking for. Then you need to set up a Contextual Filter found under the advanced section of the view. Here you pick the field you are passing the number 4 or 4.json to and choose the correct settings. You may find that you need to pick Provide Default Value for this exact case and then use raw value from url or even php code and do some magic on the $argument (depending on exactly what it is you are doing).


Drawing random subspaces from Grassmannian with uniform probability

Question: Consider the Grassmannian manifold $G(M, N)$ of $M$-dimensional subspaces in $R^N$. I want to approximate (stochastically) an integral of the form
$$
\int_{G(M, N)} f(v) \, dv,
$$
where $f : G(M, N) \to R$ is some function and $dv$ is the Haar measure on the Grassmannian. I want to approximate the integral with sampling, and therefore I need a method to uniformly draw samples with respect to the measure dv.
I'm happy about hints / references on how to do that.
Comment: Fill an $M\times N$ matrix with independent standard Gaussian random variables.  The row space will have the desired Haar distribution.
Comment: It's the pushforward measure of the Haar measure on the orthogonal group $O(N)$ under the map $f_H(g) = g H, g \in O(N)$, $f_H : O(N) \to G(N, M)$. I found this paper, https://arxiv.org/abs/math-ph/0609050 which provides a method to uniformly sample from $O(N)$ which by the above solves my question I think.
Comment: @Călin A standard reference is A. T. James, "Normal multivariate analysis and the orthogonal group". _Ann. Math. Statistics_ 25 (1954), 40–75.  But there might be newer & more accessible explanations.  If I find a good one I'll post it here.
Comment: What do you mean by Haar measure here?
Comment: @kimchilover Do you have a reference for that?
Comment: @kimchilover I think I understood why that works (see my answer), but in the meantime I came to wonder the following: is the Haar measure on the Grassmann manifold the same as the measure induced by its Riemannian structure coming from its quotient geometry? See, e.g., [Edelman et. al](https://epubs.siam.org/doi/pdf/10.1137/S0895479895290954).
Answer: To expand on one of the comments to your question. Indeed, sampling each component of an $M \times N$ matrix independently from the standard normal distribution yields a random $M$-dimensional subspace of $\mathbb{R}^N$.
Using the same reference as in this (related) question, i.e., Chikuse, Y. (2003). Statistics on Special Manifolds, we have from Theorem 2.2.2. that if the elements of $Z \in \mathbb{R}^{M \times N}$ are i.i.d. from $\mathcal{N}(0, 1)$, then $P = Z (Z^\top Z)^{-1} Z^\top$ is uniformly distributed on the subset of $\mathbb{R}^{N \times N}$ containing rank-$M$ projection matrices $P = X X^\top$, which is just another representation of the Grassmann manifold.
Thus, if you instead represent points via the column space of rank-$M$ matrices from $\mathbb{R}^{N \times M}$, you can use the matrix $Z$ directly. Note that $Z^\top Z$ has almost surely full rank, so its inverse above only amounts to a change of basis which should keep you in the same equivalence class (i.e., same Grassmann point).
Similarly, if you use orthonormal $M$-frames, then Gram-Schmidt should give you yet another representation of the same subspace.


Are there any point where the tangent plane to $f(x,y)=ye^{-x}$ is parallel to the plane $y+2z = 4$?

Question: I did try this question by finding the gradient and solving them but my answer was $(0,0,0)$. No way to check if its correct and I am unsure about it because it has couple of missing variables in either planes.
So, I need help. Thank you very much
Comment: A friendly advice: [title should NOT be the first sentence of your question](https://math.meta.stackexchange.com/a/10144/356647). In particular, see the last bullet.
Answer: Hint
The equation if the surface can be expressed as $$f(x,y,z)=z-ye^{-x}=0$$so the question is equivalent to

Is there any point on the surface whose gradient vector $\nabla f(x,y,z)$ is parallel to the perpendicular vector of the plane (which is $(0,1,2)$)?
Comment: Thank you very much.
Comment: Good luck!.....
Answer: With $z=f(x,y)$, the equation for the tangent plane is given by $z-f(x_0,y_0)=f_x(x_0,y_0)(x-x_0)+f_y(x_0,y_0)(y-y_0)$. By writing in the form $ax+by+cz+d=0$, it is clear that the normal direction is $(-f_x(x_0,y_0),-f_x(x_0,y_0),1)$.
The plane you have is $y+2z=4$, or $0x+y+2z-4=0$ so the normal direction is $(0,1,2)$. For two planes to be parallel, their normal directions must be the same. In other words, one must be a constant multiple of the other.
To match them, we want $(-2f_x(x_0,y_0),-2f_x(x_0,y_0),2)=(0,1,2)$. The problem is then solving two equations with two unknowns, $(x_0,y_0)$. For the first component, we want $-2f_x(x_0,y_0)=-2y_0e^{-x_0}=0$, which only occurs when $y_0=0$. For the second component, we want $-2f_y(x_0,y_0)=-2e^{-x_0}=1.$ This can never occur. Therefore, the tangent planei s never parallel to the plane $y+2z=4$.
Comment: thank you very much, easily cleared my confusion.


RHEL 7.5 and Tomcat 8.5 on Azure, not listening on public address

Question: I have created a RHEL 7.5 hosted on Azure and I have installed Tomcat 8.5 in it.
I have configured Tomcat server.xml as following:
<Connector port="8080" protocol="HTTP/1.1"
   address="0.0.0.0"
   connectionTimeout="20000"
   redirectPort="8443" />

And if I CURL the page locally, it works:
curl http://127.0.0.1:8080

I have open an inbound rule in Azure for any IP to 8080.
When I do a netstat -nap I get this, which I think is Tomcat listening only on IP6 (I omitted the non interesting records):
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      -
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0    352 10.0.0.4:22             184.108.40.206:58305    ESTABLISHED -
tcp6       0      0 :::8080                 :::*                    LISTEN      -

I have configured Tomcat to run as a service. Inside $CATALINA_HOME/bin/ I have created setenv.sh using this setting:
JAVA_OPTS="$JAVA_OPTS -Djava.net.preferIPv4Stack=true -Djava.net.preferIPv4Addresses=true "

But or it is not picking up the setting or I am doing something wrong. Any clue?
Comment: What is the problem you are having? You've provided many important details, but the actual problem or error is missing.
Comment: The problem is that if I call Tomcat from outside the server, I get 404. And I resolved by opening RHEL firewall port :-)
Answer: You also need to ensure that port 8080 is open on the Network Security Group (NSG) or set the NSG to none for your VM (not recommended).  NSG docs are here: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/nsg-quickstart-portal


Problem with initial conditions and partial differential equations in Maple

Question: I am new to Maple, trying to see how do I add initial conditions to a system of partial differential equations. Here is an example problem, which has some error in it. What is wrong? This appears on the worksheet:
sys:=$\frac{\partial}{\partial t}f1(x,t)=f2(x,t),\frac{\partial}{\partial x}f2(x,t)=-f1(x,t)$
pdsolve({sys})
yields
$$f1(x,t)=\frac{-C_1 C_2 c_1 e^{c_1 x}}{e^{t/c_1}},f2(x,t)=\frac{C_1 C_2 e^{c_1 x}}{e^{t/c_1}}$$
Trying to add initial conditions:
ics:=$f1(0,0)=-1,f2(0,0)=1$
And then attempting
pdsolve({sys,ics})
doesn't produce an output; No error message or anything... Only the cursor moves to the next line in the worksheet. I checked the solution, the initial conditions are consistent with the solution above and the final solution should have been:
$$f1(x,t)=-e^{x-t},f2(x,t)=e^{x-t}$$
What would be the proper way to do this?
Answer: As it turns out, Maple does not find an unique solution, since other solutions can be shown to exist (such as a sum of cos(x+t) and sin(x+t) multiplied with constants). The reason for this is - in the above exaMPLE, insufficient information HAS been fed into Maple and it cannot produce an unique solution. Adding the initial conditions still permits both the "exp" solutions shown above as well as the sin/cos combination just mentioned.
It appears in such cases Maple bails out, without an output.
Thus, other (initial) conditions are needed to produce an unique solution.


Data Analysis for Spoofed DNS

Question: A remote nameserver, that I do not have privileges on, is intermittently responding with spoofed addresses. I want to monitor this server and collect data on the spoofed responses for analysis. How should I go about doing this?
I essentially want to query for a known domain, compare it to the known IP address, and log the data. I intend to visualize the amount of time the server is responding with spoofed vs. legitimate - as well as patterns in this behavior.
Im hoping there are tools readily avaiable to do this, but I could do some python/sql if needed. Please advise.
Example:
An A record query for google.com will return 188.8.131.52.
Obviously not a google address
Comment: Since you don't own the remote IP, it's unclear whether that IP represents a single server or a farm of servers. Without knowing this I can't see useful data being derived from the test even if it's simply for idle curiosity. It would also help if we had an example of a spoofed query and answer so that we can verify that spoofing is in fact occurring. (as opposed to geolocation)
Comment: Do you only want to log the bad results and times, or all results and times?
Comment: bad results and times would suffice. I see no merit at this time in collecting all data, considering my analysis goals. Always open to enlightenment though :)
Comment: @AndrewB the remote server is a single server.
Answer: I'm going to assume that you know what you're talking about when you say that it's a single DNS server. I'm skeptical because you have not shared your methodology for determining this, but my answer will take it as a given that this information is accurate.
Normally you would perform a query, look at the observed TTL, and query again once that TTL expires. You would continue this until your predetermined sampling period is reached and compare good answers against bad answers.
Unfortunately, the operative word here is "normally". You're looking for a deterministic answer, but these are hard to come by once a server is compromised and in most cases you have to throw logic out the window until you know the specifics of the exploit methodology.

Given your other question on security.SE, it's more likely that the server software itself has been compromised than this being the result of being bombed with forged answers.
Bombing of spoofed packets would always cycle out on a TTL, but other methods
might change the reply unpredictably before the TTL window has
expired. In the latter case, it's hard to tell whether the change is
due to a refresh or not unless you're 100% certain that you're
dealing with a single server and not a farm behind a VIP. TTL will vary pretty consistently in the latter case.

Long story short, you're putting in a lot of work for a problem that isn't yours to own, and since you don't own it you have very few ways of making sure that your gathered information provides a useful conclusion. (aside from an academic exercise in ratio of raw good:bad replies over time, which would turn this Q&A into one of those "gimme the codez" questions that we frown on on this SE site)
Comment: I appreciate your insight. What clues have you leaning towards software compromise? Only reason i thought spoofs was due to the intermittent randomness of the poisoned records. My intention of data collection is to quantify a rough figure of how many users could be affected (based on time of day/length/frequency of poisoned records) which could be used to derive damage done, to find any behaviour patterns if is indeed active spoofing, and also to have a deliverable to backup my claims.
Comment: Basically Im hoping there is a tool or established process for collecting dns query data over time, transforming and loading the data into a friendly format for analysis, and icing on the cake - meaningful representation of the data. If not maybe some libraries or frameworks to help speed of development? just dropping a hook in the dark hoping for a bite.
Comment: @N.Balauro Simply visiting the IP address in a browser and reading the giant **The site ahead contains malware** warning was sufficient for me. It's time to move to security incident response.
Answer: You can use dig www.example.com in bash on most Linux systems to perform a DNS lookup, the output can be customized based on the amount of detail you would like.  You can save known good output to a file then compare results using diff.  Logging can be performed by extracting the desired info from dig output, then it you can save it in whatever format you want using a log file or database.  Using date +%s you can get a unix timestamp to add to the log, which make selecting a time range in the logs a matter of integer comparison on a single value.

Data Analysis for Spoofed DNS


error while implementing form in laravel blade template

Question: I am new to laravel.I am trying to create a basic form in my form.blade.php page.But when i try to navigate to my form.blade.php page i  am getting the following error:

FatalErrorException in 5fca28a34b9eeee32d99bfd5ad77d6a463cb98c9.php
  line 23: syntax error, unexpected 'put' (T_STRING), expecting ')'

in my route.php i am calling the View::make() method to get to the form.blade.php page
Route::get('/',function(){
   return View::make('form');
});

form.blade.php page::
<!DOCTYPE html>

   {{Form::open(array('url'=>'thanks'))}}

   {{Form::label('email','Email Address')}}
   {{Form::text('email')}}

    {{Form::label('os','operating system')}}
    {{Form::select('os',array(
                           'linux'=>'Linux',
                           'mac'=>'Mac',
                           'windows'=>'windows'
                           ))}}

    {{Form::label('comment','Comment')}}
    {{From::textarea('comment','',array('placeholder=>'put your comment here'))}}

    {{Form::checkbox('agree','yes',false)}}
    {{Form::label('agree','i agree with your terms and condition')}}

    {{Form::submit('submit')}}
    {{Form::close()}}

Answer: {!! Form::open(array('url'=>'thanks')) !!}

{!! Form::label('email','Email Address') !!}
{!! Form::text('email') !!}

{!! Form::label('os','operating system') !!}
{!! Form::select('os',array(
                   'linux'=>'Linux',
                   'mac'=>'Mac',
                   'windows'=>'windows'
                   )) !!}

{!! Form::label('comment','Comment') !!}
{!! Form::textarea('comment','',array('placeholder'=>'put your comment here')) !!}

{!! Form::checkbox('agree','yes',false) !!}
{!! Form::label('agree','i agree with your terms and condition') !!}

{!! Form::submit('submit') !!}
{!! Form::close() !!}

Above is the correct way to use form/html, here is the documentation laravelcollective/html
Answer: {{From::textarea('comment','',array('placeholder=>'put your comment here'))}}

should be
{{From::textarea('comment','',array('placeholder'=>'put your comment here'))}}

Seems like you are missing a single quote.
Comment: thanks ! i have corrected it..now it is saying "class Form not found " error
Comment: Which version of laravel are you using? Is the form facade included?
Comment: i am using version 5.2.. and i am not sure it is included or not
Comment: You need to include the form facade: http://laraveldaily.com/class-form-not-found-in-laravel-5/


Erro de ArrayIndexOutOfBoundException ao tentar armazenar valores no vetor

Question: Estou tentando,através do Scanner, pegar os valores digitados pelo usuário,armazenar em um vetor e por fim,realizar a média dos valores digitados,no caso a média das nota de um aluno. Porém,estou tendo essa exceção de array fora do index, e não estou conseguindo identificar o que está errado no código.Abaixo minha classe contendo meus métodos e minha classe contendo meu main,respectivamente.
Classe dos métodos
package classeexercicios;

public class MediaAluno {

    double vetorNotas [] = new double[5];
    double media;
    double total = 0;
    int i;

    double receberNotas() {
        if(vetorNotas[i] >= 0 || vetorNotas[i] <= 100) {
            for(i = 0;i < vetorNotas.length;i++) {
                total = total + vetorNotas[i];
            if(vetorNotas[i] < 0 || vetorNotas[i] > 100) {
                System.out.println("Insira uma nota valida entre o intervalo de 0 a 10");
            }
        }
    }
        return i;
    }
    double calcularMedia() {
        total = total + vetorNotas[i];
        return media = (total / vetorNotas.length);

    }

}

Classe contendo o Main
package classeexercicios;

import java.util.Scanner;

public class MediaAlunoTeste {

    public static void main(String[] args) {

        Scanner teclado = new Scanner(System.in);

        MediaAluno nota = new MediaAluno();
        for(int i = 0;i < 5;i++) {
        System.out.print("Insira a nota do aluno:");
            nota.vetorNotas[i] = teclado.nextDouble();

            nota.receberNotas();
        }

        nota.calcularMedia();

        System.out.println();

        teclado.close();
    }

}

Answer: Melhor seria separar a classe da execução, você misturou um pouco as coisas.
você está tentando somar o total com o vetorNotas na posicão 5?
double calcularMedia() {
                        //aqui
        total = total + vetorNotas[i];
                              // esse vetorNotas.length é apenas um 5 poderia utilizar o índice
        return media = (total / vetorNotas.length);

    }

Se já tinha o total era só dividir pela quantidade de vezes passadas no índice.
// seu pacote

import java.util.Scanner;

public class MediaAlunosNotasArray {

    double vetorNotas [] = new double[5];
    double total = 0;
    int i;
    Scanner entrada = new Scanner(System.in);

    double receberNotas() {
            for(i = 0; i < vetorNotas.length;i++) {
                System.out.println("Insira uma nota valida entre o intervalo de 0 a 10");
                vetorNotas[i] = Double.parseDouble(entrada.next());
                if(vetorNotas[i] > 0 && vetorNotas[i] <= 100) {
                    total += vetorNotas[i];
                } else {
                    i--;
                    vetorNotas[i] = vetorNotas[i-1];
                }

            }
        return total;
    }
    void calcularMedia() {
        System.out.println("media é " + total / i);
    }

    public static void main(String[] args) {
        MediaAlunosNotasArray alunos = new MediaAlunosNotasArray();
        alunos.receberNotas();
        alunos.calcularMedia();
    }
}

seu problema ficou um pouco vago na descrição, caso minha resposta não for válida posso editar.
Comment: Entendi,arrumei aqui e funcionou. Muito obrigado


Getting a formatted address component in another field's template

Question: I need to pull the administrative area component from an Address field and place the full text of it it in the template of another field on the content type. I've managed to accomplish this with the following code.
In preprocess:
function MYTHEME_preprocess_page_title(&$variables) {
$node = \Drupal::request()->attributes->get('node');
  $variables['content_type'] = $node->bundle();
  if ($node->bundle() == 'location') {
    $variables['address_state'] = $node->get('field_address')->getValue()[0]['administrative_area'];
  }
}

And in the twig template:
{% if content_type == 'location' %}

{% spaceless %}{{ title }}{% endspaceless %}{% spaceless %},{% endspaceless %} {{ address_state }}

{% endif %}

This will produce, for example "Boston, MA". But what I want is "Boston, Massachusetts", using the full name of the administrative area rather than the code. According to Drupal Commerce Address docs, you can get the full name in a twig template using {{ administrative_area.name }}. But I couldn't get that to work. How can I render the full administrative area name in the template?
Comment: `MA` is the key, so you need to get the array list and then use the key to get the value. Should be similar to **[How to access a selected label instead of value](https://drupal.stackexchange.com/a/274379/27710)**. Although the `[0]['administrative_area']` nesting sure does throw a monkey wrench.
Answer: How I understand the linked doc you need to configure the plain address formatter in a view mode to use address-plain.html.twig. Then you can output the node field as formatted in this twig:
   if ($node->bundle() == 'location') {
     $variables['address_state'] = $node->get('field_address')->view('custom_view_mode');
   }


Probability and limits

Question: I've been having some trouble with this story problem.  Any help you could give me would be really appreciated.
A store manager monitors the store's temperature by taking 4 independent temperature readings at 4 locations where, if the system is working correctly, the temp. is normally distributed with a mean of 68 degrees F and a standard deviation of 3 degrees.  What's the mean and standard deviation of the average of these 4 readings if the system is working correctly?  What upper and lower limits should the manager set for the average of these 4 readings for there to be a .01 probability of violating a limit when the system is working correctly?
Thanks for any advice/help you can give me!
Answer: The two key elements that you need to be familiar with before working through this exercise are:

The sampling distribution of a mean: in your case, the average of your four measurements will follow a normal distribution, with a mean that equals that of the parent distribution but with a standard deviation of $3/\sqrt{4}$.
How to translate probabilistic assertions in terms of the underlying Probability Density Function: given that there is an infinite number of possible PDFs for a distribution described by two parameters (its location and shape), it is often more convenient to work with the standardized normal distribution which is simply $\mathcal{N}(0;1)$, because if $X\sim \mathcal{N}(\mu; \sigma)$, then we know that $Z=\frac{X-\mu}{\sigma}\sim\mathcal{N}(0;1)$.

Then, you just have to figure out how to find $z_1$ and $z_2$ such that $\Pr(z_1\leq Z\leq z_2)=1-0.01$. It often helps to draw the graph of $\Pr(Z\leq z)$ which is bell-shaped, centered on its mean, and whose total area equals 1. For instance, for a given quantile $z_1$, $\Pr(Z<z_1)=p_1$ where $p_1$ is the shaded area shown below (here, $z_1=-1$, that is 1 standard deviation below the mean):

As the total area equals 1, the remaining (unshaded) area equals $1-p_1$. Likewise, you may readily express any bounded area as a sum or difference of such inequalities.
Comment: So in this particular case, I should calculate a z-score for probabilities of .99 and .01  (i.e. 2.326), then multiply that number by the sampling standard deviation and add or subtract to the mean to get the upper and lower limits?
Comment: @user2385 You got the idea, but don't forget that the 1% are distributed in both tails so that you have to work with .005 ($Z$ will be $<0$, $X$ will be $<68$) and .995 ($Z$ will be $>0$, $X$ will be $>68$), for the total area exceeding the limit equals 1%. No need to substract to the mean, you already know that $X=Z\mu +\sigma$. Just use the correct $\sigma$ to go back from the std normal to the sampling distribution of your empirical mean.
Comment: Ah I see.  Thanks for all the help, I really appreciate it!

Probability and limits


Will it harm technique if my thumb on the fretting hand moves a bit during different parts of a sweep picking arpeggio? (Electric Guitar)

Question: I'm currently practicing some sweep picking arpeggios, and I was wondering if it was hurting my technique to move my fretting hand's thumb around during different parts of a single arpeggio.
I play with the thumb on the back of the neck (instead of the "baseball grip"), and I feel more comfortable moving it around sometimes as some parts of the sweep are hard to reach.
Will moving it around make the technique less transferable to other sweep picking shapes?
Answer: With sweep picking, as soon as each note has been played, it is muted, so it doesn't bleed into a whole arpeggio with notes sounding together. Sometimes it's done just with fingertips releasing, sometimes the thumb needs to help release fretting pressure, so, no, move it where it's needed.
Answer: short answer: no.
long answer: it depends
the position of the thumb behind the neck isn't as important compared to the orientation of your wrist. rather the thumb should be able to support any position required to facilitate proper wrist orientation. as long the thumb isn't exerting excess pressure (really it should just sit there), and isn't in an uncomfortable or strenuous position your good. let the thumb move to where it needs to.
im currently working on a sweeping passage with lots of position shifts. in a case like this the thumb NEEDS to move around quite a bit. as long as your relaxed the thumb should move quite naturally actually. just make sure its not moving around more than an inch or 2 if you're staying in one position.


What is an atonal mode?

Question: I got an album by Ornette Coleman and Pat Metheny, "X", and on the linear notes it talks about atonal experiments within the song structures. Are there scales and chord progressions that go along with atonal music?
Answer: Yes there are scales and chords! You can have chords in atonal music. You simply cannot have a "key". A Key is a hierarchy of notes where some notes are more important that others. In atonality your goal is to have all notes equal(which is impossible to do completely and some pieces are more atonal than others).
For example, the chromatic scale, diminished scale, etc are all common in atonal music. In fact one method of atonality, serialism, is based purely on the chromatic scale.
A "mode" is a "rotation" of a scale in it's strictest sense. If a scale has no home note then a rotation shouldn't produce much of anything BUT it can! In serialism it is one of the ways of generating new material, In this case a "mode" would shift the notes in time only. In other cases it could simply be used as a device for memorizing things. (Like I used the 3rd mode of the chromatic scale which really just means I started on the 3rd note rather than the "1st")
Atonality is the absence of a key center. Modes are not keys(there is a big difference between C major and C ionian). The problem is that we are so used to keys that we can easily hear them as being part of a key. C Ionian, while different from C Major, has so much overlap that people think they are the same. This does not mean you can't do funky stuff with them by, say, taking a modal progression and using a chromatic pedal tone to ruin the sense of key.
The easiest way to create atonal music is to do the opposite of tonal music. Do not have chords, if you do make sure they are very strange so they do not hint at tonality. Can you have a major chord in an atonal piece? Sure, you can do whatever you want! Some purists may bitch though. Can you make up your own atonal chords? Sure but there are so many more it's better not to think of them as "chords". Could those chords be used in a tonal piece? Sure! The same applies to scales. (the chromatic scale is used in some very tonal pieces)
Remember that tonality is more of a large scale concept. A chord or scale cannot define tonality or atonality. It has to do about setting up the hierarchy of notes. Even atonality cannot avoid this completely and is slightly tonal. Chords and scales are about organizing and nothing more. They are concepts to allow us to reduce the complexity of pitch material. Modes, in their purest form, are simple rotations, again, another organizing tool. Inversions, rotations, Mirrors, etc are all transformation techniques and, at least in some cases, do not imply anything about tonality.
Comment: I had to read that twice to really get what you were saying. Not that it wasn't laid out well, but that it's so counter to everything I do with music. Nice answer.
Answer: Almost by definition, atonality implies that you aren't following a rigid chord and scale pairing structure. Atonal music doesn't have a key or a central tone. In the context of jazz "atonal" is often used to refer to a song that has no coherent, classic chord structure (i.e. there's no II IV V I type structure in play for the song). The chords follow each other, seemingly at random. The description "atonal" itself gets used in a lot of different situations though. You'll sometimes hear it used to describe music where the melody and chord structure combine to create a generally dissonant sound.
Tough question. I'm really curious to see what others put up for answers. The word "atonal" as a description for music passes beyond fact and musical theory and in to musical philosophy.
Answer: According to the Oxford dictionary, the term atonal is applied to music that is not tonal, i.e. not in a key. The term is in some circumstances avoided for music that is serial; and it is sometimes reserved for the post-tonal but pre-serial music of the Second Viennese School (Schoenberg, Berg and Webern). The term 'pantonal' is occasionally used in the same sense.
Credits: Oxford dictionary.
Answer: "Mode" is generally used as "scale" when talking about diatonic scales and atonal basically means it lacks a key.  So it sounds to me like an atonal mode would be a diatonic scale without a key, if that's even possible.

What is an atonal mode?


How to call this endpoint in my Rest Assured Test case

Question: Post request will generate the recordID like
{
}
I want to use the same ID in the below sample get request endpoint after ?recordId=
https://random-query-serv-poc-test-dummy.apps.dev-

How do I write a code to automate this GET Request?
I have written this code - but its not working as it is taking the request URI as below
SerenityRest.rest().given().
    header("header1", "ebc").
    header("header2", "svc").
    contentType(ContentType.JSON).
    log().all().
    when().

    then().log().all().
    assertThat().
    statusCode(200);

How can I send the request ID as it is converting the "/" as "%2F"
Comment: Nothing's wrong with your code, the problem might be the URL. You can test this in postman first.
Comment: Sure, Maybe I need to reframe the question , I haven't posted the actual endpoint
Answer: You can stop auto URLencode by URL encoding config.
given().urlEncodingEnabled(false)


SwiftUI: Navigation Bar Title in Reusable Cross-Platform (iOS & macOS) View

Question: I'm attempting to create reusable SwiftUI View for a framework, which can then be used across both iOS/iPadOS and macOS.
This generally works fine; however, because macOS views don't have navigation bars, including a navigation bar title (important for iOS) causes an error when the view's included in a macOS target:
.navigationBarTitle(Text("Page Title"))

Value of type '...' has no member 'navigationBarTitle'

Any suggestions on a conditional compilation (or any other) approach that can allow the same view to build for both platforms?
The closest I've come is the following. Including the extra Text view is easy enough, but because the bar title's a modifier, wrapping just that part in conditional compilation produces other errors:
public struct ExampleView: View {

    private let pageTitle = "Page Title"

    public var body: some View {

        VStack(alignment: .center) {

            #if os(macOS)
            Text(pageTitle)
                .font(.title)
            #endif

            Spacer()
            Text("This is the view content")
            Spacer()
        }

        #if !os(macOS)
        .navigationBarTitle(Text(pageTitle))
        #endif
    }
}

Unexpected platform condition (expected 'os', 'arch', or 'swift')
Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type
Answer: I established one approach: Move the main content to another View property, then modify it to add the navbar title (if needed) before returning it as body. When it's separated this way, conditional compilation can be used.
It's a bit inelegant, but it works. It can also be used to set macOS-specific things, such as the view's overall frame size. Suggestions on a better approach are welcome!
Swift v5.1
public struct ExampleView: View {

    private let pageTitle = "Page Title"

    #if !os(macOS)
    public var body: some View {
        main.navigationBarTitle(Text(pageTitle))
    }
    #else
    public var body: some View {
        main.frame(
            minWidth: 500,
            minHeight: 500
        )
    }
    #endif
    public var main: some View {

        VStack(alignment: .center) {

            #if os(macOS)
            Text(pageTitle)
                .font(.title)
            #endif

            Spacer()
            Text("This is the view content")
            Spacer()
        }
    }
}

Answer: you can add an extension to View struct. It will put conditional compilation outside the block and work as you expect
#if os(macOS)
extension View {
    func navigationBarTitle(_ title: Text) -> some View {
        return self
    }
}
#endif


List nodes by term on one page like Drupal 6

Question: I've searched through quite a lot of how to's now and completely stumped, In Drupal 6 with views the relative simple procedure of linking a taxonomy vocabulary to a content type then furthermore displaying it's terms on one page was a dazzle, now however in 7 running views 3+ not so simple.
I don't know if I'm searching for the wrong phase but literally this is what i want:
Content type = Article + Taxonomy vocabulary linked to content type "site content" > term "blog". Now I want to create a view with path /blog that lists all nodes with the term "blog", further down the line I want to add more entries to the "site content" e.g. "about" and link that to /about for example.
Comment: Have you add taxonomy as field to content type or not?
Comment: Yes the taxonomy is assigned to the content type
Answer: OK, cracked it, here's what I did (sleep worked!):

Create taxonomy vocabulary and term (Structure > Add vocabulary > Add term (after))
Assign to content (Structure > Content Type > Article (for example in my case) > Manage Fields)
Type a label > Field Type "Term Reference" (The vocabulary from step 1) > Widget "Select List" > Save
Create the view (Structure > Views > + Add New View > Show "Content" > of type (select the type assigned in step 2) > Continue and edit
Under "Filter Criteria" > Content: Has taxonomy terms (with depth) > Apply (All Displays) > Vocabulary (As created in step 1) > Apply and continue > In the field "Operator :: Is one of" > Type term (As created in step 1), then select from auto complete drop down > Apply (All Displays)

This will then show in the auto preview. I knew it was simple! - hope this helps someone else in my position.


How can I get arguments from standard input in C?

Question: I have a string that I want to execute in C file and I'd like to get the string from standard input.
echo "Here is some random text.\n" | ./main.c

Comment: https://stackoverflow.com/questions/5157337/c-reading-command-line-parameters
Comment: `fread` from `stdin` or `read` from `STDIN_FILENO`?
Comment: I thought that argument of the function is different from standard inputs.
Comment: @MichaelHajný What argument to which function are you referring to?
Answer: Read from stdin like any other FILE stream.
#include<stdio.h>

int main()
{
    char line[BUFSIZ];
    fgets(line, sizeof(line), stdin);
    printf("stdin: %s", line);
}


Construir modelos no PHP ou no JAVASCRIPT?

Question: A pergunta parece ser obvia, mas gostaria de entender em termos mais técnicos.
Na minha aplicação preciso colocar objetos em um modelo HTML, para visualização do usuário. Tenho duas opções e gostaria de saber qual é a mais eficiente.
1º - Enviar apenas os objetos para requisição AJAX e montar o modelo HTML no JAVASCRIPT e coloca-ló na interface.
2º - Montar o modelo HTML no PHP enviar para requisição AJAX e apenas coloca-ló na interface.
Atualmente estou utilizando a 2º, mas acho que a primeira opção é mais eficiente. Gostaria de saber se estou certo e o motivo.
Answer: Essa pergunta não tem uma resposta exata como eu disse no meu comentário nessa pergunta:
Acredito que em geral quanto mais no lado do cliente melhor, mas há casos em que isso pode mudar, se o sua aplicação é focada para usuários que não possuem máquinas muito potentes, uma ferramenta para ser usada com aplicações pesadas ou você está fazendo um sistema interno para uma empresa sustentável que ainda usa windows xp
Fazendo uma comparação entre retornar apenas os dados cruciais em formato JSON ou html pronto (dados, tags html, estilos, ...), a primeira vai ser claramente mais rápida porém depende se você quer aliviar o back-end ou o front-end
Mesmo que prefira aliviar o front-end, acredito que vale mais apenas enviar os dados no formato json, e no html criar a tabela, se precisar fazer verificações para, por exemplo, mudar a cor do fundo de cada linha de acordo com um dado específico daquela linha, pode fazer esses if else/switch case no back-end e retorna o junto com o json a cor daquela linha. O tempo perdido ao enviar mais dados, em geral, não compensa deixar tudo no back
Comment: Esse último paragrafo que você escreveu é justamente o ponto de dúvida, eu montando o card no PHP e retornando, cada objeto já montado no card fica com aproximadamente 1315 caracteres e o retorno sendo apenas o objeto puro ele fica com bem menos caracteres, porém o javascript vai ter o trabalho de estruturar e colocar no seu devido lugar no html. Pelo que você citou não existe um calculo exato de custo ou regra que deva seguir, eu entendi certo ?
Comment: Sim, entendeu. Acredito que minha resposta ficou meio confusa, mas resumindo: aliviar back ou front?, quanto mais dados passados para o front mais demorado, vale a pena deixar tudo pro back? coloque na balança, teste as duas formas e veja qual é a melhor no seu caso
Comment: Tem também a questão de compatibilidade, os navegadores dos seus usuários tem suporte a JS? O mesmo está ativo? Outra coisa que pode interferir é como está seu front, ele já está pesado com vários efeitos de animação ou com alguma outra tarefa?
Comment: Tem suporte sim, a interface está super leve. Eu entendi. Vlw muito obrigado.


How to resolve "fail to connect to MySQL Server at localhost:3306 with user root"?

Question: I have tried over and over to connect to the local server using MySQL Workbench 6.3 on my computer using the following parameters, but it won't let me connect. Do you think it is a firewall issue?
Here are my parameters:
hostname: localhost
port: 3306
username: root
password: [not_really]

Here is the picture of my problem for anyone's viewing.
Comment: check whether your mysql service is running properly and listening to 3306 port.
Comment: How do you listen to port 3306
Comment: do "telnet localhost 3306" or check in mysql logs.
Comment: I have tried to do that but it says that it can't find telnet on my system or rather it doesn't exist.
Comment: in windows by default telnet cmd not be there, so has to use putty or other party tools. But check in logs, or restart the mysql service once.
Comment: You mean restart MySQL from windows "services.msc" ?
Comment: yup, from there you can findout, the service is up or not.
Comment: Every time I do that it really doesn't help me. I know it's running but I want to be able to connect to it. Any other suggestions?
Comment: use this cmd "netstat -a -p TCP |findstr  3306" from cmd, check mysql listening.
Answer:
Check that the MySQL listen on port 3306 netstat -lnp | grep 3306 on server. Otherwise, check the configuration directive bind-address
Check that the MySQL accessible from you webserver telnet <mysql host> 3306 ( - as in your web application configuration). Otherwise, check firewall rules. Note. telnet by default is not installed in Window, and may be missing in Linux then this component must be installed manually.
If the first test is successful, you will probably need to reset a user's password in MySQL and/or reconfigure which hosts are allowed to connect to it.

Use root account for the web application with a database - a very bad idea!
Comment: Slipper are you saying that I shouldn't have chosen root as the default username, and actually specified a username. Do you think I will have to uninstall the program and then install it again?
Comment: No reinstallation of the program it does not need, it is sufficient to change the settings. But it's just a comment, **it's not your main problem**, it should work with the root account too. just not recommended to do so for security reasons.
Comment: Where do I go from here
Comment: Do you think my firewall is blocking me from connecting to it?
Comment: Firewsall - one of the possibilities. Perform the checks series.


How to set url alias as article title?

Question: I'm getting url alias for all articles like mysite.com/node/14 but I wanted to set the url as aritcle titles like this: mysite.com/article-title
So, How to set all url alias as per the articles title?
Answer: Use Pathauto module.

The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.
Comment: @NavinRauniyar It will work only for newly created node. For existing node you have to manually add the alias.
Comment: no, it worked for me. I used bulk generate option.
Comment: what should I type in path pattern?
Comment: I tried [current-page:title] but nothing change..
Comment: @wolverine -  we posted same answers, same time :) but I'm bit late. So I'm going to delete my answer
Comment: @NavinRauniyar use [node:title]
Comment: @KrishnaMohan next time I will wait for some time before posting answer
Comment: @wolverine lol, Oh no!! I didn't mean that! Please don't misunderstand. I was trying to say about the coincidence :)
Comment: @KrishnaMohan no, I didn't misunderstand you, I am just saying by waiting we can avoid similar scenarios. :)

How to set url alias as article title?


Erro ao tentar realizar backup de base de dados em postgresql

Question: Estou tentando realizar um backup de uma base de dados em Postgresql, porém estou recebendo o seguinte erro:
erro ao ler objeto grande 118287: ERROR:  permission denied for large object 118287
Pesquisei sobre o erro e encontrei as seguintes informações
Realizei os comandos indicados porém o erro persiste, alguém já passou por isso e encontrou uma solução?
Comment: como está fazendo o backup ? versão do banco... etc...
Answer: Desde a versão 9.0, cada large object no PostgreSQL possui seu OID, assim como tabelas, índices etc., não devendo ser tratado como simples registro da tabela pg_largeobject e portanto não sendo automaticamente legível pelo usuário dono desta tabela. Você pode listar os large objects e seus respectivos donos via psql com o comando \lo_list:
nunks=# \lo_list
        Large objects
  ID   | Owner | Description
-------+-------+-------------
 16820 | nunks | Smiley :D
(1 row)

Para conceder a um usuário os direitos de leitura do large object especificado na pergunta, utilize:
GRANT SELECT ON LARGE OBJECT 118287 TO nome_do_usuario;

Como seu caso implica na leitura de todo o banco, sugiro efetuar o backup com um usuário que tenha permissão para a leitura de todos os objetos. Um SUPERUSER sendo a solução mais simples de se manter, caso você só tenha problemas quando da execução de backups.

Outra alternativa é modificar o comportamento do DATABASE em questão utilizando a opção lo_compat_privileges. Assim todos os large objects do banco serão legíveis e alteráveis por todos os usuários. Entretanto, isso significa reduzir a segurança de seus dados, algo que deve ser pesado no momento da decisão por tal alternativa. Para modificar o comportamento do banco, utilize um ALTER DATABASE com um superusuário:
ALTER DATABASE nome_do_banco SET lo_compat_privileges TO true;

A solução mais indicada para casos de uso com grande variedade de usuários criadores de large objects, conforme esta resposta no DBA SE, talvez seja definir um ROLE em que todos eles estejam incluídos e, quando da criação de um large object, definir explicitamente o ROLE utilizado pela transação para que ele seja o dono efetivo dos objetos que cria. Dessa forma, todos os usuários pertencentes a esse ROLE poderão manipular tais large objects. Para definir qual ROLE será utilizado, logo antes de criar o large object utilize o comando:
SET ROLE nome_do_role;


Parâmetros dos labels em PrintPage

Question: Quais os parâmetros possíveis para definir a impressão de labels:
O código que estou a usar é o seguinte:
e.Graphics.DrawString(label_nota_entrega.Text, new Font("Arial", 14, FontStyle.Bold), Brushes.Black, new PointF(550, 50));

É possível colocar uma cor de fundo no label?
Answer: Se não estou em erro só precisa fazer algo deste género:
e.Graphics.DrawString(label_nota_entrega.Text, label_nota_entrega.BackColor = Color.Red, new Font("Arial", 14, FontStyle.Bold), Brushes.Black, new PointF(550, 50));

Answer: Você pode usar LabelTeste.BackColor = Color.DarkRed; ou ainda se preferir seguir na linha de desenhar tudo na tela. Você pode usar junto ao DrawString o DrawRectangle e o FillRectangle.
int LarguraRetangulo = 150;
int AlturaRetangulo = 20;

e.Graphics.DrawRectangle(new Pen(Color.LightGray), 0, 0, LarguraRetangulo, AlturaRetangulo);
e.Graphics.FillRectangle(Brushes.Orange, 0, 0, LarguraRetangulo, AlturaRetangulo);

e.Graphics.DrawString(label_nota_entrega.Text, new Font("Arial", 14, FontStyle.Bold), Brushes.Black, new PointF(0, 0));

Parâmetros dos labels em PrintPage


Passing props into component which has v-if set

Question: I have a page with a stepper. I conditionally display a step, based on what step user is on. When flicks between steps (user can go back and forth) I noticed that my props are no longer passed over. What can be done about it?
View page:
<v-container v-if="stepNumber === 1">
  <sectionOne :restrictions="restrictions" />
</v-container>

<v-container v-if="stepNumber === 2">
  <sectionTwo :restrictions="restrictions" />
</v-container>

Within a section component:
@Prop() readonly restrictions: RestrictionsDomain = new RestrictionsDomain([]);

I understand that I can avoid a need for passing a prop with help of vuex, but I am wondering if anything can be done to get my props to work as is? Also, I can't use v-show for this either.
Comment: There's not enough context to determine the problem. Can you share a link to a reproduction?
Answer: Since v-if destroys the element, thus removing the props' reactivity, and if you can't use v-show, I'd consider using a watcher on the prop and setting another reactive variable that'd trigger the visibility of that element.
So you'd get something like this:
<v-container v-if="step === 1">
  <sectionOne :restrictions="restrictions" />
</v-container>

<v-container v-if="step === 2">
  <sectionTwo :restrictions="restrictions" />
</v-container>

props: ['stepNumber'],
data() {
  return {
    step: 1,
  }
},
watch: {
  stepNumber(newVal) {
    this.step = newVal
  }
}


Prove discontinuity of a function

Question: A function $f$ : $\mathbb R$  → $\mathbb R$ has the following two properties: $f(0) = 0$ and $f(\frac{1}{n}) \to 1$ as $n \to + \infty$.
I need to prove directly from the $ε-δ$ definition of continuity and the $ε-N$ definition of convergence that $f$ is not continuous at $0$.
The $ε-N$ definition of convergence:
A sequence of real numbers ($x$) is said to converge to a real number $a$ if for
every $ε > 0$ there is $N ∈$ $\mathbb N$ such that
for all $n ≥ N$ we have that $|x_n −a| < ε$.
How should I start? I also don't know how to combine the two definitions.
Answer: If  $f$ is continuous at $0$, we have for any $\epsilon=1/4$, there exits $N_1$ such that for any $n>N_1$, there holds
$$|f(1/n)-f(0)|<\epsilon=1/4.$$
Now take $\epsilon'=1/2$, by the convergence of $f(1/n)$ to $1$, there must be an $N_2>N_1$ such that for any $n>N_2$, there holds that
$$f(1/n)>1-\epsilon'=1/2.$$
The two inequalities above contradict each other. So $f$ is not continuous at $0$.
Comment: I don't understand how you get this inequality f(1/n)>1−ϵ′=1/2. Can you please explain?
Comment: By your definition of $\epsilon-N$ convergence, since $f(1/n)\rightarrow 1$, for $\epsilon=1/2$, there exists $N$ such that for any $n>N$, it holds that $|f(1/n)-1|<\epsilon=1/2$, which implies $f(1/n)>1/2$.

Prove discontinuity of a function


how do you test the "goodness-of-fit" for percentages? 2x3, Expected = 0 for some

Question: I have 3 test conditions.
Condition 1: samples expected to have have 100% of product A and 0% of B and C
Condition 2: 50% A and 50%B and 0%C
Condition 3: 33.3% of each A,B and C
I can use a Chi-square test for condition 2 and 3 since I won't have to divide by 0 (if i ignore C in condition 2), but I'm wondering if there's a way to calculate all conditions the same way.
Comment: Can you say more about your situation? Can you paste in example data?
Answer: You cannot use a chi-square test for condition 1 because condition 1 follows a constant distribution, the random variable is not really random because it is constant.
If your null hypothesis predicts 100% of product A then when you collect data you have two possible outcomes:

All samples are product A, the p-value is $1.0$
One or more sample is not product A, the p-value is $0.0$

Your hypothesis is either obviously wrong or it perfectly predicts the samples observed, there is nothing between these extremes where you can have $p=0.05$ and say "the data is unlikely given the hypothesis"
Comment: I'm sure someone will feel the need to point out what I said about the constant distribution. I'm just making a point about the constant distribution, I'm not saying that it doesn't satisfy the formal definition of a random variable.
Answer: You could use: Bayesian Models Comparison based on Bayes Factor.
In this case, you have the relative probability between the various models; below I provide an R implementation.
Also, I found an article that uses Bayes Factor for a problem similar to your:
[The Bayes Factor Against Equiprobability of a Multinomial Population Assuming a Symmetric Dirichlet Prior][1]
The R language code is
library(stats)

p1 <-c(1,0,0)
p2<- c(0.5,0.5,0)
p3 <- c(1/3,1/3,1/3)

Generate a sample from p2
n.observations <-100

results<-rmultinom(1, size=n.observations, prob=p2)
prob_data_given_p1 <- dmultinom(results, prob = p1)
prob_data_given_p2 <- dmultinom(results, prob = p2)
prob_data_given_p3 <- dmultinom(results, prob = p3)

Here we define prior probabilities and assign same probability to the three models
prior_p1 <- 1/3
prior_p2 <- 1/3
prior_p3 <- 1/3

Calculate posteriors
prob_p1_given_data <- prob_data_given_p1* prior_p1
prob_p2_given_data <- prob_data_given_p2* prior_p2
prob_p3_given_data <- prob_data_given_p3* prior_p3

Calculate relative probabilities
p2_relative_to_p1 <-prob_p2_given_data/prob_p1_given_data
p2_relative_to_p3 <-prob_p2_given_data/prob_p3_given_data
print(p2_relative_to_p1)
print(p2_relative_to_p3)

Comment: its missing a link?


How to visualise "equal in distribution" in the context of stochastic dominance?

Question: I am reading about stochastic dominance in wikipedia. I don't comprehend the meaning of "equal in distribution".
$x_B \overset {d}{=} (x_A+y)$
What does $\overset {d}{=}$ mean?
I understand that equal in distribution means that they have the same distribution functions.
$P[X \le x] = P[Y \le x]$ and two random variables having equal moment generating functions have the same distribution.
But I have difficulty visualizing this. Is there a nice way to visualize this?
Comment: Visualizing it? The two distributions will be indistinguishable on any graph you care to use. Histograms, distribution functions, quantiles: it is immaterial which. In practice, your data are samples and samples will differ, but in principle, the graphs are just identical copies of each other.
Answer: Graphing distribution functions is a standard way to visualize distributions which makes "$\overset{d}{=}$" almost trivial to understand.  What is really needed in this context, though, is an understanding of how adding two random variables changes their distribution functions.  This answer develops that understanding by explaining the concepts by means of visualizations.  The result is somewhat surprising: a Wikipedia claim about the connection between stochastic dominance and equivalence in distribution appears to be wrong.
Visualizing random variables
By definition, a random variable is a (measurable) real-valued function defined on a sample space $\Omega$ ("Omega").  A common way to visualize functions is to graph them on a pair of axes.  The points on one axis represent the elements of $\Omega$ (the domain) while the points on the other axis represent the possible values a function can take on (the range).  Although conventionally a horizontal axis is used for the domain, for reasons that will soon become apparent I will dedicate the vertical axis to this role, reserving the horizontal axis to represent the range (all real numbers).
As a running example, let $\Omega = \{a, b, c, d\}$ be a set of four possible outcomes of an experiment.  Assume that all subsets are measurable (can have probabilities associated with them).  Suppose the random variable $X$ assigns the values $2$, $4$, $5$, and $5$ to these outcomes, respectively.  Then the upper left panel of the figure, "Random Variable X," is a graph of $X$.  The centers of the blue dots locate the values of $X$ for each element of $\Omega$.

Visualizing probabilities
A random variable exists independently of any probability measure on $\Omega$.  For this example, I posit a measure $\mathbb{P}$ in which $b$, $c$, and $d$ have equal probabilities of $1/5$ but $a$ has twice that probability, $2/5$.  I have depicted that measure by making the areas of the dots in the graph directly proportional to the probabilities.  The total area of all four dots therefore is taken to be unity (a probability of $1$).
Probability distribution functions
The cumulative distribution function (CDF) $F_X$ of a random variable $X:\Omega\to\mathbb{R}$ is determined by sweeping across the value ($\mathbb{R}$) axis from $-\infty$ to $\infty$ in the graph of $X$.  The total area of the dots swept up in the graph of $X$ between $-\infty$ and any point $x$ (including $x$ itself) is the value of $F_X(x)$.  This is illustrated in the left hand panels.  Because the value axis is horizontal, the sweeping proceeds from left to right.  The region in the graph that has already been swept out at $x=4.5$ is shaded.  The total shaded area covers one large dot for $a$ ($\mathbb{P}(\{a\})=2/5$) and one small dot for $b$ ($\mathbb{P}(\{b\})=1/5)$).  The total probability swept out so far is $3/5$.  Therefore, as shown in the bottom left graph "CDF," where we can envision the left-to-right sweep occurring in tandem with the sweep in the upper graph, the value of $F_X(4.5)$ equals $3/5 = 0.6$. (This is why I made the value axis horizontal in the graph of $X$, because it enables us to visualize this sweeping process using a conventional graph of the CDF, where the value axis is horizontal and the probability axis is vertical.)
(First order) stochastic dominance
The right panels use these methods to show the same random variable $X$ together with another random variable $Y$ (defined on the same set $\Omega$) that it dominates.  By definition, $X$ dominates $Y$ provided $F_X(x) \le F_Y(x)$ for all values $x$ and, for at least some values $x$, $F_X(x) \ne F_Y(x)$.  Graphically, this means that the solid blue lines and dots in the lower right panel ("CDFs of X and Y") always lie at or beneath the dashed red lines and dots.
Because a CDF can never decrease (probability can only be added in during the sweeping process, never dropped out), this geometric fact is equivalent to the graph of $F_X$ lying to the right of the graph of $F_Y$.  Compared to $Y$, $X$ is shifted towards higher values.  Notice, however, that $X$ is not uniformly greater than $Y$: whereas $X(a)=2,$ $Y(a)=3$ is larger.  Nevertheless, $X$ manages to dominate $Y$ because there is a different subset of $\Omega$ (namely $\{b,c,d\}$) at which $Y$ is clearly inferior to $X$.
The key idea worth pondering is that the probabilities for $X$ and $Y$ depicted in the lower graphs (of the distribution functions) can come from different subsets of $\Omega$.  It is not necessary, for instance, that all the probability associated with $F_X(2)$ (which comes only from $\{a\}$) correspond to the same set associated with $F_Y(2)$ (which comes from $\{b, c, d\}$). In this example the two sets have nothing in common!
Adding and subtracting random variables
Random variables are added and subtracted pointwise.  For instance, the random variable $X-Y$ has the value $(X-Y)(a) = X(a) - Y(a) = 2 - 0 = 2$.  Similar calculations hold for the rest of $\Omega$.  When, for any $\omega\in\Omega$, we add a negative value to $X(\omega)$, that must shift the point for $\omega$ to the left in the graph of $X$, because I have oriented the value axis to point to the right.
The Wikipedia claim
The Wikipedia article on stochastic dominance uses the term "gamble" without definition.  This appears to be a synonym for "random variable" (and the word "state" appears to refer to any element of $\Omega$).  It uses two forms of notation for gambles, apparently interchangeably: "$A$" and "$x_A$" refer to one gamble and "$B$" and "$x_B$" to another.  I will simply use $X$ for the former and $Y$ for the latter.  With this understanding, the article asserts that

If and only if $X$ first-order stochastically dominates $Y$, there exists some gamble $Z$ such that $Y \overset {d}{=} (X+Z)$ where $Z\le 0$ in all possible states (and strictly negative in at least one state), ...

Equivalence in distribution, "$\overset{d}{=}$", simply means that the two distribution functions are the same.  This occurs if and only if their graphs coincide.     Consider how such a coincidence could be made to happen by changing $X$ to $X+Z$: that is, by either keeping the values of $X$ the same or making some of them smaller, we wish to transform the graph of $F_X$ into the graph of $F_Y$.
The figure shows a counterexample to the claim.
In the sweeping-out construction of $F_{X+Z}$, by the time we have swept out the probability through the value $x=2$, the value of $X+Z$ at $a$ must already have been accounted for (since $Z(a)$ can be no greater than $0$).  Therefore, no matter how $X$ is altered by $Z$, the value of $F_{X+Z}(2)$ must be $2/5$ or greater.  Moreover, the graph of $F_{X+Z}$ must exhibit a vertical jump of at least $\mathbb{P}(\{a\})=2/5$ at the point where $x = (X+Z)(a)$, because all the probability of $\{a\}$ is swept up instantaneously there.  But it is obvious geometrically that the graph of $F_X$ cannot be changed in this way to coincide with the graph of $F_Y$, because the latter has no vertical jump this large until $x=3$, which is too late.
When neither graph has any discrete jumps--that is, when both $X$ and $Y$ have continuous distributions--we can systematically alter the values of $X$ to shift the graph of $F_X$ to the left until it coincides with the graph of $F_Y$.  (The proof of this involves either consideration of "infinitesimal" amounts of probability or else a measure-theoretic limiting argument.)
Comment: This is meant to be a comment on @whuber's answer, but I don't have the reputation to do this. The claim on Wikipedia refers to Strassen's theorem -- see e.g. (3) in [this note](https://projecteuclid.org/journals/electronic-communications-in-probability/volume-4/issue-none/On-Strassens-Theorem-on-Stochastic-Domination/10.1214/ECP.v4-1005.full) ("first-order stochastic dominance" is just the strict version of the usual stochastic order). It is incorrectly stated, but not for the reason mentioned here. The problem comes from the second part of the sentence "where $y \leq 0$ in all possible state
Comment: @bienvenu Thank you for your interest.  I suspect your concerns arise from two misunderstandings of my answer.  First, $X$ and $Y$ *are* defined on the same probability space, as they must be.  I have updated the figure (in the upper right panel) to make that more clear.  Second, this is not a counterexample to Strassen's Theorem, because that theorem (at least in the generality discussed by Lindvall in the note you reference ) applies only to complete *separable* metric spaces, which implies they must have at least a countable number of outcomes, which is not the case in my example.
Answer: Take an unbiased coin. The random variable "Heads" is equal in distribution to random variable "Tails".  The variable "heads" is equal almost surely to Not(Heads).
2 different unbiased coins are also equal in distribution, but they are not equal almost surely... I do not know the value of other coin from knowing value of the first.
Answer: This is meant to be a comment on @whuber's answer, but I don't have the reputation to do this. @Sycorax turned a previous answer I made into a comment but it was truncated, so I'm reproducing my original post below and adding a reply to @whuber's reply.
The claim on Wikipedia refers to Strassen's theorem -- see e.g. (3) in this note ("first-order stochastic dominance" is just the strict version of the usual stochastic order). It is incorrectly stated, but not for the reason mentioned here. The problem comes from the second part of the sentence "where $y \leq 0$ in all possible states (and strictly negative in at least one state)". The condition in parentheses is not sufficient; instead, this should be and not equal in distribution to 0. Indeed, it is possible to have $X(\omega) \neq 0$ for some $\omega$ and yet have $X$ be equal in distribution to 0.
I don't understand @whuber's post and believe it is incorrect. At any rate, his figure does not show a counter example to Strassen's theorem. The theorem says that we can find a random two random variables $X'$ and $Z$, defined on the same probability space as $Y$, such that (1) $Z$ is almost surely negative (and not equal in distribution to 0) and (2) we have $Y = X' + Z$.
After my initial reply, @whuber's said:

First, $X$ and $Y$ are defined on the same probability space, as they must be. I have updated the figure (in the upper right panel) to make that more clear. Second, this is not a counterexample to Strassen's Theorem, because that theorem (at least in the generality discussed by Lindvall in the note you reference) applies only to complete separable metric spaces, which implies they must have at least a countable number of outcomes, which is not the case in my example.

First, note that in general $X$ and $Y$ need not be defined on the same probability space. It is the new random variable $X'$ such that $Y = X' + Z$ that has to be defined on the same probability space as $Y$ (otherwise that last inequality would make no sense).
Second, every finite (or infinite countable) topological space is separable.
Third, here is one way to obtain the coupling we are looking for: let $F^{-1}_X$ and $F^{-1}_Y$ be the inverse CDFs of $X$ and $Y$ (also known as their quantile function), and let $U$ be a uniform variable on [0, 1]. Then, $F^{-1}_X(U) \sim X$, $F^{-1}_Y(U) \sim Y$ and $F^{-1}_X(U) \leq F^{-1}_Y(U)$.
Comment: +1 Thank you for your patient explanations and persistence.  I do plan to update my post to reflect the points you make.


Windows Server 2008 R2 hangs when Editing folder permissions

Question: Background:

The server in question is a member of a domain.
This is a brand new server, freshly installed.
I can log into this server using any domain user (which tells me that on some level it is accessing the DC and Active Directory).
There are no local users (other than Administrator) on this server.
NET USERS /domain returns all the users in the Active Directory.
UAC is off (for now since I wasn't sure if this was the root of the problem).
The following problem occurs whether I am logged in as the Local admin OR as the domain admin.

Problem:
All I want to do is change the permissions of a folder (and all sub items) to include one of my domain groups (the same problem occurs even if I just try to include a single user, or apply the permissions to a single file).
We have another server connected to the DC which is working perfectly. Changing file / folder permissions is generally a very simple task:

Right Click Folder (or file), and select Properties.
Under Security tab click Edit to change permissions.
Click Add to add the user or group.

And this is where my problem starts. The "From this location" field correctly displays my domain.
However, no matter what I type into the "enter object names to select" field, after clicking OK or Check Names a "Selection Progress" dialog box pops up with the content: "Objects Found: 0" and a Stop button. There is an icon indicating that the system is searching for more objects, but I can leave it for hours and it will not find anything. If I click Stop, nothing happens. Eventually, I have to force close.
Likewise, if I decide to click Locations the system will hang, and the "Select Users, Computers, Service Accounts, or Groups" dialog becomes unresponsive. The worst part is that out of the many times I have clicked on locations, one of them finally brought up the location dialog after around 30 minutes (so it's working on some level, but it's unbelievably slow). Of course, I clicked the little plus symbol next to the domain and it hung there indefinitely.
I am really at a loss here. This behavior seems related to Active Directory and my domain controller, but it doesn't make much sense since I can log in as domain user and validate within seconds.
Comment: eventvwr errors?  Specifically in System and Security...and for system even if it doesn't pertain directly to this issue/time.  For instance, any errors about Domain Controllers unavailable, etc?
Comment: I don't see anything of value there. In the Event Viewer tree, do I just expand Windows Logs and look at System, and Security there? Because I see nothing out of the ordinary in those.
Comment: I'm thinking there may be some communications issue between the server and the global catalog.  A few things, how many DCs are there?  If more than 1, can you check to see if there are any errors on those (in the event log)?  When was the server attached to the domain (wondering if maybe the computer password expired but there were still cached credentials)? Can you resolve the domain name from the server (nslookup yourdomain.local)?
Comment: Confused about something are you logged in locally via RDP when changing these permissions?
Comment: @tonyroth This actually occurred BOTH when logged in locally as local admin, and then via RDP as local admin OR domain admin.
Comment: use `DCDIAG` for replication/communication issues
Comment: @Snowburnt There is only 1 DC. nslookup seems to work (I get the expected results), and don't really see any valuable errors in the event viewer (I think you meant for me to check in the DC's event viewer). The server was attached yesterday.
Comment: What output do you get if you run `nltest /sc_verify:DOMAINNAME`? Have you considered turning on NTDS diagnostic logging?
Comment: @charleswj81 `Flags: b0 HAS_IP  HAS_TIMESERV`
`Trusted DC Name \\MyDC.DOMAINNAME`
`Trusted DC Connection Status Status = 0 0x0 NERR_Success`
`Trust Verification Status = 0 0x0 NERR_Success`
`The command completed successfully` I'm a novice at server administration, thus I don't anything about NTDS diagnostic logging. I will look into it however.
Comment: I'd like to add that I was able to "solve" this by simply waiting long enough. It literally took 30 minutes to finally find the user group and thus add it to the folder permissions. However, this is still a problem, because it should not take so long to change or edit folder permissions. Not to mention that in other cases I left it running for longer, and it never completed (so it doesn't find the users consistently either).
Comment: NTDS Diagnostic Logging can be turned on per DC, depending on the settings you choose, can log an ENORMOUS amount of information to the Directory Service event log. See here for how to enable: http://support.microsoft.com/kb/314980. The changes are immediate, and since your issue is so unclear at this point, you may just try setting them all to "5", cliecking "Check Names", and setting them back to "0". THen get a cup of coffee and get inside AD's brain! I'm actually quite interested to see if you find a resolution.
Comment: One other thing you may try is NetMon to see if there is a network issue or if you see any hints in a capture. Who knows, maybe you have an MTU issue or something.
Comment: Are you sure that the client is resolving the domain's DNS name correctly? I experienced similar issues at a customer where the local.domain.com name of AD domain was also a public DNS record and the problematic clients did resolve the public ip instead of the local one.
Comment: @Marco I'm not sure why this question was bumped to the homepage, but this was "resolved" years ago. I mentioned in the comments what it took (waiting long enough), but I never really got a solid answer as to what was causing this. Since then the server seems to be running just fine.
Comment: Sorry I didn't noticed it was from far 2013!
Answer: Try clicking the "Locations..." button and selecting "Entire Directory". If it starts working, then you have an LDAP issue. Selecting "Entire Directory" forces the Select dialog to use a GC port to execute the query. Selecting a specific domain will cause it to use an LDAP port.


interpreting HR from the time-dependent cox regression

Question: I have done two time-dependent cox regression. My time to event is time to disability, and exposure is disease (0/1). I have done a cox regression considering disease as time-dependent covariate. I want to know if my interpretation below is correct? if not what is the interpretation of the given HR?
<code>1) HR = 1.5 , 95% CI =(1.15, 10.63)

2) HR = 1.15 , 95%CI = (1.11,1.42)
</code>
Comment: The values in the question are internally inconsistent. The CI for the HR don't cover the first point estimate of `HR=1.33`, and it seems that you might have a misprint further down when you say "1.23 time risk." Please edit the question to provide the correct values.
Comment: @
EdM Please see the completely new updated question.
Comment: Thanks for the update. In case 2, however, the point estimate of 1.25 isn't within the 95% CI (1.11,1.15). Also, it's not clear why you have two separate HR values here. Please edit the question to provide that information, as comments are easy to overlook and can be deleted.
Comment: @EdM
 I have two, because it is done the same for two population samples. I have updated in the Q. i dont know why 1.25 isn't within the 95% CI (1.11,1.15). That is the result I got.
Answer: A Cox model is based on whatever covariate values are in place at each event time. Prior history of covariate values isn't considered. So hazard ratios have the same interpretation regardless of whether the covariates were time-varying or not.
Be careful in jumping from "hazard" to "risk," however. The hazard at an event time in a Cox model is the probability of an event given that the individual has already survived that long. Most people think of "risk" in a more general sense, taking into account the entire survival curve. With time-varying covariates you need to know the entire covariate history to judge "risk" in that sense. It's safest to use the words "hazard" and "hazard ratio" to be specific about what you have estimated.
If your model meets the proportional hazards and other assumptions needed for a Cox model, one way to proceed with a HR of 1.25 is to say something like "among individuals still having 'normal ability,' those with cancer are 1.25 times more probable at any time to develop 'weak ability' than those without." That's a fair statement that doesn't depend on knowing details of survival curves.
You might look at an answer to a similar question, which has a link to a freely available paper that discusses the distinction between hazards and risks in more detail.
Comment: @ EdM you are right. Thanks for the point. There was a typo. I just corrected in the updated Q the 95%CI. .Could you please help me with the interpretation of e.g one of the HR? as I mention cancer is a time-varying covariate meaning that can happen at baseline or any time during follow-up. And, the event of interest is time-to-ability decline
Comment: @user358238 I added a bit to the answer. You have to be very careful in how you word such things, as the word "risk" isn't always as well defined as you might hope. Also, you don't need to call the author out with `@` if you comment on an answer. As I understand the system, the author of an answer always gets notified of comments on that answer; similarly for authors of questions.
Comment: @ EdM another question is that does it make sense to check the PH assumption when using the time-dependent cox regression? To me does not make sense to check it anymore. Is that true?
Comment: @user358238 it's still important to check PH with time-dependent covariates, maybe more so. If you want to describe results in terms of hazard ratios, you want relative hazards to be constant over time--the PH assumption.  Otherwise you won't know if some change in survival has to do with changes in the covariates themselves or with the passage of time. With your model of developing 'weak ability' as a function of time and of developing cancer, both of which risks tend to increase with time, that would be very important to document.
Comment: @ EdM thanks. Good point. My exposure is cancer status. If assumption for PH is not fulfilled for this, is it an issue? other covariates are age+gender+education+... which if the PH assumption is not fulfilled, I can stratify on that specific covariate. But what if cancer status is not. Using let us say cox.zph() or  scaled Schoenfeld residuals. To me it is fine if it is not fulfilled for cancer status as it is already time-varying in the cox model. Do you have any comment on this? thanks I always get very nice comment and clear explanation from you. Thanks a lot.
Comment: @user358238 having time-dependent covariates doesn't remove the need to evaluate PH. You should at least report the apparent time-dependence of the coefficient/HR estimate, e.g. by showing the smoothed plot of scaled Schoenfeld residuals over time. As I recall, your time scale is actual age of the individuals; it's quite possible that the relative hazard between those who have developed cancer and those who haven't changes with age. You need to provide that information to your audience.


Logistic regression probabilities in scikit-learn

Question: When using logistic regression in Python's scikit-learn, one may handle multiclass problems even with binary logistic regression. If there are $K$ classes, then coefficients (i.e. weights and biases) for $K$ logistic functions will be produced. But this is using a 'one vs. rest' approach, and the probabilities from the individual logistic functions won't necessarily add up to 1 since this is binary logistic regression. Therefore, when using predict_proba with sklearn's logistic regression, how are probabilities handled in multiclass problems?
I've investigated this and it appears to be similar to applying a softmax function to the individual probabilities of the $K$ logistic functions, but this is not exactly correct. I also do not see explicit mention of this in the documentation.
Answer: It appears that, they just apply simple normalization (i.e. divide by the sum of the probabilities) or softmax when multi_class option is set to ovr or multinomial respectively.
Comment: I had tested so many alternatives...yet somehow missed the simplest approach. Thank you. Although, is there any meaningful justification in applying the simple normalization they've used for the case of `ovr`? Since these are essentially from separately trained binary logistic classifiers, there doesn't appear to be any reason why the probabilities from the different models are valid for direct comparison.


Will URLs with spaces in the path work on all major browsers?

Question: Will a path to content such as example.com/content type/page name work? or must it have a filler such as dashes -  example.com/content-type/page-name?
Answer: Spaces should be at least encoded as %20 .
It's not a good practice, not a standard, to use spaces in URLs at all. In my opinion it is better to replace all spaces with dashes or to concatenate them.
Spaces will cause problems with links, for example you might get:

www.example.com/problem with link

instead of:

www.example.com/problem with link
Comment: see also: http://stackoverflow.com/questions/2547783/do-spaces-in-your-url-20-have-a-negative-impact-on-seo


Como fazer foreign key um-para-muitos no mysql?

Question: Eu tenho uma tabela alunos e uma tabela cursos, minha tabela cursos tem o curso por exemplo de administração, como eu relaciono vários aluno a essa tabela usando Foreign key ?
Comment: Não tenho muita experiencia em sql, mas normalmente cria-se uma terceira tabela... ex: `aluno_curso`, aonde um aluno pode se matricular em mais de um curso e um curso pode ter vários alunos matriculados. Essa tabela, teria basicamente um id, idaluno, idcurso. Eu faria desta forma.
Answer: Primeiro você cria a Tabela CURSOS com a coluna ID_CURSOS (PRIMARY_KEY), depois você cria uma tabela ALUNOS com a coluna ID_ALUNOS (primary_key) e a coluna ID_CURSO. Esta coluna ID_CURSO você aponta como FOREIGN_KEY tendo como referência a tabela CURSOS, coluna ID_CURSOS. Segue exemplo:
<code>CREATE TABLE `database`.`cursos` (
  `id_cursos` INT NOT NULL AUTO_INCREMENT,
  `nome_curso` VARCHAR(45) NULL,
  PRIMARY KEY (`id_cursos`));

CREATE TABLE `database`.`alunos` (
  `id_alunos` INT NOT NULL AUTO_INCREMENT,
  `id_curso` INT NULL,
  `nome_aluno` VARCHAR(45) NULL,
  PRIMARY KEY (`id_alunos`),
  INDEX `FK_ALUNO_CURSO_idx` (`id_curso` ASC),
  CONSTRAINT `FK_ALUNO_CURSO`
    FOREIGN KEY (`id_curso`)
    REFERENCES `vigilant`.`cursos` (`id_cursos`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);
</code>
Qualquer dúvida só falar.
Abraços.
Comment: Entendi, como eu coloco as unidades curriculares(modulos) associado com o nome do curso ? os modulos são uma lista como eu faria para criar esse modulo, seria uma tabela para cada modulo ?
Comment: Desculpa, mas não entendi. Explica direito o que são módulos. São as matérias do curso? Deixa ver se entendi. Exemplo: Curso de Administração (Módulo I: matéria 1, matéria 2, matéria 3; Módulo II: matéria 4, matéria 5, matéria 6). É isso?
Comment: Caso seja da forma como entendi, terá que criar uma tabela MÓDULOS e criar uma FOREIGN_KEY referenciando para o ID_CURSO da tabela CURSOS. Ou seja, através disso, você estará ligando módulos a cada curso.
Comment: Os relacionamentos em DB são feitos através das FKs. Você tem relacionamento 1 para 1 (1:1); 1 para N (1:N); e N para N (N:N). Isto é, relacionamento 1:1 é quando uma tabela está relacionada a outra, mas cada registro aponta apenas a outro de outra tabela; o 1:N é quando um registro de uma tabela se relaciona a vários outros de outra tabela; e N:N é quando vários registros de uma tabela se relaciona a vários registros de outra tabela. Este último, para ser implementado, deve-se criar uma terceira tabela para criar o relacionamento de vários para vários. Exemplo é o que está na resposta acima.