$\mathbb{Q}$ is closed in itself

Question: It is known that every space is both open and closed in itself. If the space is a metric vector space, then being closed is equivalent that every sequence that converges, converges to a point in the space.
For example, $\mathbb{Q}$ is closed in itself. What does it say about the sequence of rational approximations of some irrational number? Does it not converge? It is a Cauchy sequence so how can we say it does not converge?
Comment: $C$ is a closed subset of a metric space $X$ if, whenever a sequence of points $c_1, c_2, c_3, \ldots$ all in $C$ converges to a point $x \in X$, we have $x \in C$. Now plug in $C=X=\mathbb Q$.
Comment: Check the definition of Cauchy sequence. It does not imply convergence to a limit.
Comment: The criterion for closed using sequential limits doesn't require the space to be a vector space - metric is enough. You can actually generalize this further to first countable spaces or sequential spaces, where
$$ \text{metric}\ \implies\ \text{first countable}\ \implies\ \text{sequential}. $$
Answer: I think you are mixing two concpets:
Yes, $\mathbb Q$ is a "closed set", since $(\Omega, \mathscr T)$ as a topological space by its own is always defined as open and closed, or we sometimes call it clopen.
But at the same time, we call a space "complete" if every Cauchy sequence converges within the space - and in this case, $\mathbb Q$ is not complete.
Answer: $(\mathbb{Q},|.|)$ is closed in itself.
But a sequence of $q_n$ rational numbers which converges to an irrational $r$, does not converge in $\mathbb{Q}$
It is a Cauchy sequence but does not converge in $(\mathbb{Q},|.|)$
Thus we can say that $\mathbb{Q}$ with the subspace topology inherited from the usual topology of $\mathbb{R}$ is not a complete space.
Take for instance $x_n=(1+1/n)^n \rightarrow e$.
Thus $x_n$ is a Cauchy sequence but $e \notin \mathbb{Q}$
Answer: If $A$ is a subset of a topological space $X$, then "$A$ is closed (in $X$)" implies that if a sequence of points of $A$ converges to a point in $X$, then the limit is itself in $A$.
This doesn't say anything about the possibility of converging to points outside $X$ -- indeed, the topology on $X$ that declares $A$ to be closed does not even know whether such points exist or what it would mean to converge towards them.

What does it say about the sequence of rational approximations of some irrational number? Does it not converge? It is a Cauchy sequence so how can we say it does not converge?

It doesn't converge in $\mathbb Q$ because there is no point in the topological space that it converges to. Some metric spaces have the property that all Cauchy sequences converge (they're called complete), but $\mathbb Q$ is not one of them.
Comment: So convergence is also a relative term? The same sequence can converge in some vectors spaces and not in others? How would you call a Cauchy sequence that does not converge in some vector space? Does it "diverge"?
Answer: The "Cauchy criterion" does NOT hold in the rational numbers.  There are, as you say, "Cauchy" sequences of rational numbers that do not converge to a rational number.
That is, in fact, one way of "constructing" the real number system:  We say that two Cauchy sequences of rational numbers are "equivalent" if and only if their "difference" (if the sequences are $\{a_n\}$ and $\{b_n\}$ then their "difference" is the sequence $\{a_n- b_n\}$.)  converges to 0.  We then identify the equivalence classes with the real numbers.  It is easy to show that if two Cauchy sequences of rational number converge to the same rational number then they are equivalent in this sense and that any other such sequence that is equivalent converges to the same rational number.  We identify that equivalence class with that rational number so that, in this sense, the set of rational number is a subset of the set of real number.  But since there exist Cauchy sequences that do not converge to a rational number, the corresponding equivalence classes give us the irrational numbers.
Answer: The equivalence statement you stated in the first paragraph is more tricky than it appears! Note that the necessary and sufficient condition you stated is equivalent to that the set equals its closure. However, when we say $\mathbb{Q}$ is closed in itself, we are certainly not saying $\mathbb{Q}$ is its closure that is usually taken to be $\mathbb{R}$ for granted unless otherwise declared. You probably are having trouble with the "inconsistency" of these pieces of information. The crux is this. We say $\mathbb{Q}$ is closed in itself because $\mathbb{Q}^{c} = \varnothing$ is open by definition. But note that here $\mathbb{Q}^{c}$ is the complement of $\mathbb{Q}$ with respect to $\mathbb{Q}$. So, when $\mathbb{Q}$ itself is considered the ambient space, the closure of $\mathbb{Q}$, which is by definition (if you are not using this definition, never mind; they are equivalent.) the intersection of all closed sets that includes $\mathbb{Q}$, is $\mathbb{Q}$ itself. So, if you go through the proof of the equivalence theorem again, then you will see why the "contradiction" resolves.

$\mathbb{Q}$ is closed in itself


How to get a PDF which converts an already drawn sample to uniform

Question: Suppose i have a large data pool with a particular PDF, $F(x)$, interval $[x,y]$ estimated from KDE of the datapool. I drew $N$ samples at random from that data pool and saw that their distribution is also represented quite well by $F(x)$. let this draw be $D_{bef}\sim F(x)$
Now I want another distribution $G(x)$, on same interval, such that, if i draw another $N$ sample from $G(x)$, $D_{aft}\sim G(x)$, then total $2N$ samples follow $(D_{bef} + D_{aft}) \sim Uniform(x)$.
Is it possible?? A lot of questions here want to generate uniform from PDF, but I want to draw from a PDF which when combined with my original draw, will convert them uniform.
Comment: I do not understand the question: what is the meaning of the interval $[x,y]$? What is the role of $N$? How do you get $2N$ samples $D_{bef}+D_{aft}$? What is the meaning of Uniform$(x)$ and is this $x$ related with the $x$ in $[x,y]$? What is the connection between the title of the question and the contents of the question?
Answer: It's not always possible: suppose that $F$ samples almost entirely from a subinterval $[a,b]$.  The combined sample will be almost 50% from that subinterval, so if $b-a <\frac{1}{2}(y-x)$ you can't get uniformity on $[x-y]$.
This shows what you need: for every subset of $[x,y]$, $F$ must put no more than twice as much probability on it than the uniform distribution does. That is,
you need the density $f(s)$ of $F$ to  be less than twice the uniform density $1/(y-x)$ everywhere on the interval.  You can then sample from the distribution $G$ with density
$$g(s) = \frac{2}{y-x}-f(s)$$
to get up to uniformity.
Comment: Thank you. That was informative. I understood the limitation of uniform and sampling bias as you said. Suppose if I remove the $N$ new samples limit, and say that the new pdf $G$ shall approach uniform as N approaches infinity, will that change the answer?
Comment: If the second round can  go to $\infty$ then you can handle any $F$ that has a density.  But if the interval is [0,1] and $F$ is the Bernoulli CDF you are still out of luck.


Node SerialPort leitura de dados sem quebra de linha

Question: estou trabalhando em um projeto com leitura de dados serial, utilizando a biblioteca Node SerialPort, porem ao imprimir os dados no console tenho os dados quebrados em varias linhas, exemplo: send = "1000", obtenho na leitura
received = "1"
"00"
"0"

var SerialPort = require('serialport');
var Readline = SerialPort.parsers.Readline;
var parser = new Readline({delimiter:'\n\r'});

var serveStatic = require('serve-static');
const express = require('express');
const socketIo = require('socket.io');
const http = require('http');
var path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIo.listen(server);

server.listen(3000, () => {
 console.log('Servidor Online na porta 3000');
});

const port = new SerialPort('COM3', {
 baudRate: 115200,
    dataBits: 8,
    paridade: 'nenhum' ,
    stopBits: 1,
    flowControl: false ,
    parser: new SerialPort.parsers.Readline('\n\r')
});

//define um diretorio commo public para acesso as propriedades
app.use(serveStatic(path.join(__dirname, 'public'), {
 maxAge: '1d'
  }));

// retorna index quano recebe requição
app.get('/', (req, res, next) => {
 res.sendFile(__dirname + '/index.html');
});

 port.open(function()
 {
  console.log('Porta aberta');
 });

 port.on('data', function (data)
 {
   ModbusTCP = data.toString('utf8');
   ModbusTCP = ModbusTCP.replace(/(\r\n|\n|\r)/gm,"");
   var infLeng = ModbusTCP.length;

   console.log('tamanho do envio:',infLeng);
   console.log('Valor Hexadeciaml: ' + ModbusTCP);

   // cria conexao de dados entre o js e o index.html
   io.emit('arduino:data', {
    value: data.toString()
   });
 });

"0"
Comment: ps dados são enviados a cada 5 segundos pelo arduino.
Comment: tentei definir um delimiter, porem não funcionou !!
Comment: acho que conseguiria resolver se soubesse como ler  o inicio da mensagem e o final.
Comment: consegui resolver o problema.
Answer: Consegui resolver o problema utilizando ByteLength Parser, quem precisar de uma olhada na documentação.
https://serialport.io/docs/en/api-parser-byte-length
segue exemplo, código esta bagunçado sou novo nisso, então estou trabalhando nisso ainda, mas acredito que ajude.

var SerialPort = require('serialport');
var Readline = SerialPort.parsers.Readline;
const Ready = require('@serialport/parser-ready')

var serveStatic = require('serve-static');
const express = require('express');
const socketIo = require('socket.io');
const http = require('http');
var path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIo.listen(server);

const port = new SerialPort('COM3', {
 baudRate: 115200,
    dataBits: 8,
    paridade: 'nenhum' ,
    stopBits: 1,
    flowControl: false ,
    parser: new SerialPort.parsers.Readline('\r')
});

//define um limite para acionar um evento
const ByteLength = require('@serialport/parser-byte-length');
const parser = port.pipe(new ByteLength({length: 4}))

server.listen(3000, () => {
 console.log('Servidor Online na porta 3000');
});

//define um diretorio commo public para acesso as propriedades
app.use(serveStatic(path.join(__dirname, 'public'), {
 maxAge: '1d'
 }));

// retorna index quano recebe requição
app.get('/', (req, res, next) => {
 res.sendFile(__dirname + '/index.html');
 app.use(serveStatic(path.join(__dirname, 'public'), {
  maxAge: '1d'
  }));
});

 port.open(function()
 {
  console.log('Porta aberta');
 });
 var ModbusTCP = "";
 parser.on('data', function (data)
 {
   ModbusTCP = data.toString();
   ModbusTCP = ModbusTCP.replace(/(\r\n|\n|\r)/gm,"");
   var infLeng = ModbusTCP.length;

   console.log('tamanho do envio:',infLeng);
   console.log('Valor Hexadeciaml: ' + ModbusTCP);

   // cria conexao de dados entre o js e o index.html
   io.emit('arduino:data', {
    value: data.toString()
   });
 });


Upgrading Postgres Aurora Major Version

Question: According to:
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Upgrading.html

Manually Upgrading the Engine Version
To perform a major version upgrade of a DB cluster, you can restore a
  snapshot of the DB cluster and specify a higher major engine version.
  For information about restoring a DB cluster, see Restoring from a DB
  Cluster Snapshot.

Yet I don't see anywhere the option of choosing a database engine at restore.
Is the documentation incorrect?
Am I missing something?
Answer: This is now supported by Aurora Postgres. There is no need to restore a snapshot into a new cluster anymore. The procedure is explained in the documentation.
As of 2020/05/22:
"Currently, you can do a major version upgrade from Aurora PostgreSQL version 9.6.11 or 9.6.12 database clusters to Aurora PostgreSQL version 10.11."
Answer: I also encountered the same issue when attempting to upgrade Aurora Postgres from 9.x to 10.x.  The GUI and aws-cli does not allow you to specify a higher version number when restoring a snapshot.
AWS support confirms this is NOT supported at this time, this from my chat session with the tech:

I should have recollected earlier. Currently there isn't an in-place upgrade path from Aurora 9.x to version 10.
  This is something that is frequently requested for and the engineering team is working on but we don't have an ETA as to when this will be fixed.

AWS did offer two options:

Use pg_dump and pg_restore to extract and load the data into an    upgrade target cluster.
Use AWS Data Migration Services to migrate data. DMS has the advantage of minimal downtime but it comes with many limitations you would have to evaluate. For example some data types, like JSON and timestamps with time zones are 'partially migrated'.

Links to AWS DMS documentation using PostgreSQL as a source and/or target of DMS:
Postgres as DMS Source: https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.PostgreSQL.html#CHAP_Source.PostgreSQL.Homogeneous.DMS
Postgres as DMS Target:
https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.PostgreSQL.html
The tech I chatted with favored pg_dump/pg_restore because it's more native, but it involve more downtime.
Comment: This is now supported by Aurora. https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.PostgreSQL.html
Comment: I think that DMS is supported only for MysQL Aurora. (Not postgres)
Comment: Actually PostgreSQL is supported as **both a source and target of DMS**, see the links for more documentation:

[Postgres as DMS Source](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.PostgreSQL.html#CHAP_Source.PostgreSQL.Homogeneous.DMS) **and** [Postgres as DMS Target](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Target.PostgreSQL.html)

The AWS tech I spoke with was the one who suggested DMS is an option for our Aurora PostgreSQL data migration.
Comment: It seems you're right: https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.html Until few months ago this was not the case.
Comment: @Spiff What do I need to add to make this the accepted answer?

Upgrading Postgres Aurora Major Version


Multivariable version of the extreme value theorem

Question: The Wikipedia entry on the extreme value theorem
says that if $f$ is a real-valued continuous function
on a closed and bounded interval $[a,b]$,
then $f$ must attain a maximum value,
i.e. there exists an $x \in [a,b]$
such that $f(x) \geq f(y)$ for all $y \in [a,b]$.
I think that there is a more general version of the extreme value theorem
which states a similar result for a closed and bounded subset of $\mathbb{R}^n$.
(At least I think I remember hearing about this in a class on metric spaces.)
Is there a statement of this more general version of the theorem,
hopefully with a reference as well?
Comment: The general thing is compactness. A continuous function on a [non-empty] compact space attains its maximum (and minimum). That's because a continuous image of a compact space is compact.
Answer: Yes, in fact they both come from two standard results in analysis:
Theorem 1: A subset of $\mathbb{R}^n$ is compact if and only if it is closed and bounded.
Theorem 2: Continuous image of a compact set is a compact set.
Corollary: Given $f:\mathbb{R}^n\to \mathbb{R}$ is continuous and $A\subset \mathbb{R}^n$ is closed and bounded. By Theorem 1, $A$ is compact. Hence $f(A)$ is a compact subset of $\mathbb{R}$. So $f(A)$ is closed and bounded. That proves the Extreme Value Theorem.
Comment: We need a theorem saying that the closed and bounded set $B:=f(A)\subset{\mathbb R}$ has a maximal element.
Answer: There is this document that states the theorem even more générally:
Theorem 3.4. (The Extreme Value Theorem) If $f : X \to R$ is real valued [edit: and continuous] function
from a compact space to the real numbers, then f attains a greatest value, that is
there is an $x \in X$ such that $f(x) \geq f(y)$ for all $y \in X$.
Comment: In proof of Theorem 3.4 the Lemma 3.1 is used (but not referenced with name). In the lemma 3.1 f is correctly required to be continuous. Thus is should be included in Theorem 3.4 that f is required to be continuous.
Comment: Thanks, dioid, I've edited my post


What are the K groups of $X_n$, the wedge sum of $n$ circles at a single point?

Question: If $X_n$ is the bouquet of n circles, then what is $K_0(X_n)$ and $K_1(X_n)$? I am super confused on how to approach this problem, since I've only seen $K_0$, $K_1$ computed for algebras, but I don't understand how the topological space $X_n$ is a C* algebra.
I imagine the solution would involve computing $K_0(\mathbb{R})$, $K_1(\mathbb{R})$ since $X_n$ is the one point compactification of $n$ copies of $\mathbb{R}$. $K_0(\mathbb{R}) = [\mathbb{R}]$ and $K_1(\mathbb{R}) = \frac{GL(\mathbb{R})}{[GL(\mathbb{R}), GL(\mathbb{R})]}$, so would $K_0(X_n) = \Pi_{i=1}^{n}[\mathbb{R}]$, $K_1(X_n) = \Pi_{i=1}^{n}\frac{GL(\mathbb{R})}{[GL(\mathbb{R}), GL(\mathbb{R})]}$?
Comment: I recommend looking up what topological K-theory is. It is a type of cohomology theory for spaces.
Answer: I assume you want to find the $K$-theory of $X_n$, not the $K$-homology of it (the $K$-theory groups of a space are typically denoted $K^i(X)$, not $K_i(X)$).  For a compact Hausdorff space $X$, $K^i(X)$ is naturally isomorphic to $K_i(C(X))$, the (operator) $K$-theory of the $C^*$-algebra of complex-valued functions on $X$.
Note that we have a split exact sequence of algebras:
$$0\to C_0\left(\bigsqcup^n_{i=1}\mathbb R\right)\to C(X_n)\leftrightarrows\mathbb C\to 0.$$
Thus, we get split exact sequences in both $K$-groups:
$$0\to K_i\left(C_0\left(\bigsqcup^n_{i=1}\mathbb R\right)\right)\to K_i(C(X_n))\leftrightarrows K_i(\mathbb C)\to 0,$$
and so
$$K_i(C(X_n))\cong K_i\left(C_0\left(\bigsqcup^n_{i=1}\mathbb R\right)\right)\oplus K_i(\mathbb C)\cong K_i(\mathbb C)\oplus\left(\bigoplus_{i=1}^nK_i(C_0(\mathbb R))\right)$$
Now we have $K_0(\mathbb C)=\mathbb Z$, $K_1(\mathbb C)=0$, $K_0(C_0(\mathbb R))=0$, and $K_1(C_0(\mathbb R))=\mathbb Z$, and therefore
\begin{align*}
K^0(X_n)&\cong K_0(C(X_n))\cong\mathbb Z\\
K^1(X_n)&\cong K_1(C(X_n))\cong \mathbb Z^n
\end{align*}


pip exists, says no module named pip

Question: I have pip installed and can clearly see the file (by using which pip) but, when I go to actually run a command like pip install -r requirements.txt (or even just pip to get help), I get the following error:
Traceback (most recent call last):
  File "/usr/local/bin/pip3", line 7, in <module>
    from pip._internal import main
ModuleNotFoundError: No module named 'pip'

I get this whether I'm using pip 2 or 3. What is going on here? Any way to fix it without reinstalling the whole thing?
Comment: Are you using a virtual environment (venv).
Comment: Yes I am. I can easily move on by just making a new virtual env but I want to know what's going on under the hood
Comment: Have you activated the environment? I missed that a few days ago.
Answer: Force a reinstall by running
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py --force-reinstall

Answer: Try this command
python -m pip <action>

Answer: Succinct answer - I ran pip -m site to see where my site packages are, and poked around in there and couldn't find pip. It must have gotten deleted...
This makes me wonder, though, why did pip disappear when I ran pip install --upgrade pip as it instructed me to do!

pip exists, says no module named pip


Subspace of polynomials vanishing to order $n$

Question:
Let $V\subset\mathbb{R}[x]$ be a vector space of dimension $k$. We say that a polynomial $f$ vanishes to order $n$ at $a\in\mathbb{R}$ if $f(a)=0$ and $n$ is the smallest positive integer such that $f^{(n)}(a)\not=0$.
a) Show that $V_n=\{f\in V|f\text{ vanishes to order}\geq n\text{ at }a\}$ is a subspace of $V$.
b) Let $a\in\mathbb{R}$. Show that $\dim(V_n)-\dim(V_{n+1})$ is either $0$ or $1$.
c) Conclude that there are precisely $k$ integers $n$ such that there exists a nonzero $f\in V$ that vanishes to order $n$ at $a$.

I have already proved part a. I think we can use rank-nullity on part b, but I am not sure how. I don't see how simply changing $a$ will cause the difference in dimensions to change. And how can I use this to prove part c? Any advice?
Comment: There is no "change in $a$." You pick $a$, you get your $V_n$ and $V_{n+1}$ *relative to that $a$*, and the question is about those two. There is one fixed $a$ throughout. As to part (b), consider the differentiation map from $V_{n+1}$ to $V_n$ (or from $V$ to itself, and what it does when you apply it to an element of $V_{n+1}$).
Comment: Regarding the fact that changing $a$ changes the difference in dimensions: note that we could have $V \subsetneq \Bbb R[x]$.
Comment: You might find it helpful to consider an example. For instance, $V = \operatorname{span}(\{x^3,x+1\})$. Consider what happens relative to $a = 0,1,2$.
Answer: Part b: Let $W = \Bbb R_m[x]$ denote the set of polynomials of degree at most $m$, where $m$ has been chosen so that $V \subset W$.  Note that $\dim(W_n) = m+1-n$, and $W_{n+1} \subset W_n$. Let $S_n$ denote a subspace of $W_n$ such that $W_{n} = S_n \oplus W_{n+1}$; note that $\dim(S_n) = 1$.
Now, we note that $V_n = W_n \cap V$, and that $V_{n+1} \subset V_n$. With that, we have $\dim(V_{n+1}) \leq \dim(V_n)$ and
$$
\begin{align}
\dim(V_{n+1}) &= \dim(W_{n+1} \cap V)
\\ & \geq \dim([W_{n+1} \oplus S] \cap V)  - \dim(S \cap V)
\\ & = \dim(W_n\cap V) - \dim(S \cap V) = \dim(V_n) - \dim(S \cap V)
\\ & \geq \dim(V_n) - \dim(S) = \dim(V_n) - 1.
\end{align}
$$
The conclusion follows.
Regarding part c, it is helpful to note that $V_0 = V$, note that there exists an $n$ such that $V_n = \{0\}$, and consider the sequence $\dim(V_0),\dim(V_1),\dim(V_2),\dots$.
Comment: Actually, it is not clear that $V$ is closed under $D$, is it? E.g., we could take the vector space spanned by $x^3$. Then $D(x^3) = 3x^2\notin V$.
Comment: @ArturoMagidin It is not. I'm sure there must be something involving the map $D$ here but having thought about it again I'm not sure what the exact connection is
Comment: Yup, I was just getting there. I was going to pick the basis $1,(x-a),(x-a)^2,\ldots,(x-a)^m$ and go from there...
Comment: @ArturoMagidin I have a feeling that there's a more elegant way to package this proof that I'm missing, though. At the very least, I could be more specific and take $S_n = \operatorname{span}\{(x-a)^n\}$, but that doesn't seem very illuminating on its own.
Answer: For $(b)$, let $\varphi \colon V_n \rightarrow \mathbb{R}$ be the linear functional given by $\varphi(f) = f^{(n)}(a)$. Note that
$$ V_n = \{ f \in V \, | \, f(a) = f'(a) = \dots = f^{(n-1)}(a) = 0 \}, \\
\ker(\varphi) = \{ f \in V_n \, | \, f^{(n)}(a) = 0 \} = \{ f \in V \, | \, f(a) = \dots = f^{(n-1)}(a) = f^{(n)}(a) = 0 \} = V_{n+1} $$
and so by rank-nullity or directly, there are two options:

Either $\varphi = 0$ and then $V_{n+1} = \ker(\varphi) = V_n$.
Or $\varphi \neq 0$ and then $\dim V_{n+1} = \dim \ker(\varphi) = \dim V_n - 1$.

For part $(c)$, let $M \geq k - 1$ be the maximal degree of an element in $V$ (this exists because $V$ is finite dimensional) and consider the sequence of descending subspaces
$$ V := V_0 \supseteq V_1 \supseteq V_2 \supseteq V_3 \supseteq \dots \supseteq V_{M+1}. $$
Prove that $V_{M+1}= \{ 0 \}$. Taking dimensions, we get
$$ k = \dim V \geq \dim V_1 \geq \dim V_2 \geq \dim V_3 \geq \dots \geq 0. $$
By part $(b)$, whenever we have a strict inequality the dimension decreases by $1$ and so there are precisely $k$ non-negative distinct integers $0 \leq n_1,\dots,n_k \leq M$ such that $\dim V_{n_i + 1} + 1 = \dim V_{n_i}$. Finally, note that $0\neq f \in V$ vanishes to order $n$ iff $f \in V_n \setminus V_{n+1}$ which implies that $\dim V_n > \dim V_{n+1}$ which happens iff $n = n_i$.
Comment: For point 2, did you mean $^*\varphi=1^*$ implies $\dim V_{n+1}=\dim\text{ker}(\varphi)=\dim V_n-1$?
Comment: @Sunyata: Sorry, I meant $\varphi \neq 0$.
Comment: Last question: how do we know $V=V_0$? Is this vacuous?
Comment: @Sunyata: I defined it to be $V$. In fact, the problem as stated is wrong because you need to define that $f = 0$ vanishes to order $n$ for all $n \in \mathbb{N}_0$ (otherwise, $V_n$ isn't even a subspace with your given definition) and also say that $f$ vanishes to order zero at $a$ if $f(a) \neq 0$. Then, the correct conclusion is that there are precisely $k$ **non-negative** integers $k$ (you must include zero) such that there exists $f \neq 0$ which vanishes to order $k$.
Comment: Got it, thanks.


Drupal 7 not able to run cron after views/panels update

Question: After an update of several modules to their latest versions (views, panels, ctools) it seems Drupal can no longer run cron, whether automatically or manual. It gives the error: "Cron run failed."
I have no idea what might be causing this and only discovered it some 10 days after performing the updates. The lightweight cron (for scheduled content) that I have set up externally in cpanel still runs.
Also a bit worrying is, when visiting mywebstie.com/cron.php (as an anon) it shows me my actual frontpage with some broken css. Which, I believe, is an unintended behaviour as it should show a blank page or a "content not found" page.
I believe the number 1 suspect is the views module, since immediately after the update I noticed that admin/content view no longer updates the "node views today" value and it just continuously increments this value without reinitialising every 24hours.
Any ideas of what might be the issue here?
Everthing was normal before the said updates: I have Unix server using Centos. BTW I have a local copy of the site using Xampp and it has the same cron problem as the live site. I am inclined to believe this is not a server problem.
PS: I have never used drush..
Comment: What do the logs say?
Comment: Hello, you mean the logs in admin/reports/dblog? or another one you access through ssh command? In the former I see some "Attempting to re-run cron while it is already running." errors which seem to be triggered when a node is viewed..
Answer: For troubleshooting cron.php problems found this:
https://www.drupal.org/node/553430
Cron stopped running; logs say: "Attempting to re-run cron while it is already running."
I have been able to trigger cron using the ultimate cron module, which is in beta.
Still don't understand what was going and didn't find the faulty module but the "attempting to re-run cron while it's already running" error msg has gone away from the logs.


Stuttering HTML 5 video while looping

Question: The video loops seamlessly when played using a Media Player. It's not the video file that is stuttering. I cant for the life of me, find a solution to this.
I've setup a jsfiddle here:
https://jsfiddle.net/Dillybob/to30r7rv/4/
(Please give it a few seconds to load, I'm using a free hosting account)

 <video id="video1" width="1280" height="973" autoplay="true" loop="true">
   <source src="http://dillybob.byethost14.com/background.webm" type="video/mp4">
 </video>

The problem:
The video is roughly 17 seconds long. Wait until 16 seconds pass, and stare at the video, you will notice a tiny 100-300 ms 'freeze' before it begins the next loop.
Edit: I tested this on Firefox and it does the same thing, but the freeze isn't as long. I also tested   a very low quality .webm version of my video (around 2MB in size) and the freeze seemed even shorter... but you can still notice it.  I am thinking this is a video filesize issue w/ looping maybe?
Comment: The test file is encoded using VP9 and I am having troubles watching it. My versions of VLC and avplay don't support it. This is just a wild guess but have you tried converting it to h264 or VP8?
Comment: @SvetlinMladenov Yeah, I have tried H264 mp4's as well. Here is a vp8 encoded one: https://jsfiddle.net/Dillybob/to30r7rv/5/   The freeze is still there, and that one works in VLC so u can see the seamless.
Answer: Your Working Code is Here :
<video id="video1" width="1280" height="973" controls autoplay loop>
<source src="http://dillybob.byethost14.com/background.webm" type="video/webm">
</video>

Your Mistakes were :

Video type was wrong
loop is boolean itself so it should be defined explicitly only in XHTML because there attribute minimization is forbidden

Cheers :)

Stuttering HTML 5 video while looping


Ito with the function containing stochastic integral

Question: Statement of problem
From Oksendal SDEs question 5.18:
The geometric mean reversion process is a solution to:
$$ dX_t = k (a - \log X_t) X_t dt + \sigma X_t dB_t $$
In showing that solution is given by:
$$ X_t = \exp ( e^{-k t}\log X_0+(a-\sigma^2/2k)(1-e^{k t})+\sigma e^{-k t}\int_0^t e^{k s}dB_s)$$
It says to take $Y_t = \log X_t$
Then:
$$ Y_t= e^{-k t}\log X_0+(a-\sigma^2/2k)(1-e^{k t})+\sigma e^{-k t}\int_0^t e^{k s}dB_s$$
and go from there..
Attempt:
I have seen elsewhere that the next step should lead to:
$$dY_t = \left( -kY_t+k\left(a-\frac{\sigma^2}{2k}\right)\right)dt+\sigma dB_s$$
But I am unsure about $Y_t = f(t,B_t)$, and when using Itô's formula to evaluate $$dY_t = \partial_t f(t,B_t)dt + \partial_x f(t,B_t)dB_t + \frac{1}{2}\partial_{xx}f(t,B_t) dt$$
I do not know how to determine the function $f(t,x)$ for use in the formula due to the stochastic integral contained in $Y_t$.
After saz post
$$f(t,x)=\sigma  e^{-k t}x + \left(a -\frac{\sigma ^2}{2k }\right)\left(1-e^{k  t}\right)$$
For the formula you need the following partial derivatives:
$$ \partial_t f(t,x)=-e^{-k t} k x \sigma -e^{t k } k  \left(a -\frac{\sigma ^2}{2 k }\right) $$
$$ \partial_x f(t,x) = e^{-k t} \sigma $$
Then:
 $$ Z_t = \left(\frac{1}{\sigma }Y_0+\int_0^t e^{k s} \, dB_s\right) $$
$$Y_t = f(t,Z_t)$$
So:
$$dY_t =\left[ -e^{-k t} k \left(\frac{1}{\sigma }Y_0+\int_0^t e^{k s} \, dB_s\right) \sigma -e^{t k } k  \left(a -\frac{\sigma ^2}{2 k }\right) \right] dt + e^{-kt} \sigma dZ_t $$
$$ dY_t = \left[ k\left(a-\frac{\sigma^2}{2k}\right) -kY_t \right] dt + e^{-kt} \sigma dZ_t $$
$$ dY_t = \left[ k(a-Y_t)-\frac{\sigma ^2}{2}\right]\text{dt} + \sigma  \text{dB}_t $$
If
$$ dY_t = \left[ k(a-Y_t) - \frac{\sigma^2}{2}\right]dt + \sigma dB_t $$
Then by Ito's with $X_t = e^{Y_t}$:
$$ dX_t = k(a-\log X_t) X_t dt + X_t \sigma dB_t \,\,\,\, \blacksquare$$
Comment: related: https://math.stackexchange.com/q/3703112/532409
Answer: No, you cannot simply set
$$g(t,x) = \int_0^t e^{ks} \, dx$$
since the stochastic integral $\int_0^t e^{ks} \, dB_s$ is not pathwise defined. In order to find the differential of $(Y_t)_{t \geq 0}$, you have to apply Itô's formula for Itô processes. Namely, if
$$dZ_t = \sigma_t \, dB_t$$
then Itô's formula states that
$$\begin{align*} f(t,Z_t)-f(0,Z_0) &= \int_0^t \partial_x f(s,Z_s) \sigma_s \, dB_s + \int_0^t \left( \frac{1}{2} \partial_{xx} f(s,Z_s) \sigma_s^2 + \partial_t f(s,Z_s) \right) \, ds. \end{align*}$$
Apply this to
$$\begin{align*} Z_t &:= \left(\frac{1}{\sigma} Y_0 + \int_0^t e^{ks} \, dB_s \right) \\ f(t,x) &:= \sigma e^{-kt} x + \left(a- \frac{\sigma^2}{2k} \right) (1-e^{kt}). \end{align*}$$
Comment: I assumed you mean $Y_0$ in $Z_t$, is this correct? I have got slightly further in my attempt, I think.
Comment: @shilov Yes, you are right. I didn't check all your calculations, but it looks pretty good.


Read inputfile as csv in python

Question: I want to read a csv file from STDIN and operate on it.
The following is the code for reading the csv file and doing the operation needed. This works fine. But I want to take the input from STDIN.
import csv
with open('hospital_data.csv', 'rb') as csvfile:
    myDict = {}

    csvreader = csv.reader(csvfile, delimiter=',')
    for row in csvreader:
        if row[6] not in myDict.keys():
            #print 'Zipcode: ' + row[6] + ' Hospital code: ' + row[1]
            myDict[row[6]] = 1
        elif row[6] in myDict.keys():
            #print 'value in row '+ str(myDict[row[6]])
            myDict[row[6]] += 1

Is there a way in Python to read the file from STDIN as a csv file ?
Answer: csv.reader will take anything that yields lines, so you can use any of the methods shown at this answer to get lines from stdin:
How do you read from stdin in Python?
I'm partial to fileinput myself due to its flexibility. EG:
import csv
import fileinput

myDict = {}
csvreader = csv.reader(fileinput.input(mode='rb'), delimiter=',')

But this works too:
import csv
import sys

myDict = {}
csvreader = csv.reader(sys.stdin, delimiter=',')

If you do that, you'll want to run with the -u command line argument to make stream binary, if that makes a difference on your platform:
https://docs.python.org/2/using/cmdline.html#cmdoption-u
In either case you'll need to use control-D to mark the end of the input.
Note that the correct way to check if a key is in a dict is if row[6] in myDict rather than checking keys. And in fact if you just want a default value when the key is not present, use get:
for row in csvreader:
    myDict[row[6]] = myDict.get(row[6], 0) + 1

Or look into collections.Counter, since you're on 2.7:
myDict = collections.Counter(row[6] for row in csvreader)

Answer: Use sys.stdin, it's file-like object.
import sys
import csv

data = sys.stdin.readlines()
csvreader = csv.reader(data, delimiter=',')
for row in csvreader:
    print row

Read inputfile as csv in python


How to reuse variable for NSWindowController when opening and closing window

Question: Goal: I want to create a controller class (preferably singleton) to programmatically manage opening and closing NSWindows. When a window is closed it should be released so it does not take up memory. Only one window is available at a time. I'm not using nib-files.
Instantiating a new NSWindowController for each view and using it's close method close it appear to cause memory issues (EXC_BAD_ACCESS).
In this example, the app crashes when re-opening the window via the scheduled timer.
AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
  self.controller = [[MyController alloc] init];
  [self.controller open];
  [self.controller close];
  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self.controller selector:@selector(open:) userInfo:NULL repeats:false];
}

MyController
- (void) open:(NSTimer *) timer {
    [self open];
}
- (void) open {
    self.windowController = [[NSWindowController alloc]
                             initWithWindow: [[NSWindow alloc]
                                              initWithContentRect:NSMakeRect(30, 30, 300, 300)
                                              styleMask:NSTexturedBackgroundWindowMask
                                              backing:NSBackingStoreBuffered
                                              defer:false]];
    [[self.windowController window] setReleasedWhenClosed:true];
    [[self.windowController window] orderFrontRegardless];
}
- (void) close {
    [self.windowController close];
}

Clearly this feels like a bad approach. What would be a better design to achieve the goal?
Answer: I'm not sure if you refer to self.windowController anywhere else, but as a matter of safety you should have:
- (void) close {
    [self.windowController close];
    self.windowController = nil;
}

So you don't accidentally touch the window after it's been released.
Also, as a matter of style, don't use one-shot timers like that, just use -perform:withObject:afterDelay:
Finally, when you think about creating a singleton class just to control instances of another class, think about making those methods class methods on a subclass, instead. Like, you could write your own NSWindowController class with +open and +close methods.
Comment: And Objective-C convention is to use `YES/NO` instead of `true/false`. :)
Comment: That makes sense, Wil, but if I set self.windowController = nil; the app crashes when trying to use the variable again: self.windowController = [[NSWindowController alloc]..
Comment: Is there more code in these classes? What do the headers look like?


Consulting values of the first order temporal correlation coefficient CORT when clustering time series in R

Question: I am doing cluster analysis of several time series in R (the sales of a product in different stores).
I am using the first order temporal correlation coefficient CORT(S1,S2), in package TSclust, where S1 and S2 are two time series.
The literaure (https://cran.r-project.org/web/packages/TSclust/TSclust.pdf) explains that CORT belongs to the interval [-1,1]: when CORT(S1,S2)=1 both series show a similar dynamic behavior, and when CORT(S1,S2)=-1 they have opposite behavior.
I would like to know how to see the results of CORT, in order to observe the values of CORT for each pair of time series.
We can see the next example in TSclust package:
## Create three sample time series
x <- cumsum(rnorm(100))
y <- cumsum(rnorm(100))
z <- sin(seq(0, pi, length.out=100))

## Compute the distance and check for coherent results
diss.CORT(x, y, 2)
diss.CORT(x, z, 2)
diss.CORT(y, z, 2)

So with the above code we can calculate de dissimilarity index using the coefficient CORT(S1,S2), but we cannot consult the values of the CORT coefficient.
So, does anyone how to see the values of CORT coefficient in R?
Thanks in advance.
Answer: I am not sure if this is what you want, but any how this is what I did:
View(diss.CORT)

where R shows:
function (x, y, k = 2, deltamethod = "Euclid")

{
  .ts.sanity.check(x, y)
  .check.equal.length.ts(x, y)
  corrt <- corrtemporder1(x, y)
  type <- (pmatch(deltamethod, c("Euclid", "Frechet", "DTW")))
  typedist <- 0
  if (is.na(type)) {
    stop(paste("Unknown method", deltamethod))
  }
  else if (type == 1) {
    typedist <- as.numeric(dist(rbind(x, y)))
  }
  else if (type == 2) {
    typedist <- diss.FRECHET(x, y)
  }
  else if (type == 3) {
    typedist <- dtw(x, y, dist.method = "Manhattan", distance.only = T)$distance
  }
  (2/(1 + exp(k * corrt))) * typedist
}

Now if you go through that and start reading the script it seems that you are looking for line where corrt <- corrtemporder1(x, y). google it and you get to: https://github.com/cran/TSclust/blob/master/R/diss.R
#############################################################################
#################   Temporal Correlation Distance   #########################
#############################################################################

##CHOUAKRIA-DOUZAL

corrtemporder1 <- function (x, y) {
    p <- length(x)
    sum((x[2:p] - x[1:(p-1)]) * (y[2:p] - y[1:(p-1)])) / ( sqrt( sum((x[2:p] - x[1:(p-1)])^2) ) * sqrt( sum((y[2:p] - y[1:(p-1)])^2) ))
}

Now, I think this is what you are looking for.
Comment: thank you so much, this is what I was looking for! Now, I would like to do it for 30 time series, I would like to plot the `CORT` matrix, as we do with the command `corrplot`. Do you know if there is a way to do it with `CORT`?
Comment: I have done it, but I get the message: "Thanks for the feedback! Once you earn a total of 15 reputation, your votes will change the publicly displayed post score"
Comment: @AnaA appreciate it! Thanks


Debian 8(Jessie): netbios name resolution

Question: To resolve netbios names on Debian 7(Wheezy) I used to install winbind and append a 'wins' in /etc/nsswitch.conf. This procedure appears to not work on a freshly installed Debian 8.2(Jessie). It does, however, work on a Debian Jessie upgraded from Debian Wheezy.
So is there anything wrong with Jessie or is it that I am missing something? How does one go about enabling netbios name resolution in Jessie?
Answer: I had the same problem and I managed to fix it by installing package libnss-winbind.


C# DateTime Exception error

Question: I have dates column within an excel which are 01.02.2016 format all the way through (and maybe changed to 01/02/2016 in the future) and for each row they are added to a data table in my backgroundworker.
Looping through each datatable row i grab the date column and try to change the date a few times to get the correct sqlite format to save to the database.
See below;
foreach datatablerow {

    //change dots to slashes
    string dateString = Convert.ToString(rowData["Date"]).ToString().Replace(".", "/");

    //do DateTime C# Formatting..
    //This is causing the crash/exception
    DateTime _dateString = Convert.ToDateTime(dateString);
    //also have used & crahses as well
    //DateTime _dateString = DateTime.Parse(dateString);

    //Change agian to suit sqlite database entry - 2016/02/01
    string change_dateString = _dateString.ToString("yyyy-MM-dd");

    //Insert database data...

}

However, I get System.FormatException: String was not recognized as a valid DateTime errors on the transaction loop (even though on another computer the same transaction works using the above code...
When I console each date I can see thet it gets converted correctly to 01/02/2016 but the DateTime part crashes..
Comment: No it doesn't have anything with 32x or 64x. Every machines runs an OS that has a default culture, like "en-US" or "en-UK". now each culture have different date format and currency and so on. when you force your app to store/read date in a format different than the culture on the machine you get this exception
Comment: this problem is related to the date culture on the machine that you are using
Comment: As in the machines OS is corrupt?
Comment: are you developing web or desktop app?
Comment: WPF Desktop program..would it have something to do with 32x and 64x Bit computers??
Comment: `string newDate = Convert.ToDateTime("01/02/2016").ToString("yyyy-MM-dd");`
Comment: Rohit Convert.ToDateTime("01/02/2016").ToString("yyyy-MM-dd"); works but when I use Convert.ToDateTime(dateString).ToString("yyyy-MM-dd"); it crashes even through the string returns 01/02/2016 (after converting using replace())
Comment: @BENN1TH: Which Data Type is your DateString in your SQLite DB? And which Provider are you using?
Comment: It is TEXT but the issue is manipulating the date from excel to prepare it for sqlite injection..once the format is changed to yyyy-MM-dd it will work but the DateTime change is crashing it..
Answer: Have you tried setting the invariant culture ?
 DateTime yourdate= DateTime.ParseExact(rowData["Date"], "yyyy-MM-dd",
                                       CultureInfo.InvariantCulture)

Comment: This is the better solution, because it's independent of `CultureInfo`. +1
Comment: DateTime.ParseExact("01.02.2016", "yyyy-MM-dd", CultureInfo.InvariantCulture);  & DateTime.ParseExact("01/02/2016", "yyyy-MM-dd", CultureInfo.InvariantCulture); still crashed the program
Comment: The OP mentioned "01.02.2016 format", which is *not* "yyyy-MM-dd". InvariantCulture *may* not apply in this case.
Answer: First of all, remove this String manipulation. It's bad coding...
string dateString = Convert.ToString(rowData["Date"]).ToString();

.Replace(".", "/");

Update
There is a common misunderstanding of the DateTime Value in Sqlite.
Why?
Because Sqlite has no storage data type for DateTime values build in. By default Sqlite handles Date and Time Values like this, in his DataTypes:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER
as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

How to catch the Error
So the problem could be

A : Casting the wrong DataType to String
B : An other Date Format than ISO8601 in your TEXT Colum(["Date"])
C : Other Culture Setting in your Connection String

Try some Code like this:
try
{
    string dateString = rowData["Date"].ToString();
}
catch (System.Exception ex)
{
    throw new System.Exception("Couldn't get Data from Row! Maybe wrong DataType?")
}

DateTime dateValue;
if (!DateTime.TryParse(dateString, out dateValue))
{
    // handle parse failure
    throw new System.Exception("Couldn't parse this String: " + dateString)
}

Comment: I removed the string manipulation still got exception following the above. Just checked the excel cells and all are 01.02.2016 date format no whitespace

C# DateTime Exception error


Changing part of map (image) color on hover

Question: I work on this project that includes regions of Croatia for search real estates. So I try to get every region on hover to change color from blue to orange. I try to go with javascipt on hover and png, but no good. I only cut image like that and get square images that go one above another. Does anybody have a idea, or work on same stuff to give me guidelines. Customer don't wont a flash.
Answer: You can use SVG:
1) You download svg world map or Croatia map(in this case skip step 2) from that internets
2) Open it in any program that can edit svg(I prefer Adobe Illustrator) and remove all the regions except Croatia
3) Load the result svg file to your document
4) Via pure js or Jquery bind svg polyline or any other element you have to change its fill attribute on mouseenter.


Please double check my SSL config. Is it OK?

Question: I'm new to SSL. I set it up on my CentOS 5 system running Apache 2.2.3-65. It appears to be working -- a can browse my site and the https protocol is displayed in the address bar.
Here's my SSL vhost config. Does it look OK? Did I make any major errors?
The intention is for all traffic for this particular site to be encrypted, so there's no vhost for port 80, just this one.
<VirtualHost *:443>
    ServerName www.mydomain.com
    ServerAlias mydomain.com
    DocumentRoot "/opt/deployed_rails_apps/my_app/current/public"

    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/www.mydomain.com.crt
    SSLCertificateKeyFile /etc/pki/tls/certs/www.mydomain.com.pem
    SSLCACertificateFile /etc/pki/tls/certs/www.mydomain.com.ca-bundle

    ErrorLog "logs/mydomain.com-ssl-error_log"
    CustomLog "logs/mydomain.com-ssl-access_log" common
    CustomLog "logs/mydomain.com-ssl-deflate_log" deflate
    <Directory "/opt/deployed_rails_apps/rock_pebble/current/public">
        Options -MultiViews FollowSymLinks
        AllowOverride None
        Order allow,deny
        Allow from all
    </Directory>
</Virtualhost>

Comment: Qualsys SSL Labs check page: https://www.ssllabs.com/ssltest/index.html Lets you know if there's any concerns by an external check.
Answer: That will work, certainly. But here are a few more options that you should include for better security:
SSLHonorCipherOrder On
SSLCipherSuite ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH
SSLProtocol all -SSLv2
Header add Strict-Transport-Security "max-age=15768000"

You should also check your server security against SSL Pulse and see their SSL Best Practices Guide. There's also an SSL Rating Guide which explains why these options are a good idea.
Answer: Looks fine, but remove the ServerAlias directive unless your cert will work on both "www.example.com" and "example.com".
Comment: Thanks -- the cert (Commodo "PositiveSSL") is advertised as being able to work for both.


WatiN doubleclick not working in IE9

Question: I'm using watin testing tool for our asp.net mvc 3 web application.
The same test works for ie 8 but not for ie9.
Element element = frame.ElementWithTag("td", Find.ByText("a14"));
element.DoubleClick();

Any Idea? or workaround to simulate doubleclick in ie 9.
Comment: did you get anywhere with this, run into same issue?
Answer: As a workaround, if you have jquery available on your page you could do as I did:
row.DomContainer.Eval(string.Format("$('#{0}').dblclick();", row.Id));

I had tried several different variations on the ondblclick event, which WatiN uses itself (line 470 of Core.Element), to no avail.
Comment: With the help of @dove's answer, I end up with: Browser.Eval(string.Format("$('#{0}').dblclick();", id));

WatiN doubleclick not working in IE9


Exchange - Mail Users with local "alias" mailbox with auto-forwarding

Question: Currently I am working with an environment that looks like this:
Smaller organization using Google Apps for e-mail, let's say this domain is @gapps-example.com
Larger organization using MS Exchange for e-mail, let's say this domain is @msexchange-example.com.
There is now a need to give users at the smaller organization AD accounts in the larger organization. Users should show up in the Exchange GAL with their primary e-mail address on record being their @gapps-example.com e-mail address. This alone would be easily doable using Exchange "Mail Users".
The hard part is that we also want to have a hidden / secondary "alias" e-mail address @msexchange-example.com that would auto-forward to their normal GApps @gapps-example.com e-mail address, for each user from the smaller organization.
This would be for odd cases where someone needs to verify their employment at the larger organization by getting a verification e-mail sent to them at an @msexchange-example.com e-mail address.
Does anyone have any advice on how to technically achieve something like this with Exchange?
Thanks!
Comment: Well I think the secondary Alias email is not an issue here as Exchange already allows you to have multiple SMTP addresses for users but only one of those emails can be the primary SMTP address. If you want to forward the email from exchange then the users will need an inbox or a distribution list or something to work.
Comment: As far as I know (feel free to correct me if I am wrong) you can only have multiple SMTP addresses for an Exchange Mailbox, not for a "Mail User" (which is essentially just a Mail Contact that's an actual AD user also).
Answer: This is exactly what a Mail Contact in Exchange does.  The Primary SMTP address for the object is for an external domain, but there is a default alias for the internal Exchange domain, which would pass your requirement.

Mail Contact:

No AD account, just an Exchange object which has an alias in the Exchange domain.
Primary email address (as well as the one shown in the GAL) is for the external domain.

Mail User:

Has an AD account, and the primary SMTP address is shown in the Exchange domain.
Exchange attribute ExternalEmailAddress is set to the external mail domain.
Comment: I have a bunch of Mail Users, pending an acquisition to go-live.  Primary SMTP is my exchange domain, and the exchange attribute *ExternalEmailAddress* is configured for the remote mail domain (which does happen to be on GApps.)
Comment: Not exactly. A mail contact is a non-user object that shows up in the GAL with an external e-mail address. I could create a normal Exchange user with an @ msexchange-example.com mailbox, then create a new contact object for that user's @ gapps-example.com e-mail address, and then configure the user's mailbox to forward to the contact object, however that would still have the user's primary e-mail in the GAL show up as their @ mxexchange-example.com address.
Comment: I guess I glossed over the 4th paragraph.  You are actually looking for a Mail User, which does have an AD account and shows the Exchange domain as the primary email address.
Comment: I do not believe you will be able to set the primarySMTPAddress attribute for an *external domain* on a Mail User.
Comment: A Mail User wouldn't show the Exchange domain as the primary e-mail address, since a Mail User is just like a Mail Contact, except that it is an actual AD user as well. Mail Users, just like Mail Contacts, have an external e-mail address. As far as I know (and please correct me if I am wrong) any solution involving an actual, functional e-mail address at the Exchange domain name would involve creating a mailbox of some sort.
Comment: Oh wow, that is awesome! I was a bit confused by the MS documentation. Thank you so much @blaughw!


Compute E(4X−5X^2)

Question: Suppose that a random variable $X$ is distributed according to the gamma distribution with mean $10$ and variance $20$.
Compute $E(4X−5X^{2})$
When calculating this I got - $560$ doing $4(10) - 5(120)$
But I was not sure if you could have a negative value to this equation, can someone tell me if I am on the right track as far as my thought process goes?
Comment: Yes, it is correct.
Answer: Note $$4X - 5X^2 = 500 - 96X - 5(X-10)^2,$$ so that $$\operatorname{E}[4X - 5X^2] = \operatorname{E}[500] - 96 \operatorname{E}[X] - 5 \operatorname{E}[(X-10)^2],$$ and since $\operatorname{E}[X] = 10$ and $\operatorname{Var}[X] = \operatorname{E}[(X-10)^2] = 20$, it follows that
$$\operatorname{E}[4X-5X^2] = 500 - 960 - 100 = -560.$$
Note that we did not need to use the fact that $X$ is gamma distributed.
Answer: From $\text{Var}(X)=E(X^2)-(E(X))^2$ you can compute $E(X^2)$ to be $\text{Var}(X)+100 = 120$ indeed.
The rest is just applying linearity of expectation. $-$ instead of $+$ is no problem there. I mean, you expect the difference of two dice to be $0$, right?

Compute E(4X−5X^2)


Web Forms - Repeater's Enum Display Value

Question: I have a list of objects that I want to bind to a repeater (not necessarily displayed in a table format) using the following code:
C# object code:
public enum CategoryEnum
{
    [Description("Entertainment and Film")]
    EntertainmentFilm = 1,
    [Description("Audio and Music Cover")]
    AudioCover = 2,
    [Description("Others")]
    Others = 0
}

public class Document
{
    public string Name { get; set; }
    public CategoryEnum Category { get; set; }
}

Web Forms code:
        <asp:Repeater id="listDoc" runat="server" >
            <ItemTemplate>

                    <asp:Label id="lblName" runat="server" Text='<%#Eval("Name") %>'/>
                    <asp:Label id="lblCategory" runat="server" Text='<%#Eval("Category") %>'/>

            </ItemTemplate>
        </asp:Repeater>

Is there a way to display the results as

Name  |   Category
  music1  |   Audio and Music Cover
  movie1  |   Entertainment and Film
  movie2  |   Entertainment and Film
  series1 |   Entertainment and Film
  sports  |   Others

Instead of:

Name  |   Category
  music1  |   AudioCover
  movie1  |   EntertainmentFilm
  movie2  |   EntertainmentFilm
  series1 |   EntertainmentFilm
  sports  |   Others

Or is there a better approach for this?
Thanks in advance!
Answer: public static class EnumHelper<T>
   {
       public static string GetEnumDescription(string value)
       {
           Type type = typeof(T);
           var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

           if (name == null)
           {
               return string.Empty;
           }
           var field = type.GetField(name);
           var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
           return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
       }
   }

var movieDesc = EnumHelper<CategoryEnum>.GetEnumDescription("EntertainmentFilm");
var audioDesc = EnumHelper<CategoryEnum>.GetEnumDescription("AudioCover");
var othersDesc = EnumHelper<CategoryEnum>.GetEnumDescription("Others");

Above is an example to show how you can get description from your Enum value. Hope it helps
Answer: You can add these 2 members in your "Document" class. One is the read only property that gets the category value and calls the second member the static function that uses reflection to get the description of enum:
public string CategoryDescription
    {
        get
        {
            return GetEnumDescription(this.Category);
        }
    }

public static string GetEnumDescription(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }


Devel issue - "Rebuild the theme registry on every page load" won't work

Question:
I use D7. My site is being hosted on a "Shared" Server at Siteground.com. My site doesn't have any CSS/JS aggregation what so ever (see attachment), and I'm sick and tired of clearing the cache after the smallest of the CSS changes.
Many people told me that installing Devel and enabling "Rebuild the theme registry on every page load" should solve the problem, and will let me see the CSS changes after a refresh (F5/ctrl+r/ctrl+f5), but the fact is that even after I did that and enabled the Theme registry rebuilding option, I still have to clear caches to see the CSS changes, so I'm still stuck with this, and it's indeed frustrating!.
So, why would "Rebuild the theme registry on every page load" won't work? Why do I still need to flush all caches to see the CSS changes?
Answer: Not a straight solution and not really the best one but it seems that the co-problem; clearing the cache after every css change, was mainly server-sided, rather than Drupal sided --- I store at siteground.com and it was a Cpanel tool named "Supercacher" that caused all this mess and apparent lifetime wasting (and yet it raises the chance for good SEO when you site is finished).
Anyway, When you develop, better turn it off in Cpanel.
Btw, this was enough by it's own for me... Neither Devel nor any other external module is needed for this solution to work... Just disable the tool at Cpanel.


Integrate acts_as_rated plugin in rails application

Question: I am creating a user-boards applicationin rails in which a user owns any number of boards and can rate the boards.I want to install acts_as_rated plugin in my rails application. Since this is not available as a gem i have used following command to install it as a plugin:
rails plugin install svn://rubyforge.org/var/svn/acts-as-rated/trunk/acts_as_rated

This command installs all required plugin files in the vendor directory. Next I include the following code in my Boards model
class Board < ActiveRecord::Base
  acts_as_rated
end

Next i restart my console and run the following commands
u=User.first
 => #<User id: 1, first_name: "taroon", created_at: "2012-03-26 09:18:20", updated_at: "2012-03-26 09:18:20">

b=Board.first
 => #<Board id: 1, name: "boards_1", created_at: "2012-03-26 09:19:39", updated_at: "2012-03-26 09:19:39">

b.rate 5, u

It gives me the following error
ActiveRecord::StatementInvalid: Could not find table 'ratings'
from /home/swati/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.0.10/lib/active_record/connection_adapters/sqlite_adapter.rb:295:in `table_structure'
from /home/swati/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.0.10/lib/active_record/connection_adapters/sqlite_adapter.rb:186:in `columns'
from /home/swati/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.0.10/lib/active_record/base.rb:685:in `columns'
from /home/swati/.rvm/gems/ruby-1.9.2-p318/gems/activerecord-3.0.10/lib/active_record/base.rb:698:in `column_names'
from /home/swati/projects/test_projects/dummy_project/vendor/plugins/acts_as_rated/lib/acts_as_rated.rb:193:in `rate'
from (irb):6
from /home/swati/.rvm/gems/ruby-1.9.2-p318/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in `start'
from /home/swati/.rvm/gems/ruby-1.9.2-p318/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in `start'
from /home/swati/.rvm/gems/ruby-1.9.2-p318/gems/railties-3.0.10/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `'

I checked out the migartion but no migration for rating tables was created. Neither I have an idea of the fields in this table.
Can anyone please suggest me a solution for this problem..
Answer: The README of act_as_rated plugin says that you need to do your own migration based on this file: test/fixtures/migrations/001_add_rating_tables.rb.
Quote from the README:

The file test/fixtures/migrations/001_add_rating_tables.rb
  shows examples of all types of migration options.
See also the detailed documentation for the acts_as_rated
  method on how to declare it, and the rest of the documentation for how
  to generate the migration columns/files and how to use it.

So download and extract your module from here, then you can find the corresponding file and you can do your own migration.


Generating non-homogeneous spatial Gaussian data

Question: I want to generate a spatial data following multivariate Gaussian distribution.
However, I don't want it to be homogeneous, meaning I don't want the correlation/covariance to be homogeneous. I want it to be heterogeneous.
Any suggestions on how to generate such data?
Here is an example of what I mean by heterogeneous covariance matrix
   25.8621   25.1207   24.6305   24.3867
   25.1207   25.3719   24.8768   24.6305
   24.6305   24.8768   25.3719   25.1207
   24.3867   24.6305   25.1207   25.8621

There are four variables. As you can see the marginal variance is different which means C(0) is dependent on location. So does C(h) for any h. This is one method of generating heterogeneous data.
But I want some spatial data consisting of like land, lakes which have very less covariance between each other.
Comment: Sure, there are plenty of ways. It's important to specify more precisely what you mean by "multivariate gaussian" and non "homogeneous." After all, you can take any finite number of locations and generate multivariate gaussian values according to any positive semidefinite covariance matrix associated with those locations. Ultimately this kind of construction, by its very generality, is not very useful: what is your *real* question? Why do you need to generate such data?
Comment: @whuber. Yeah they are my criteria. I want a heterogeneous spatial gaussian field. Lets say  an area/land with a lake in between two pieces of land and I am measuring a field. All the locations in the land they have smooth covariance dropping at the lake suddenly. Similarly the location in the lakes have smooth covariance with the locations in the lake and dropping suddenly with the locations in the land. Let say Two pieces by land divided by a lake. I want to simulate some synthetic data with that criteria. I can try tuning the sharpness of the discontinuity
Comment: @whuber. Actually, my data is spatial and the variables in each location form a multivariate gaussian distribution. Normally, when I specify the correlation lets say, then I am assuming that it is homogeneous meaning it behaves the same everywhere. However, I want to make it heterogeneous meaning different blocks in the spatial data could have different correlation function so it's not consistent with distance
Comment: It is hard to tell whether you are talking about *heteroscedastic* variables, which may have different covariance matrices at different locations, or a *non-stationary* field, where the covariance matrix relates variables at one location to those at another location, or both. Could you please clarify this?
Comment: @whuber. I meant the first
Comment: Then what is the matter with stipulating separate covariance matrices for each of your spatial locations and generating data independently from those distributions?
Comment: @whuber. I can do that. But that will give me sharp discontinuity. Lets say I divide the region into four draw from a different covariance/correlation function/matrix. It will give me four totally discontinuous regions. I want somewhat smoother transition not totally discontinuous. Lets say I have two separate regions. For one I will draw samples from gaussian with mean 0, other with mean 10,further use different correlation structure. Definitely the values will be different. But I want somewhat smoother transition
Comment: @whuber. What I want is kind of a partition. Suppose I have land followed by a lake followed by the land itself. What I want is the variables in the land are correlated more with the variables of the land but less with that of lake and the variables of the lake with the variables of the lake itself. How can I generate such data. So I want some kind of discontinuity
Comment: @whuber. What about the second one and both?
Comment: Are those your only criteria? Or are you trying to reproduce the characteristics of actual data?
Comment: It's still unclear what you're looking for. For instance, you could independently generate data on land and on lakes: that would assure a vanishingly small covariance between land data and lake data. But what do you mean by "tune the sharpness"? I suspect you have some mental picture of what you want that you haven't fully or accurately expressed yet.
Comment: @whuber. If I generate a covariance matrix for a grid of size 100x100 with different marginal variance and the covariances not being a function of distance only but location itself, then it is heterogeneous by itself isn't it?
Comment: I'm afraid I don't understand adequately what you mean by "marginal variance" nor "heterogeneous," but if I interpret this as saying that when the covariance matrix is not invariant under translations of the data supports, then it must be a covariance matrix for a nonstationary process, then I can agree that you're right.
Comment: @whuber. I have an example in my original question. I am assuming that nonstationary is equivalent to heterogeneous. I have read that stationary being equivalent to homogeneous. So I am assuming the opposite case as well
Comment: What is your software tool?  (R, Matlab, Python, other)
Comment: @EngrStudent Matlab
Answer: You might find this useful:
http://www.mathworks.com/help/stats/gmdistribution.fit.html
MU1 = [1 2];
SIGMA1 = [2 0; 0 .5];
MU2 = [-3 -5];
SIGMA2 = [1 0; 0 1];
X = [mvnrnd(MU1,SIGMA1,1000);mvnrnd(MU2,SIGMA2,1000)];

scatter(X(:,1),X(:,2),10,'.')
hold on
options = statset('Display','final');
obj = gmdistribution.fit(X,2,'Options',options);
h = ezcontour(@(x,y)pdf(obj,[x y]),[-8 6],[-8 6]);

Now these covariances are only diagonal.  You can fix that by changing numbers.
The "gmdistribution.fit" is where you get the contour values.
So here is a plot that this would create:

Now you can see that it creates two multivariate gaussian distributions.  You only need to create one.
The function that generates the data is:
mvnrnd(MU1,SIGMA1,1000)

the mvnrnd, or mv-n-rnd is the multivariate normal random number generator.  Its inputs are the multivariate mean, covariance matrix, and desired sample count.  The output is an array of numbers of dimension informed by mu1.
The example covariance that you provided was 5 dimensional.  Here is something "hackable" that you should be able to convert for your own non-nefarious purposes.
%this creates a 5-dimensional mean
MU1 = rand(1,5)+[1,2,3,4,5];

%this creates a 5x5 covariance, diagonally dominant
SIGMA1 = 23*rand(5,5)+eye(5);

%this is for consistent notation.  previously it stacked multiple multivariate gaussians.
X = [mvnrnd(MU1,SIGMA1,1000)];

%this plots the dots
scatter(X(:,1),X(:,2),10,'.');

%this lets multiple plots overlay
hold on;

%this is a parm of the gm fit function.  It says "display final result".
options = statset('Display','final');

%this fits a gaussian to the data
obj = gmdistribution.fit(X,1,'Options',options);

%this plots the contours of the fitted gaussian over the domain of the data
h = ezcontour(@(x,y)pdf(obj,[x y]),[min(X(:,1)) max(X(:,1))],...
                                   [min(X(:,2)) max(X(:,2))]);

Best of luck.
Comment: Some explanation would be welcome for those who do not care, or are unable, to run your code.  What is it doing?  What numbers must be changed to produce non-diagonal covariances? How exactly does your answer solve the problem?
Comment: @whuber - that is how I often feel when I see R code.  I will get to it later on (hopefully this evening) but I will try to annotate and describe.


expected value of Consecutive numbers

Question: We choose randomly a subset $\mathit S$ of size 25 from the set $\{ 1,2,...,100\}$  , what is the expected value of number of Consecutive numbers in $\mathit S$?
Consecutive numbers in $\mathit S$: is a pair $\{ i,i+1\}$ where i$\in$$\mathit S$ and i+1$\in$$\mathit S$.
Comment: Hint: What is the probability that both $1$ and $2$ are in your randomly chosen subset?
Comment: it is:$\frac{\binom{98}{23}}{\binom{100}{25}}$ as Parcly mentioned below,that is the probability of any consecutive pairs not only 1 and 2.If we multiply that by number of possible consecutive pairs we will get the expected value we are looking for.@JMoravitz
Answer: Linearity of expectation is the key. There are 99 consecutive pairs, each one having a $\frac{\binom{98}{23}}{\binom{100}{25}}=\frac{25×24}{100×99}$ chance of being selected. Thus the expected number of consecutive pairs is $\frac{25×24×99}{100×99}=6$.

expected value of Consecutive numbers


How to add a textfield to an NSMutableArray

Question: I'm trying to present what was entered into a textfield into a nsmutable array that will later be displayed.
I think that the problem is in the -(void)viewDidLoad method but I included all of the code just in case.  The catch is that I will be leaving this page and then returning to it after another piece of information is selected.  As this happens, I need to keep track of EACH thing that was entered into the textfield. Thanks for any help!
<code>#import "EnteringCoursesViewController.h"
#import "SelectRotationController.h"

@implementation EnteringCoursesViewController

@synthesize classField;
@synthesize indicatedClass;
@synthesize labelClassTitle;
@synthesize selectRotationController;
@synthesize classesEnteredTable;

- (IBAction)chooseType {
    UIActionSheet *typeSheet = [[UIActionSheet alloc]
                                initWithTitle:@"Class types"
                                delegate:self
                                cancelButtonTitle:nil
                                destructiveButtonTitle:nil
                                otherButtonTitles:@"Core Class", @"Elective", nil];
    [typeSheet showInView:self.view];
    [typeSheet release];
}

- (void)actionSheet:(UIActionSheet *)typeSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        self.indicatedClass = classField.text;
        NSString *indicatedString = indicatedClass;
        NSString *greeting = [[NSString alloc]
                              initWithFormat:@"%@ meets 6 times per rotation", indicatedString];
        labelClassTitle.text = greeting;
        labelClassTitle.hidden = NO;
        [greeting release];
        [indicatedClass release];
    }
    else if (buttonIndex == 1) {
        self.indicatedClass = classField.text;
        NSString *indicatedString = indicatedClass;
        NSString *greeting = [[NSString alloc]
                              initWithFormat:@"%@ meets 3 times per rotation", indicatedString];
        labelClassTitle.text = greeting;
        labelClassTitle.hidden = NO;
        [greeting release];
        [indicatedClass release];
    }

}

- (IBAction)chooseFirstMeeting:(id)sender {
    SelectRotationController *selectView = [[SelectRotationController alloc]
                                                 initWithNibName:@"SelectRotationController"
                                                 bundle:[NSBundle mainBundle]];
    [selectView.navigationItem setTitle:@"First Period Day Choose"];

    [self.navigationController pushViewController:self.selectRotationController animated:YES];
    self.selectRotationController = selectView;
    [selectView release];
}

- (IBAction)enteredClassText:(id)sender {
    NSMutableArray *classesEntered = [[NSMutableArray alloc] init];
    [classesEntered addObject:indicatedClass];
    [classesEntered release];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (void)viewDidLoad {
    self.navigationItem.hidesBackButton = YES;
    [super viewDidLoad];

}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [classField release];
    [labelClassTitle release];
    [indicatedClass release];
    [selectRotationController release];
    [classesEnteredTable release];
    [super dealloc];
}

@end
</code>
Answer: If viewDidLoad is called "indicatedClass" is not yet initialised and therefore nil.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
<code>Important Raises an NSInvalidArgumentException if anObject is nil.
</code>
If you want to save that by leaving the view, add the addObject-Call in the viewDidUnload-method. Definitely you should check if the value is nil ;)
I dont see any alloc for your variable indicatedClass but an release!? It might be that the variable doesnt exists if viewDidUnload is calling.
EDIT
You init an NSMutableArray, add the object to this array and after that you released that object. Therefore the Data is away. You must save your array therewith you can use the content later. Keyword: NSUserDefaults ;)
Check also of nil values:
<code>- (IBAction)enteredClassText:(id)sender {
    if (indicatedClass != nil) {
       NSMutableArray *classesEntered = [[NSMutableArray alloc] init];
       [classesEntered addObject:indicatedClass];
       [classesEntered release];
    }
}
</code>
If the sender is an UILabel you can also use this snippet:
<code>- (IBAction)enteredClassText:(id)sender {
    if (sender.text != nil) {
       NSMutableArray *classesEntered = [NSMutableArray arrayWithObject:sender.text];
       // TODO: Save your array to NSUserDefaults...
    }
}
</code>
Comment: so what about this changed code? with the code in another method.


Question about interpretation of the divergence of a vector field

Question: I've been explained that a vector field, when seen as "arrows" in the plane, has 0 divergence when its magnitude doesn't change, i.e. when the "arrows" keep same length. But the following examples puzzle me:
$F(x)=x/|x|$ has always norm 1 but its divergence is not 0
$F(x)=x/|x|^2$ has not constant norm but its divergence is 0
Is there some contradiction or do I have a wrong/incomplete picture?
Comment: Just want to mention that looking on divergence in that way is really a very narrow point of view and losses it's actual physical meaning which is the net field flow through closed surface.
Answer: I don't think your examples contradict your view on the divergence. Take your first example, the divergence is
$$\frac{\partial}{\partial x}\left(\frac{x}{\sqrt{x^2}}\right) = \frac{\sqrt{x^2} - x\frac{2x}{2\sqrt{x^2}}}{x^2} = \frac{\sqrt{x^2} - \frac{x^2}{\sqrt{x^2}}}{x^2} = 0.$$
And similarly we find for your second example:
$$\frac{\partial}{\partial x}\left(\frac{x}{x^2}\right) = \frac{x^2 - x\cdot2x}{x^4} = -\frac{x^2}{x^4} = -\frac{1}{x^2},$$
which is clearly not zero.


PHP - Square Brackets Before Functions

Question: I use array_rand function  to get random arrays value.
after searching i found this code :
$random = $arList[array_rand($arList)];

My questions: Why use Square brackets before array_rand function? and when should we use it in our code?
[array_rand($arList)]

Answer: The square brackets don't have anything to with the array_rand() function. The code
$random = $arList[array_rand($arList)];

can be rewritten as
$randomIndex = array_rand($arList);
$random = $arList[$randomIndex];

The code basically gets a random index and passes the value of that index to the $random variable. The square brackets are PHP array syntax to represent a particular index in the array.
The first value of $arList would be $arList[0] (it starts counting from 0). The second would be $arList[1] and so on. So, as I mentioned before, array_rand doesn't have anything to do with the square brackets.
You can find out more about arrays in PHP here.

PHP - Square Brackets Before Functions


Exoplayer is removing preview with PageTransformer

Question: I have a viewPager with CubeTransformer, which is transforming every fragment. And inside every fragment is Image or Video view (with Exoplayer). And when you are trying to change a framgnet with transformation, exoplayer losses preview (I've got a black screen), even it's not playing. But after you changing condition to normal, preview is coming back
Ohterwise, if you will remove pageTransformer, review is not dissapears. How to keep preview always on screen?
CubeTransformer

class CubeTransformer : ViewPager.PageTransformer {
    override fun transformPage(view: View, position: Float) {
        if (view.visibility != View.VISIBLE) return

        view.apply {
            cameraDistance = (view.width * distanceMultiplier).toFloat()
            pivotX = if (position < 0f) view.width.toFloat() else 0f
            pivotY = view.height * 0.5f
            rotationY = 90f * position

            if (position < -1 || position > 1) {
                alpha = 0f // item not visible
            } else {
                alpha = 1f
            }
        }
    }

    private companion object {
        private const val distanceMultiplier: Int = 20
    }
}

VideoView
class VideoView(context: Context) : ConstraintLayout(context, null) {
    private val player = ExoPlayerFactory.newSimpleInstance(context, DefaultTrackSelector(), DefaultLoadControl())
    private val dataSourceFactory = DefaultDataSourceFactory(context, "android")

    private lateinit var model: Model

    init {
        inflate(context, R.layout.story_item_video, this)
        video_view.player = player
        video_view.keepScreenOn = true
        video_view.setBackgroundColor(Color.TRANSPARENT)
        video_view.setShutterBackgroundColor(Color.TRANSPARENT)
    }

    fun setData(model: Model?) {
        if (model== null) return

        this.model = model

        val mediaSource = HlsMediaSource
                .Factory(dataSourceFactory)
                .setExtractorFactory(DefaultHlsExtractorFactory())
                .createMediaSource(Uri.parse(model.streamLink))

        player.playWhenReady = true
        player.prepare(mediaSource)

        player.addListener(object: Player.EventListener {
            override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters?) {
            }

            override fun onSeekProcessed() {}

            override fun onTracksChanged(trackGroups: TrackGroupArray?, trackSelections: TrackSelectionArray?) {
            }

            override fun onPlayerError(error: ExoPlaybackException?) {
            }

            override fun onLoadingChanged(isLoading: Boolean) {
            }

            override fun onPositionDiscontinuity(reason: Int) {
            }

            override fun onRepeatModeChanged(repeatMode: Int) {
            }

            override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) {
            }

            override fun onTimelineChanged(timeline: Timeline?, manifest: Any?, reason: Int) {
            }

            override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {

            }
        })
    }
}

Answer: After a day of searching, I've found an answer to my question. You just need to add app:surface_type="texture_view" to your PlayerView
Comment: You just saved my life - the exact fix that i needed. Thanks


Why aren't these non-capturing regex groups working right?

Question: So I spent a lot of time on another stack overflow question, and the same problem came up with a previous one.  Non-capturing groups aren't working as I'd expect them to, or so I believe.
This is a silly example along the lines of someone else's CSS test string...
Here's my regex:
<code>(?:(rgb\([^)]*\)|\S+)(?:[ ]+)?)*
</code>
And here's the test string:
<code>1px solid rgb(255, 255, 255) test rgb(255, 255, 255)
</code>
I'm expecting match groups of "1px","solid", "rgb(255, 255, 255)", "test", "rgb(255, 255, 255)"
But I'm only getting the last token matched.
This is the link for testing:
http://regex101.com/r/pK1uG7
What's going wrong here?  I thought I had non-capturing groups down, and the way it's explained at the bottom of regex101 makes sense, including the "greediness".
Comment: http://regex101.com/r/kW7uE6
Comment: Have a look at option g
Comment: I know how to do it that way.  There's nothing related to this that I actually need to do :)  ... aside from it being a learning exercise.  I'm trying to understand why I can't reliably use non-capturing groups.
Answer: The capture group overrides each previous match. Capture group #1 first matches "1px", then capture group #1 matches "solid" overwriting "1px", then it matches "rgb(255, 255, 255)" overwriting "solid", etc.
Comment: @sdanzig Only .NET can match repeated groups, see this [extensive answer](http://stackoverflow.com/a/17004406). I've also [stumped onto this comment](http://stackoverflow.com/questions/13587023/capture-multiple-subgroups-of-repeated-group#comment18631689_13587023) which says that a certain implementation of Python supports it too.
Comment: @HamZa Well, I'd never choose .NET willingly, but that Python library makes me like Python just a bit more :)  But I don't want to make a habit of something that's generally not supported.  Regex muscle-memory should be portable.  I also worry about performance implications of supporting that.
Comment: Darn it, regexes would have been much more fun if you could repeat capturing groups.  You're right though.  Oh well.
Comment: There are a lot of different rules for different regex languages. You might be able to in one of them: http://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines
Comment: As others have said, you can use the g (global) option to accomplish what your trying to do, the problem isn't to do with the non-capturing groups.
Comment: @graeme, /g isn't a silver bullet though.  You'd have a lot more flexibility if you can specify how many matches of a group to capture.  For instance, one of these, two of these, and 3-5 of those.  While you can capture a repeated expression, you then have to further parse the sub-expression on a second pass.  Which is understandable, but it's the poop in my regex party.
Answer: For this you would want to use the global option:
<code>/(rgb\([^)]+\)|\S+)/g
</code>
http://regex101.com/r/kF2uV4
Non-capturing groups eliminate their results from the groups.
So if you want to match:
<code>"1px","solid", "rgb(255, 255, 255)", "test", "rgb(255, 255, 255)"
</code>
Then you don't want to use capturing groups that way.
See: What is a non-capturing group? What does a question mark followed by a colon (?:) mean?
See the answer of Ricardo Nolde at the top.
You're eliminating the ones you say you want back.
Comment: I'd kill my post, but you're title header might bring people that need it. It's a good question you asked.
Comment: Yeah, my misunderstanding didn't have anything to do with non-capturing groups.  @graeme couldn't have been any more on point than he was :)


Deploy an Azure VM of image Windows 10 Pro (with license)

Question: I am trying to create a Windows VM in Azure using the Azure Portal.
The image (base OS for the VM) I selected for the VM was :
Windows 10 Pro, Version 20H2 - Gen 1
But the licensing for this Image differs from windows server images.
Licensing section in basic tab of Azure VM creation also differs according to the image selected:

In the pricing calculator page, I can choose the option Windows OS before selecting a VM Size. And we can check the pricing for the licence too. But does that Windows OS refers to only Windows server ? Or does it mean Windows 10 Pro or Enterprise too?
When searched in the Microsoft documentation, they are mentioning Windows 10 Enterprise only as Windows 10 image. I couldn't find deploying VM with Windows 10 Pro, version 20H2 anywhere.
https://docs.microsoft.com/en-us/azure/virtual-machines/windows/windows-desktop-multitenant-hosting-deployment

Users must have one of the below subscription licenses in order to use
Windows 10 images in Azure. If you do not have one of these
subscription licenses, they can be purchased through your Cloud
Service Partner or directly through Microsoft.
Eligible subscription licenses:

Microsoft 365 E3/E5
Microsoft 365 F3
Microsoft 365 A3/A5
Windows 10 Enterprise E3/E5
Windows 10 Education A3/A5
Windows VDA E3/E5

It is very confusing.
Is it possible to deploy an Azure VM with Windows 10 Pro, Version 20H2 image ?
If yes, how should i get the license?

Can i purchase that Windows 10 pro licence with the Azure VM itself by paying more?

Or should i get a Microsoft 365 E3 license? (But the Microsoft 365 E3/E5/F3 all provides Windows 10 Enterprise licence with it, not windows 10 pro!)

Would Purchasing a new Windows 10 pro retail license for this azure VM work? If yes, when this VM is removed, Can i reuse that windows 10 pro license for any of my on-premises machine or for any other azure VM?

Or can i use/transfer an existing Windows 10 pro license (that i already used for my on-premises machine) to this Azure VM?
Answer: To deploy a Windows 10 VM in Azure you must already own Windows 10 Enterprise E3/E5 per user or Windows Virtual Desktop Access per user licences for Windows 10, you cannot use an Azure provided licence.
You cannot use Windows 10 Pro, it must be Enterprise. Details here.


Animate line chart in d3

Question: I find the example of animated line series in d3.
I am trying to do the same animation in my TS code.
but its not successful.
// Start Animation on Click
d3.select("#start").on("click", function() {
    var path = svg.append("path")
        .datum(data)
        .attr("class", "line")
        .attr("d", line);

    // Variable to Hold Total Length
    var totalLength = path.node().getTotalLength();

    // Set Properties of Dash Array and Dash Offset and initiate Transition
    path
        .attr("stroke-dasharray", totalLength + " " + totalLength)
        .attr("stroke-dashoffset", totalLength)
    .transition() // Call Transition Method
        .duration(4000) // Set Duration timing (ms)
        .ease(d3.easeLinear) // Set Easing option
        .attr("stroke-dashoffset", 0); // Set final value of dash-offset for transition
});

// Reset Animation
d3.select("#reset").on("click", function() {
    d3.select(".line").remove();
});

how can I embed the above code in my angular code.
The Data is fetching from API. Although the charts working perfectly fine, I need to just add the animation as per reference.
private drawPath(): void {
    let city = this.g
      .selectAll(".city")
      .data(this.TEMPERATURES)
      .enter()
      .append("g")
      .attr("fill", "transparent")
      .attr("class", "city")
      .style("stroke", "transparent");

    city
      .append("path")
      .attr("class", "line")
      .attr("d", d => this.line(d.values))
      .style("stroke", function(d) {
        return d.color;
      });

    let totalLength = city.length;
    console.log(totalLength, "Length total");

    city
      .append("text")
      .datum(function(d) {
        return { id: d.id, value: d.values[d.values.length - 1] };
      })
      .attr(
        "transform",
        d =>
          "translate(" +
          this.x(d.value.date) +
          "," +
          this.y(d.value.temperature) +
          ")"
      )
      .attr("x", 3)
      .attr("dy", "0.35em")
      .transition()
      .style("font", "10px sans-serif")
      .text(function(d) {
        return d.id;
      });
  }

Result as per @SmokeyShakers
Answer: Your totalLength calculation isn't right. Working from your example:
let totalLength = city.select('.line').node().getTotalLength();

city.select('.line')
    .attr("stroke-dasharray", totalLength + " " + totalLength)
    .attr("stroke-dashoffset", totalLength)
    .transition() // Call Transition Method
    .duration(4000) // Set Duration timing (ms)
    .ease(d3.easeLinear) // Set Easing option
    .attr("stroke-dashoffset", 0);

Comment: You really save my day,
Comment: I see some white stripe animate as well and cut the other series. do you have any idea why?
Comment: I didn't realize you had multiple lines. You'll need to use `selectAll` then `each` to get the computed length for each line and start the transitions.

Animate line chart in d3


When a reflection over the y axis is applied first, does it apply to a horizontal translation?

Question: For example, if I reflect something over the y axis and it becomes $f(x) = -x$, does horizontally shifting it $2$ units right cause it to look like this:
$$f(x) = -(x-2)?$$
Furthermore, if the horizontal shift is applied first, does the equation become $-(x-2)$ or $-x-2?$ My main question is, does the order of transformations matter when it is just horizontal translation, reflection in the y axis, or horizontal stretches.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: $-x=(-1)x$. If you instead had $f(x)=-2x$, what would you get after shifting it two units to the right?
Answer: A translation of a function horizontally two units to the right and then reflected about the y-axis:
Original Function: f(x)
Translated 2 to the right: f(x-2) = g(x)
Reflected about the y-axis: g(-x) = f(-x-2)
To understand more clearly, we can take a point on a function as an example. Let's use the function f(x) = x and take the point (3,3) on that function.
Beginning Point: (3,3)
Translated 2 units to the right: (5,3)
Reflected about y-axis: (-5,3)
Since our original function was f(x) = x, our new function should be f(-x-2) = -x-2.
Since h(-5) = -(-5)-2 = 3, our function demonstrates these translations.
A function reflected about the y-axis and then shifted horizontally:
Original function: f(x)
Reflected about the y-axis: f(-x) = g(x)
Translated 2 units to the right: g(x-2) = f(-(x-2)) = f(-x+2)
If we take the point (3,3) again:
Reflected about y-axis: (-3,3)
Translated 2 units to the right: (-1,3)
Since our original function was f(x) = x, our new function should be f(-x+2) = -x+2.
Since h(-1) = -(-1) + 2 = 3, our function demonstrates these translations.
Although most problems arise when transforming functions horizontally, order does matter when transforming vertically as well. For example, an upward shift of a function 3, then a reflection about the x-axis: -(f(x) + 3) is much different than a reflection about the x-axis, then vertical shift 3: -f(x) + 3
Answer: I think of this as a composition of functions.
let $h(x) = x-2$ be our horizontal translation and $g(x) = -x$ be our reflection
$(f\circ g) (x) = f(-x)$ is our function reflected.
$(f\circ h) (x) = f(x-2)$ is our function translated.
$(f\circ g\circ h) (x)$ is our function first translated then reflected.
$(g\circ h) (x) = -(x-2) = 2-x\\
(f\circ g\circ h) (x) = f(2-x)$
$(f\circ h\circ g) (x)$ is our function first reflected then translated.
$(h\circ g) (x) = g(x) - 2 = -x -2\\
(f\circ g\circ h) (x) = f(-x-2)$


Why is the Ribbon UI disappearing when I resize my app window horizontally?

Question: I wanted to adopt the Ribbon UI for my new project, I know it might be focusing more on the WoW factor than the true use of a Ribbon which is to replace the toolbar clutter. However when I started playing around with resizing the window, checking out some of the features related to automated scaling. After shrinking the window than a minimum width in size the Ribbon UI just disappeared, I even thought this might not exist in commercial software that have already adopted the Ribbon UI. Paint seems to be suffering from the same problem, don't know if Office 2007 or 2010 are also plagued by the same problem.
Answer: Paint and the other built-in Windows applications use the scenic Ribbon API that Microsoft is now including in the OS for all developers to use. Presumably, this is the same one you're using for your project. Microsoft Office uses proprietary ribbon controls, invented by the Office team in-house. That explains the difference in behavior.
And yes, it hardly shocks me that the ribbon disappears entirely when you make the window too small for it to appear. Eye candy has that way about it. Consider that the ribbon isn't very useful or functional when there isn't enough space to display its massive buffet of options. You can see that it tries to shrink itself down as much as possible, but you just can't fit 10 pounds in a 5 pound bag. Hiding it altogether seems like just as elegant an option as anything else.
Answer: This is spelled out in the Ribbon guidelines, page 76, lines 1026-1027:

Microsoft® Office User Interface Design Guidelines
Guidelines for Licensing the Microsoft Office User Interface
DEFINING GROUP COMBINATIONS FOR RIBBON RESIZING
13.. The entire Ribbon SHOULD completely disappear when the application window is less than 300 pixels wide or 250 pixels tall to provide more space for displaying the document.

Therefore the answer to your question about why it is doing that: it's trying to follow the rules.
What are you going to do with a ribbon that covers your entire window?
Comment: This seems to apply to the .NET WPF System.Windows.Controls.Ribbon also


Fontes instaladas não sendo exibidas em versões antigas do IReport

Question: Apenas para fins de catalogação, estive envolvido em um problema com a instalação de fontes em versões antigas do IReport (3.7.2 e 4.0.2), e o problema era que ao instalar uma fonte textual a mesma era listada no menu de configuração mas ao criar um novo relatório, a opção da nova fonte não era exibida no combobox de fontes disponíveis.
Demorei bastante para descobrir o problema tendo em vista que aparentemente ninguém mais teve esse problema além de mim, mesmo nos fóruns internacionais e pelo fato de não haver documentação suficiente da ferramenta. Vou postar a solução aqui como resposta e espero que ajude quem estiver passando por esse problema também.
Instalando a fonte 'N&D font' de exemplo:
Imagem da instalação N&D font
Como resultado atual a fonte não aparece no combobox de fontes: Problema fonte não aparece
Answer: Para que a fonte apareça, é necessário dois passos a mais:
1 - exportar a fonte como uma extensão .jar no menu de configuração de fontes:
Exportar como extensão
2- incluir a extensão .jar gerada no menu de configuração do classpath(não marcar reloadable):
Incluir fonte no classpath
Agora sim a fonte é exibida.
Segue o resultado final esperado:
Fonte sendo exibida corretamente
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Relationships between health conditions - Spearman's correlation?

Question: I am examining the relationships between health issues in pigs. I want to know which conditions tend to co-occur. All animals have at least one condition and 5 at most. I have coded each condition in SPSS as  0 = absent, 1 = present. How should I examine the relationships between these? I have tried a Spearman's correlation but something is not right, maybe I have organised the data in the wrong way.
This is an example of how I have organised the data:
<code>Pig ID  Tail lesions    Lameness    Bursitis
1            1              0           0
2            0              1           0
3            0              0           1
</code>
When I am looking at the output in SPSS I can't tell if/how these conditions are related to each other when I carry out a Spearman's correlation.
Comment: Please include more information. What is not right for example?
Comment: I haven't included animals that had no health conditions. I'm not sure if i should leave them out or not. When I do the analysis there are very few significant findings but from looking at the data, when one health condition is present, i lot of the time other ones are also present. This makes em think I'm doing something wrong
Answer: Peter's answer has addressed the technical part. For SPSS, you can do a few things to improve the readability of the output:
First, go to Edit > Options > Pivot Tables, and specify the output table to be in Academic format:

Academic format inserts some horizontal lines into the table and is generally more compact than the default SPSS output table. It'll make reading your matrix more enjoyable.
Second, because your sample size seems to be 171 with one missing in one variable, you can exclude that case and keep the sample size at 170. With that decision, you can simplify the output by clicking the Options button at the bivariate panel, and check the listwise option:

This should give a prettier table with correlation in the first row and p-value in the second.

To better visualize a correlation matrix, there are some tricks as well.
First, generate a matrix that doesn't have any significant correlation flagged by unchecking the flagging option:

Copy and paste your output table to MS Excel. Now, hold down your "Ctrl" key and highlight the cells that contain correlation coefficients. Do not highlight the diagonal cells because they are all 1.0 by default and are going to make visualizing harder:

Now, apply conditional formatting to give different gradients of color to the coefficient cells, that way you should be able to spot some pattern quite quickly:
Answer: If you just want to see which ones co-occur, and you don't have a huge number of conditions, relative to the number of pigs, you can make a matrix, with conditions in both rows and columns and the cells filled with "number co-occurences". Something like
<code>                 tail lesions lameness bursitis
tail lesions        X            2       1
lameness            X            X       3
bursitis            X            X       X
</code>
You would only need the upper triangle of the matrix (or lower triangle).
Whether you should include pigs that had no conditions depends on what you are trying to find out, but I'd guess you don't need to include them; in the above matrix, they would add nothing. However, you might want to include them in the denominator. E.g. you could say
Conditions 1 and 2 occurred together in 5 pigs, which is 12% of all pigs that had any condition, and 2% of all pigs in the sample.
What else you might do also depends on what you want; possibly cluster analysis or factor analysis or even multidimensional scaling. But the above might be enough.
Comment: Thanks, I want to be able to say for example, when tail lesions are present, there is a 20% chance that lameness will also be present
Comment: Then you can look at what % of the pigs with tail lesions also have lameness, or whatever other particular relationship you want to examine.