The set of ultrafilters on an infinite set is uncountable

Question: After recently learning about filters and ultrafilters, we looked into further problems and properties. I am having trouble with this one:
If $X$ is an infinite set, then the set of all ultrafilters on $X$ is uncountable.
Comment: Hint: Any infinite set can be split into two disjoint infinite subsets. You can use this to prove something stronger than what the question asks, namely: if $X$ is an infinite set then there are at least $2^{\aleph_0}$ ultrafilters on $X$. By a more difficult argument you can prove the optimal result, that if $X$ is infinite there are $2^{2^{|X|}}$ ultrafilters on $X$.
Comment: Some references concerning the cardinality of set of ultrafilters are given in this answer: http://math.stackexchange.com/questions/34838/are-there-uncountably-many-non-homeomorphic-ways-to-topologize-a-countably-infin/34841#34841
Answer: A family of sets is said to be almost disjoint if the intersection of any two distinct members of the family is finite.
For each real number $x$ let $\langle q_n(x):n\in\mathbb{N}\rangle$ be a sequence of distinct rational numbers converging to $x$, and let $A_x=\{q_n(x):n\in\mathbb{N}\}$. Let $\mathscr{A}=\{A_x:x\in\mathbb{R}\}$. Suppose that $x,y\in\mathbb{R}$ with $x\ne y$. There is some $\epsilon>0$ such that $(x-\epsilon,x+\epsilon)\cap(y-\epsilon,y+\epsilon)=\varnothing$, and there is an $m\in\mathbb{N}$ such that $q_n(x)\in(x-\epsilon,x+\epsilon)$ and $q_n(y)\in(y-\epsilon,y+\epsilon)$ whenever $n\ge m$. It follows that $A_x\cap A_y\subseteq\{q_n(x):n<m\}\cup\{q_n(y):n<m\}$ and hence that $A_x\cap A_y$ is finite. $\mathscr{A}$ is therefore an almost disjoint family of subsets of $\mathbb{Q}$. Moreover, $|\mathscr{A}|=|\mathbb{R}|=2^\omega=\mathfrak{c}$.
For each $x\in\mathbb{R}$ let $\mathscr{U}_x$ be a non-principal ultrafilter on $A_x$, and let $$\mathscr{V}_x=\{V\subseteq\mathbb{Q}:\exists U\in\mathscr{U}_x[U\subseteq V]\}\;;$$ it's not hard to check that $\mathscr{V}_x$ is a non-principal ultrafilter on $\mathbb{Q}$. Now suppose that $\mathscr{V}_x=\mathscr{V}_y$ for some $x,y\in\mathbb{R}$. $A_x\in\mathscr{V}_x$ and $A_y\in\mathscr{V}_y=\mathscr{V}_x$ so $A_x\cap A_y\in\mathscr{V}_x$. If $x\ne y$, $A_x\cap A_y$ is finite. But $\mathscr{V}_x$ is a non-principal ultrafilter, so it contains no finite sets, and therefore we must have $x=y$. Thus, $\{\mathscr{V}_x:x\in\mathbb{R}\}$ is a family of $2^\omega=\mathfrak{c}$ distinct non-principal ultrafilters on $\mathbb{Q}$ (and hence certainly an uncountable family).
Now let $S$ be any infinite set. $\mathbb{Q}$ is countable, so $|S|\ge|\mathbb{Q}|$, and there is therefore an injection $\varphi:\mathbb{Q}\to S$. For each $x\in\mathbb{R}$ let $$\mathscr{W}_x=\bigg\{W\subseteq S:\exists V\in\mathscr{V}_x\big[\varphi[V]\subseteq W\big]\bigg\}\;;$$ it's not hard to check that $\mathscr{W}_x$ is a non-principal ultrafilter on $S$ and that $\mathscr{W}_x=\mathscr{W}_y$ if and only if $x=y$. Thus, $\{\mathscr{W}_x:x\in\mathbb{R}\}$ is a family of $2^\omega=\mathfrak{c}$ distinct non-principal ultrafilters on $S$.
As Carl mentioned in the comments, it's actually possible to show that there are  $2^{2^{|X|}}$ ultrafilters on any infinite set $X$, but that takes a bit more work. If I have time, I may add that argument later.
Added: Let $X$ be an infinite set. A family $\mathscr{A}$ of subsets of $X$ is independent if $$\bigcap_{A\in\mathscr{F}}A\cap\bigcap_{A\in\mathscr{G}}(X\setminus A)\ne\varnothing$$ whenever $\mathscr{F}$ and $\mathscr{G}$ are disjoint finite subsets of $\mathscr{A}$.

Theorem: (Hausdorff) Let $\kappa=|X|$; then there is an independent family $\mathscr{A}$ of subsets of $X$ such that $|\mathscr{A}|=2^\kappa$.

Assuming the theorem, it's not hard to show that there are $2^{2^\kappa}$ ultrafilters on $X$. Let $\mathscr{A}$ be an independent family of subsets of $X$ such that $|\mathscr{A}|=2^\kappa$. For each $f:\mathscr{A}\to\{0,1\}$ and $A\in\mathscr{A}$ let $$\hat f(A)=\begin{cases}A,&f(A)=1\\X\setminus A,&f(A)=0\;,\end{cases}$$ and define $$\mathscr{F}_f=\left\{\bigcap_{A\in\mathscr{G}}\hat f(A):\mathscr{G}\subseteq\mathscr{A}\text{ is finite}\right\}.$$ Clearly each $\mathscr{F}_f$ is closed under finite intersections and is therefore a filterbase on $X$. For each $f:\mathscr{A}\to\{0,1\}$ let $\mathscr{U}_f$ be an ultrafilter on $X$ extending $\mathscr{F}$. If $f,g:\mathscr{A}\to\{0,1\}$ are distinct, there is an $A\in\mathscr{A}$ such that $f(A)\ne g(A)$ and hence $\hat f(A)\cap \hat g(A)=\varnothing$; since $\hat f(A)\in\mathscr{U}_f$ and $\hat g(A)\in\mathscr{U}_g$, it follows that $\mathscr{U}_f\ne\mathscr{U}_g$. Thus, $$\left\{\mathscr{U}_f:f\in {}^\mathscr{A}\{0,1\}\right\}$$ is a family of $2^{2^\kappa}$ distinct ultrafilters on $X$. (Since every ultrafilter on $X$ is a subset of $\wp(X)$, it's clear that there can be no more than this.)
Proof of Theorem: Let $Y=\{\langle F,\mathscr{H}\;\rangle:F\subseteq X\text{ is finite and }\mathscr{H}\subseteq\wp(F)\}$ For each $A\subseteq X$ let $$Y_A=\bigg\{\langle F,\mathscr{H}\;\rangle\in Y:A\cap F\in\mathscr{H}\bigg\},$$ and let $\mathscr{Y}=\{Y_A:A\subseteq X\}$; clearly $|\mathscr{Y}|=2^{|X|}=2^\kappa$, and I claim that $\mathscr{Y}$ is an independent family of subsets of $Y$.
To see this, suppose that $\mathscr{F}$ and $\mathscr{G}$ are disjoint finite subsets of $\mathscr{Y}$, say $\mathscr{F}=\{Y_{A_1},\dots,Y_{A_m}\}$ and $\mathscr{G}=\{Y_{A_{m+1}},\dots,Y_{A_{m+n}}\}$. To show that $$Y_{A_1}\cap\dots\cap Y_{A_m}\cap (Y\setminus Y_{A_{m+1}})\cap\dots\cap(Y\setminus Y_{A_{m+n}})\ne\varnothing\;,$$ we must find $\langle F,\mathscr{H}\;\rangle\in Y$ such that $A_k\cap F\in\mathscr{H}$ for $k=1,\dots,m$ and $A_k\cap F\notin\mathscr{H}\;$ for $k=m+1,\dots,m+n$. The sets $A_k$ are all distinct, so for each pair of indices $\langle i,k\rangle$ such that $1\le i<k\le m+n$ there is an $x(i,k)\in X$ that belongs to exactly one of $A_i$ and $A_k$. Let $F=\{x(i,k):1\le i<k\le m+n\}$, and let $\mathscr{H}=\{A_k\cap F:1\le k\le m\}$; clearly $\langle F,\mathscr{H}\;\rangle\in Y$, and $A_k\cap F\in\mathscr{H}\;$ for $k=1,\dots,m$. Moreover, the choice of $F$ ensures that the sets $A_k\cap F$ ($k=1,\dots,m+n$) are all distinct, so $A_k\cap F\notin\mathscr{H}\;$ for $k=m+1,\dots,m+n$. Thus, $\mathscr{Y}$ is indeed independent.
To complete the proof, note that $|Y|=|X|=\kappa$, so there is a bijection $\varphi:Y\to X$. Let $\mathscr{A}=\{\varphi[S]:S\in\mathscr{Y}\}$; clearly $\mathscr{A}$ is an independent family of subsets of $X$ of cardinality $2^\kappa$.
Comment: There is a complete proof of the optimal result in *Counterexamples in Topology* #111 on the Stone-Cech compactification.
Comment: @alancalvitti: Because mathematics, to the extent that it is done within any formal system, is done in ZFC. This is not something that needs to be mentioned. And anyone who really cares about such matters should certainly know that the ultrafilter extension theorem requires some of the strength of the axiom of choice.
Comment: @alancalvitti: I said nothing about whether mathematics **can** be done in ZF+AD.
Comment: @alancalvitti: The difference between **is** and **can be** seems pretty straightforward.
Comment: @Dune: Elementary. If $X$ is infinite, and $\mathscr{F}$ is the set of finite subsets of $X$, then $|\mathscr{F}|=|X|$. $\wp(F)$ is finite for each $F\in\mathscr{F}$, so the set of pairs $\langle F,\mathscr{H}\rangle$ with $\mathscr{H}\subseteq F$ is finite. Thus, $|Y|\le|X|\cdot\omega=|X|$, and obviously $|Y|\ge|X|$, so we get equality.
Comment: @alancalvitti: There are quite a few formal systems. Reverse mathematics isn't one of them, however; it's a program for determining the strength of ordinary mathematical theorems. Yes, there are areas of mathematics in which a category-theoretic outlook is probably the norm. That, however, has no bearing on this particular answer.
Comment: @Dune: My pleasure! And thanks again for catching those horrible typos.
Comment: @Brian, this is an amazing proof! Thank you!
Comment: The proof you give in the **Added** part is very close to [Hausdorff's original one](http://matwbn.icm.edu.pl/ksiazki/sm/sm6/sm612.pdf). Stefan Geschke has collected a number of arguments and references [in a set of notes here](http://www.hcm.uni-bonn.de/fileadmin/geschke/papers/IndependentFamilies_03.pdf) (see also [this MO thread](http://mathoverflow.net/questions/48914/) $${}$$ A small TeX-remark: If you write `f \in ^X \{0,1\}` the `X` becomes a superscript of the `\in` symbol. To make this look a little better, use `f \in {}^X \{0,1\}`. Compare $f \in ^X \{0,1\}$ and $f \in {}^X \{0,1\}$.
Comment: @t.b.: I discovered that later, in another post, though my solution was different: `f\in{^X\{0,1\}}`
Comment: @t.b.: I think that I first saw that proof from Ken Kunen.
Comment: @BrianM.Scott, not that I can follow your proof, but why is there no mention of the set axioms? According to Herrlich's *AC*, there are no nontrivial ultrafilters on $\mathbb N$ in ZF+AD.
Comment: @BrianM.Scott, Interesting, so what MacLane told Bergman, that UCB mathematicians worship at the temple of ZFC, holds even outside of Berkeley? You seem to be saying that ZF+AD is not a formal systems within which math can be done - after all it precludes Banach-Tarski type decompositions, so it's an advantage in geometry.
Comment: "mathematics, to the extent that it is done within *any* formal system, is done in ZFC." How should I interpret your quantifier
Comment: @BrianM.Scott, good 1. Aren't there other formal systems, like categories and "reverse mathematics" , in addition to multiple set theories?
Comment: @Brian, could it be, that you have a few typos with cardinalities in Hausdorff's theorem? You claim, that there is an $\mathcal{A}$ with cardinality $2^\kappa$, but you use the theorem to get an $\mathcal{A}$ with cardinality $2^{2^\kappa}$. On the other hand in the proof you claim $|\mathcal{Y}| = 2^{2^\kappa}$ where I think, it should be $2^\kappa$.
Comment: @Dune: Thanks very much! I sure did; I'm amazed that no one caught them before. I think that I've caught and fixed all of them now; let me know if you find any more.
Comment: @Brian, thanks - it looks good now. I just wonder, why $|Y| = |X|$ holds at the end of the proof. I am not very familiar with cardinality calculations. Could you give me a little hint? Does one need Zorn's lemma here or is there an elementary argument?
Comment: @Brian, great - thanks! :)
Comment: Nice proofs. You should have $A_k \cap F \not\in \mathscr{H}$ rather than $A_k \cap F \ne \mathscr{H}$ in the start and end of the middle paragraph of the last theorem. I was gonna mention that you don't know the $Y_A$ are distinct (needed for $|\mathscr{Y}|=2^{|X|}$), but luckily the proof that they form an independent set implies this.
Comment: @Displayname: Thanks for catching the typos. The fact that the sets $Y_A$ are distinct is easy. If $A,B\subseteq X$, and $A\ne B$, WLOG there is $x\in A\setminus B$. Let $F=\{x\}$; then $\langle F,\{F\}\rangle\in Y_A\setminus Y_B$.
Answer: Here is the first argument I alluded to in my comments. I think it may convey a little more of the way I look at these things.
The idea is to build an embedding $E$ of the upside-down tree of all finite sequences of 0s and 1s into the collection of infinite subsets of $X$ in such a way that if sequences $\sigma$ and $\tau$ are incompatible then $E(\sigma)$ and $E(\tau)$ are disjoint, and if $\sigma$ is an initial segment of $\tau$ then $E(\tau)\subseteq E(\sigma)$.
The embedding is constructed inductively. Let $E$ send the empty sequence to $X$. Assuming $E$ is defined on a sequence $\sigma$ we divide $E(\sigma)$ into two disjoint infinite pieces, and let $E(\sigma + \langle 0\rangle)$ be one of them and $E(\sigma + \langle 1 \rangle)$ be the other.   It can be verified without much work that $E$ has the desired properties.
Now any poset into which we can embed a binary tree in this way has to have at least $2^{\aleph_0}$ ultrafilters. Each $f \colon \mathbb{N} \to \{0,1\}$ gives a path through the infinite binary tree, and via $E$ that path becomes a decreasing sequence $E(f)$ in the poset. Any such sequence extends to an ultrafilter on the poset. On the other hand, two distinct paths $f,g$ must give distinct ultrafilters, because there will be a pair $p,q$ of incompatible elements of the poset such that $p \in E(f)$ and $q \in E(g)$. This $p,q$ can be found by looking at the place where $f$ and $g$ diverge in the binary tree.
I personally find this method very visual, and easier to follow than some other methods. It shows concretely how the structure of the poset itself is reflected in the collection of ultrafilters.
Comment: This is indeed very nice!
Answer: Here are some arguments which are not fundamentally different from the ones in the other answers, but are possibly made more enlightening by being cast in the language of topology.
If $X$ is uncountable, there are uncountably many principal ultrafilters on $X$, so we may assume $X$ is countable.  In particular, we can identify $X$ with $\mathbb{Q}$.  Now in any topological space $S$, if $D\subseteq S$ and $x\in\overline{D}$, there is an ultrafilter on $D$ which converges to $s$ (proof: take the filter of neighborhoods of $x$ intersected with $D$ and extend it to an ultrafilter).  In particular, considering $D=\mathbb{Q}$ and $S=\mathbb{R}$, for each $x\in\mathbb{R}$ there is an ultrafilter on $\mathbb{Q}$ converging to $x$.  Since $\mathbb{R}$ is Hausdorff, a filter cannot have more than one limit, and so these ultrafilters corresponding to each point of $\mathbb{R}$ must be distinct.  This gives uncountably many distinct ultrafilters on $\mathbb{Q}$.
More generally, the same reasoning shows that if $S$ is a Hausdorff space with a dense subset $D$, then there are at least $|S|$ different ultrafilters on $D$.  Given any set $X$, we can take $S=\{0,1\}^X$, and $D$ to be the set of points that are $0$ on all but finitely many coordinates.  If $X$ is infinite then $|D|=|X|$, and we conclude that there are at least $|S|=2^{|X|}$ ultrafilters on $X$.
We can use a similar but trickier construction to prove the sharp lower bound of $2^{2^{|X|}}$ ultrafilters.  Let $S=\{0,1\}^{\mathcal{P}(X)}$.  For each $x\in X$, we have a map $u_x:\mathcal{P}(X)\to \{0,1\}$ given by $u_x(A)=1$ iff $x\in A$.  Now let $D$ be the set of functions $\mathcal{P}(X)\to\{0,1\}$ which can be written as a finite pointwise Boolean combination of functions of the form $u_x$.  Clearly $|D|=|X|$ if $X$ is infinite, and I claim $D$ is dense in $S$.
To prove this, let $A_1,\dots,A_n\in\mathcal{P}(X)$ be distinct.  We can find a finite subset $X_0\subset X$ such that $A_1\cap X_0,\dots, A_n\cap X_0$ are all distinct.  The functions $u_x$ for $x\in X_0$ generate the Boolean algebra of all functions $\mathcal{P}(X_0)\to \{0,1\}$ (the characteristic function of any singleton $\{B\}\subseteq\mathcal{P}(A_0)$ is just the join of all the $u_x$ for $x\in B$ and the negations of the $u_x$ for $x\not\in B$).  In particular, we can find a Boolean combination of the $u_x$ for $x\in X_0$ which takes arbitrary specified values on the sets $A_1\cap X_0,\dots,A_n\cap X_0$ and thus will take the same values on $A_1,\dots,A_n$.  This exactly proves that $D$ is dense in $S=\{0,1\}^{\mathcal{P}(X)}$ in the product topology.  Since $S$ is Hausdorff and has $2^{2^{|X|}}$ points, this shows there are $2^{2^{|X|}}$ ultrafilters on $D$ and hence on $X$.  (For more discussion of this construction, see Is $2^{\frak{c}}$ separable?)
The arguments above are all in the spirit of Brian Scott's answer, just in the language of topology.  Here is a topological argument which is instead along the lines of Carl Mummert and Alex Ravsky's answers.  Note that the set of nonprincipal ultrafilters on a set $X$ can naturally be identified with the Stone space of the the Boolean algebra $\mathcal{P}(X)/\mathrm{fin}$, where $\mathrm{fin}$ is the ideal of finite subsets of $X$.  This Stone space is compact Hausdorff, nonempty if $X$ is infinite, and has no isolated points since $\mathcal{P}(X)/\mathrm{fin}$ is atomless (given an infinite subset of $X$, we can partition it into two infinite subsets).  But a nonempty compact Hausdorff space with no isolated points is uncountable, so there are uncountably many nonprincipal ultrafilters if $X$ is infinite.
Comment: What does "finite pointwise Boolean combination" mean? Using just $\sup$, $\inf$, negation, and finite amount of functions of the form $u_x$?
Comment: Thank you for this answer, I was wondering how to motivate the proof that there's $2^{2^{|X|}}$ ultrafilters on infinite set $X$ a little better.
Comment: That's correct.  If you like, you could also say $D$ is the subring of $\{0,1\}^\mathcal{P(X)}$ (identifying $\{0,1\}$ with $\mathbb{Z}/2$) generated by the elements $u_x$.
Answer: Assume to the contrary that $\{\mathcal F_n:n\in\Bbb N\}$ is a sequence of all distinct ultrafilters on the set $X$. Put $F_0=X$ and inductively for each natural $n$ choose any proper infinite subset $F_n\not\in \mathcal F_n$ of $F_{n-1}$ and any point $x_n\in F_n\setminus F_{n-1}$. For each natural $n$ put $F'_n=\{x_m:m\ge n\}$. Then $F'_n\not\in\mathcal F_{n}$. Hence a filter $\mathcal F=\{F'_n:n\in\Bbb N\}$ cannot be contained in any ultrafilter on $X$, a contradiction.
Answer: The complement $\beta\mathbb N \setminus \mathbb N$ is a perfect set
(and therefore
uncountable), by the lemma below.
Lemma (courtesy of Alex Kruckman).  $\beta\mathbb N \setminus \mathbb N$ is perfect.
It suffices to show that the set of non-principal ultrafilters has no isolated points. Equivalently, every basic open set in $\beta\mathbb{N}$
which contains a non-principal ultrafilter in fact contains more than one non-principal ultrafilter. Such a basic open set $U$
is the set of all ultrafilters containing some set $X\subseteq \mathbb{N}$. This set $X$
must be infinite (else it is not contained in any non-principal ultrafilter). Now pick an infinite and coinfinite subset $Y\subset X$
and find non-principal ultrafilters containing $Y$
and $X\setminus Y$
respectively. These are distinct elements of $U$, as desired.
Comment: @AlexKruckman, Nice argument!  Do you mind if I include this in my *answer*?
Comment: I don't mind at all.


VueJS refresh content after database operation

Question: I'm using a v-data-table component to display data from firestore database. It looks something like this:

The approve/disapprove functionality works well, updating the firestore database with the below code:
database
      .collection(member)
      .doc(userId)
      .update({
        approved: status
      })
      .then({
        console.log("School member details updated successfully")
          return this.teachers.filter(teacher => {
            return teacher.id != userId;
          });
      })
      .catch(err => {
        console.log(
          "An error occured trying to update the school member details:",
          err
        );
      });

However, after the content is updated successfully on firestore database I no longer want to show the list item, I thought filtering the array as I have done in the then() code block would work but its not.
How could I refresh the data for the client without reloading the whole page again?
Comment: `Array.filter` is not in-place. You'll have to reassign.
Answer: You mentioned that you don't want to show the particular list Item after successful approved. As you used teacher.id != userId. Have you used teacher.id !== userId?


Help solving a predicate logic question:

Question: A(x,y,z): adding vector y to vector x results in vector z
Translate the statement into english:
∀x.∀y.∀z.A(x,y,z) --> A(y,x,z)
Answer: For any vectors x,y, and z, if x+y=z then y+x=z.
Answer: Why is this hard for you?   Where are you having trouble?   Take it step by step.

∀x.∀y.∀z.A(x,y,z) --> A(y,x,z)

Begin with the quantifiers.   $\forall$ become "any" and the domain is 'vectors', so:

Any vector x, any vector y, any vector z: A(x,y,z) --> A(y,x,z)

Move to the connectives.   It is a material implication; an "if-then" clause.

Any vector x, any vector y, any vector z: if A(x,y,z) , then A(y,x,z) .

Now for the predicates.   Ensure that you substitute the letters in the required order.

Any vector x, any vector y, any vector z: if adding vector y to vector x results in any vector z , then adding that vector x to that vector y results in that vector z.

Finally, rearrange to more natural language.

If adding any vector y to any vector x results in a vector z, then too adding vector x to vector y results in vector z.

Well, that is as far as you need to go; it is what an exam marker would be looking for.   However you might want to take the extra step and eliminate the x,y,z symbols.   That is okay too.   Just make sure you preserve the intent and meaning of the statement.   ( On an exam I'd put both down, just to show you understood both the process, and meaning, of the statement. )

The order of addition of any two vectors is irrelevant, as either way yields the same result.

Which simply means that: "Vector addition is commutative."


Atributo json_array vazio ao persistir no BD

Question: Boas Galeri.
Estou com um problema curioso ao utilizar DoctrineFixturesBundle.
Tenho uma classe Application do tipo Entity Class que mapeia para a tabela sistema.
Nessa classe há um atributo chamado options que é do tipo json_array mapeada para a coluna de sistema opções e eu a inicializo como um ArrayCollection.
Options está logicamente codificada para que cada elemento desta coleção seja um Objeto (Entidade OptionAttribute).
Fiz desta forma porque precisava ter um Form que possuisse a capacidade de adicionar/remover/editar cada elemento desta coleção, e então criei a Entity OptionAttribute que não está mapeada no Banco de Dados.
Criei os FormType tanto para Application quanto para OptionAttribute e tudo funcionou a contento.
Agora fui criar Fixtures para a Entidade Application e a coluna sistema opções fica apenas com '{}', ou seja, vazia. Não há erro de execução, apenas não está persistindo a coleção de entidades OptionAttribute.
Segue as classes
A classe de fixtures para Application
class ApplicationFixtures extends Fixture
{
    public function load(ObjectManager $oManager)
    {
        $types = ['TextType', 'TextareaType', 'EmailType', 'IntegerType', 'MoneyType',
            'NumberType', 'UrlType', 'TelType', 'DateType', 'DateTimeType', 'TimeType', 'PercentType',
            'SearchType', 'BirthdayType', 'CheckboxType', 'FileType'];
        $appsAlias = [1 => 'Facebook', 'Twitter', 'Instagram', 'Tumbler', 'Tinder'];
        foreach ($appsAlias as $k => $app) {
            /* @var $application Application */
            $application = new Application();
            $application->setName('Application Number ' . $k)
                ->setIsActive(true)
                ->setAlias($app);

            $rand_keys = array_rand($types, 5);

            foreach ($rand_keys as $typesKey) {
                $optionAttribute = new OptionAttribute();
                $optionAttribute->setName('Option ' . str_replace('Type', '', $types[$typesKey]))
                    ->setDefaultValue('Default Value for Option ' . $typesKey)
                    ->setRequired(($typesKey % 2 == 1))
                    ->setType($types[$typesKey]);

                $application->addOption($optionAttribute);
            }

            $oManager->persist($application);
        }
        $oManager->flush();
    }

}

Entidade Application
/**
 * @ORM\Table(name="sistema")
 * @ORM\Entity
 */
class Application
{

    // Several attributes...

    /**
     * @var ArrayCollection|OptionAttribute[]
     * @ORM\Column(name="sistema_opcoes", type="json_array", length=255, nullable=true)
     */
    private $options;

    public function __construct() {
        // ...
        $this->options = new ArrayCollection();
    }

    // Several getters and setters for ordinary fields
    /**
     * @return ArrayCollection
     */
    public function getOptions()
    {
        $options = new ArrayCollection();
        foreach($this->options as $k => $value) {
            /* @var $option OptionAttribute */
            $option = new OptionAttribute();
            $option->unserialize($value);
            $options->add($option);
        }
        return $options;
    }

    /**
     * @param ArrayCollection $options
     * @return Application
     */
    public function setOptions(ArrayCollection $options)
    {
        foreach ($options as $option) {
            $this->addOption($option);
        }
        return $this;
    }

    /**
     * @param OptionAttribute $option
     * @return $this
     */
    public function addOption(OptionAttribute $option)
    {
        $this->options->add($option->serialize());
        return $this;
    }

}

E a Entidade OptionAttribute
class OptionAttribute implements \Serializable
{
    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $defaultvalue;

    /**
     * @var string
     */
    private $type;

    /**
     * @var boolean
     */
    private $required = false;

    // Getters and Setters

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->name,
            $this->defaultvalue,
            $this->type,
            $this->required,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->name,
            $this->defaultvalue,
            $this->type,
            $this->required,
            ) = unserialize($serialized);
    }
}

Onde será que estou errando???
Answer: Para quem tiver o mesmo problema.
Percebi que a conversão de ArrayCollection para json_array não funcionava como eu esperava e então alterei o código para que o atributo fosse preenchido apenas com o tipo array no atributo em questão e tudo funcionou como esperado.
Não precisei alterar o método getOptions.
Segue as alterações
/**
 * @ORM\Table(name="sistema")
 * @ORM\Entity
 */
class Application
{

    // Several attributes...

    /**
     * @var array
     * @ORM\Column(name="sistema_opcoes", type="json_array", length=255, nullable=true)
     */
    private $options;

    public function __construct() {
        // ...
        $this->options = [];
    }

    // Several getters and setters for ordinary fields

    /**
     * @param ArrayCollection $options
     * @return Application
     */
    public function setOptions(ArrayCollection $options)
    {
        $this->options = [];
        foreach ($options as $option) {
            $this->addOption($option);
        }
        return $this;
    }

    /**
     * @param OptionAttribute $option
     * @return $this
     */
    public function addOption(OptionAttribute $option)
    {
        $options = $this->getOptions();
        if ($options->contains($option)) {
            return;
        }
        $this->options[]= ($option->serialize());
        return $this;
    }

}

A partir desse ponto consegui utilizar a classe de Fixture normalmente.


Usando filter_input_array(INPUT_POST,"var_name") vs. $_POST

Question: Eu tenho a seguinte variável input no meu formulário:
<input class="caption_text" type="text" name="caption[]" required/>

Que eu criar dinamicamente com JS.
Depois de submeter eu testo o seguinte:
$mycaption = \filter_input_array(\INPUT_POST, 'caption');
foreach ($mycaption as $eachInput) {
    echo "Caption " . $eachInput . "
";
}

Eu descobri que o código acima não funcionou.
Contudo, unsando $_POST, assim:
$cpost = $_POST["caption"];

foreach ($cpost as $eachInput) {
    echo "Caption " . $count. " - " . $eachInput . "
";
}

Em seguida, ele funciona como esperado.
Alguém pode, por favor, me dizer por que a primeira abordagem não funciona?
Comment: O que são aquelas barras invertidas no seu código?
Comment: Está usando o `filter_input_array` e mandando ele validar o que ? Lógico que o retorno será `null`, tente adicionar alguma expressão para validar o que esperar receber neste campo.
Comment: Olá, não quero validar nada, apenas buscar a varíavel submetida. Recomenda-se não usar mais a variável global $_POST direto e sim através de um filter_input.
Answer: Fiz um teste simulando o código que postou e formulei o código abaixo com o uso da função:
<?php
$filtro = array(
    'caption' => array(
        # aqui pode variar de acordo com o valor esperado do seu input
        'filter' => FILTER_VALIDATE_STRING,
        'flags' => FILTER_REQUIRE_ARRAY
    )
);
$form = filter_input_array(INPUT_POST, $filtro);
if (array_key_exists("caption", $form))
{
    foreach($form['caption'] ...)
    {
         # ...
    }
}

Saída
<?php
var_dump($form);
# array(1) { ["caption"]=> array(2) { [0]=> int(2) [1]=> int(3) } }

Comment: Olá Wilian, obrigado pela ajuda.
Comment: Visto que o NetBeans IDE avisa: "do not access superglobal $_POST array directly", eu estou utilizando os "filter_input" conforme recomendado. Para todas as varíaveis do meu form eu faço isso e funciona certinho. No entanto, para esse campo que é um array (caption[ ]) ele não funciona. Essa caption é um array que crio dinamicamente e recebe um texto normal, apenas para descrever as imagens selecionadas. Por ora, vou continuar acessando assim: $caption = $_POST['caption'];


Linting with standard.js in Intellij IDEA

Question: I'm trying to use standard.js for linting in Intellij. I followed the instructions for installing the node module and the Webstorm directions for manually enabling linting since the IDE did not enable it automatically. I am still getting no indication that lint is working in the editor, as I've introduced a bunch of obvious code standard flaws.
Here is the general sequence I followed:

Installed the standard.js module. Verified that it and eslint are both included as project level node modules in package.json.
Removed any other references to lint modules from project level package.json.
Disabled tslint plugin.
Removed tslint.json
Preferences | Editor | Code style | JavaScript and click Set from Predefined Style – Standard
Languages & Frameworks | JavaScript | Code quality tools | ESLint

in EsLint package: select node_modules/standard

Did another npm install and restarted a few times. Attempted to enable and disable EsLint a couple times just in case.

Still no lint messages appearing directly in the editor. Anyone else run into this issue?
Comment: we are not aware of such issues. Please provide your package.json, screenshot of **Languages & Frameworks | JavaScript | Code quality tools | ESLint** and idea.log (https://intellij-support.jetbrains.com/hc/en-us/articles/207241085-Locating-IDE-log-files). Note that **Set from Predefined Style** doesn't enable linting - it just  changes your code style preferences to the predefined "standard" scheme
Comment: BTW, what files are you trying to lint? javascript or typescript?
Comment: I think I'm just going to create a support ticket through my JetBrains account for this one since I have some company-specific information that I'd rather not post on stack. Once we figure it out I'll post the solution here.
Answer: standard.js only lints Javascript by default. To make it work for Typescript, you need to set it up to use typescript-eslint-parser as the parser and eslint-plugin-typescript as a plugin (https://standardjs.com/#can-i-use-a-javascript-language-variant-like-flow-or-typescript):
"standard"       : {
    "parser" : "typescript-eslint-parser",
    "plugins": [
      "typescript"
    ]
  },
  "devDependencies": {
    "eslint-plugin-typescript": "^0.9.0",
    "standard"                : "^11.0.0",
    "typescript"              : "2.6.1",
    "typescript-eslint-parser": "^9.0.0"
  }


ORACLE - Problem understanding NOT EXISTS operator

Question: I ran into a simple bit of code, but I've been wracking my brains ever since.
It's either counter-intuitive, or I'm missing something, either simple or fundamental. No idea.
WITH T1 AS
(
SELECT TO_DATE ('14/11/19', 'DD/MM/YY') as SomeDate FROM DUAL
UNION
SELECT TO_DATE ('28/11/19', 'DD/MM/YY') as SomeDate FROM DUAL
),
T2 AS
(
SELECT TO_DATE ('14/11/19', 'DD/MM/YY') as SomeDate FROM DUAL
UNION
SELECT TO_DATE ('28/11/19', 'DD/MM/YY') as SomeDate FROM DUAL
)
SELECT * FROM T1 WHERE T1.SomeDate >= TO_DATE ('05/11/19','DD/MM/YY')
AND NOT EXISTS
(SELECT 1 FROM T2
WHERE T2.SomeDate >= TO_DATE ('05/11/19','DD/MM/YY')
AND T2.Somedate < T1.Somedate
);

Excluding all other conditions, the basic version does something like the code above.
The subquery returns all rows where SomeDate = 14/11/19 since those are the ones that are greater than the 5th but strictly lower than the 28th.
And Not Exists should evaluate to false when rows are returned.
So by my logic, that means that excluding all rows with 14/11/19, the code above should return 28/11/19.
But it returns '14/11/2019'.
Could someone please explain what I'm missing?
Thank you very much.
Answer: I would write the query like this so I can read it more easily:
WITH T1 AS  (
      SELECT DATE '2019-11-14' as SomeDate FROM DUAL UNION ALL
      SELECT DATE '2019-11-28' as SomeDate FROM DUAL
    ),
    T2 AS (
     SELECT DATE '2019-11-14' as SomeDate FROM DUAL UNION ALL
     SELECT DATE '2019-11-28' as SomeDate FROM DUAL
    )
SELECT *
FROM T1
WHERE T1.SomeDate >= DATE '2019-11-05' AND
      NOT EXISTS (SELECT 1
                  FROM T2
                  WHERE T2.SomeDate >= DATE '2019-11-05'  AND
                        T2.Somedate < T1.Somedate
                 );

I'm not sure where your confusion is.  There are two possibilities for T1.SomeDate, 2019-11-14 and 2019-11-18.
Only the earlier date (2019-11-14) has no rows in T2 that are less than the date.  Hence, NOT EXISTS matches this date.
I suspect that you are confused by the inequality in the subquery.
Comment: Hey Gordon, you're absolutely right, I was basically looking at it upside down. When the value in T1 is 28/11 the subquery returns a row, hence NOT EXISTS evaluates to false. I was hung up on what values are returned by the subquery, instead of what value gets fed. Thank you very much!


What does GEOSGeometry exactly

Question: Sorry it may be absurde but I got confused. I have seen two ways of creating a Polygon.
from django.contrib.gis.geos import GEOSGeometry, LineString, Polygon
1- geometry = GEOSGeometry(Polygon(coordinates, srid=4326))
2- geometry = Polygon(coordinates, srid=4326)

Why is it important to add GEOSGeometry instead of just using the 2) ?
Comment: I'm not sure you need the GEOSGeometry call at all. Polygon is already a subclass of GEOSGeometry.
Comment: ```GEOSGeometry``` is a lower level tool. It allows you to tap in the GEOS engine which powers geometry calculation and geometry data. So? You can handle WKT-B instead of the typical coordinates.
Answer: It seems, that GEOSGeometry() can format text and JSON (etc. compatible formats) in to spesific objects, like Point(), or Polygon().
So you don't need to use GEOSGeometry(), if you can do without.
These two definitions are equal (as far I understand). source
from django.contrib.gis.geos import GEOSGeometry, Point
pnt = Point(954158.1, 4215137.1, srid=32140)
pnt = GEOSGeometry('SRID=32140;POINT(954158.1 4215137.1)')

What does GEOSGeometry exactly


Type of Relation

Question: "is the reciprocal of"...over the set of non-zero real numbers is:
(a) Symmetric
(b) Reflexive
(c) Transitive
(d) Equivalence
I know that it is definitely symmetric, as, in (a, b), if a is the reciprocal of b, then obviously b is the reciprocal of a.
Also, it is not reflexive, as no number can be reciprocal of itself, therefore none of the element is related to itself.
I think this relation should be transitive, because, for a relation to be transitive, if (a, b) belong to R and (b, c) belong to R, then (a, c) should also belong to R. Also, a, b, and c should be distinct. In this relation, we cannot find two pairs of the format (a, b) and (b, c) such that a, b, and c are different. Therefore, the question of proving that (a, c) does not belong to R does not arise. Hence the relation should be transitive. I'm basing this on what I read in one of the answers on this website only that we should think in this manner, "a relation is not transitive only if we can find something which makes it non transitive".
Please help.
Comment: $1$ and $-1$ is the reciprocal of itself. It's "not all" numbers are reciprocal of itself.
Answer: It is not transitive. $2$ is the reciprocal of $\frac 1 2$ and $\frac 1 2$  is the reciprocal of $ 2$ but $2$ is not the reciprocal of $2$.

Type of Relation


Facebook profile details

Question: I have a webform (survey) on my site, some of the fields are personal details (age, name, DOB, etc). I want to actually force the user to login with facebook and pro grammatically obtain those few details from facebook.
Which module(s) would I be most interested in, in achieving?
Answer: Find the drupal facebook module listing on this link
So far I find fb module will be worth starting with.

This set of modules turns Drupal into a platform for developing
  Facebook Applications. This allows you to embed your content and
  features within facebook, or allow facebook users onto your site via
  Facebook Connect.

A quick glance for module description is here.
Answer: There is no module that can do this for you. You would need to make your own according to what fields you want. You would need to use the Facebook SDK and PHP (or Javascript) to query the graph and fill in the details you need.
See https://developers.facebook.com/docs/reference/api/user/ for details on how to get the data.
Comment: I was starting to get that impression as well, as I researched deeper

Facebook profile details


Form added to content in hook_page_build lacks of AJAX

Question: I'm adding a form to the footer using hook_page_build because a want to show it using a popup, so when user launches the popup the form appears inmediatly.
The problem is that the form is not AJAX processed: the submit button hasn't the ajax-processed class so AJAX is not working. But if I render the form using hook_menu and drupal_get_form the form has the ajax-processed class and AJAX is working.
Form code fragment:
  $form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Your Personal Message'),
    '#default_value' => '',
    '#cols' => 50,
    '#rows' => 5,
    '#description' => '',
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send Message'),
    '#ajax' => array(
      'wrapper' => 'myform-wrp',
      'callback' => 'myform_ajax_callback',
    ),
  );

Implementation of hook page build:
function mymodule_page_build(&$page) {

  // Get the current $node
  [...]

  $form = drupal_get_form('mymodule_form', $node);

  $page['footer']['my_form'] = $form;

}

Hook menu that the retrieves a working AJAX form:
function mymodule_menu() {

  $items = array();

  $items['node/%node/mymodule-form'] = array(
    'title' => 'My form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form', 1),
    'access callback' => TRUE,
  );

  return $items;
}

I've tested it with hook_page_alter too.
What can be needed to ajaxify this form? I suppose is something related to adding the form too late...
Answer: The problem is the element's name: submit. In the rendered page there's another form that have the same button name (submit), so the AJAX layer just ofund one of the buttons but not the two.
To fix this just rename the element's name:
 $form['myform-submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send Message'),
    '#ajax' => array(
      'wrapper' => 'myform-wrp',
      'callback' => 'myform_ajax_callback',
    ),
  );


Find the mass of a rod with the given density function

Question: Reviewing for my final. I found this question and decided to do it. Can anyone look over my work and tell me if it's correct?
Find the mass of a rod of length 3 with density function $$p(x)=\frac{x^3}{(x^2+1)^3}$$ where x is the distance from one of the rod's ends.
So here's my work:
$$M=\int_0^3\frac{x^3}{(x^2+1)^3}dx$$
I'm having trouble integrating this, but I have reason to believe it can be done with $$u=x^2+1$$
After you integrate it should be easy to just plug in 3 and 0 to p'(x). Is that the correct way to do it, and how do I integrate that equation?
Comment: You mean linear mass density?
Comment: The question I was given by my professor just states mass of a rod, however I'm guessing she probably meant linear mass density?
Answer: You made the right substitution. $$u=x^2+1\implies du=2xdx$$
$$\int\frac{x^2xdx}{u^3}$$
$$=\frac 1 2\int\frac{u-1}{u^3}du=\frac 1 2\int\frac{1}{u^2}-\frac{1}{u^3}du$$
Can
 you do it now?
Comment: Oh wow, how did I not get that to start with? That definitely helps me integrate, is my method for solving the problem correct though?
Comment: @user133707 It's perfect!
Comment: Thanks, that's a huge help!
Comment: @user133707 Anytime.


Upload video / image on a server (Nodejs without express)

Question: I'm trying to upload a video on a nodejs server thanks to AJAX, here is the current script :
home.ejs :
    <form action="#" method="post" enctype="multipart/form-data">
        <input type="file" name="file" class="file" />
        <input class="submit" type="submit" value="Send" />
    </form>

server.js :
router.matchURL("/server", (req, res, data) => {
    if (req.method === "POST") {
        let writer = fs.createWriteStream("../test.mp4")
        req.pipe(writer)
    }
})

Here router is just my own module who create the HTTP server and the matchURL method execute the callback if the URL is good
The problem is that the video is well uploaded but I can't run it, like if the file was corrupted...
Thanks a lot !
EDIT :

This code works with a txt file, so I don't know where come the problem, maybe the encoding (Even if I tried to change the write encoding to binary and it not worked), I also tried to use an ArrayBuffer but it doesn't worked !

I also tried to upload a 1px * 1px image (So it only take 1 chunk) but it also doesn't work. So the problem is maybe a lose of data but I don't know how to solve it. I noticed a change between original image and the uploaded image : The original image size is 802o and the uploaded image size is 998o, but this kind of changes doesn't appear on txt files
Answer: There is a solution here : https://nodejs.org/en/knowledge/HTTP/servers/how-to-handle-multipart-form-data/
In fact multipart/form-data formular can contains boundary which corrupt the file.
So, we have to use a module which can parse the data (Here it's formidable)
formidable link : https://www.npmjs.com/package/formidable
Here is the solution with AJAX :
home.ejs :
<form action="#" method="post" enctype="multipart/form-data">
    <input type="file" name="file" class="file" />
    <input class="submit" type="submit" value="Send" />
</form>

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method (https://developer.mozilla.org/en-US/docs/Web/API/FormData)

// Function which execute the callback if /upload is called
const formidable = require("formidable")

// Execute the callback if the URL is requested
router.matchURL("/upload", (req, res, data) => {
    if (req.method === "POST") {
        let form = new formidable.IncomingForm()

        // We parse the request to get fields and files
        form.parse(req, (err, fields, files) => {
            if (err) throw err

            res.writeHead(200, {'content-type': 'text/plain'});

            // We write the copy of the video using the path of the temp video file
            let writer = fs.createWriteStream("../video.mp4")
            let reader = fs.createReadStream(files.file.path).pipe(writer)
            writer.on("finish", () => {
                // Once the video uploaded, we delete the temp file
                fs.unlink(files.file.path, err => {
                    if (err) throw err
                })
            })
        })
    }
})


jquery "this" is confusing here

Question: I have a code snippet that's working for my "maps" feature - following is the code:
var latlang = new google.maps.LatLng(myjsonobject[pos].geocode.latitude, myjsonobject[pos].geocode.longitude);

$('#map_canvas').gmap({
    'center': latlang,
    'zoom': 10,
    'disableDefaultUI':false,
    'callback': function() {
        var self = this;
        self
            .addMarker({'position': this.get('map').getCenter() })
            .click(function() {
                self.openInfoWindow({ 'content': address }, this);
            });
    }
});

The variable latlang is provided with the latitude and longitude of a given location. Then, the map_canvas is the div where the Google map is displayed with the latlang as its inputs.
In the callback function, self is a variable assigned with this. This is the place where I am confused. What is this in this context? Can anyone throw some light on getCenter() and the this inside self.openInfoWindow please?
How is the whole code working and showing me the result?
Comment: See: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628. Specifically this is in the context of an onclick handler so check out rule 4. But jQuery can change what `this` is as well so check out jQuery documentation.
Comment: thanks for your response... The code is being used in my HTML5 mobile app where a set of addresses are shown as result and when I click on an address, the map is shown for that address. All this is working only for first time (first address click).i.e. if I select a new address next, the map is still showing the old address and its position :(
Answer: 'this' is context to $('#map_canvas')
The whole DOM tree of map_canvas is stored into 'this' variable
Comment: thanks for your response...
All this is working fine only for the first time. The code is being used in my HTML5 mobile app where a set of addresses are shown as result and when I click on an address, the map is shown for that address.
All this is working only for first time (first address click).i.e. if I select a new address next, the map is still showing the old address and its position :(
Answer: $('#map_canvas').gmap({'center': latlang, 'zoom': 10, 'disableDefaultUI':false,
'callback': function(   event   ) {
           var self = this;
...

as you capture the event in that function this will (always?!) be equivalent to
$(event.currentTarget)[0]

Answer: Javascript has function scope.
This actually means that inside each function this refers to a different thing.
If you want to access a certain scope in another function, a common approach is to store the desired context (this) in another variable (such as self because it's naming is suggestive of it's value).
Here's a simple demo that might clear this:
function a() {
    this.someValue = 'some value';
    var self = this;

    function b() {
        alert(this.someValue); // it's undefined, because "this"
                               // refers to function b's context

        alert(self.someValue); // this works as expected, because self
                               // is a reference to a's context
    }

    // call b(), to actually test this
    b();
}
a();

To simplify your code and make it more readable, let's separate the functions and name them.
So your old code:
$('#map_canvas').gmap({
    'center': latlang,
    'zoom': 10,
    'disableDefaultUI':false,
    'callback': function() {
        var self = this;
        self
            .addMarker({'position': this.get('map').getCenter() })
            .click(function() {
                self.openInfoWindow({ 'content': address }, this);
            });
    }
});

becomes:
$('#map_canvas').gmap({
    'center': latlang,
    'zoom': 10,
    'disableDefaultUI':false,
    'callback': callback
});

function callback() {
    var self = this;

    this
        .addMarker({'position': this.get('map').getCenter() })
        .click(onClick);
}

function onClick() {
    // self is callback's context
    // which actually points to the map instance

    // this points to the context of the click function,
    // which actually is the dom element that was clicked on,
    // which is the marker
    self.openInfoWindow({ 'content': address }, this);
}

Comment: thanks for your response... The code is being used in my HTML5 mobile app where a set of addresses are shown as result and when I click on an address, the map is shown for that address. All this is working only for first time (first address click).i.e. if I select a new address next, the map is still showing the old address and its position :(
Comment: in my code, when I alert "self" it says [object, object]. The "latlang" is being updated fine (with any new address' lat, lang coordinates) but that's not reflecting in the "addmarker"...
It always shows my first address! :(
Comment: Please see the full (updated) answer. Maybe it will help you understand the issue better :)
Comment: Sure. this should really help. I was going through a similar post here - http://stackoverflow.com/questions/7701077/add-marker-function-with-google-maps-api
Answer: 'this' is a jQuery object when you are inside your own jQuery functions.

jquery "this" is confusing here


Is the quotient of an infinite product of fields by the direct sum injective?

Question: Let $k$ be any field and consider $R=\prod_{\mathbb{N}}k$ the product of copies of $k$ indexed over the natural numbers. The direct sum $\sum_{\mathbb{N}}k=I$ is an ideal of $R$, hence we can form the quotient $R/I$. My question is the following: is the ring $R/I$ injective? Since $R\rightarrow R/I$ is a flat ring homomorphism, $R/I$ being injective as $R$-module is equivalent to being self-injective. I believe that these should be a result in the literature pointing toward this, yet I did not manage to find anything useful.
I am also interested in this generalization: let $S$ be a commutative,  von Neumann regular ring which is not semi-artinian (i.e. $\text{Spec}(S)$ is not scattered) and consider $J$ to be the intersection of all maximal ideals of $S$ which are belong to the perfect subset of $\text{Spec}(S)$. Is the ring $S/J$ injective?
Observe that in the case of $R$ the Zariski spectrum is homeomorphic to $\beta \mathbb{N}$, the set of ultrafilters on $\mathbb{N}$ with the Stone topology. This space consists in its isolated points, corresponding to the principal ultrafilters, and its perfect subset whose points correspond to the non-principal ultrafilters. The fact that $I$ coincides with the intersection of all ideals associated to non-principal ultrafilters follows from the fact that the cofinite filter coincides with the intersection of all non-principal ultrafilters. See this old question: cofinite filter is intersection of all non-principal ultrafilter.
Answer: The main theorem of
Osofsky, B. L., Noninjective cyclic modules, Proc. Am. Math. Soc. 19, 1383-1384 (1968)
implies that $\prod_{\mathbb{N}}k/\sum_{\mathbb{N}}k$ is not an injective $\prod_{\mathbb{N}}k$-module.


Existence of operator with certain properties on a Banach space

Question: I ran across this question, and was a little puzzled by it. I neither know how to solve it, nor its meaning:
Let $X$ be a Banach space, and let $A,B$ be bounded linear operators on $X$ such that $A$ is injective. Prove there is a bounded linear operator $C$ on $X$ with $B=AC$ if and only if $\rm{Range}(B) \subset \rm{Range} (A)$.
At the point in this book where the problem is presented, one has learned the open mapping theorem, closed graph theorem, bounded inverse theorem, and the Hanh-Banach theorem. I tried a few things with the OMT and got nowhere.
But what does this actually mean? Why would one care about this?
And how do you solve it?
Answer: If there exists $C$ with $B=AC$, then $\operatorname{Range}(B)=\operatorname{Range}(AC)=A(C(X))\subseteq A(X)=\operatorname{Range}(A)$.
For the converse, we use the closed graph theorem. Suppose $\operatorname{Range}(B)\subseteq\operatorname{Range}(A)$. Note that $C=A^{-1}B$ is well-defined as a linear operator, and it satisfies $B=AC$ (in fact, it is the only such option), o we simply need to prove that $A^{-1}B:X\to X$ is continuous, which from the closed graph theorem reduces to the following: Suppose $x_n\to 0$ and $A^{-1}Bx_n\to p$, for some $p\in X$, and we need to show that $p=0$. Indeed, $A^{-1}Bx_n\to p$ implies $Bx_n\to Ap$, since $A$ is continuous, but $x_n\to 0$ implies $Bx_n\to B0=0$, since $B$ is continuous, so $Ap=0$ and hence $p=0$ because $A$ is injective.
As for "why would one care": This is a generalization of the bounded inverse theorem (which should have its importance clear). Let's deduce it from this exercise: Suppose $A:X\to X$ is bijective and continuous. Take $B=\operatorname{Id}_X$. Then $\operatorname{Range}(B)\subseteq\operatorname{Range}(A)$, so there exists $C$ bounded (and linear) with $\operatorname{Id}_X=B=AC$. The only possibility is $C=A^{-1}$, which is therefore bounded.
Comment: Aha...I hadn't thought of it this way (though I apparently read the problem wrong). Thanks!


Excel formatação Condicional

Question: Tenho uma duvida e gostaria de saber se é possível uma vez que não estou a conseguir.
Eu tenho uma célula que me mostra um resultado (Célula D4)
E quero que com o resultado ele me sublinhe dois linhas.
Exemplo:
Se a celula D4 for igual a "G4" Sublinha a linha X
Se a celula D4 for igual a "G6" Sublinha a linha Y
Eu coloquei esta regra e não está a funcionar:
=SE($D$4="G$";"")
Comment: Acho não seja possível usando fórmulas, tu teria que construir uma macro em VBA.
Comment: construir uma macro só para mostrar uns dados a sublinhar?
Comment: Não queria usar Macro por nunca ter estudado isso. Mas estou a ver que so tenho essa forma.
Answer: Você pode fazer duas regras de formatação condicional separadas:

No seu caso, substitua =$A$3<>1 e =$A$3=1 por =$D$4=$G$4 e =$D$4=$G$6

Excel formatação Condicional


Curse of dimensionality: why is it a problem that most points are near the edge?

Question: ESL, p. 42 says:

Hence most data points are closer to the boundary of the sample space
  than to any other data point. The reason that this presents a problem
  is that prediction is much more difficult near the edges of the
  training sample. One must extrapolate from neighboring sample points
  rather than interpolate between them.

I understand that extrapolation is harder than interpolation. And I understand that if we choose a point to predict and it happens to be near the edge of the sample space, we are more likely to have to extrapolate.
But a large part of the training data set is also near the edge. And the more training points nearby, the better chance we have to interpolate instead of extrapolate. Doesn't the fact that many training points are near the edge reduce or even eliminate the problem that many points we want to predict for are near the edge?
Answer: The problem is that "the edge" is not just one place in $d$-dimensional space. "The edge" is a big part of your volume, and the volume of "the edge" grows very quickly. Thus, even if more and more training data points lie near "the edge", the density of training data will still decrease very quickly as $d$ increases.
As a little visualization, consider a two-dimensional square with sides of length 2, and inscribe a circle of radius 1 within it. Let's call the area of the square outside the circle "the edge". "The edge" has area $\frac{4-\pi}{4}$, and it consists of four disjoint pieces.
Now consider the same situation in three dimensions. Then in four. And so forth. You can show that the volume of "the edge" will take up as much of the volume of the $d$-dimensional cube as we want, if we just increase $d$ sufficiently. "The edge" is not disjoint any more for $d\geq 3$, but your training data will get lost in it.
Alternatively, draw $n$ points randomly and uniformly distributed in the $d$-dimensional unit cube, for increasing $d$, and check on the average pairwise distance. You will see that this distance increases quickly with $d$. How quickly will you need to increase $n$ with $d$ for this average distance to stay constant? Very quickly indeed.
Bottom line: "the more training points nearby" is where your argument goes astray. In high dimensions, there are very few points nearby.
Answer:
And the more training points nearby

max's answer touches on the primary point but I just wanted to point out that the above quote was your erroring assumption, give some more intuition about how points all end up on the edge and point out how this causes sparsity issues. The erroring assumption is that the edge is small. It is not. It is massive in high dimensions. The proportion of volume within the 0.1% of the radius that is closest to the surface of the unit ball goes to 100% exponentially as the number of dimensions grows.
An algebraic/probabilistic way to look at is that to be in the middle you need to have low values for all dimensions simultaneously. To be at the edge you just need to have a high value for one dimension. As the number of dimensions grow the chances of at last one dimension having a high value goes to 100%. If each dimension could only have values of 0 or 1 there would still be  possible values in n dimensions. And you consider all of those as regions if we allow continuous values.
This creates issues with sparsity. Most regions of the space don't exist in your training dataset. If you choose points at random almost no points will be near your training dataset. But a few of those regions will be in your test dataset.


Value from @Parameter

Question: Im trying to do this
SELECT     CAST(date AS datetime) + CAST(time AS datetime) AS NewDT, variable, value
FROM         batch
WHERE     (NewDT <= @BatchStartDate)

But i get the error "Invalid colum name NewDT"
The problem is that date and time is in two colums in the database.
Comment: I added `sql` tag, but wich RDBMS are you using?
Answer: Guessing you are using MS SQL Server. You can't reference an alias on the WHERE clause, you should use the full CAST(date AS datetime) + CAST(time AS datetime) so it would be:
SELECT CAST(date AS datetime) + CAST(time AS datetime) AS NewDT, variable, value
  FROM batch
 WHERE (CAST(date AS datetime) + CAST(time AS datetime) <= @BatchStartDate)

Answer: (Also guessing that you use SQL Server)
You cannot use an alias in the where clause, so you can use the whole expression (as in Yaroslav's answer) or you can wrap the original select as a subquery, like this:
select * from
(
   SELECT CAST(date AS datetime) + CAST(time AS datetime) AS NewDT, variable, value
   FROM batch
)
WHERE NewDT <= @BatchStartDate

Value from @Parameter


Compare slopes of multiple time-series but only one dependent variable

Question: I am looking to determine if there are regional differences in single common measurement across time, using R.
The data is of annual frequency for 51 years (1961 to 2011) for seven regions.
The variable measured is per capita emissions.
Plotting the data visually suggests that not all regions exhibit the same trend (some appear constant, others increase/decrease while yet others look like their trends may be increasing - getting steeper).
What statistical test(s) should be used to determine if the slopes of these regional time-series trends are indeed different from each other?  The measurements are likely not independent of each other within Region (behaviour is sticky), but we might presume that they are between Region...
If it helps, my dataset (in wide mts R format) is below.
Thanks!
     Year    Europe Indus.Asia    Lat.Am NAfr.WCAsia NAm.Oceania       SSA  SSE.Asia
1961    1 0.3330287 0.08342768 0.2988371   0.1970832   0.6036110 0.2771904 0.1491002
1962    2 0.3399356 0.08739431 0.3050448   0.1957801   0.6072381 0.2774883 0.1519685
1963    3 0.3497737 0.09234678 0.3064860   0.1967561   0.6188448 0.2808335 0.1513993
1964    4 0.3506815 0.09567696 0.2994094   0.1964786   0.6400042 0.2846973 0.1527038
1965    5 0.3517937 0.10081783 0.2971080   0.1959702   0.6371043 0.2882228 0.1495615
1966    6 0.3655056 0.10409945 0.3022665   0.1959077   0.6513748 0.2845789 0.1506697
1967    7 0.3751051 0.10359561 0.3085563   0.1962348   0.6527076 0.2934402 0.1529256
1968    8 0.3847365 0.10244660 0.3181694   0.2015809   0.6682721 0.2886078 0.1558793
1969    9 0.3838484 0.10135446 0.3214369   0.2004127   0.6670239 0.2939225 0.1563187
1970   10 0.3936929 0.10550931 0.3190227   0.2011312   0.6736572 0.3029824 0.1582456
1971   11 0.3911788 0.10782480 0.3005018   0.2061686   0.6810935 0.3015153 0.1555705
1972   12 0.3888467 0.10796591 0.2995851   0.2042940   0.6862982 0.2964260 0.1543937
1973   13 0.4042535 0.11137749 0.2966723   0.1998279   0.6666261 0.2920530 0.1576311
1974   14 0.4114716 0.11116291 0.3081587   0.2041539   0.6770527 0.2975302 0.1573771
1975   15 0.4088594 0.11213601 0.3195318   0.2093902   0.6990652 0.2992955 0.1605997
1976   16 0.4124370 0.11137034 0.3329371   0.2110148   0.7338768 0.2997060 0.1594188
1977   17 0.4125538 0.11234512 0.3337914   0.2126674   0.7226528 0.3039447 0.1620297
1978   18 0.4198469 0.11851035 0.3397066   0.2194563   0.7101107 0.3064783 0.1637319
1979   19 0.4232864 0.12057965 0.3380299   0.2209554   0.6810473 0.3040716 0.1602157
1980   20 0.4218926 0.12148329 0.3505814   0.2280130   0.6721993 0.3029758 0.1621418
1981   21 0.4172976 0.12375568 0.3494269   0.2311256   0.6807635 0.3051217 0.1660875
1982   22 0.4223521 0.13089340 0.3373198   0.2317372   0.6819238 0.3058660 0.1661771
1983   23 0.4261567 0.13512950 0.3316797   0.2311859   0.6781721 0.2947787 0.1713330
1984   24 0.4327464 0.13905190 0.3364816   0.2352414   0.6853792 0.2891287 0.1726075
1985   25 0.4327769 0.14014033 0.3448070   0.2415244   0.6955721 0.2943122 0.1725749
1986   26 0.4384473 0.14360094 0.3596229   0.2449454   0.6966196 0.2941324 0.1753695
1987   27 0.4409924 0.14773305 0.3481004   0.2412722   0.6998172 0.2942876 0.1750773
1988   28 0.4418265 0.14960314 0.3485329   0.2437859   0.6900106 0.2968633 0.1778406
1989   29 0.4447421 0.15081434 0.3546949   0.2384495   0.6866791 0.3024815 0.1810750
1990   30 0.4304627 0.15639769 0.3570101   0.2413544   0.6841630 0.3049107 0.1816244
1991   31 0.4142964 0.15557267 0.3595744   0.2363494   0.6824669 0.3054693 0.1803897
1992   32 0.4099102 0.16369167 0.3620947   0.2492692   0.6920663 0.3002969 0.1849306
1993   33 0.3970080 0.17536967 0.3649345   0.2463124   0.6811545 0.3011804 0.1872747
1994   34 0.3827137 0.18347220 0.3754718   0.2482677   0.7008975 0.2940523 0.1884567
1995   35 0.3823503 0.19545531 0.3861121   0.2491750   0.6987574 0.2967518 0.1917361
1996   36 0.3844043 0.20075046 0.3952523   0.2507883   0.6990538 0.3023953 0.1937828
1997   37 0.3812992 0.20906418 0.3934072   0.2484025   0.6972838 0.3041432 0.1930203
1998   38 0.3798254 0.21622077 0.3870048   0.2545955   0.7007982 0.3047103 0.1946998
1999   39 0.3773650 0.22288219 0.4024141   0.2563572   0.7167966 0.3103474 0.1975481
2000   40 0.3792981 0.23270136 0.4036371   0.2594711   0.7132213 0.3080760 0.1984123
2001   41 0.3740450 0.23275714 0.4023274   0.2531616   0.7031493 0.3120869 0.1994249
2002   42 0.3778445 0.23755244 0.4036734   0.2609872   0.7121247 0.3163197 0.1958088
2003   43 0.3830538 0.24061360 0.4048166   0.2666359   0.7032099 0.3208936 0.2019877
2004   44 0.3879519 0.24239370 0.4106120   0.2687964   0.7123248 0.3294516 0.2035080
2005   45 0.3927197 0.24813350 0.4215930   0.2742297   0.7061623 0.3348791 0.2080581
2006   46 0.3947798 0.25229643 0.4313497   0.2810117   0.7046364 0.3409603 0.2142793
2007   47 0.3980420 0.25871431 0.4414887   0.2843196   0.7053338 0.3409665 0.2222694
2008   48 0.3975002 0.26601418 0.4477263   0.2842824   0.6871963 0.3479022 0.2245092
2009   49 0.4016810 0.27165581 0.4399089   0.2869924   0.6803058 0.3448820 0.2265546
2010   50 0.3940681 0.27902452 0.4439119   0.2939435   0.6725924 0.3563978 0.2337000
2011   51 0.3887767 0.28328307 0.4481589   0.3020620   0.6633836 0.3586240 0.2358033

Comment: What do you think about my answer?
Answer: One simple idea (perhaps too simple) would be to assume the time trends are linear in all the cases and then compare the slope coefficients.
Suppose you only had two series and three years (rather than seven series and 51 years), hence, $x=(x_1,x_2,x_3)$ and $y=(y_1,y_2,y_3)$. Then you could build the following variables:
$z=(x,y)=(x_1,x_2,x_3,y_1,y_2,y_3)$,
$\text{intercept}_1=(1,1,1,0,0,0)$,
$\text{intercept}_2=(0,0,0,1,1,1)$,
$\text{time}_1=(1,2,3,0,0,0)$,
$\text{time}_2=(0,0,0,1,2,3)$
and estimate the following model
$$ z = \beta_{0,1} \text{intercept}_1 + \beta_{0,2} \text{intercept}_2 + \beta_{1,1} \text{time}_1 + \beta_{1,2} \text{time}_2 + \varepsilon $$
and test for $\beta_{1,1}=\beta_{1,2}$.


How do I change text every time I click the button?

Question: I'm clicking a button to make a call to an API to get a random fact and length. This is then displayed in two input fields which works. I'm struggling with how to change the text in the input fields to the new fact and length from the API when the button is clicked again. I know it is something simple but can't seem to find the solution. Any help would be appreciated.
 <template>
    <form>

            <input type="text" id="idFact" v-model="facts">

            <input type="text" id="idLength" v-model="lengths">

            <button v-on:click="callAPI" type="button">Call</button>

    </form>
</template>

Thanks
Answer: Invoke the getData method inside the click handler callAPI, and remove the call from created hook in order to avoid redundant calls:


Ubuntu uninstall elasticsearch

Question: I installed elasticsearch.90.7 with a deb file in ubuntu.
I tried to uninstall elasticsearch.90.7 with this command:
sudo apt-get --purge autoremove elasticsearch

And then I downloaded elasticsearch-1.6.0.deb to install elasticsearch 1.6.
When I run this command to install elasticsearch 1.6 by deb file:
dpkg -i elasticsearch-1.6.0.deb

It shows me this:
Selecting previously unselected package elasticsearch.
(Reading database ... 89826 files and directories currently installed.)
Preparing to unpack elasticsearch-1.6.0.deb ...
Creating elasticsearch group... OK
Creating elasticsearch user... OK
Unpacking elasticsearch (1.6.0) ...
Setting up elasticsearch (1.6.0) ...
Processing triggers for ureadahead (0.100.0-16) ...

When I start elasticsearch with service elasticsearch start it's starting, but when i run this command: curl  http://localhost:9200
It shows this error:
curl: (7) Failed to connect to localhost port 9200: Connection refused

I think elasticsearch is not installed properly. I want know what I should do to install elasticsearch properly.
Comment: Please post the output of "lsof -Pni | grep 9200"  (or netstat equivalent).
Comment: @Jeroen i run this `lsof -Pni | grep 9200` its show nothing.
Comment: Have you checked the process tree to see if it's actually running, or the ES to figure out what's going on?
Comment: @GregL i checked process there isn't any elasticsearch process.
Comment: Have you checked the log files?
Comment: Yeah... that ^.
Answer: (1) Remove previous versions of ElasticSearch:
sudo apt-get --purge autoremove elasticsearch

(2) Remove the ElasticSearch directories:
sudo rm -rf /var/lib/elasticsearch/
sudo rm -rf /etc/elasticsearch

(3) Install ElasticSearch 1.6:
sudo dpkg -i elasticsearch-1.6.0.deb

(4) Start the service:
sudo service elasticsearch start

(5) Test if it works:
sudo service elasticsearch status
curl -XGET "http://localhost:9200/_cluster/health?pretty=true"
curl "localhost:9200/_nodes/settings?pretty=true"

Comment: @Abbas: Try Oracle Java installation (no OpenJDK).
Comment: @ArturBarseghyan Thank You very much. It solve the issue. Now I install the java by following http://ubuntuhandbook.org/index.php/2018/05/install-oracle-java-jdk-8-10-ubuntu-18-04/ and it is working.
Comment: Try

```
sudo /etc/init.d/elasticsearch start
```
Comment: I get `elasticsearch: unrecognized service` after installing the `.deb` file and trying to run `sudo service elasticsearch start`.
Comment: I am using elasticsearch version 5.2.0. And I follow your steps and now when I check log I am getting the error. Active: failed (Result: exit-code) since Wed 2018-09-19 20:39:29
     Docs: http://www.elastic.co
  Process: 16709 ExecStart=/usr/share/elasticsearch/bin/elasticsearch -p ${PID_DIR}/elasticsearch.pid --quiet -Edefault.path.logs=${LOG_DIR} -Edefault.path.data=${DATA_DIR} -Edefault.path.conf=${CONF_DIR}
  Process: 16708 ExecStartPre=/usr/share/elasticsearch/bin/elasticsearch-systemd-pre-exec (code=exited, status=0/SUCCESS)
 Main PID: 16709 (code=exited, status=1/FAILURE)
Comment: @Abbas: How did you install Elasticsearch 5.2.0?
Comment: I download the 5.2.0 deb file from https://www.elastic.co/downloads/past-releases/elasticsearch-5-2-0 and then follow the steps you mentioned in the post.
Comment: I have set the JAVA_HOME at /etc/environment like this JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64. Do you think is it ok or not?
Comment: When I check my log file at /var/log/elasticsearh/elasticsearch.log I found [o.e.b.Bootstrap          ] Exception
java.lang.IllegalStateException: No match found
        at java.util.regex.Matcher.group(Matcher.java:645) ~[?:?]
Answer: Instead of starting elasticsearch with service elasticsearch start, try to start it with the following command:
sudo /usr/share/elasticsearch/bin/elasticsearch --default.config=/etc/elasticsearch/elasticsearch.yml --default.path.home=/usr/share/elasticsearch --default.path.logs=/var/log/elasticsearch --default.path.data=/var/lib/elasticsearch --default.path.work=/tmp/elasticsearch --default.path.conf=/etc/elasticsearch

And see if the output of the application is giving you any advice on what's going wrong ...
Posting the output here may help us to find the origin of the problem.
Answer: It appears you have installed/updated ElasticSearch correctly and it appears to be running. You needn't re-install it.
It may be your CURL command is incomplete. Try this instead:
curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

You should receive a json response which reads like this:
{
  "cluster_name" : "your_clusters_name",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 1,
  "number_of_data_nodes" : 1,
  "active_primary_shards" : 0,
  "active_shards" : 0,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0
}

Comment: I don't see your explanation of why he gets a Connection refused on port 9200. This answer is irrelevant without it.
Answer: "sudo service elastic search start
elasticsearch: unrecognised service"
I had a corrupt ElasticSearch installation.
I deleted and re-installed ElasticSearch as mentioned in (Remove previous versions of ElasticSearch:)
Problem solved, good luck

Ubuntu uninstall elasticsearch


"Let random variables $X_1,\dots, X_n$ be a iid random sample from $f(x)$" - what does it mean?

Question: In books it is often written, Let random variables $X_1,\dots, X_n$ be a iid random sample from $f(x)$. What does it mean?
Are $X_1,X_2,\dots,X_n$ different values of one random variable $X$ which follows distribution $f(x)$, or all of them are different random variables?
If I have a dataset of 1000 persons' height (normally distributed) and $X$ is height of an individual and if I take a random sample then what are $X_1,X_2,\dots,X_n$? What does the term iid means?
Comment: A random sample from a finite population is not an iid sample unless you specify that the sampling is _with replacement_ meaning (among other things) that it is possible to pick the same person more than once. In the standard meaning of "the phrase", $X_1, X_2, \ldots, X_n$ would the heights of 10 different people from the set of 1000 people whose heights have been recorded in your dataset.
Comment: Some textbooks do write realized values as for example $P(X = x_1), P(X = x_2), ... $.
Comment: I am little bit confused, if X1,X2,…,Xn are realized value of a rv X~f(x) then how X1,X2,…,Xn are called random variable?
Comment: The second paragraph of your question asks about something that is different from the query in the third paragraph.
Comment: I am a little bit confused here regarding the second paragraph.. If X1,X2,…,Xn are realized value of a random variable X taken as a random sample from a population which have distribution f(x), then why books write these realized values as random variable X1,X2,…,Xn instead of x1,x2,...,xn (realized value)? how the realized value are random variable?
Answer: That's correct, $X_1, X_2, ..., X_n$ are $n$ independent and identically distributed (i.i.d.) values of the same variable drawn from the same distribution $f(x)$.
The term "i.i.d." means the values of $X$ are completely independent (the probability that $X$ assumes a particular value for record $i$ is unrelated to the values of $X$ for other records) and all values of $X$ are random pulls from the same distribution (e.g., the normal distribution with a given mean and variance).
Comment: It seems like one perhaps implicit issue raised by the OP is whether $X_i$ are *random variables* from a given distribution, or samples of a common random variable $X$.
Comment: @AntoniParellada - Yes the notation can be confusing. Sometimes $X_1, X_2, ...$ refers to completely separate variables (e.g., height, weight, etc.) from different distributions while in other cases $X_1, X_2, ...$ are specific values of a single random variable (and perhaps ought to be written as $X_1=x_1, X_2=x_2, ...$). One clue is the notation: $X_1, X_2, ..., X_k$ typically refers to $k$ different random variables while $X_1, X_2, ..., X_n$ refers to $n$ values of the same random variable.
Comment: RobertF I am now thoroughly confused. How can I tell whether $X_1,X_2,X_3$ refers to $k=3$ different random variables or $n=3$ values of the same random variable?
Comment: @DilipSarwate - I look at context. For example, if you're reading a textbook or paper about multiple regression then it should be clearly stated that $X_1, X_2, ..., X_k$ are separate predictor variables. If you're studying sampling distributions with/without replacement from a univariate distribution (like height of an individual) then it ought to be clearly specified that $X_1, X_2, ..., X_n$ are random variables from the same distribution which may or may not be i.i.d. depending on whether you're sampling with/without replacement.
Comment: @RobertF Oh, come on! That is a nonsensical response. You said "One clue is the notation: $X_1, X_2, ..., X_k$ typically refers to $k$ different random variables while $X_1, X_2, ..., X_n$ refers to $n$ values of the same random variables."  So I ask you again: How can I tell whether $X_1,X_2,X_3$ refers to $k=3$ different random variables or $n=3$ values of the same random variable? I have used _your_ notation exactly. So, tell us, pretty please: what is the clue that your notation is providing to help us to distinguish between the two cases?
Comment: @DilipSarwate - $n$ typically refers to the number of records in a dataset, while $k$ often refers to the number of variables. If all you have is $X_1, X_2, X_3$ then there's nothing in the notation to tell the difference except context.


Probability of observing sequence Markov model

Question: I have been trying to understand hidden Markov models with observational probability but I often find myself confused. I have discussed with my tutor for further help however, he is often rude and does not help and so I have decided to turn to the community.
I am trying to determine the probability of observing the following sequences:
AABGA, ABBGT.
From what I understand, you would first need to find probabilities of the sequence occurring without observations and then begin looking for probabilities of the sequence with observational probability. I think I am often confused on questions like this because I do not know how I could check my answer to ensure I have obtained all the possible probabilities of the sequence. Would appreciate on insight into whether my approach was correct and if I have correctly obtained the probability of observing the sequences. Thanks in advance.

States with their initial probabilities
$A(0.3) $
$A(0.4) $
$B(0.2) $
$G(0.0) $
$T(0.1) $
Markov model - Updated based on suggestion:

AABGA
$A,A,A,G,G = 0.3 * 0.7 * 0.1 * 0.5 * 0.2 = 0.21%$
$A,A,A,A,A = 0.3 * 0.7 * 0.1 * 0.3 * 0.5 = 0.315%$
$A,A,A,A,A = 0.3 * 0.7 * 0.1 * 0.3 * 0.1 = 0.063%$
$A,A,A,G,G = 0.4 * 0.5 * 0.1 * 0.5 * 0.2 = 0.2%$
$A,A,A,G,G = 0.4 * 0.1 * 0.1 * 0.5 * 0.2 = 0.04%$
$A,A,A,A,A = 0.4 * 0.1 * 0.1 * 0.3 * 0.5 = 0.06%$
$A,A,A,A,A = 0.4 * 0.1 * 0.1 * 0.3 * 0.1 = 0.012%$
$P(AABGA)$ = 0.21% + 0.315% + 0.063% + 0.2% + 0.04% + 0.06% + 0.012% = $0.9%$
ABBGT
$A,A,A,G,G = 0.4 * 0.1 * 0.1 * 0.5 * 0.2 = 0.04%$
$A,A,A,A,T = 0.4 * 0.1 * 0.1 * 0.3 * 0.5 = 0.06%$
$P(ABBGT)$ = 0.04% + 0.06% = $0.1%$
Comment: Looks like a hidden Markov model.
Answer: Not yet an answer, but too long for the comments section.
Updated in light of added diagram
It would appear from the added diagram that the underlying Markov chain has $5$ states $\ 1,2,\dots,5\ $, with transition matrix
$$
\pmatrix{0.2&0.7&0&0.1&0\\
0&0&0.5&0.5&0\\
0.7&0&0.3&0&0\\
0&0&0&0.2&0.8\\
0.4&0.2&0.4&0&0}\ ,
$$
and initial state probabilities $\ \pmatrix{0.3&\color{red}{0.4}&0.1&0&0.2}\ $.
It's not clear what the emission probabilities are, however.  Is $\ P(A|1)=1.0\ $ or is it $\ 0\ $, for instance? It can't be both, but you've given both as its value.  The same inconsistency occurs for $\ P(A|i)\ $ for all the other states.  The labels on the diagram seem to suggest that the output is always $\ A\ $ whenever the state is $\ 1\ $ or $\ 2\ $ and always $\ T, G\ $ or $\ B\ $ whenever the state is $\ 3,4\ $ or $\ 5\ $  respectively.  But if that were the case, what would be the meaning of the quantities $\ P(A|i), P(B|i)\ $ etc. given in the question?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/135581/discussion-on-answer-by-lonza-leggiera-probability-of-observing-sequence-markov).


Is there a way to submit values not contained in input fields as part of a form in ASP.NET?

Question: I want to modify values in the model used in a form, but I don't want to allow all values to be modified. For example (sudo code)
Model: User
Id : Guid
Name : string
Address : string
Username : string

View
<form action="Save">
  <input value=Model.Name />
  <input value=Model.Address />
  <input value=Model.Username />
  <button type="submit">Submit</button>
</form>

From this I want to be able to have the Save method take in a User model as the parameter and contain the Id of the original model, is this possible to do in ASP.NET?
Controller
public IActionResult Save(User model) {
   // Save model changes based on original Id value
   return View(model);
}

Answer: You have a couple of ways to achieve that, being the best ones done in the server side:
Lets asume we have a model like this:
1- You could bind the specific properties you want to be able to change it would look something like this:
public class Person
{
    public string Id { get; set; }
    public string Description { get; set; }
    public string Name{ get; set; }
    public int Age { get; set; }
}

    public async Task<IActionResult> Edit([Bind("Id,Name,Description")] YourModel model)
    {
       //Here only the properties Id, Name and Description would be populated
       //it wont matter if there are any other properties they will be ignored
    }

2 - Another way would be to manually choose which properties to change so back to the Model
   public async Task<IActionResult> Edit(YourModel model)
    {
      YourModel original; //Get it from database!
      original.Name = model.Name;
      //Here save changes and it will only modify the name
    }

3 - Another way would be to explicitly tell your ORM if using any that you dont want to change that particular property
On the frontend you can achieve this by disabling those properties, making them readonly but this not a good approach since the user can change it from the inspector.
Comment: Hi Nalnpir, thanks for the answer to this, I completely agree about controlling this from the backend, I think you missunderstand my intention by the question however, my concern is how I get the `YourModel` to populate with the Id of the origional model? Since the values I'm submitting from the Form don't include an Id property?

I guess in the "Edit" method I can pull together the Form results and the model values I have stored?
Comment: `` unless the ID is also a route / action parameter.
Comment: That makes sense as an option, it's not a route parameter no, would this not just be adding unnecessary html though? I mean if it's the only solution then no it's not I guess :)
Comment: No, its not adding unnecesary html, like you can perhaps do some custom controller like [HttpGet("/api/v1/edit/{Id}")] so you can have an Id parameter that comes from the url so your action would need to target that. But there is no other way. Take into account that thise approaches need to be verified by the backend since the user can change the hidden value and also the route action


Visual Studio pre-increment bug

Question: Found a weird behaviur on my code.
Code:
char foo[] = {64, 1};
int i = 0;

char c = ((foo[i]) | (foo[(++i)]));

cout << "Text: " << c << " " << (int)c << endl;

Results:
Text: ☺ 1

I was specting "Text: A 1" instead of "Text: ☺ 1". For some reason the compiler is ignoring the "| foo[++i]" part.
Well the solution for this is quite simple, it would just take another line, but what I'm interested in is to know if this is a compiler bug or just c++ being weird.
Tested in VC10 and VC11.
edit: Added () to the code, still the same behaviou.
Comment: The order of the evaluations in `foo[i] | foo[++i]` is not specified. There are many questions about similar problems, e.g. [Undefined behavior and sequence points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points). In your particular case, I guess `i` is first incremented (`++i`), and then you get `c = foo[1] | foo[1]`, which is `c = 1 | 1`, i.e. `c = 1`. Note that relying on unsequenced operations does not only make results hard to predict, but can cause undefined behaviour.
Comment: @TheVTM Brackets don't change the situation. You still have two arguments to the `|`-operator, and the order of evaluation for operator arguments (as well as function arguments) isn't specified by the Standard.
Comment: @jogojapan @jprofitt its not an eveluation ordening problem, because the result is the same when I do something like this `char c = ((foo[i]) | (foo[(++i)]));`
Answer: The order of expression(not well-formed formula) is not documented in C++ standard. It depend on compiler behaviour. For example:
push(pop() * pop());

C++ doesn't document the order of calling pop(). So results are different in MSVC and GCC. You should call foo[i] and foo[++i] step-by-step.

Visual Studio pre-increment bug


String interpolation in graphQL query

Question: I am new to Gatsby and its graphQL query system to retrieve assets. I have a working component Image that fetches an image and displays it. I want to have the name of the image customizable but I can't figure out how to dit.
Here is the working component:
const Image = () => (
  <StaticQuery
    query={graphql`
      query {
        // fetching the image gatsby-astronaut.png
        placeholderImage: file(relativePath: { eq: "gatsby-astronaut.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => }
  />
);

And here is what I tried to have a customizable image:
const Image = ({ imgName }: { imgName: string }) => (
  <StaticQuery
    query={graphql`
      query {
        // fetching the image imgName
        placeholderImage: file(relativePath: { eq: "${imgName}.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => }
  />
);

But it raises the following error for the query:
Expected 1 arguments, but got 2.ts(2554)
How can I have a customizable image name?
Answer: Here is the easy way I ran into:
const Image = props => {
  const data = useStaticQuery(graphql`
    query {
      firstImg: file(relativePath: { eq: "firstImg.png" }) {
        childImageSharp {
          fluid(maxWidth: 300) {
            ...GatsbyImageSharpFluid
          }
        }
      }

      secondImg: file(
        relativePath: { eq: "secondImg.png" }
      ) {
        childImageSharp {
          fluid(maxWidth: 300) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  `)

  switch (props.name) {
    case "firstImg":
      return
    case "secondImg":
      return
    default:
      return
  }
}

and use it like this:
<Image name="firstImg" />

You can also make it typo-safe by introducing an object with all the images you might want to display, like this:
const Images = { firstImg: 'firstImg', secondImg: 'secondImg' }

and then use it like this:
<Image name={Images.firstImage} />

and
...
switch (props.name) {
case Images.firstImage:
...

Comment: Very convenient
Answer: Check the docs for static query

StaticQuery can do most of the things that page query can, including fragments. The main differences are:

page queries can accept variables (via pageContext) but can only be
  added to page components
StaticQuery does not accept variables (hence the name "static"), but
  can be used in any component, including pages

So you might want to query for the image's GatsbyImageSharpFluid in your page query and pass it as the fluid prop directly to gatsby image.
Comment: I didn't manage to make it work but your answer is relevant. Thanks!
Answer: Using ksav answer I managed to make this work by using pageQuery and receive the images i want to use in a specific page through props.
Like this:
export const pageQuery = graphql`
  coverImage: file(relativePath: { eq: "coverImage.png" }) {
    childImageSharp {
      fluid(maxWidth: 600) {
        ...GatsbyImageSharpFluid_tracedSVG
      }
    }
  }
}`

If you add this to your page component you will receive the props coverImage with the coverImage.png image.
Hope this helps!
Answer: This is one area where Gatsby could do better imho. I appreciate @ramzesenok's answer and if you must use the Gatsby framework with graphql that's probably the best you're going to do. But you could also just fall back to normal React like this:
import React from 'react';
import gatsbyAstronaut from './gatsby-astronaut.png';

and use it like this.

Even this seems a little heavy but the import is required so webpack can bundle the image properly.

String interpolation in graphQL query


Script within a jQueryUI modal dialog box only works once

Question: I have a table that, when any row is clicked, launches a jQueryUI modal dialog box to allow users to edit that record. I use the following script which seems to work, successfully loading the relevant record's details in using AJAX:
$("#datatbl tr").bind('click', function() {
        var url = 'item_edit.asp?id='+$(this).attr("data-myid");
        var dialog = $('

').appendTo('body');
        // load remote content
        dialog.load(
            url,
            {},
            function (responseText, textStatus, XMLHttpRequest) {
                dialog.dialog({
                    height: 440,
                    width: 550,
                    autoOpen: false,
                    modal: true,
                    buttons: {
                        "Update this record": function() {
                         $('#editform').submit();
                            },
                        Cancel: function() {
                        $( this ).dialog( "close" );
                        }
                    }
        });
        dialog.dialog('open');
            }
        );
        //prevent the browser to follow the link
        return false;
});

It works ok the first time I click on a record, but if I click cancel and try to edit another record, the dialog box does appear (with the correct record details) however, no scripts within the dialog box work - eg: there's a jqueryUI datepicker input and some validation.
There are no javascript errors and, from my limited understanding of FireBug, I can't spot anything going wrong so I would appreciate some advice how to proceed, thanks!
EDIT: Argh! Sometimes, it takes something like typing it out here to spot the obvious. I just realised that the DIV created for the dialog box doesn't get destroyed when the box closes. I've added a line to do this and it now works. Thanks for listening. :)
For future reference, I added an ID to the DIV created in 'var dialog' and removed it in the Cancel function:
Cancel: function() {
                        $( this ).dialog( "close" );
                        $('#dialogbox').remove();
                        }

I'd still appreciate if anybody suggests a better way to handle this behaviour.
Comment: you should add your edit to an answer and accept the answer.
Comment: I tried, but need to wait 8 hours. I'll do it then, but in the meantime I'll edit the original post, thanks.
Answer: I fixed it: the DIV created for the dialog box doesn't get destroyed when the box closes.
I added an ID to the DIV created in 'var dialog' and removed the DIV in the Cancel function:
Cancel: function() {
                        $( this ).dialog( "close" );
                        $('#dialogbox').remove();
                        }

Answer: You can create the dialog at one time only, not on every load of its content, just set the autoOpen to false.

$('#dialog').dialog({
    height: 440,
    width: 550,
    autoOpen: false,
    modal: true,
    buttons: {
        "Update this record": function() {
            $('#editform').submit();
        },
        Cancel: function() {
            $( this ).dialog( "close" );
        }
    }
});
$("#datatbl tr").bind('click', function() {
    var url = 'item_edit.asp?id='+$(this).attr("data-myid");
    // load remote content
    $('#content').load(url);
    $('#dialog').dialog('open');
    return false;
}};

Comment: The autoOpen is set to false. Opening the dialog wasn't the problem, it was the fact that the box didn't work the same if opened, closed then opened again. (see above). Thanks for reply


Why does some music sound faster than others even though its BPM is the same?

Question: For example, a symphony orchestra playing Trepak at 150 BPM feels so fast, but certain types of rock music being played at 150 BPM might be considered slow.
A house track at 140 BPM would be considered on the fast side of things, but a trance track at that speed is about normal.
How does the genre of music affect the feel of speed? And how does a genre hit upon an inherent range of tempos to use, as in this question?
Answer:
How does the genre of music affect the feel of speed? And how does a genre hit upon an inherent range of tempos to use, as in this question?

Before I answer your question, it should be clarified that there is a difference between genre and ensemble.  Genre concerns identifiable stylistic traits, whereas ensemble concerns instrumentation.  In other words, a full size orchestra can still play Bluegrass.
The difference in feeling you experience has to do with perceived tempo as opposed to written tempo.  This funny phenomenon is known as hypermeter.  The definition contained in the link is a little academic, so in more accessible terms, hypermeter is the perception of smaller metrical divisions combining to form larger metrical divisions.  In other words, your brain sticks things together and simplifies the music into larger aural shapes.
This is why all metronomes usually top out at 200-208bpm; because beyond those tempi the brain will actually perceive the "beats" as subdivisions of larger beats - creating hypermeter.
All of that said, as you alluded to in your question, whether or not hypermeter is perceived largely depends on the musical material - hypermeter is not exclusively contingent upon tempo.
It's for this reason that you can listen to two pieces at 160bpm - one will sound blazing fast, and the other "slower" - sometimes accompanied by the sensation of floating.
Conductors often employ hypermeter into their conducting - probably some of them without realizing it.  The next time you are watching a conductor for a orchestra conduct a very fast piece of music, watch how they only conduct the "big" beats as the music becomes "too fast" to conduct each individual beat.

As for genres containing an inherent range of tempi, I would say that it is two fold: in part through tradition in performance, and in part through listener expectation.  For example, Klezmer music is usually traditionally played with a rather brisk tempo (though many instances of slow Klezmer may be found.)  So, when people listen to Klezmer (or Polka or a March or Disco or Lounge or Funeral Music, they're going to have a certain amount of expectations that they believe should be fulfilled.
Some things need to be a certain tempi because they are not practical otherwise.  For example: Marches.  A parade march at 108bpm just won't make any sense at 32bpm.  And likewise a funeral march at 44bpm won't make any sense at 172bpm.
Yes, you can generate a list if you'd like or find hundreds of lists on the internet about how certain genres fit into certain tempi, but for practically every example found an equal antithetical example may also hypothetically be found.
Hope that helps.
Comment: You know come to think about it, now I kinda want to hear a 172 BPM funeral march.
Comment: Hypermeter link is dead.
Answer: An interesting phenomenon for sure, here's how I would explain it.
Beats Per Minutes is simply your base speed.  Let's use a car ride as an analogy.  Cruising across prarie flatland at 50 miles per hour is slow and predictable.  Take that same car and put it on a winding mountain road, and you now have a white knuckle cliffhanger.  The speed is identical in both, just the context has changed.
It comes down to how the musical lines interact with one another.  Some types of music are more intricate in their melodies and orchestration.  Heavy counterpoint produces a lot of perceived movement. Back to the car analogy, in the second scenario, you can think of the car as chasing the contour of the road.  As it navigates tight turns, the path of the car will diverge and converge, as it skids and swerves to follow the passage.
In Trepak, the tempo is relatively slow, but the melody lines move rather quickly.

Look at the average rhythmic value of the notes.  In Trepak, you can see that there are quite a few sixteenth notes.  This effectively multiplies the base BPM to a faster cycle.  If you look at comparable rock, where the average rythmic value is a quarter note, it will seem slow by comparison.
Comment: You say it is "relatively slow", but the tempo notation at the beginning say "Molto Vivace", which means "very lively and fast". I clocked the actual tempo played to be about 141bpm, which in the lower range of "Vivacissimo", whick also means "very lively and fast" (see [Wiki:Tempo](http://en.wikipedia.org/wiki/Tempo#Basic_tempo_markings)). So the question is: relative to what?


Apache folder redirects also lose www

Question: Let's say I have the domain "example.com" which works both with and without the "www." prefix.
And let's say I have a folder thereon called "extra".
When someone visits www.example.com/extra I would expect Apache to redirect them to www.example.com/extra/. But no! Instead, they're sent to example.com/extra/. Losing the www. prefix means that (a) a new session is generated, and the user is signed out, and (b) the security certificate becomes invalid.
I'm using Apache on a shared hosting platform (hsphere).
.htaccess file is as follows:
ErrorDocument 500 "
Application error
Web application failed to start properly"

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)$ index.php/$1
</IfModule>

Comment: could you show your configuration? are there any redirect rules?
Comment: No redirect rules, only rewrites. I've added the .htaccess file above.
Comment: The rules you posted don't perform any redirection.  Can you post your configs? At least the virtualhost definition.
Answer: I guess it is because of a UseCanonicalName directive in your Apache httpd configuration. Just set it to UseCanonical off or delete the directive.
Comment: Thanks. I'll try playing with that and see what happens.

Apache folder redirects also lose www


Memory leaks in Core Data

Question: Can somebody help me here?. New as iPhone Developer. I am getting a memory leak in Core Data, and I don't see how to fix it. I am running this method several times in a UIViewController ( I am not using Table Viiew):
<code>-(void)fetchEvents: (NSString *) predicateSearch localEvent:thisEvent {
    NSManagedObjectContext *context = [thisEvent managedObjectContext];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [thisEvent entity];
    [request setEntity:entity];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors];

    [sortDescriptors release];
    [sortDescriptor release];

    // Predicate for main screen
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type matches %@", predicateSearch];
    [request setPredicate:predicate];

    NSError *error;
    NSArray *fetchResults = [context executeFetchRequest:request error:&error];

    if (fetchResults == nil) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }

    [self setMyPhotoEventsArray:fetchResults];

    [request release];

}  // fetchEvents
</code>
And I am getting these memory leaks in Instruments:!
<code>Leaked Object # Address Size Responsible Library Responsible Frame
_PFArray 3 < multiple > 96 CoreData -[NSSQLCore _prepareResultsFromResultSet:usingFetchPlan:withMatchingRows:]

Leaked Object # Address Size Responsible Library Responsible Frame
GeneralBlock-32 2 < multiple > 64 CoreData PF_ALLOCATE_OBJECT_ARRAY
</code>
The method runs fine, however, I keep getting these leaks
Answer: It's hard to tell from what you show here, but here's a guess:
[self setMyPhotoEventsArray: fetchResults] probably retains "fetchResults" and then in the View Controller's dealloc and viewDidUnload you may be forgetting to release them.
As such, when the view controller is dismissed, the reference to the array is lost, and you have a leak.
Comment: Thanks for your response. I will look into this, the part that confuses me is getting all these leaks from Core Data.

Memory leaks in Core Data