Glivenko-Cantelli Theorem

Question: The Glivenko-Cantelli Theorem states that if $F$ is a distribution function, $X_1,\dots,X_n \sim F$, and $\hat{F}_n$ is the empirical distribution function, then
$$\sup_{x \in \mathbb{R}} \lvert \hat{F}_n(x) - F(x) \rvert \xrightarrow{a.s.} 0 . \tag{1}$$
How does this differ from simply stating the following?
$$\hat{F}_n(x) \xrightarrow{a.s.} F(x) \tag{2}$$
Using the definition of convergence almost surely, from (1):
$$\begin{align*}
\mathbb{P} \left( \lim_{n\rightarrow\infty} \left\lvert \sup_{x \in \mathbb{R}} \lvert \hat{F}_n(x) - F(x) \rvert \right\rvert = 0 \right) &= 1 \\
\mathbb{P} \left( \lim_{n\rightarrow\infty} \sup_{x \in \mathbb{R}} \lvert \hat{F}_n(x) - F(x) \rvert = 0 \right) &= 1 \tag{1a}
\end{align*}$$
Using the definition of convergence almost surely, from (2):
$$\begin{align*}
\mathbb{P} \left( \lim_{n\rightarrow\infty} \left\lvert \hat{F}_n(x) - F(x) \right\rvert = 0 \right) = 1 \tag{2a}
\end{align*}$$
To me, it seems that (1a) and (2a) are equivalent statements because of the least upper bound, and thus (1) and (2) are equivalent statements. But I have a feeling that I'm missing a subtle difference since otherwise I would think the Theorem would just be stated the simpler way (Equation (2)).
Answer: The differerence is in uniform convergence.  1 is saying that for all x there is a single n such that error is less than epsilon ( uniform). The other one is saying for each x there is a large enough n that error is less than epsilon(pointwise). An example from wikipedia of pointwise but not uniform convergence is $ f_n (x)=x^n $ on $0\le x\le 1$. You need larger and larger n as you get closer to $x=1$.
Comment: Hmm. Did you really mean for that to end with "closer to $x=0$"? I'd have thought that the need for larger $n$ was near $x=1$.
Answer: It is perhaps worth noting that pointwise convergence of $\hat F_n(x)$ to $F(x)$ already implies uniform convergence where $F$ is continuous (because the cdfs are bounded and monotone).  More precisely, if $[a,b]$ is an interval that does not contain any discontinuities of $F$, the convergence is uniform on $[a,b]$ -- and that's still true for $a=-\infty$ or $b=\infty$.
The conclusion of the Glivenko-Cantelli theorem is stronger: that the convergence is uniform even at discontinuities, and this is important. By contrast, if $\hat F_n$ are a sequence of empirical CDFs from distributions $F_n$ converging in distribution to $F$, we have pointwise convergence of $\hat F_n(x)$ to $F(x)$, and uniform convergence on intervals with no discontinuities, but not uniform convergence everywhere.

Glivenko-Cantelli Theorem


Reflexivity of $\ell^p$

Question: I'm having bad difficulties in understanding how to prove that $\ell^p$ with $1<p<\infty$ are reflexive spaces.
Every text I have consulted give that as a trivial result because "observing that $(\ell^p)^{\ast\ast} = ((\ell^p)^\ast)^\ast$, $\ell^q$ is isomorphic to $(\ell^p)^\ast$ and $\ell^p$ is isomorphic to $(\ell^q)^\ast$ then $(\ell^p)^{\ast\ast}$is isomorphic to $\ell^p$ and the result follows trivially".
Maybe trivially for you, books!! I want to show formally that the canonical application $J_{\ell^p}:\ell^p \rightarrow (\ell^p)^{\ast\ast}$ is surjective.
I tried for hours but nothing, I'm blocked.
Let be $j_p: \ell^q \rightarrow (\ell^p)^\ast$ and $j_q: \ell^p \rightarrow (\ell^q)^\ast$ the isomorphisms that I have.
Let be $z \in (\ell^p)^{\ast\ast}$. I want to find an $x \in \ell^p$ such that $J_{\ell^p}(x)=z$, i.e. $\langle z,x'\rangle=\langle x',x\rangle$ for every $x' \in (\ell^p)^\ast$.
Probabily there will be many "$j_p, j_q, j_p^{-1}, j_q^{-1},J_{\ell^p}$" but I have no idea about how to choose them.
Some help is greatly appreciated!
Thank you!
Comment: You really do want to use the definition of the double dual as an iterated dual. Then if you can show that $\ell^q=(\ell^p)^*$, it follows by dualizing $\ell^q$. Can you prove the $\ell^p=(\ell^q)^*$?
Comment: Yes I can prove that $l^p$ and $(l^q)^\ast$ are isomorphic. The isomorphism is $j_q$. I just don't know how to use this isomorphism.
Comment: By definition $X^{**}$ is the dual space to $X^*$. Since $(\ell^p)^*=\ell^q$, by definition $(\ell^{p})^{**}=(\ell^{q})^{*}=\ell^p$
Comment: Yes, this is readily seen! My problem is to show that this equality is the same of the surjectivity of the canonical application $J_{l^p}$!
Comment: Benzio:  in that case it's just a matter of writing it as a composition. See my answer below.
Comment: One has to be careful with the definition of reflexivity: It is **not enough** that $X^{**}$ is isomorphic to $X$ but the canonical embedding of $X$ into $X^{**}$ has to be an isomorphism. James constructed non-reflexive Banach spaces isomorphic to their second dual.
Answer: So you have the canonical maps:

$$\begin{cases} f_q: \ell^p\to (\ell^q)^* \\ f_p: (\ell^q)^*\to (\ell^p)^{**}\end{cases}$$

which are the isomorphisms between $\ell^p$ and $(\ell^q)^*$ and $\ell^q$ and $(\ell^p)^*$ respectively. Then just write $f_p\circ f_q=j_p:\ell^p\to (\ell^p)^{**}$.
Comment: @Benzio I've tried to clarify the language. See if it makes more sense now.
Comment: @Benzio I got notation mixed up, I'll switch it. I guess that's what they mean when they say "mind your p's and q's." In any case your notation isn't standard, so really I could define my $j$ functions to be whatever. ;-)
Comment: shouldn't $j_p$ go from $l^q$ to $(l^p)^\ast$ and viceversa for $j_q$? Why you are saying $j_p: l^p \rightarrow l^q$? What operator do you intend with $j_p$?
Comment: no problem for the different notation, but the isomorphisms I have are from $l^p$ to $(l^q)^\ast$, not to $(l^p)^\ast$. Or maybe you are not intending the same thing as mine.
Comment: @Benzio OHHHHH, I see. Yes, your notation confused me with all the different $J$s. One more edit, I'll just use new names, it's easier that way.
Comment: I'm sorry if I insist! You are saying that $f_q$ is the isomorphism between $\ell^p$ and $(\ell^q)^\ast$ but you write anyway: "$ f_q: \ell^p\to \ell^q=(\ell^p)^*$" On the right I see $(\ell^p)^*$ not $(\ell^q)^*$! Am I having a mistake pretending that what you claim to be an isomorphism between $\ell^p$ and $(\ell^q)^\ast$ should be like $ f_q: \ell^p\to (\ell^q)^* \neq \ell^q$? (Probabily yes but why!? :-p)
Comment: @Benzio do you see now? I mean, the second map isn't even any random isomorphism, it'literally the **equality** isomorphism because $X^{**}$ is *defined* to be $(X^*)^*$. It's so simple, it's hard to write more, but ultimately the composition of surjective functions is surjective, and that's really **all** that's going on.
Comment: I've answered the post, and in my answer there still are some question about your answer. Take a look if you mind :-)
Answer: This is the answer I've unravelled:
Let $z \in (\ell^p)^{\ast\ast}$.
I want to prove that exists $x \in \ell^p$ such that $\langle z,f\rangle=\langle f,x \rangle$ for every $f \in (\ell^p)^\ast$.
I know that there are the isomorphisms:
$j_p: \ell^q \rightarrow (\ell^p)^\ast$ and $j_q: \ell^p \rightarrow (\ell^q)^\ast$
Now, fix $z \in (\ell^p)^{\ast\ast}$.
$\langle z, f\rangle = \langle z, j_p(y)\rangle$ for some $y$ in $\ell^q$.
I define $g(y)=\langle z, j_p(y)\rangle$. It's seen that $g$ is an element of $(\ell^q)^\ast$
then
$\langle z, f\rangle = \langle z, j_p(y)\rangle = \langle g, y \rangle$
Being an element of $(\ell^q)^\ast$, the number $\langle g, y \rangle$ can be represented as $\sum_{k=1}^\infty x_ky_k$ for some $x \in \ell^p$
Now fix that $x$. This sum, $\sum_{k=1}^\infty x_ky_k$ can be seen as a functional $u$ on $\ell^p$ described by $j_p(y)$.
Then $u=f$ and $\langle z, f\rangle = \langle z, j_p(y)\rangle = \langle g, y \rangle = \sum_{k=1}^\infty x_ky_k = \langle f,x \rangle$ as I wanted.
${}$
Now the answer seems correct to me, but still a bit confused because I would like to avoid to mix the $\langle \cdot, \cdot \rangle$ with the sum notation. And some suggestions to avoid that are appreciated.
After I would like to understand why the answer provided by Adam Hughes is rigorous:
why does he claims that his $f_p: (\ell^q)^*\to (\ell^p)^{**}$ is the equality isomorphism? Indeed it's needed the isomorphism $j_p: \ell^q \rightarrow (\ell^p)^\ast$ to show that it is the equality isomorphism, but how? And then, acknowledged that his $f_p\circ f_q$ is an isomorphism from $l^p$ to $(l^p)^{\ast\ast}$, why it is said that it's equal to the canonical isomorphism?
I'm slow in understanding... I know! :-p
Answer: This can be done with adjoints and I think it is more enlightening to do it this way.
Lemma: If $T:X\rightarrow Y$ is a surjective isometry between Banach spaces, then $T^*: Y^* \rightarrow X^*$ is also a surjective isometry.
Proof: We will only need to use that $T^*$ is surjective, but this is immediate: $T^*(x^* \circ T^{-1})=x^*$. I will prove that it preserves the norm because it is also straightforward, but we will not need this:
$$\lVert T^*(y^*)\rVert=\sup_{x\in B_X} \lVert y^*(T(x))\rVert=\sup_{y\in B_{Y}}\lVert y^*(y)\rVert=\lVert y^*\rVert\quad \quad\square$$
Now let us continue with our quest of proving reflexivity of $\ell^p$ for $1<p<\infty$.
If we consider the canonical surjective isometry $\phi: (\ell^p)^*\rightarrow l^q$, then its adjoint will satisfy:
$$\phi^*:(\ell^q)^*\rightarrow (\ell^p)^{**}$$
Next we consider $\psi: \ell^p \rightarrow (\ell^q)^*$ the canonical isometry. By using these maps we gain with our Lemma that composition is surjective:
$$\phi^*\circ \psi: \ell^p\rightarrow(\ell^p)^{**}$$
Furthermore let us denote $q$ and element of $\ell^q$ and $p$ an element of $\ell^p$ and $f_p$ the dual version of $p$ in $(\ell^q)^*$ and $f_q$ the dual version of $q$ in $(\ell^p)^*$:
$$\phi^* \circ \psi(p)(f_q)=\phi^*(f_p)(f_q)=f_p(\phi(f_q))=f_p (q)=\sum p_i q_i=f_q(p)=J_{\ell^p}(p)(f_q)$$
Hence, $J_{\ell^p}=\phi^* \circ \psi$ which we know to be surjective!

Reflexivity of $\ell^p$


Como informar de quem uma classe se vai estender em tempo de execução?

Question: Tenho a classe
<code>public class Conhecimento{}
</code>
Essa classe se estende de uma outra classe "CteProc"
Só que essa classe CteProc tem "versões" exemplo.
v200.CteProc
v300.CteProc
Meu problema é que na criação da classe Conhecimento preciso informar se ele vai se estender da CteProc 200 ou CteProc 300 de acordo com a versão que recebo.
Queria saber se é possível fazer isso, alterar o extends ou deixar dynamic.
Comment: Seria melhor se explicasse qual é o problema que quer resolver.
Comment: @Articuno parece erro de arquitetura, se tem duas classes para serem herdadas, devem existir duas classes herdadas, simples assim, mas se o problema for outro aí pode ter uma solução, pode ser caso de composição, talvez usando um *pattern*  específico.
Comment: Criar classe em tempo de execução?
Comment: Não, as classes já existem, só quero informar de quem uma classe vai se estender em tempo de execução.
Comment: Não tem como, se a classe já está escrita, como você vai alterar após compilado, isso aparentemente é impossivel. Pensei que você queria escrever a classe em tempo de execução.
Comment: Não entendi. Ou se entendi, é o normal. Se o entendimento for o contrário do que estou pensando, aí não dá e nem faria sentido. Se esclarecer, talvez colocar um exemplo, tento comentar melhor ou responder. É isto o que o Articuno está dizendo? Talvez tenha como criar um padrão de projeto.
Comment: Irei editar a pergunta.
Comment: Se quer fazer isso é melhor usar só _generics_, não faz muito sentido em usar herança assim.
Comment: É, parece gambiarra e deve ter outra forma de resolver isso, faça o que o ramaral disse.
Comment: @bigown se não entendi errado, me parece que ele quer alterar a herança em "tempo de execução". Isso não seria o mesmo que "reescrever a classe"? Me parece algo meio impossivel, já que na execução, a classe já está compilada.
Comment: Esse 'de acordo com versão que vc recebe'. Vc recebe como? O que define  que será uma ou outra? E qual a diferença de uma pra outra? Os métodos de ambas as classes são os mesmos porém com execuções diferentes?  Me parece que vc esta querendo usar herança e polimorfismo. Mas tá faltando um entendimento de como funciona aí não consegue encaixar no seu problema.
Answer: Não é possível uma classe, numa determinada altura, herdar de A e em outra altura herdar de B.
Se eu entendi bem o que pretende, use uma destas abordagens:

Bridge Design Pattern
Se as classes v200.CteProc e v300.CteProc implementam uma mesma interface(CteProc), ou seja as duas classes tem os mesmos métodos mas com implementações diferentes.
Implemente a classe Conhecimento de forma a receber um objecto de uma classe que implemente a interface CteProc.
De acordo "com a versão que recebo" você passa um objecto v200.CteProc ou v300.CteProc.
Internamente, a classe Conhecimento, usa os métodos da interface cuja implementação é dada pelo objecto passado.
Adapter Design Pattern
Se as classes v200.CteProc e v300.CteProc não implementam uma mesma interface, ou seja as duas classes tem métodos diferentes(nomes ou assinaturas).
Extraia uma interface a partir da classe Conhecimento.
Escreva duas classes que implementem essa interface: v200.Conhecimento e v300.Conhecimento.
Para o processamento, a classe v200.Conhecimento usará internamente um objecto v200.CteProc e a v300.Conhecimento um v300.CteProc.
De acordo "com a versão que recebo" você usa um objecto v200.Conhecimento ou v300.Conhecimento.
Os clientes da antiga classe Conhecimento deverão passar a referenciar a interface.


Feeds import - If title has "=" at the end, check whether duplicate content exists

Question: I have an XML to import products to Drupal Commerce site. But some products are duplicates. Duplicate products are having "=" at the end of their title, but NOT all products with "=" at the end of their title are duplicates.
What I need is, on importing XML, check whether product exists, if exist, do not import (easy), if product has "=" at the end of title, check whether product WITHOUT "=" at the end of the title exist. If exist, do not import, else import.
I am totally lost how to do that, should I write some feeds tamper module to handle such a behaviour or go completely outside the drupal and parse XML, compare it to current product database of drupal and export new XML to import to drupal? Any advice would be greatly appreciated!
Answer: Set product title as unique
First, you'll need to set the product title as unique. This way, Feeds will only import one product per title.
Is the "=" at the end important to the product title? If not, you'll need to find a way to remove that sign from the product title. This way, Feeds will treat a product title with an "=" as equal to the same product title without the "=".
Find replace Tamper plugin (D7 and D8)
If you are certain that the sign "=" is only used at the end of the product title (or meaningless if it appears anywhere else), you can use the easiest solution: Use the Tamper plugin "Find replace" to replace "=" with "". This plugin is available for both D7 and D8.
Find replace REGEX Tamper plugin (currently D7 only)
If the "=" sign can appear elsewhere in the product title and is important there, you'll need to use the "Find replace REGEX" tamper plugin. In the field "REGEX to find", enter a regex that matches strings ending with a "=":
/\=$/

And replace with an empty string.
D7 or D8?
At the moment of writing, the Tamper plugin "Find replace REGEX" has not been ported to D8 yet (see https://www.drupal.org/project/tamper/issues/2975179 for the status). If you are using D8 and the Tamper plugin "Find replace" does not suffice, you'll to create a custom module and listen to the Feeds parse event in order to apply modifications on the product titles.
Example:
namespace Drupal\mymodule\EventSubscriber;

class ProductFeedSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[FeedsEvents::PARSE][] = ['afterParse', FeedsEvents::AFTER];
    return $events;
  }

  /**
   * Act on parser result.
   */
  public function afterParse(ParseEvent $event) {
    // Check if this is the feed we want to edit.
    $feed_type_id = $event->getFeed()->getType()->id();
    if ($feed_type_id != 'myfeedtype') {
      // Not the feed type we want to edit. Abort.
      return;
    }

    /** @var \Drupal\feeds\Result\ParserResultInterface */
    $parser_result = $event->getParserResult();

    /** @var \Drupal\feeds\Feeds\Item\ItemInterface */
    foreach ($parser_result as $item) {
      // Get product title.
      $title = $item->get('title');

      // Remove "=" sign from the end if there is any.
      $title = preg_replace('/\=$', '', $title);

      // Set title back on item.
      $item->set('title', $title);
    }
  }

}

Be sure to replace "myfeedtype" in the example above with the name of the feed type that you created for importing products.
An event listener always needs to be declared in your module's 'services.yml' file:
services:
  mymodule.product_feed:
    class: Drupal\mymodule\EventSubscriber\ProductFeedSubscriber
    tags:
      - {name: event_subscriber}

In the D7 version, you would need to implement the hook hook_feeds_after_parse() to alter the parsed result.
Comment: Thank you very much for a very detailed explanation! I am using D7. Based on your explanation I assume feeds tamper functions happen before importing, not after, Now I am curious, I am trying to set Title of commerce product to be a unique, but I am using x-path parser module and it has no option to set title value as unique.
Comment: So, I tried to set a product title as unique, but it did not worked by any way. Then I somewhere read that GUID must not have to be only a number, so I set GUID to be mapped to @Title, and then I proceeded with your suggestions. It works nicely so I mark this answer as correct. Even field validation module did not helped me to set title as unique in feeds import.


Finding a basis for the intersection of two vector subspaces.

Question:
Suppose:
$V_1$ is the subspace of $\mathbb{R}^3$ given by $V_1 =
 \{(2t-s,t,t+s)|t,s\in\mathbb{R}\}$
and
$V_2$ is the subspace of $\mathbb{R}^3$ given by $V_2 =
 \{(s,t,s)|t,s\in\mathbb{R}\}$.

How could a basis and dimension for $V_1 \cap V_2$ be determined?
I thought of maybe setting the respective components of the two spaces equal to each other such that $2t-s = s$, $t=t$, and $t+s=s$.
Solving each of these equations it can be found that $2t=2s$, $t=t$, and $t=0 \implies s=0 \implies V_1 \cap V_2 = \{(0,0,0)\} \implies \text{dim}(V_1 \cap V_2)=0$.
This seems like it isn't right though, but I'm really uncertain.
Comment: You can't use the same $s,t$ for both equations.
Comment: $V_1$ and $V_2$ are both planes through the origin, so if they're not identical their intersection must be a line.
Comment: @amd What indicates that $V_1$ and $V_2$ are planes through the origin? If that's true, where would I go from there?
Comment: @copper.hat I'd started to suspect that.That leaves me pretty lost, unfortunately. I'm uncertain of how exactly to translate the two spaces to their unparemeterised forms, which I've been told are planes.
Comment: There are two free parameters in the specifications of each space, so they're both two-dimensional. You can verify this by separating each into a linear combination of two linearly independent vectors. E.g., $(2t-s,t,t+s)=s(-1,0,1)+t(2,1,1)$. You're on the right track, but take copper.hat's comment into account: instead of setting $(2t-s,t,t+s)=(s,t,s)$, set $(2t-s,t,t+s)=(a,b,a)$ and solve.
Answer: Here is one way:
The idea is to write $V_k$ as $\ker u_k^T$ for some $u_k$,
then
$v \in V_1 \cap V_2$ iff  $v \in \ker \begin{bmatrix} u_1^T \\ u_2^T \end{bmatrix}$. If $u_k$ are linearly independent, then if $u_3\neq 0$  is
orthogonal to $u_1,u_2$, we see that $V_1 \cap V_2 = \operatorname{sp} \{ u_3 \}$.
In the following we use the fact that $(\ker C)^\bot = {\cal R} C^T$.
It should be straightforward to show that $\dim V_1 = \dim V_2 = 2$,
Hence $\dim V_1^\bot = \dim V_2^\bot = 1$.
Suppose $(x,y,z)^T \in V_1^\bot$, then we must
have $t(2x+y+z) + s(z-x) = 0$ for all $s,t$. Hence $z=x$ and $y=-3x$. Letting
$x=1$ gives $u_1=(1,-3,1)^T$ and hence $V_1^\bot = \operatorname{sp} \{u_1\}$, and so $V_1 = \ker u_1^T$.
Suppose $(x,y,z)^T \in V_2^\bot$, then we must have $s(x+z)+ty=0$ for all $s,t$. Hence $y=0, z=-x$. Letting $x=1$ gives $u_2=(1, 0 ,-1)^T$
and hence $V_1^\bot = \operatorname{sp} \{u_2\}$, and so $V_2 = \ker u_2^T$.
Hence $v \in V_1 \cap V_2$ iff $v \in \ker u_1^T$ and $v \in \ker u_2^T$ iff
$u \in \ker \begin{bmatrix} u_1^T \\ u_2^T \end{bmatrix}$.
Solving
$\begin{bmatrix} u_1^T \\ u_2^T \end{bmatrix} (x,y,z)^T = 0$ gives
$z=x, y = {1 \over 3} 2x$. Choosing $x=3$ gives $u_3 = (3,2,3)^T$.
Hence $v \in V_1 \cap V_2$ iff $v \in \operatorname{sp} \{ u_3 \}$.
Comment: Hmm, the idea is very straightforward, but I seem to unable to communicate effectively above. May try again in the morning.
Answer: Another possibility:
Let us first consider the set of points in $V_1\cap V_2$. Suppose $v\in V_1\cap V_2$. Then $v$ must be in the form of $(a,b,a)$ for some $a,b\in \mathbb{R}$. In addition. $(a,b,a)=(2t-s,t,t+s)$ for some $t,s\in \mathbb{R}$. Then we obtain the relation $2a=3b$. This shows that $V_1\cap V_2\subseteq \{ (a,2a/3,a) | a\in \mathbb{R} \}$.
Now we will show that $\{ (a,2a/3,a) | a\in \mathbb{R} \}\subseteq V_1\cap V_2$. Note that for $(t,s)=(2/3,1/3)$, we have that $(2t-s,t,t+s)=(1,2/3,1)$. Thus $(1,2/3,1)\in V_1\cap V_2$. Since $V_1\cap V_2$ is a subspace, we have that $\{ (a,2a/3,a) | a\in \mathbb{R} \}\subseteq V_1\cap V_2$
Hence $V_1\cap V_2= \{ (a,2a/3,a) | a\in \mathbb{R} \}$. This gives us the basis and dimension for $V_1\cap V_2$.
Answer: In general, to find the intersection of two subspaces, you express a vector in the intersection in two different ways and then solve the system of linear equations that result, a la copper.hat's answer.
In the special case of $\mathbb R^3$, there's a quick and dirty way to find the intersection of two different planes through the origin. Since their intersection will be orthogonal to both normals, you can get the answer by computing three cross products—two to compute the normals and another to find a vector orthogonal to them. With only 3 dimensions, this last vector must lie on the line of intersection.
To illustrate, the plane $V_1$ is spanned by $(-1,0,1)^T$ and $(2,1,1)^T$, so a normal is $(-1,0,1)^T\times(2,1,1)^T=(-1,3,-1)^T$, while $V_2$ is spanned by $(1,0,1)^T$ and $(0,1,0)^T$ with normal $(1,0,1)^T\times(0,1,0)^T=(-1,0,1)^T$. The cross product of these normals is $(-1,3,-1)^T\times(-1,0,1)^T=(3,2,3)^T$, just as was found by the general method.
This also gives a way to find the intersection of two lines in the plane or the line through two points in the plane: use homogeneous coordinates and take their cross product.


Cancel button/touch for UIWebView

Question: I wonderd if there is any way to make the user dismiss the WebView window if he doesn't want it anymore on the screen...?
I looked at this post but i didn't understand it well.
How to cancel a UIWebView?
can anyone give me an example please?
This is the code i have:
CGSize webScreen1;
webScreen1 = [[UIScreen mainScreen] applicationFrame].size;
CGRect webFrame1 = CGRectMake((webScreen1.width/11.0) ,(webScreen1.height/19.0)  ,webScreen1.width/1.2,webScreen1.height/1.25);
defaultWebView.frame = webFrame1;
self.defaultWebView = [[UIWebView alloc] initWithFrame:webFrame1];
self.defaultWebView.backgroundColor = [UIColor whiteColor];
self.defaultWebView.scalesPageToFit = YES;
self.defaultWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

defaultWebView.inputView.hidden = YES;

[self.view addSubview: self.defaultWebView];

[self.defaultWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:
                                                            [NSString stringWithFormat:(NSString *)@"%@", @"http://www.google.com"]]]];

Thanks!
Answer: There is no such thing as cancel a webView, what you need to do is remove the UIWebView from the parent view. If your UIWebView is a subview of self.view then you can provide a button named Close which behaves like this -
- (IBAction)closeWebView:(id)sender
{
    [self.webView removeFromSuperView];
    self.webView = nil;
    return;
}

This should remove the webview from your view.
Comment: Thanks Srikar!
For anyone who needs - this is how i did it:

    UIButton* hideWebViewBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    hideWebViewBtn.frame = CGRectMake(5, 5, 20, 30);
    [hideWebViewBtn addTarget:self action:@selector(hideWebViewBtn:) forControlEvents:UIControlEventTouchUpInside];
    [defaultWebView addSubview:hideWebViewBtn];
    [self.defaultWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:
    [NSString stringWithFormat:(NSString *)@"%@", @"http://www.oranim.ac.il/sites/heb/guide/lessons-administration/faq/Pages/default.aspx"]]]];
Comment: And this is the method that release the webview:

    - (IBAction)hideWebViewBtn:(id)sender
{
    [self.defaultWebView removeFromSuperview];
    self.defaultWebView = nil;
    return;
}
Answer: ...way to make the user dismiss the WebView window...
[self.defaultWebView removeFromSuperview];

Answer: look I will explain what happenes in the post you attached above and you will understand the technique,
the UIWebview is a component which views an web page, it may be html or other types,
there is one way to hide your webview is to add an action in the html of the webview and ovveride the request in the code of your app,
when you click on link or ahref or any action on UIwebview there is a delegate method which automatically runs before continuing with the request

(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

you can add a button or link on the html page and ovveride the request on this method
for example
Thing to click
and in the delegate method

(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] absoluteString] isEqualToString:@"http://hideWebView/"]) {
    [self.webview setHidden:YES];
    return NO;
}
return YES;
}

here you ovveride the request http://hideWebView/ and in the delegate you searched for this request and then hiddes the web view or anything else you want to do

Cancel button/touch for UIWebView


Allow users to moderate taxonomy terms

Question: Is there a way to allow users to moderate nodes and their comments by taxonomy terms? And also allow other moderators to add users to to that term as well? It seems that the standard roles aren't granular enough. I don't want users assigned to a "moderator" role to be able to moderate ALL nodes and comments, just those within a particular taxonomy term.
Basically allowing each term to be a "discussion board" where a group of users are the moderators of that term. Similar to how Reddit works.
Thanks
Answer: Taxonomy Access Control - access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.
Answer: Organic groups is another possibility that is more focussed on the people instead of categories.

Allow users to moderate taxonomy terms


file or image migrate from drupal 6 to drupal 7 using Migrate D2D module?

Question: I am using migrate_d2d module to migrate my Drupal 6 website to Drupal 7, I succeed to transfer every thing except for images.
I read the new documentation sever times and I managed to migrate the files into the file_managed but I cant link them with the nodes any hints or examples will be greatly appreciated
Answer: In your migrate register function define the files table migration.
<code>/**
 * Migrate files table
 */
// The description and the migration machine name are also required arguments,
// which will be unique for each migration you register.
$file_arguments = $common_arguments + array(
  'description' => t('Migration of files from Drupal 6'),
  'machine_name' => 'Files',
  'source_dir' => '/var/www/drupal6/files/xxxx/',
);

// We just use the migrate_d2d D6 migration class as-is.
Migration::registerMigration('DrupalFile6Migration', $file_arguments['machine_name'],
$file_arguments);
</code>
Then in your node migration class set the files migration as the source.
<code>// Map the image field to the new image field, base this on the Files migration
// to map the files to the imported files table.
$this->addFieldMapping('field_image', 'field_image')
  ->sourceMigration('Files');
$this->addFieldMapping('field_image:file_class')
  ->defaultValue('MigrateFileFid');
</code>
Hope that helps
Comment: thanks ,I think this will do very well I was missing                  $this->addFieldMapping('field_image:file_class')
  ->defaultValue('MigrateFileFid');                   will try  it and come back to you
Comment: Does this work also for user profile pics?
Answer: Migrating images and files are similar. Check this:
Migrate Contents from Drupal 6 to Drupal 7 Using Migrate 2
Here's the pieces of code for images and files migration. You can put it in your migration class and remember to change the database name, field names, urls to yours.
<code><?php
// Add other source fields which may be populated in prepareRow()
$source_fields = array(
  'image_filename' => t('img_filename'),
  'attachments_filename' => t('attachments_filename'),
  'attachments_filepath' => t('attachments_filepath'),
  'attachments_description' => t('attachments_description'),
);

// Create a MigrateSource object, which manages retrieving the input data.
$this->source = new MigrateSourceSQL($query, $source_fields);

$this->addFieldMapping('field_image', 'image_filename');
$this->addFieldMapping('field_image:source_dir')->defaultValue('http://DOMAINNAME.COM/sites/default/files/THE_DIR_YOU_PUT_IMAGES');

$this->addFieldMapping('field_attachments', 'field_attachments');
$this->addFieldMapping('field_attachments:source_dir', 'field_attachments_filepath');
$this->addFieldMapping('field_attachments:description', 'field_attachments_description');

public function prepareRow($current_row) {
  // Set image data for the image fields.
  $query = db_select(SOURCE_DATABASE . '.content_type_NAME', 'i')
  ->condition('i.vid', $current_row->vid, '=');
  $query->join(SOURCE_DATABASE . '.files', 'f', 'i.field_image_fid = f.fid');
  $query->addField('f', 'filename');
  $result = $query->execute();

  foreach ($result as $row) {
    $image = array(
      'filename' => $row->filename,
    );
    $current_row->image_filename = $image['filename'];
  }

  // Set file data for the attachment file fields.
  $query = db_select(SOURCE_DATABASE . '.content_field_attachment', 'a')
    ->fields('a', array('field_attachment_data'))
    ->condition('a.vid', $current_row->vid, '=');
  $query->join(SOURCE_DATABASE . '.files', 'f', 'a.field_attachment_fid = f.fid');
  $query->addField('f', 'filename');
  $query->addField('f', 'filepath');
  $query->orderBy('a.field_attachment_fid', 'ASC');
  $result = $query->execute();

  foreach ($result as $row) {
    $field_data = unserialize($row->field_attachment_data);
    $field = array(
      'filename' => $row->filename,
      'filepath' => str_replace($row->filename, '', $row->filepath),
      'description' => $field_data['description'],
    );
    $current_row->attachments_filename[] = $field['filename'];
    $current_row->attachments_filepath[] = 'http://DOMAINNAME.COM/' . $field['filepath'];
    $current_row->attachments_description[] = $field['description'];
  }
}
?>
</code>


SQL Order By - Show certain records last

Question: I want to list my products in sorted by price from low to high, but I also want out of stock products show after products that have quantity.  I'm not sure how to do that with an ORDER BY
Here is my current query, I want to add something to show out of stock products last:
SELECT * FROM products WHERE cat_id='$cat_id' ORDER BY price LIMIT $start,$record

Comment: Use two queries.
Comment: @Sammitch if i use two query i can't make correct pagination for that
Answer: Use a CASE statement in your ORDER BY:
ORDER BY CASE WHEN quantity <> 0 THEN 0 ELSE 1 END, price


Request laravel não retorna input file

Question: Por que não consigo pegar o arquivo da View?
Tenho um formulário que direciona pra uma rota. Entre outros atributos, tenho um upload de arquivos. Este upload de arquivos é o único atributo que não aparece na request.
Foto:
 <input id="foto" type="file" name="foto" accept="image/*" enctype="multipart/form-data">
 @if ($errors->has('foto'))

      {{ $errors->first('foto') }}

 @endif

No controller, tenho:
dd($this->request->all());

Isso retorna todos os atributos, mas nem aparece o 'foto'.
Também já tentei:
dd($request->file('foto'));

O que retorna null mesmo com um arquivo selecionado.
Comment: o `enctype="multipart/form-data"` não é na `input` `file` é na tag `form`, exemplo, `` um exemplo do formulário: https://www.w3schools.com/tags/att_form_enctype.asp
Comment: no form esta habilitado envio de email? p.x: `{{ Form::open(array('url' => '/form', 'files' => true)) }}`
Comment: Email ou arquivo? Obrigado pela resposta. Estou usando a tag html form normal sem facade. Como seria em HTML?
Comment: Sim, está habilitado no form.
Comment: Tá usando ajax pra mandar pro php  ou submit no form?
Comment: @GabrielAugusto de uma conferida na resposta que postei, caso ainda assim seu problema não seja resolvido, poste seu form completo e o conteúdo obtido com o DD do `$request`
Answer: O seu input está correto exceto pelo fato do enctype="multipart/form-data" este é um atributo do form e não do input
Porém com o form correto este não atrapalha no envio
Assim, apesar de não ter postado o seu form, o erro deve estar neste ou na sua rota, para fazer um pequeno teste coloquei neste form:
<form action="api/annex" method="post" enctype="multipart/form-data">

    Foto:
    <input id="foto" type="file" name="foto" accept="image/*" enctype="multipart/form-data">
        @if ($errors->has('foto'))

            {{ $errors->first('foto') }}

        @endif

    <input type="submit">
</form>

E este funcionou corretamente, como demonstro abaixo:
Request {#39 ▼
  #json: null
  #convertedFiles: null
  #userResolver: Closure {#123 ▶}
  #routeResolver: Closure {#124 ▶}
  +attributes: ParameterBag {#41 ▶}
  +request: ParameterBag {#40 ▶}
  +query: ParameterBag {#47 ▶}
  +server: ServerBag {#44 ▶}
  +files: FileBag {#43 ▼
    #parameters: array:1 [▼
      "foto" => UploadedFile {#28 ▼
        -test: false
        -originalName: "Dassad.png"
        -mimeType: "image/png"
        -size: 346505
        -error: 0
        path: "/tmp"
        filename: "phpJRjAf5"
        basename: "phpJRjAf5"
        pathname: "/tmp/phpJRjAf5"
        extension: ""
        realPath: "/tmp/phpJRjAf5"
        aTime: 2017-12-28 17:26:39
        mTime: 2017-12-28 17:26:39
        cTime: 2017-12-28 17:26:39
        inode: 1079759
        size: 346505
        perms: 0100600
        owner: 33
        group: 33
        type: "file"
        writable: true
        readable: true
        executable: false
        file: true
        dir: false
        link: false
      }
    ]
  }
  +cookies: ParameterBag {#42 ▶}
  +headers: HeaderBag {#45 ▶}
  #content: null
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: "/api/annex"
  #requestUri: "/apiapp/public/api/annex"
  #baseUrl: "/apiapp/public"
  #basePath: null
  #method: "POST"
  #format: null
  #session: null
  #locale: null
  #defaultLocale: "en"
  -isHostValid: true
  -isClientIpsValid: true
  -isForwardedValid: true
  basePath: "/apiapp/public"
  format: "html"
}

Sendo assim confira no seu form se esta com o atributo
enctype="multipart/form-data"
Caso ainda não funcione confira no seu form se está com o método correto:
method="post"
Caso ainda não funcione confira sua rota se está com o método correto, ex:
Route::resource('annex', 'AnnexController', [
    'only' => [
            'store',
    ]
]);

ou
Route::post('annex', 'AnnexController@store');

Answer: Possivelmente está usando Ajax para mandar os dados para o controller. Neste caso, como existe um input do tipo file o ajax nao enviará o conteudo do mesmo.
Use FormData ao inves de serialize. a baixo mostro um trecho de codigo no qual envio dados de um formulário que contem um input do tipo file.

$('#btnAddProjecto').click(function () {
            var data = new FormData($('#myFormProjecto')[0]);// codigo antigo $('#myFormProjecto').serialize();

            $.ajax({
                type: 'jax',
                method: 'post',
                url: "{{ route('projecto.store')}}",
                data: data,
                processData: false,
                contentType: false,
                async: true,
                dataType: 'json',
                success: function (resposta) {
                    alert(resposta);
                },
                error: function (error) {
                    console.log(error);

                }
            });
        });

Request laravel não retorna input file


Volume / Surface of a Paraboloid through Integration

Question: Given is a Paraboloid delimited as following:
$$z_1 = a(x^2 + y^2),\ z_2 = h  $$
That's my try for the Volume computation:
First I find the radius of the circle resulting from the intersection between $z_1$ and $z_2$ :
$ z = a(x^2 + y^2) = h \\ \frac{h}{a} = x^2 + y^2   $
so that means that the radius is $  \sqrt{ \frac{h}{a}}$.
Setting up the triple integral:
$$\int_0^{\sqrt{ \frac{h}{a}}} dr \int_0^{2\pi} d \theta \int_h^{a(x^2 + y^2)} dz \cdot 1$$
Now the change of variables:
$ x = r cos \theta \ \  y =  r sin \theta$ , where the Jacobian $J = r$.
The integral would then look like this:
$$\int_0^{\sqrt{ \frac{h}{a}}} dr \int_0^{2\pi} d \theta \int_h^{ar^2} dz  \cdot r = - \frac{1}{2} \pi \frac{h^2}{a}$$
The negative sign, I assume, is due to fact that at the first integration I integrated from $h$ to $ar^2$ and the other way around.
Is that correct?
Now, how do I compute the surface of the paraboloid ?
Answer: The correct set up for the volume in cylindrical coordinates should be
$$\int_0^{2\pi} d \theta \int_0^h \, dz   \int_0^{\sqrt{ \frac{z}{a}}}r \,dr $$
For the surface let use
$$S=2\pi \int_0^h f(z)\sqrt{1+[f'(z)]^2}\,dz$$
with $$f(z)=\sqrt{ \frac{z}{a}}$$
Comment: why is the lower bound $0$ at the $dz$ integral ??
Comment: Maybe I didn't get what are the limits for $z$. We need an equation for the paraboloid that is $z=a(x^2+y^2)$ and 2 limits for z. I've assumed z=0 and z=h.
Comment: I thought the lower bound would actually be the function $z$ itself. By the way why did you substitute $h$ with $h$ ??
Comment: You need to specify the interval of variation according to cylindrical coordinates, take a look to the original problem to see how those limits are specified.
Comment: you mean the one I set up before the change of variables?
Comment: It seems to me that your problem is to find the volume between the paraboloid $z=a(x^2+y^2)$ and the plane $z=h$. The set up I've given is for that volume.
Comment: Ah ok maybe now I get the meaning of your set up! It is almost correct too but you need to reverse the limits for the last integral in order to obtain a positive volume!
Comment: yes that's correct, could you please specify the parametrisation you applied ?
Comment: ok then, if mine is correct you've got to explain the difference between mine and yours eheh
Comment: We have made two different but correct choices. You have considered the variation of r first and the z between the paraboloid and z=h. I have considered first a variation of z and the r as a function of z.
Comment: ok, perfect thanks, by changing the order of the last integral you mean the right most integral right?
Comment: yes since the paraboloid is downvand the plane z=h is up
Comment: what if I define $\vec{x} = \{ rcos\theta, rsin\theta, ar^2 \} $and then compute the surface like this: $\int_0^{2\pi} d\theta \int_0^{h} dr \left| \frac{\partial x}{\partial r} \times   \frac{\partial x}{\partial \theta} \right|$ ? would that work?
Comment: @Leroy Yes of course, you can try both methods and compare. For the one I gave refer also to https://en.wikipedia.org/wiki/Surface_of_revolution


Pegar valor de  com PHP

Question: Onde está "VALOR" é o resultado que preciso pegar e mostrar
VALOR

$el = $dom->getElementsByTagName('span');

Parei nessa parte e não sei o que fazer.
Comment: Olá @Paulo Previatto,

Você quer obter o valor de um input, isso?
Comment: desculpe, o site nao mostro o código inteiro, atualizei aki o  post , de uma olhada novamente
Comment: atualizei, então é o valor de um elemento html, no caso uma span. Vc tem conhecimento em jquery?
Comment: pouco conheçimento amigo
Comment: vc já obteve o valor vindo do banco de dados com php e agora gostaria de ler com js/jquery para poder manipulá-lo em demais situações de sua aplicação, isso?
Comment: estou puxando uma pagina de fora, pra eu nao puxar toda a pagina e ficar carregado de conteudo, queria pegar apenas esse VALOR  que esta na pagina dentro dessa span
Comment: Paulo com ou sem jquery se span não tiver um IDm você precisa de encontrar outra forma de encontrar o elemento na página, é necessário o endereço da página ou então o código HTML para poder criar um query
Comment: Muito obrigado pela ajuda Neo, consegui resolver o problema !
Answer:
A sua pergunta é bem ampla pois nada sabemos a respeito do código fonte da página que deveremos extrair o texto de determinada tag span cuja classe é nomeClass.
Podem existir inúmeras tags span com a classe nomeClass e até mesmo, - porque não -  outros elementos com a mesma classe nomeClass, veja por exemplo o código HTML a seguir:

exemplo.html

<title>Página</title>

div 1

     Previous

    <input type="text" class="nomeClass">

    Complete HTML

    Next

div 2

     Previous

    Complete HTML

    VALOR

    Esse VALOR Não interessa

    Outro VALOR Não interessa

Note que o texto do elemento que queremos obter é o elemento de índice 8, ou seja o nono elemento cuja classe é nomeClass, independentemente de ser uma tag span.

Supondo o HTML acima podemos fazer da seguinte forma:
loadexemplo.php
    <?php
    $html = file_get_contents("exemplo.html");
    $DOM = new DOMDocument();
    @$DOM->loadHTML($html);
    $finder = new DomXPath($DOM);

    $classname = 'nomeClass';

    $nodes = $finder->query("//*[contains(@class, '$classname')]");
    foreach ($nodes as $node) {
      $result=$result.$node->nodeValue.",";
    }

    $partes = explode(',',$result);
    $textoSpan=$partes[8];

    echo $textoSpan;

    ?>

exemplo acima rodando no servidor

De qualquer forma, mesmo que haja apenas um elemento com class nomeClass o código acima funcionará perfeitamente. Não se esqueça que neste caso o índice do elemento deverá ser 0 (zero)
Comment: muito obrigado pela ajuda amigo, consegui resolver o problema!
Answer: Paulo você pode colocar um id no span para pegar o valor do mesmo.

Conteúdo do meu span
//No javascript
document.getElementById("mySpan").innerHTML;

Para pegar com elemento class.
var elementoUm = document.getElementsByClassName('mySpan')[0].innerHTML;

Nesse caso o document.getElementsByClassName vai pegar todos os elementos com a classe mySpan e no [0] estou pegando o primeiro elemento da página com a class mySpan.
Espero ter ajudado.
Comment: estou puxando conteudo de outra pagina, e no código nao tem ID a span
Comment: em vez de puxar a id da span, nao poderia puxar tipo atraves da class ou title ??
Comment: Acrescentei o exemplo com class na resposta, pois como comentário é difiícil de visualizar.
Comment: sim com esse script consigo pegar a linha, e pra mostrar  como faço ?
Comment: Nesse caso é só você jogar a variável elementoUm onde deseja. Por exemplo se quiser que o conteúdo vá para a div teste seria. document.getElementById("teste").innerHTML = elementoUm;
Comment: Muito Obrigado Roberto, consegui resolver o problema !
Answer: Se o seu problema é de PHP, resolva-o com PHP - não entendi porque outras respostas utilizaram JavaScript.
Você iniciou bem. De fato, a solução será utilizando a classe DOMDocument, porém, para fazer a busca do elemento na árvore, será melhor você utilizar a classe DOMXPath
$html = <<<HTML
    VALOR
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

foreach($xpath->query('//span[@class="nomeClass"]') as $span) {
    echo $span->nodeValue, PHP_EOL;
}

Veja funcionando no Repl.it
Perceba que foi instanciado o objeto DOMXPath em relação ao DOMDocument e executado a busca //span[@class="nomeClass"], que buscará todos os elementos span que possuem a classe igual a nomeClass. Como o retorno pode ser um array, é necessário iterar sobre o resultado com o foreach, obtendo o valor do elemento com nodeValue.
Para o exemplo acima, a saída será VALOR.
Comment: muito obrigado pela ajuda amigo, consegui resolver o problema!
Answer: creio q com jquery vc consegue pegar o q precisa.
var valor = $('.nomeClass').text();
alert(valor);// VALOR
lember-se q geralmente se usa a mesma classe para vários elementos na mesma página html. prefira usar o Id, por exemplo.
Comment: Deixei meu voto negativo por dois motivos: 1) a pergunta é sobre PHP, não JavaScript; 2) porque mesmo se fosse JavaScript, usar jQuery para apenas isso seria completamente desnecessário.
Comment: nem sempre o q se quer e como se quer fazer não são as melhores opções. os comentários podem ajudam ou não.
Comment: eu teria vergonha de fazer uma pergunta dessas com um curriculo igual ao seu. boa sorte!
Comment: Obrigado, problema ja foi resolvido !

Pegar valor de  com PHP


Is a finite von Neumann algebra with separable predual always a subalgebra of a type $II_1$ factor with separable predual?

Question: As in the title, given $N$, a finite von Neumann algebra with a separable predual, does there always exist a type $II_1$ factor $M$ with a separable predual such that $N \subseteq M$? I've heard that letting $M = N \bar{\ast} R$, the tracial free product of $N$ and the hyperfinite $II_1$ factor $R$, gives a solution, but I am unable to find a proof of this.
Answer: It can be done as you say.
As far as I can tell, the first source (which uses a different technique) is Elliott-Handelman, Math. Scand. 49 (1981), no. 1, 95–98. The requirement of properly infinite commutant is no big deal since it can be achieved by tensoring.
The free-product argument appears for instance in Proposition 8.1 in Bercovici-Collins-Dykema-Li-Timotin, JFA 258 (2010) 1579–1627.


Java selenium - Can't select date from calendar popup

Question: I'm new to automation with selenium webdriver. I'm trying to book a flight on a travel website. (ryanair.com)
I'm getting stuck with a popup datepicker. I can use .sendkeys to enter the day only, after any field on the date inputs is clicked it triggers the popup calendar to appear so if the format of the inputis dd/mm/yyyy and I want to enter "20042019" it only enters 20 in the dd and then automatically selects the current month and year as autocomplete and opens the calendar popup.
I'ver read a few articles saying that these calendars are usually of two types
1. iframe
2. datepicker  - I think the one on ryanair is datepickers based on the xpath below
//div[@id='datetimepicker_dateview']//table//tbody//td[not(contains(@class,'k-other-month')

Maybe that's the wrong xpath? But I think it's correct
I have tried to find the list of dates to book using :
   List<WebElement> list_AllDateToBook = driver.findElements(By.xpath()
   System.out.println("size of list is : " + list_AllDateToBook.size() );
   System.out.println("list is : " + list_AllDateToBook );

Output is:
size of list is : 0
list is : []
When I use xpath to enter the date of the date field it works for the first input using:
WebElement day = driver.findElement(By.xpath("//*[@id='row-dates-pax']/div[1]/div/div[1]/div/div[2]/div[2]/div/input[1]"));

However when I change the xpath to the second input it won't enter the second input(month)
WebElement day = driver.findElement(By.xpath("//*[@id='row-dates-pax']/div[1]/div/div[1]/div/div[2]/div[2]/div/input[2]"));

A sample of the datepicker HTML is below (it's too long to add it all!)
   <core-datepicker class="start-date" default-date="" start-date="18-03-2019" end-date="28-03-2020" highlight-from="20-03-2019" highlight-to="20-04-2019" end-show="true" fly-out="true" value="dateRange.startDate" cb-event-id="cal-selector:select-start-date" unavailable-dates="dateRange.unavailabiltyStartDates" selected-month-view="dateRange.startDateSelectedMonthView" show-month-toggle="::dateRange.showMonthToggle" show-single-month="">

March 2019

I'm really stuck here. Any advice would be great.
Thanks
Comment: Have you tried to access particular day in the calendar by 'data-id' attribute? Say //*[@data-id='24-03-2019']
Comment: Can you please add some HTML into the question, it doesn't have to be the full date picker code, but an example of a couple of the date elements you're trying to select, or if it's a public website you're working on can you provide a link? (You mentioned Ryanair but i can't find elements matching the one in the question on the date picker on the homepage)
Comment: Please add the html of the element you are trying to access here
Comment: @SameerArora - the html is too long for the comment box
Comment: @Hairdo please add that in the question only.
Comment: @SameerArora. It seems it's too long for the question section also. Body is limited to 30000 characters; you entered 58960.
Comment: @Matthewek. Tried that but it's giving the following:  no such element: Unable to locate element: {"method":"id","selector":"//*[@data-id='24-03-2019']"}                        I'm using driver.findElement(By.id("//*[@data-id='24-03-2019']"));
Comment: @Hairdo it should be By.xpath not By.id in this case.
Comment: @Matthewek. Unfortunately not working either. WebElement date = driver.findElement(By.xpath("//*[@data-id='24-03-2019']"));
  date.click();
Comment: @Jsmith2800. URL is https://www.ryanair.com/ie/en/
Answer: Here is the working code from python. Please see the approach that I followed and simulate the same in java.
import os
import time
from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

def get_full_path_to_folder(folderName):
    folders = os.path.abspath(os.pardir).split(os.sep)
    folderPath = ''
    for folder in folders:
        if folderPath == '':
            folderPath = folder
        else:
            folderPath = folderPath + "\\" +folder
        if os.path.isdir(os.path.join(folderPath, folderName)):
            return os.path.join(folderPath, folderName)
            break
def wait_for_element_present(locator_type, locator):
    if locator_type == 'xpath':
        return (wait.until(EC.presence_of_element_located((By.XPATH, locator))))
    elif locator_type == "css":
        return (wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, locator))))

chrome_options = ChromeOptions()
chrome_options.add_argument("--incognito")
driver = webdriver.Chrome(executable_path=os.path.join(get_full_path_to_folder('drivers'), "chromedriver.exe"))
driver.implicitly_wait(10)
wait = WebDriverWait(driver,10)
url = "https://www.ryanair.com/us/en/"
# go to url
driver.get(url)
#================ you should focus the below code=======================
# close the cookie pop up, otherwise the date and country elements not interable for selenium for interaction
wait_for_element_present('css',".cookie-popup__close").click()
#click on destination edit box
driver.find_element_by_css_selector(".route-selector-destination").click()
# select desitnation country
destiCountry = wait_for_element_present('xpath',"//div[@ng-repeat='option in $ctrl.firstOptions track by option.id' and text()=' Italy']")
destiCountry.click()
#select destination airport
desti = wait_for_element_present('xpath',"//span[contains(@ng-if,'secondOptionsEnabled') and .='Naples']")
desti.click()
# select outbound date
dateEle = wait_for_element_present('css',"li[data-id='24-03-2019']")
if dateEle.value_of_css_property('font-size') == '15px':
    dateEle.click()
#select in bound date
dateEle = wait_for_element_present('css',"li[data-id='20-04-2019']")
if dateEle.value_of_css_property('font-size') == '15px':
    dateEle.click()
#hurry, the date selection is successful.

Comment: thanks for your help. Unfortunately this isn't the issue. The font size is 15px. There are flights available on those dates, if I enter it manually into the website and click next, all is fine.
Comment: Sorry, that mean you are able to select the date in both the fields but not able to navigate to next page when clicked on `Let's go` button? or selecting dates with automation is not allowing you to navigate to next page?
Comment: I'm not able to select any date. I cannot seem to interact with the datepicker at all. I can click on the dd or mm  or yyyy fields and this will enable the popup. But after this I cannot interact with the calendar popup at all. Or enter any date in the input fields
Comment: Are you able to select the destination?
Comment: I can select destination only by sendkeys and entering destination country that has only one available airport. I cannot select from a list of airports
Comment: ok. Let me try in python, I don't have Java selenium setup on my machine. Will get to know if there are issue at least by working on python code.
Comment: Updated the working code in python. Please post me if you get any hurdles in java.
Comment: Thanks so much, that works for me! But I have a (probably) stupid/rookie quesion. How did you identify the cssSelectors and By.xpath ("//span[contains(@ng-if,'secondOptionsEnabled') and .='Naples']")));     I could not identify this and it something I think I should understand
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/190261/discussion-between-supputuri-and-hairdo).
Comment: Cool. You can use the Inspect in the chrome dev tools. Always first type the string that you are trying find in html, then you will see the matching html tag. Then develop the xpath/css.
Answer: Please try with :
li[data-id='12-04-2019'] span

Note: Add till span tag. Just tried via console and working.
document.querySelector("li[data-id='12-04-2019'] span").click()

Comment: Thanks for your help. Unfortunately i'm getting the following:
   invalid selector: Unable to locate an element with the xpath expression li[data-id='12-04-2019'] span because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string 'li[data-id='12-04-2019'] span' is not a valid XPath expression.
Comment: I'm using  WebElement date = driver.findElement(By.xpath("li[data-id='12-04-2019'] span"));
  date.click();
Comment: The website is full of these popup elements that I will have to select from. I don't know how to handle these types of elements but it seem I really need to!
Comment: Provided path is CSS one. For xpath, please use driver.findElement(By.xpath("//li[@data-id='12-04-2019']/span"))
Comment: no such element: Unable to locate element: {"method":"xpath","selector":"//li[@data-id='12-04-2019']/span"}
Comment: Hope date picker popup opened before performing date click option.
Comment: yes the popup is open. But it cannot be located or clicked at all it seems. I even tried doing this with selenium ide to check what it's using to locate this element and it can't find it either, even thought he popup is open. Am I calling it the right name when i say "datepicker"? Could this be something else?
Comment: Then try with Java script option, JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.querySelector('li[data-id=\'12-04-2019\'] span').click();");


How to send a key using winapi's SendInput?

Question: I am trying to convert this example to Rust 1.3 with winapi-rs 0.2.4.
I have:
fn send_key_event(vk: u16, flags: u32) {
    let mut input = winapi::INPUT {
        type_: winapi::INPUT_KEYBOARD,
        union_: winapi::KEYBDINPUT {
            wVk: vk,
            wScan: 0,
            dwFlags: flags,
            time: 0,
            dwExtraInfo: 0,
        }
    };
    unsafe {
        user32::SendInput(1, &mut input, mem::size_of::<winapi::INPUT>() as i32);
    }
}

which does not compile with:
error: mismatched types:
 expected `winapi::winuser::MOUSEINPUT`,
    found `winapi::winuser::KEYBDINPUT`
(expected struct `winapi::winuser::MOUSEINPUT`,
    found struct `winapi::winuser::KEYBDINPUT`) [E0308]

Haw do I send keystrokes to the active window?
Comment: The correct way to automate a UI is [UI Automation](https://msdn.microsoft.com/en-us/library/windows/desktop/ee684009.aspx). What you are trying is a brittle hack. It will fail if the designated receiver is not the foreground window, for example. As an aside, the active window is of no relevance. Input goes to the foreground window. The foreground window happens to be the active window of the foreground thread.
Comment: @IInspectable thanks for the link! Do you have an example for rust?
Answer: The definition of winapi::INPUT in the version of winapi-rs you use is incorrect. It appears to have been fixed today (or yesterday, depending on where you are).
Comment: The clearest way would be to zero-initialize the `u` member, then use the `ki_mut` method to get a mutable reference to a `winapi::KEYBDINPUT`, then assign to it: `let mut input = winapi::INPUT { type_: winapi::INPUT_KEYBOARD, u: Default::default() }; *input.ki_mut() = winapi::KEYBDINPUT { ... };`
Comment: so when the next version comes out, what code will get this to work?


How to return empty string if an object is null?

Question: Here is a snippet of my code:
var link = socials.Where(p => p.type == Facebook).FirstOrDefault().URL;

the problem is that there aren't any social object in the list, FirstOrDefault() return null, and .URL trigger an exception.
How can I avoid this in "one" line with LINQ? Thus, if null return empty "" (or custom even better) string, else .URL?
Comment: @SirwanAfifi: which causes an exception if there is no type==facebook.
Comment: you can use .First();
Answer: You can use DefaultIfEmpty with an argument to specify the fallback value:
var link = socials
    .Where(p => p.type == Facebook)
    .Select(p => p.Url)
    .DefaultIfEmpty("")
    .First();

FirstOrDefault is not necessary anymore, it is safe to use First with DefaultIfEmpty.
Comment: Yes, that's the sole purpose of `DefaultIfEmpty`. It comes only into play if the sequence contains no elements. Then it uses the default value of the type or - if you use the overload as in my answer - it uses the value provided. So with the same result as if the sequence contained only one element with that value.
Comment: But DefaultIfEmpty works even if the Select return 0 object? I mean, if the where count is 0, it returns at least one ""?
Comment: Saved few additional lines of code and time. Works as expected
Answer: Another option is to use null coalesce operator
var link = (socials
    .Where(p => p.type == Facebook)
    .Select(p => p.Url)
    .FirstOrDefault()) ?? string.empty;

I understood that string.empty is preferred over "" but that may not be the case - see comment below.
UPDATE
In C# 6 there is a null conditional operator (also known as the "Elvis" operator):
var link = socials
    .Where(p => p.type == Facebook)
    .Select(p => p.Url)
    .FirstOrDefault()?.URL ?? string.empty;

A simple example:
stringbuilder sb = null;
// do work
string s = sb?.ToString() ?? "no values found";

Comment: Why is `string.empty` preferred over `""`? Tha's just a matter of personal preferences. Imo `""` is very clear.
Comment: There's a subtle difference between yours and mine answer. You get `String.Empty` if there is no `type==facebook` and also if the first matching `Url` is `null`. [My approach](http://stackoverflow.com/a/32138070/284240) still yields `null` in that case.
Comment: http://stackoverflow.com/questions/263191/in-c-should-i-use-string-empty-or-string-empty-or
Answer: Using C# 6 you can use a null-conditional operator (?.) to return the URL if the object returned from the LINQ statement isn't null, i.e. if a value was found, or null otherwsie.
var link = socials.Where(p => p.type == Facebook).FirstOrDefault()?.URL;

If you then want to change a null value to an empty string or a custom string  then use the null-coalescing operator (??).
var link = socials.Where(p => p.type == Facebook).FirstOrDefault()?.URL ?? "No URL";

It should be noted that this won't make any distinction between whether an object wasn't found or an object was found but had a null URL value.


How to use CSS with Django forms?

Question: I have a HTML and CSS template done already, and now I have to use Python and Django to give life to the system. But I stuck into something: how to use my css with django forms ?
For example, this is what I have use in Django:
Username:
{{ form.username }}

And this is what django generates:
<input id="id_username" maxlength="100" name="username" type="text" />

As the fields in the form are automatically generated by django, how can I apply style for the input field and the others fields too ?
This is my login form for example and I would like to use django with the css done so far, but how ?
<form class="form-signin" action="" method="post">

Pydorado

        <input type="text" class="form-control" placeholder="User ID" autofocus>
        <input type="password" class="form-control" placeholder="Password">

      //..

</form>

I read the django documentation related to this but I couldn't find any solution so far. Any idea or suggestions ?
Answer: You can apply your styles in the formfield by adding extra attributes like this:
myfield = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))

I also saw a neat solution where someone created a custom template tag where you could add classes in the template itself.

How to use CSS with Django forms?


Writing a matrix with imaginary eigenvalues in a block-diagonal form

Question: Trying to write a 4x4 matrix $C$ in a block diagonal form $A$ where $C=QAQ^{-1}$ is valid and I am also supposed to find $Q$. I thought I could reach this in a similar fashion to finding Jordan form through using eigenvalues and eigenspaces.
However, the matrix $C$ has the characteristic polynomial ${\lambda}^4-1=0$ which leads to the eigenvalues -1, 1 but also $-i$ and $i$. I am assured that the characteristic polynomial is correct. This is given as a hint in the question.
Unfortunately, I am not getting any feedback from prof or assistants other than that I am not supposed to get on with imaginary numbers (Despite this not being mentioned anywhere in the question). So I am stumped on how to move forward. I am refraining from adding the matrix here since I do not want a solution to the question I'm supposed to solve myself, rather I'd like to know how to proceed further or at least a similar example. At this point, the lack of useful help from my course is driving me crazy. Excuse my frustration. Any help is appreciated.
Answer: Not a complete solution, but a hint
Hint: your block diagonal form will look something like
$$
\pmatrix{
1 & & & \\
& -1 & & \\
& & & 1\\
& & -1 & }
$$
with the second block being the part corresponding to the complex eigenvalues.
It might help to look at the $2 \times 2$ matrix $M = \pmatrix{ 0 & 1 \\ -1 & 0}$ and compare what you get from diagonalizing it (the matrix $Q$ has complex entries; after diagonalization, you get a diagonal matrix with  $\pm i$ on the diagonal) and what you get by block-diagonalizing it (you get back $M$!). And then maybe look at
$$
M = \pmatrix{c & -s \\
s & c}
$$
where $c$ and $s$ are the sine and cosine of some angle like $\pi/3$, and see whether you can do something similar. By then, you'll be 90% of the way to being done.
Incidentally, there's a cheap trick that's perfectly valid: you could say that $A = C$ and $Q = I$ represents $C$ as a block diagonal matrix with exactly one $4 \times 4$ block. But it's pretty clear that this isn't what your teacher really wants. (I might suggest considering finding a different teacher, or taking the course a different year, if that's an option...)
Comment: I'm sorry the first example got me confused. Diagonalising M leads to eigenvalues $i$ and $-i$ and eigenvectors $(-i,1)$ and $(i,1)$ respectively. This does not lead to $Q$ having complex entries in the diagonal but rather one compex entry in the diagonal. Did you perhaps mean $A$?
Comment: The diagonalizing matrix generally has the eigenvectors as its columns (or its inverse does, depending which side you put the inverse!). When I said "you get $\pm i$ on the diagonal", I meant "the diagonal of the resulting diagonalized matrix"; I'll edit to clarify.
Answer:
You have to calculate the eigenvectors, e.g. $v_1$, $v_2$, $v_3$ and $v_4$. Let the last two be the complex eigenvectors.

Calculate $w_1 := \frac{1}{\lVert v_1 \rVert}v_1$, $w_2 := \frac{1}{\lVert v_2 \rVert}v_2$ and $w_3 := \frac{1}{\lVert v_3 \rVert}v_3$.

Then $Q := \left(w_1, w_2, \frac{1}{\lVert \mathrm{Re}(w_3)\rVert}\mathrm{Re}(w_3), \frac{1}{\lVert \mathrm{Im}(w_3)\rVert}\mathrm{Im}(w_3) \right) \in \mathbb{R}^{4 \times 4}$ should do the job.
Comment: What is the reasoning behind this approach? Could you give me a keyword so I can read more about why this approach works?
Comment: Did work in your case? This does not really have a name. But "orthogonal normal/canonical form" should give you results. You search for a normal form that consists of rotation matrices $\begin{pmatrix} \cos(\alpha) & - \sin(\alpha) \\ \sin(\alpha) & \cos(\alpha) \end{pmatrix}$.


Does Amazon manage time synchronization on ECS/Fargate containers?

Question: I'm trying to use NTP to synchronize local time in ECS containers using the ntpdate command, but it gives me this error:
ntpdate[770]: Can't adjust the time of day: Operation not permitted

Investigating the issue, I realized that local time is managed on the host where containers are running, but in this case the container is running as an ECS Task in a Fargate cluster. So I don't know if Amazon is handling time synchronization by default for ECS containers or not, and how it works.
Is this something I do not need to worry about?  Is there any AWS link explaining this?
Answer: Short version: This is something you do not need to worry about.
Longer version: You couldn't do anything about it even if you wanted to, because Fargate doesn't allow privileged containers, which is what is needed to adjust the host clock.
I couldn't find any specific documentation about this, but it seems very likely that AWS uses their own NTP service for the Firecracker VMs which run Fargate containers.
Here's a test I did with ntpdate -d from an ECS container:
10 Mar 23:59:58 ntpdate[6661]: ntpdate email@example.com (1)
Looking for host 169.254.169.123 and service ntp
transmit(169.254.169.123)
receive(169.254.169.123)
transmit(169.254.169.123)
receive(169.254.169.123)
transmit(169.254.169.123)
receive(169.254.169.123)
transmit(169.254.169.123)
receive(169.254.169.123)
server 169.254.169.123, port 123
stratum 3, precision -26, leap 00, trust 000
refid [169.254.169.123], delay 0.02576, dispersion 0.00000
transmitted 4, in filter 4
reference time:    e212a876.488c7014  Tue, Mar 10 2020     23:59:50.283
originate timestamp: e212a885.19ee802f  Wed, Mar 11 2020  0:00:05.101
transmit timestamp:  e212a885.19e43c89  Wed, Mar 11 2020  0:00:05.101
filter delay:  0.02585  0.02576  0.02582  0.02579
         0.00000  0.00000  0.00000  0.00000
filter offset: -0.00000 -0.00004 -0.00005 -0.00003
         0.000000 0.000000 0.000000 0.000000
delay 0.02576, dispersion 0.00000
offset -0.000041

11 Mar 00:00:07 ntpdate[6661]: adjust time server 169.254.169.123 offset -0.000041 sec

As you can see, the container is 41 microseconds off from the time server, which is about right for a host synced to a very nearby time source.


Tkinter e classe

Question: Sou iniciante em classes e tkinter e estou tendo um problema que acho ser por pouco conhecimento meu em POO.
No código abaixo, apenas uma label está executando, nem os botoes nem nada executam, oq pode ser? Dei uma diminuida na lista para caber aq na pergunta. Tive uns erros de identação ao postar o codigo aq, me desculpem.
from tkinter import *
import tkinter as tk
from tkinter import ttk

currencys_id = ['AED', 'AFN', 'ALL', 'AMD']

class CurrencyConverter(tk.Frame):
def __init__(self, master):
    super().__init__(master)
    self.master = master
    self.font = ('Courier',15,'bold')

    # Labels
    self.subtitle = tk.Label(self, text='Welcome to Real Time Currency Converter', font=self.font, fg='#ffffff', bg='#245985')
    self.toLabel = tk.Label(self, text='TO', font=self.font)

    # Combobox
    self.toCurrency = ttk.Combobox(self, values=currencys_id, font=self.font, width=10, justify='center', state="readonly")
    self.toCurrency.set('BRL')
    #self.toCurrency.bind('<<ComboboxSelected>>', currencyToConvert)

    self.fromCurrency = ttk.Combobox(self, values=currencys_id, font=self.font, width=10, justify='center', state="readonly")
    #self.fromCurrency.bind('<<ComboboxSelected>>', currencyConverted)

    # Entrys
    self.inputValue = tk.Entry(self, font=self.font, width=8, justify='center')
    self.inputValue.insert(0, '1')

    self.outputValue = tk.Entry(self, font=self.font, width=8, justify='center')

    # Buttom
    self.convertButtom = tk.Button(self, text='Convert', font=self.font, width=8, bg='#097FDF', fg='#ffffff')

    # Pack()
    self.pack()
    self.subtitle.pack()
    self.toLabel.pack()
    self.toCurrency.pack()
    self.fromCurrency.pack()
    self.inputValue.pack()
    self.outputValue.pack()
    self.convertButtom.pack()

    # position
    self.toLabel.place(x=230, y=100)
    self.toCurrency.place(x=50, y=100)
    self.fromCurrency.place(x=300, y=100)
    self.inputValue.place(x=70, y=140)
    self.outputValue.place(x=320, y=140)
    self.convertButtom.place(x=195, y=160)

    #def clickButtom(self):

def main():
root = tk.Tk()
app = CurrencyConverter(master=root)
root.title('Currency Converter')
root.maxsize(500, 200)
app.mainloop()

if __name__ == '__main__':
    main()

Answer: O problema esta no uso de dois gerenciadores de layout que esta sendo usado no script
pack é um, e place é outro, o mesmo objeto não deve usar os dois ao mesmo tempo, no momento não recordo a forma correta de usar place, se vc comentar esta parte o layout feito com pack ira funcionar

fiz um teste rapido com o place, e o tamanho do frame realmente influencia
from tkinter import *

r = Tk()
r.minsize(200,200)

f = Frame(r, width=100, height=100, bg='#aabbcc')
f.pack()

l1 = Label(f, text='teste1')
l2 = Label(f, text='teste2')

l1.place(x=0, y=0)
l2.place(x=90, y=90)

r.mainloop()

ao rodar o codigo vc podera ver que a label l2 fica cortada. Isso mostra que em seu codigo deve especificar um tamanho para o frame
Comment: Muito obrigado, realmente ja me ajudou a detectar o erro!
Comment: @lucas_boscatti tente começar com algo simples (faça apenas um frame com um botão) para intender como o place funciona, acho que o problema esta no tamanho do frame, tente colocar um tamanho fixo para o frame, e então posicionar alguma widget no x=0 y=0, e depois ir fazendo teste tipo: x=10 y=10.
Answer: Conforme Elton Nunes comentou, ao "inutilizar" o place do seu código ele já apresenta mudanças. como nas imagens a seguir:

Mas se a sua intenção for apenas essa, apesar de ser uma solução ruim, ela funciona. No entanto se vc estiver pensando na funcionalidade do seu conversor, se perguntando do porquê dele não estar funcionando, é por causa do seu código ainda estar muito superficial, não há atribuições de eventos para o click, por exemplo:
import tkinter as tk
from tkinter import ttk, messagebox

[...]

# Buttom
        def nova_caixa():
            messagebox.showinfo('Olá', 'Eu sou o Goku!')

        self.convertButtom = tk.Button(self, text='Convert', font=self.font, width=8, bg='#097FDF', fg='#ffffff',
                                       command=nova_caixa)

Espero que de alguma forma isso possa ter esclarecido alguma coisa.
Comment: Então, eu entendi esta parte, porém agora não estou conseguindo mais ajeita as posições dos meus widgets.  Estou ainda fazendo apenas a parte visual do projeto, sem as funções de conversões e clicks. De qual maneira agora posso reposicionar meus widgets? obrigado pela contribuição

Tkinter e classe


PUGXMultiUserBundle: custom profile template

Question: A method to enable custom user profile templates involves modifying the vendor's Configuration.php.  Is there a method that does not?  Or is this a viable solution? Current method appears below:
Update: I'm thinking my bundle needs to take responsibility for the configuration so I'm in the throes of deciphering and applying the CompilerPassInterface.
[Edit: another way to ask the question - can this be done by prepending the template option with PrependExtensionInterface?  If so, how might that work?]
config.yml
pugx_multi_user:
  users:
    staff:
        entity:
          class: Acme\MyBundle\Entity\Staff
#          factory:
        registration:
          form:
            type: Acme\UserBundle\Form\RegistrationStaffFormType
            name: fos_user_registration_form
            validation_groups:  [Registration, Default]
          template: AcmeUserBundle:Registration:staff.form.html.twig
        profile:
          form:
            type: Acme\UserBundle\Form\ProfileStaffFormType
            name: fos_user_profile_form
            validation_groups:  [Profile, Default]
# template line added
          template: AcmeUserBundle:Profile:staff.form.html.twig
         ...

excerpt from PUGX\MultiUserBundle\DependencyInjection\Configuration.php
[Note addition of ->scalarNode('template')->defaultValue(null)->end()]
...
                        ->children()
                            ->arrayNode('profile')
                                ->addDefaultsIfNotSet()
                                ->children()
                                    ->arrayNode('form')
                                    ->addDefaultsIfNotSet()
                                        ->children()
                                            ->scalarNode('type')->defaultValue(null)->end()
                                            ->scalarNode('name')->defaultValue('fos_user_profile_form')->end()
                                            ->arrayNode('validation_groups')
                                                ->prototype('scalar')->end()
                                                ->defaultValue(array('Profile', 'Default'))
                                            ->end()
                                        ->end()
                                    ->end()
                                    ->scalarNode('template')->defaultValue(null)->end()
                                 ->end()
                            ->end()
                        ->end()
...

ProfileController (in extended User Bundle)
class ProfileController extends BaseController
{

    /**
     * Edit the user
     */
    public function editAction(Request $request)
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        $discriminator = $this->container->get('pugx_user.manager.user_discriminator');
        $users = $this->container->getParameter('pugx_user_discriminator_users');
        $class = $discriminator->getClass($user);

        foreach ($users as $userType) {
            if ($userType['entity']['class'] == $class) {
                $templateString = $userType['profile']['template'];
                if (false === strpos($templateString, $this->container->getParameter('fos_user.template.engine'))) {
                    $template = 'FOSUserBundle:Profile:edit.html.';
                } else {
                    $l = strrpos($templateString, ".");
                    $template = substr($templateString, 0, $l + 1);
                }
            }
        }

        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->container->get('fos_user.profile.form.factory');

        $form = $formFactory->createForm();
        $form->setData($user);

        if ('POST' === $request->getMethod()) {
            $form->bind($request);

            if ($form->isValid()) {
                /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
                $userManager = $this->container->get('fos_user.user_manager');

                $event = new FormEvent($form, $request);
                $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

                $userManager->updateUser($user);

                if (null === $response = $event->getResponse()) {
                    $url = $this->container->get('router')->generate('fos_user_profile_show');
                    $response = new RedirectResponse($url);
                }

                $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

                return $response;
            }
        }

        return $this->container->get('templating')->renderResponse(
                        $template . $this->container->getParameter('fos_user.template.engine'), array('form' => $form->createView())
        );
    }

Answer: I have create a pull request here that handles custom profile templates.
Comment: I look forward to its implementation! Upvote for now.
Comment: I am using my own fork so far, you could do the same I guess. The logic is the same as the registration.
Comment: Creating a viable solution myself is clearly outside of my skill set. I've been trying to grasp the process the past couple of days without any real success. I do, however, have nothing else to do so I'll keep at it.  Love them steep learning curves!
Comment: I've posted a solution within my skill set, but I'd rather have yours = v2 of PUGXMultiUser.
Comment: The [RollerworksMultiUserBundle](https://github.com/rollerworks/RollerworksMultiUserBundle/blob/master/docs/index.md) appears to have profile templates already.  Have you looked at it?
Comment: I've made a PR that includes custom profile templates.  It includes the means to pass configuration options to reg & profile forms.  There's also a mechanism for creating a template array in the controllers to pass to reg & profile templates.  The repo is [here](https://github.com/truckee/PUGXMultiUserBundle).  Comments always appreciated.
Answer: Progress of a sort.  It took a while but it became clear I would not be able to add a template parameter to the PUGXMultiUserBundle configuration.  So I decided to create my own configuration.  Had to be sure to make a couple of other hack-like fixes to my own code, but this at least seems to work.  (I won't accept my answer; I'd rather Patt's solution gets implemented.)  But here's what I did:
config.yml addition:
vol_user:
    staff: VolUserBundle:Profile:staff.form.html.twig
    volunteer: VolUserBundle:Profile:volunteer.form.html.twig
    admin: VolUserBundle:Profile:admin.form.html.twig

routing.yml change to fos_user_profile (added _edit to parameter name):
fos_user_profile_edit:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

Revised controller:
    public function editAction(Request $request)
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        $discriminator = $this->container->get('pugx_user.manager.user_discriminator');
        $users = $this->container->getParameter('pugx_user_discriminator_users');
        $class = $discriminator->getClass($user);
        $templates = $this->container->getParameter('vol_user');

        foreach ($users as $userType) {
            if ($userType['entity']['class'] == $class) {
                $l = strrpos($class, DIRECTORY_SEPARATOR ) + 1;
                $type = strtolower(substr($class, $l));
                $templateString = $templates[$type];
                if (false === strpos($templateString, $this->container->getParameter('fos_user.template.engine'))) {
                    $template = 'FOSUserBundle:Profile:edit.html.';
                } else {
                    $l = strrpos($templateString, ".");
                    $template = substr($templateString, 0, $l + 1);
                }
            }
        }
...
}

Configuration.php
namespace Vol\UserBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('vol_user');

        $rootNode->
                children()
                    ->scalarNode('staff')->defaultValue(null)->end()
                    ->scalarNode('volunteer')->defaultValue(null)->end()
                    ->scalarNode('admin')->defaultValue(null)->end()
                ->end()
                ->end();

        return $treeBuilder;
    }
}

VolUserExtension
class VolUserExtension extends Extension
{

    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('vol_user', $config);
    }

}


panning cells with custom action in ios

Question: Hi i am trying to make a tableview with mailbox style panning http://www.mailboxapp.com/ for that i am using this library https://github.com/gloubibou/HHPanningTableViewCell and it is working fine, i swipe the cell and it moves just fine, the problem is that i want to trigger a custom action when i swipe the cell and i have only been able to do it when it is open and then i touch it.
This is the code where the action is happening
    #import "TableViewController.h"

#import "HHPanningTableViewCell.h"

@interface TableViewController ()

@property (nonatomic, retain) NSArray *rowTitles;

@end

@implementation TableViewController

#pragma mark -
#pragma mark Initialization

- (id)init
{

    self = [super initWithNibName:@"TableViewController" bundle:nil];

    if (self != nil) {
        self.rowTitles = [NSArray arrayWithObjects:@"Pan direction: None", @"Pan direction: Right", @"Pan direction: Left", @"Pan direction: Both", @"Custom trigger", nil];
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

#pragma mark -
#pragma mark Accessors

@synthesize rowTitles = _rowTitles;

#pragma mark -
#pragma mark Rotation

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.rowTitles count] * 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    HHPanningTableViewCell *cell = (HHPanningTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSInteger directionMask = indexPath.row % 5;

    if (cell == nil) {
        cell = [[HHPanningTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                              reuseIdentifier:CellIdentifier];

        UIView *drawerView = [[UIView alloc] initWithFrame:cell.frame];

        // dark_dotted.png obtained from http://subtlepatterns.com/dark-dot/
        // Made by Tsvetelin Nikolov http://dribbble.com/bscsystem
        drawerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"dark_dotted"]];

        cell.drawerView = drawerView;
    }

    if (directionMask < 3) {
        cell.directionMask = directionMask;
    }
    else {
        cell.directionMask = HHPanningTableViewCellDirectionLeft + HHPanningTableViewCellDirectionRight;

        if (directionMask == 4) {
            cell.delegate = self;
        }
    }

    cell.textLabel.text = [self.rowTitles objectAtIndex:directionMask];

    return cell;
}

- (void)gestureRecognizerDidPan:(UIPanGestureRecognizer*)gestureRecognizer{

}

#pragma mark -
#pragma mark Table view delegate

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
     NSInteger directionMask = indexPath.row;
    NSString *celda = [NSString stringWithFormat:@"%d", directionMask];

    [cell isKindOfClass:[HHPanningTableViewCell class]];
    HHPanningTableViewCell *panningTableViewCell = (HHPanningTableViewCell*)cell;

    if (directionMask == 1) {
        if (HHPanningTableViewCellDirectionRight) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Custom Action"
                                                            message:@"1"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
        }
        if ([panningTableViewCell isDrawerRevealed]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Custom Action"
                                                            message:@"1"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
        }
        else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Custom Action"
                                                            message:@"2"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }

    return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

#pragma mark -
#pragma mark HHPanningTableViewCellDelegate

- (void)panningTableViewCellDidTrigger:(HHPanningTableViewCell *)cell inDirection:(HHPanningTableViewCellDirection)direction
{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Custom Action"
                                                    message:@"You triggered a custom action"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

@end

I know i could use a Gesture recognizer to trigger the action but i think the library is already doing that.
in this part i trigger an action knowing exatly the cell, where was it paned to and if the back of the cell is revealed or not, but always by clicking it since it is a select function.
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
     NSInteger directionMask = indexPath.row;
    NSString *celda = [NSString stringWithFormat:@"%d", directionMask];

    [cell isKindOfClass:[HHPanningTableViewCell class]];
    HHPanningTableViewCell *panningTableViewCell = (HHPanningTableViewCell*)cell;

    if (directionMask == 1) {
        if (HHPanningTableViewCellDirectionRight) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Custom Action"
                                                            message:@"1"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
        }
        if ([panningTableViewCell isDrawerRevealed]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Custom Action"
                                                            message:@"1"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
        }
        else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Custom Action"
                                                            message:@"2"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }

    return indexPath;
}

and i believe this other part is where the custom action should be trigered but the program never enters this function
- (void)panningTableViewCellDidTrigger:(HHPanningTableViewCell *)cell inDirection:(HHPanningTableViewCellDirection)direction
{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Custom Action"
                                                    message:@"You triggered a custom action"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

I hope i made myself clear and thank you in advance.
Answer: Change the delegate method to
- (void)panningTableViewCell:(HHPanningTableViewCell *)cell didTriggerWithDirection:(HHPanningTableViewCellDirection)direction;

Answer: For the delegate method to trigger you need to set your controller as delegate for the cell. Currently in your cellForRowAtIndexPath the controller is assigned as delegate only when directionMask is 4. So you either set directionMask to be 4 in your current code (which is returning a value based on the cell position instead) or you set the controller as delegate in every case, as I've done below.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    HHPanningTableViewCell *cell = (HHPanningTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSInteger directionMask = indexPath.row % 5;

    if (cell == nil) {
        cell = [[HHPanningTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                              reuseIdentifier:CellIdentifier];

        UIView *drawerView = [[UIView alloc] initWithFrame:cell.frame];

        // dark_dotted.png obtained from http://subtlepatterns.com/dark-dot/
        // Made by Tsvetelin Nikolov http://dribbble.com/bscsystem
        drawerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"dark_dotted"]];

        cell.drawerView = drawerView;
    }

    if (directionMask < 3) {
        cell.directionMask = directionMask;
    }
    else {
        cell.directionMask = HHPanningTableViewCellDirectionLeft + HHPanningTableViewCellDirectionRight;

        // previous code
        //if (directionMask == 4) {
        //    cell.delegate = self;
        //}
    }
    cell.delegate = self;

    cell.textLabel.text = [self.rowTitles objectAtIndex:directionMask];

    return cell;
}

panning cells with custom action in ios


Simplicity of Cuntz algebra

Question: It is well known that the Cuntz algebra $\mathcal{O}_N$ (for fixed $N$) is simple. Is there any easy way to exhibit it (as a Banach algebra only) as a quotient of a Banach algebra modulo some maximal ideal? Of course, I am not interested in the quotient of the form $\mathcal{O}_N/ \{0\}$.
Answer: Cuntz introduced the algebras $\mathcal O_n$ in the paper "Simple C*-algebras generated by isometries", 1977.  Section 3 of the paper is called "Extensions of $\mathcal O_n$."  It is proved there that if $n$ is finite, and if $V_1,\ldots V_n$ are isometries on Hilbert space such that $\sum\limits_{k=1}^n V_k V_k^*\leq I$ and $\sum\limits_{k=1}^n V_k V_k^*\neq I$ (i.e., if $V_1,\ldots, V_n$ are isometries with orthogonal ranges that do not add up to the whole space), then $\mathcal O_n$ is a quotient of $C^*(V_1,\ldots,V_n)$ by the ideal generated by the projection $I-\sum\limits_{k=1}^n V_k V_k^*$, and this ideal is isomorphic to the algebra of compact operators.
Since it is easy to give examples of such isometries, this might be the easy way you're looking for.  Here is one particular construction that may not be the easiest, but that has an important role in the subject, and appears in D.E. Evans's "On $O_n$", 1980.  Let $H$ be an $n$-dimensional Hilbert space with orthonormal basis $\{e_1,\ldots,e_n\}$.  Let $F(H)=\mathbb C\oplus H\oplus (H\otimes H)\oplus (H\otimes H\otimes H) \oplus \cdots=\sum\limits_{k=0}^\infty H^{\otimes k}$ be the full Fock space of $H$, and for $i\in\{1,2,\ldots,n\}$, let $V_i\in B(F(H))$ be defined by $V_i x=e_i\otimes x$.  Then each $V_i$ is an isometry, $\sum\limits_{k=1}^n V_kV_k^*\leq I$, and $I-\sum\limits_{k=1}^n V_kV_k^*$ is the projection onto the first summand of $F(H)$.  In this case the ideal in question is precisely the set of compact operators on $F(H)$, $K(F(H))$, and $C^*(V_1,\ldots,V_n)/K(F(H))\cong \mathcal O_n$.

Simplicity of Cuntz algebra


Is it valid to use a difference score between sequential timepoints as an independent variable in a longitudinal regression analysis?

Question: Is it valid to use change scores, i.e. like change in body weight taken between consecutive time points in longitudinal analysis where I'm using nlme/gee?
For example,
bodyweight at hour 3 minus bodyweight at hour 2, body weight at hour 4 minus bodweight at hour 3 to predict a binary outcome?
Is logit(odds)=intercept+$\beta_1$*(change in bodyweight between two time points) + $\beta_2$*(change in bodyweight between two other time points) +.... $\beta_n$(change in body weight between $x_{k+1}$ and $x_k$th time) + country effect + time*drug effect valid?
Answer: Apart from the points mentioned already some other issues potential considerations are:

The time points need to be the same for all subjects. If you have someone coming at 1.4 hours and someone at 1.6 hours, it could be problematic round these up or down at 1 hour and at 2 hours.
Related to the above point, you will potentially have problems with these change scores if some subjects have missing data. You would need to impute first.

An alternative approach could be to fit a mixed model for bodyweight and use the empirical Bayes estimates of the random effects as a summary of the longitudinal profile of each subject.
Answer: You could. The real problem with using change scores (regardless of whether it's an independent or a dependent variable) is issues with regression to the mean. Those with extreme baseline ("pre") scores--in either direction--are more likely to have large change scores. This information is therefore packed into the change score, but may not be what you're targeting when you calculate it; that is, your change score is actually reflecting a mixture between what you're trying to measure (the magnitude of change), and something about the baseline score.
A second, closely related, limitation is that the change score can have different meaning depending what the baseline score was; is the scale you're dealing with an interval scale? In other words, does the different $\delta$ have the same meaning regardless of where you are on the scale?