Reference: Is a simple k-vector an equivalence class?

Question: My understanding of a simple k-vector is that it is the wedge product of k vectors.
Also, two simple k-vectors are the same, when their magnitude, attitude and orientation match. Now my question is, could I just define a simple k-vector in this way?
Meaning "a simple k-vector is an equivalence class of ordered k-tuple of vectors. Two tuples are equivalent if their attitudes and orientation match, and if the parallelograms they span attain the same magnitude."
Especially a reference where this is stated would be greatly appreciated! I feel like I have read something like this somewhere, but I cannot find it anymore.
I am only using k-vectors for something I am writing for university and having to explain the wedge product would deviate from my topic a little. That's why I am trying to avoid this definition.
Comment: You could define the equivalence for two sets of $k$ linearly independent vectors in terms of them (i) having the same span and (ii) the linear transformation taking one set to the other having determinant $1$.
Comment: @blargoner Thank you for your contributions to the discussion. Your remarks on the determinant were quite helpful :)
Comment: Can you give an example of two ordered tuples that are equivalent but not equal?
Comment: @JohnDouma yes. From what I understand the wedge product of [v1,v2,v3,v4] in that order would be the same as [v2,v1,v4,v3] for any four linearly independent vectors.
Answer: Yes, this works, though I'm not sure you'll find any reference.
(I assume we're talking about the Euclidean case. This fails in general since we can have nonzero $k$-vectors which have a "magnitude" of zero.)
What you mean by orientation of a $k$-vector is two things: the subspace represented by the $k$-vector and the "orientation" as described by an ordered basis. Define the (squared) $k$-vector magnitude $M(v_1,\dotsc,v_k)$ of vectors $v_1,\dotsc,v_k$ by
$$
  M(v_1,\dotsc,v_k) = \det\Bigl(v_i\cdot v_j\Bigr)_{i,j=1}^k.
$$
For example, with $k=3$ we have
$$
  M(v_1,v_2,v_3) = \det\begin{pmatrix}
    v_1\cdot v_1&v_1\cdot v_2&v_1\cdot v_3 \\
    v_2\cdot v_1&v_2\cdot v_2&v_2\cdot v_3 \\
    v_3\cdot v_1&v_3\cdot v_2&v_3\cdot v_3
  \end{pmatrix}.
$$
The theorem you are interested in can be stated as follows:

Suppose $k\ne 0$. Define a relation $\sim$ between $k$-tuples of linearly independent vectors as follows:
$$
    (v_1,\dotsc,v_k)\sim(w_1,\dotsc,w_k) \iff \Bigl[\mathrm{span}\{v_1,\dotsc,v_k\} = \mathrm{span}\{w_1,\dotsc,w_k\}\Bigr]\text{ and }\Bigl[\exists T : S\to S.\; \det T > 0\text{ and }(Tv_1,\dotsc,Tv_k) = (w_1,\dotsc,w_k)\Bigr]\text{ and }\Bigl[M(v_1,\dotsc,v_k) = M(w_1,\dotsc,w_k)\Bigr]
  $$
where $S = \mathrm{span}\{v_1,\dotsc,v_k\}$.
Then $(v_1,\dotsc,v_k) \sim (w_1,\dotsc,w_k)$ iff $v_1\wedge\dotsb\wedge v_k = w_1\wedge\dotsb\wedge w_k$.

The restriction to linearly independent tuples is crucial (though we could add the stipulation that any two linearly dependent tuples are equivalent).
I will sketch a proof that equivalence of tuples implies equality of $k$-vectors. First note that
$$
  \mathrm{span}\{v_1,\dotsc,v_k\} = \{v \;:\; v\wedge v_1\wedge\dotsb\wedge v_k = 0\}.
$$
Additionally, for any $k$-vector $X$, if $v\wedge X = 0$ then we can factor $X = v\wedge Y$ for some $(k-1)$-vector $Y$. Inducting on $k$, this shows that there is a scalar $\alpha$ such that
$$
  v_1\wedge\dotsb\wedge v_k = \alpha w_1\wedge\dotsb\wedge w_k.
\tag{$*$}
$$
Let
$$
  S = \mathrm{span}\{v_1,\dotsc,v_k\} = \mathrm{span}\{w_1,\dotsc,w_k\}.
$$ The subalgebra generated by $S$ of the exterior algebra is naturally isomorphic to the exterior algebra of $S$, so conflate the two and consider the outermorphism of $T_\wedge$ of $T$. Then
$$
  w_1\wedge\dotsb\wedge w_k = T_\wedge(v_1\wedge\dotsb\wedge v_k) = (\det T)v_1\wedge\dotsb\wedge v_k = \alpha(\det T)w_1\wedge\dotsb\wedge w_k
$$
so $1 = \alpha(\det T)$ and thus $\alpha > 0$. Finally, take the magnitude of both sides of ($*$) to get
$$
  M(v_1,\dotsc,v_k) = \alpha^2M(w_1,\dotsc,w_k) \implies 1 = \alpha^2.
$$
Because of the Euclidean assumption we know that these magnitudes are nonzero,
so $\alpha = 1$ and this completes the proof.
Comment: Do we really need the Euclidean structure for the equivalence relation, or just to formalize that notion of magnitude? In your proof since $\alpha=1$, it follows that $\det T=1$, so can't we just use that?
Comment: @blargoner If we want to involve the magnitude then yes we need the Euclidean structure to rule out the magnitudes being zero (otherwise you cannot conclude that $\alpha^2 = 1$, only that $\alpha = 1/\det T$). We could ignore the magnitude and just assume $\det T = 1$, but I think that is against the spirit of the question.
Comment: I hear you re: spirit -- sorry, I wasn't suggesting totally ignoring the magnitude concept but rather, if we just assume $\det T=1$ in the equivalence relation, we get that the magnitudes agree in the Euclidean case for free.
Comment: @blargoner What I'm saying is that if we use $\det T = 1$ in the definition of $\sim$ then the use of the magnitude is redundant---we can remove it entirely, whereas OP wanted to capture equality of $k$-vectors as subspace+orientation+magnitude. So instead I opted for $\det T > 0$ which ensures that $v_1,\dotsc,v_k$ has the same orientation as $w_1,\dotsc,w_k$ without saying anything about scaling, and then scaling is taken care of by constraining the magnitudes; and under this definition $\sim$ fails to capture the equality of arbitrary $k$-vectors when we use an indefinite metric.
Comment: Thank you! This helped me a lot.
Answer: I think the reference you are looking for is my article, The Wedge Product and Analytic Geometry, in the August-September 2008 edition of The American Mathematical Monthly, pp. 623-644.  The idea there is to define the wedge product of k given vectors as an equivalence class representing an oriented parallelpiped.  This is meant to extend the elementary concept of a vector as an equivalence class of directed line segments.  You can find a copy of it at https://www.mdeetaylor.com/wp-content/uploads/2017/06/wedge_monthly.pdf.


How to add metatags in hook_preproccess_node()?

Question: How to add variable meta tags depending on the node that is loaded?
The node has a picture and custom title field and the need to be variable.
What is the best practice to change them in: hook_preprocess_node()?
Answer: I am aware that this does not directly answer the question, which was about adding in a preprocess function, but I would suggest that you also consider the metatag module, which is pretty full featured.
https://www.drupal.org/project/metatag
Answer: yes, you can, place this code in template.php in your subtheme folder
function yourtheme_preprocess_node(&$vars) {
        $element = array(
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'robots',
            'content' => 'index',
          ),
        );
        drupal_add_html_head($element, 'robots');
 }

Comment: Thanks allot. However I am working with Drupal 8 (sorry forgot to mention that).  I found this post: https://stackoverflow.com/questions/36905114/what-is-the-drupal-8-equivalent-of-drupal-7s-drupal-add-html-head-within-a-mo but I am not sure if it works in the hook_preproccess_node(). Do you know how it works in 8?
Comment: my code is for D7, not shure if works in D8
Answer: For me the following worked:
I managed to load the current node in the hook_preprocess_node().
Based on this answer: How do I get the current node ID?
function module_name_page_attachments_alter(array &$page) {

            $node = \Drupal::routeMatch()->getParameter('node');
            if ($node instanceof \Drupal\node\NodeInterface) {
            // You can get nid and anything else you need from the node object.
            $nid = $node->id();
        }

        $ogImage = array(
            '#tag' => 'meta',
            '#attributes' => array(
                'property' => 'og:image',
                'content' => 'location of the image'.$nid.'.png',
    //my picture has the node id before the file format
            ),
        );

        $page['#attached']['html_head'][] = [$ogImage, 'ogImage'];
    }


Mehcanical metronome losing precision

Question: I have a nice wittner which seems to slows down and lose precision around and below 60 bpm afer a while. It seems however that above 100 bpm works fine.

How could I be sure that it works correctly (i.e. the beat is steady and even)?
How could I fix it in case it is not perfect?
Can it be fixed?
Has anyone had or noticed the same problem with mechanical metronomes?

N.B the metronome is new from the shop and it never fell or sustained any damage since I had it (about a month).
Thanks.
Comment: Take it back for exchange.
Comment: Of course you can compare it aginst an electronic one as in a smartphone app.
Comment: My mechanical metronome died about 15 years ago. I replaced it with a Seiko electronic metronome. Its primary advantages are that the tick sound can be turned all the way down, leaving the only the flashing tempo indicator, and that it can also generate an A 440 tone for tuning.
Comment: If it is this new and did not fell maybe it is covered by warranty you may claim at your dealer, or at their site (https://wittner-gmbh.de/).  If pure mechanical, working similar to a watch which rate is adjustable, a local watchmaker could replace the spring, etc.
Comment: I'd suggest exchanging your clockwork metronomes for an electronic one. I had a mechanical one for years - but it developed a limp, so the ticks weren't evenly spaced. Electronic ones are more portable, more accurate, more versatile. In fact, I can't think of any advantages a mechanical metronome has over an electronic one.
Comment: Mechanical metronomes are best reserved for mantelpiece show.  Electronic ones are far cheaper and much more accurate & reliable.
Answer: Mechanical metronomes tend to slow down as the spring runs down and the amplitude of the pendulum swing reduces.
This is likely to be more significant at a slow tempo simply because the pendulum is getting fewer "pushes" per minute to keep it going.
The clockwork mechanism is usually quite simple and easy to clean, but if you are tempted to try oiling it, only use non-acidic "clock oil," not something you bought cheaply to stop a door hinge squeaking - and don't go anywhere near it with a can of WD-40!
Answer: By lifting the left or right side of a mechanical metronome you can alter the ratio of the left-to-right and right-to-left timings.
The amount of sideways inclination needed to compensate for the metronome's mistakes, however, may vary with speed, so you you may find that, e.g. by placing a piece of cardboard under the right side of the metronome you can get it to play precisely at MM=40, but at 30 or 50 BMP there will be some amount of error.
Anyway I suggest you give it a try -- try placing the metronome on a surface that you can tilt sideways, and see if you can find a position that makes it work well enough for your needs.
Comment: True, but the OP is asking about speed accuracy, not loss of uniformity
Comment: You're right, but I hope this point is somewhat related and might be useful to someone anyway.

Mehcanical metronome losing precision


Permutations and fixed points

Question: The permutation σ ∈ S2020 has its order = 2019. What is the maximum number of fixed points?
I was thinking that since its order is 2019, the permutation with 2019 different elements is equal to the neutral permutation. So in essence, there is only one point which stays the same, and by that I mean fixed. Is this correct or am I missing something ?
Answer: $$2019=3×673$$
We can achieve a permutation of order $2019$ by letting there be a $3$-cycle and a $673$-cycle. Thus $2020-3-673=1344$ points are fixed, and since there is no other factorisation of $2019$ with smaller sum of factors, this is the best we can do.

Permutations and fixed points


Como manipular onde o foco do VoiceOver do Iphone ira aparecer na tela seguinte quando a acessibilidade esta ativa?

Question: Tenho um problema de Acessibilidade apenas no Iphone, algumas paginas do APP são em Webview feitas em .aspx e essas telas usa uma estrutura de MultiView, ou seja uma unica pagina .aspx pode ter varias telas seguintes e são carregadas como se fosse um ajaxs. Ao clicar em um botão de avançar o conteúdo da tela seguinte é carregado e a marcação da acessibilidade continua no mesmo ponto da tela anterior que foi o botão de avançar por exemplo. Existe alguma forma de determinar onde o foco da acessibilidade tem que aparecer?
Comment: Cara, vale dar uma olhada em ARIA que é o que faz a parte de acessibilidade em web, imagino que o iPhone siga essa especificação. https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA
Answer: Bom, após muitas tentativa, acho que isso foi o que conseguimos ter um melhor resultado.
A ideia é usar o a tabindex="-1" e tag role="status". É preciso seguir essa combinação pra funcionar.
<code>     <script>
        function subirFoco() {
            if (navigator.platform.match(/iPhone|iPad/i)) {
                setTimeout(function () {
                    $('#foco').attr('tabindex', -1);
                    $('#foco').attr('role', 'status');
                    $('#foco').focus();
                }, 100);
            }
        }
    </script>
</code>


If $(f_1,...,f_n)\in \text{Maps}(X,k)$ are linearly independent, then there exist $x_1,...,x_n\in X$ s.t. $(f_i(x_j))$ is invertible.

Question: Here is an assertion that seems correct to me (source: Algebraic Groups and Algebraic geometry  by Geck; cf proof of 2.4.3, although its an elementary statement) but I can't see an immediate proof.
If $f_1,...,f_n\in \text{Maps}(X,k)$ are linearly independent (in the $k-$vector space of maps from a set $X$ to a field $k$), then there exists elements $x_1,...,x_n\in X$ such that $(f_i(x_j))$ is an invertible matrix.
Here is an idea : Let $V:=\operatorname{Span}(f_1,...,f_n)$. Considering the functionals $\pi_x=f\mapsto f(x)\colon k^X\to k$ (for $x\in X$) can we show that $\operatorname{Span}(\pi_x|_V\mid x\in X)=V^*$?
Then we can use the fact that if $V$ is any finite dimensional vector space with $b_1,...,b_m$ as a basis and $g_1,...,g_m$ is a basis of $V^*$ then $(g_i(b_j))$ is invertible (this follows from $\cap \ker(g_j)=0$).
A proof of the above fact or any other elementary proof of the statement (in bold) would do. Thanks in advance.
Answer: Consider the composite map $F := (f_1, \ldots, f_n) : X \to k^n$.  Then we first see that $\{ F(x) \mid x \in X \}$ must span all of $k^n$; otherwise, there would be some nonzero functional $\varphi \in (k^n)^*$ whose kernel contains the span, and taking the coefficients of $\varphi$ would give a contradiction to the linear independence of $f_1, \ldots, f_n$.
So now, since $k^n$ has dimension $n$, there are $n$ elements $F(x_1), \ldots, F(x_n)$ of this spanning set which form a basis of $k^n$.  That implies directly that the matrix $(f_i(x_j))$ is invertible.
Comment: Ah...that was simple and slick...thanks...Also discovered this https://math.stackexchange.com/a/2661385/492061


Can a function satisfy two different elliptic PDEs?

Question: Let $D\subset \mathbb{R}^2$ be a simply connected finite domain and consider two different 2nd order elliptic operators $\nabla^2$ and $\widetilde{\nabla}^2$. We set some continuous arbitrary function $\Omega_{\mathsf{B}}$ defined on the boundary of $D$.
Apart from the case of $\widetilde{\nabla}^2$ and ${\nabla}^2$ being linearly dependent, is there an $\Omega$ such that
$$
\begin{align}
\nabla^2\Omega=0\:\:\:\text{with}\:\:\:\Omega\Big|_{\partial D}=\Omega_{\mathsf{B}}\\
\widetilde{\nabla}^2\Omega=0\:\:\:\text{with}\:\:\:\Omega\Big|_{\partial D}=\Omega_{\mathsf{B}}
\end{align}
$$
By different I mean, for instance, that writing $\nabla^2=a_{ij}(x,y)\:\partial^2_{ij}$ and $\widetilde{\nabla}^2=\tilde{a}_{ij}(x,y)\:\partial^2_{ij}$  we have that $a_{ij}\neq\tilde{a}_{ij}$ for at least one point in the interior of $D$.
(As a special case I wish to take $\nabla^2$ to be the Laplacian, so the question would be rephrased as: given an elliptic $\widetilde{\nabla}^2$, can we find a harmonic function $f$ with fixed boundary value such that $\widetilde{\nabla}^2f=0$ ?)
Answer: Consider a linear function $f.$ Notice that it is in the kernel of any second order operator.
Otherwise, consider the operator $L=\nabla^2 - \widetilde{\nabla}^2.$  You are looking for a solution with vanishing boundary condtions.
If this difference is elliptic, then existence and uniqueness hold, and there is no such function. However, unless I am confused, if the difference of the operators is not elliptic, there may be a solution (the wave equation comes to mind).
Comment: True, but it may not satisfy a given arbitrary boundary condition.
Comment: Whatever boundary condition it satisfies, it will satisfy it for all the PDEs.
Comment: I am trying to show that for an arbitrary $given$ boundary condition, there will be (or not) such an $f$.
Comment: @DanielKatzner OK, see the edit.
Comment: Thanks. Why should the boundary condition be zero ? We assume that $\nabla^2 f=0$ and $\widetilde{\nabla}^2 f=0$ with $f|_\partial$ some given function. It merely means that $Lf=0$, but the condition has not changed. Or am I interpreting your argument wrongly ?
Answer: It is in fact possible to find a smooth $u : D \to \mathbb{R}$ and a smooth $\varphi : \partial D \to \mathbb{R}$ such that
$$
\begin{cases}
L_s u = 0 &\text{in }D \\
u = \varphi &\text{on }\partial D
\end{cases}
$$
for infinitely many elliptic operators $\{L_s\}_s$.  The idea is to build elliptic operators out of elliptic operators in lower dimension.
Here's a very simple example for $D \subset \mathbb{R}^2$, indexed by $s \in (0,\infty)$.  Define $u$ and $\varphi$ via $u(x,y) = ax+b$ and $\varphi = u \vert_{\partial D}$.  For $s \in (0,\infty)$ consider the elliptic operator
$$
L_s = \partial_x^2 + s \partial_y^2.
$$
This is a constant coefficient operator that is elliptic since $s >0$.  A trivial computation reveals that $L_s u =0$ in $D$, and $u = \varphi$ on $\partial D$ by definition.
This idea obviously generalizes to higher dimensions.  Pick a second order elliptic operator $M = \sum_{i,j=1}^n a_{ij} \partial_i \partial_j$ and a smooth, nontrivial $v: \mathbb{R}^n \to \mathbb{R}$ satisfying $Mv =0$ in $\mathbb{R}^n$.  We then consider, for $s \in (0,\infty)$ again,
$$
L_s = M + s \partial_{n+1}^2,
$$
which is an elliptic operator on $\mathbb{R}^{n+1}$. Now suppose we have a bounded domain $D \subseteq \mathbb{R}^{n+1}$.  Then upon setting $u : D \to \mathbb{R}$ and $\varphi : \partial D \to \mathbb{R}$ via $u(x,y) = v(x)$ for $(x,y) \in D$ (now viewing $x \in \mathbb{R}^n$ and $y \in \mathbb{R}$) and $\varphi = u \vert_{\partial D}$, we readily deduce that $L_s u =0$ in $D$ and $u= \varphi$ on $\partial D$ for all $s >0$.
Similar tricks can be used if you want something other than zero on the right side of the equation, say $L_s u = f$.  Just pick a smooth pair $v,f : \mathbb{R}^n \to \mathbb{R}$ satisfying $Mv =f$ and then set $F: D \to \mathbb{R}$ via $F(x,y) =f(x)$ to get $L_s u = F$ in $D$ with $u = \varphi$ on $\partial D$.  These ideas will also work for boundary conditions other than Dirichlet and elliptic operators of higher order.
Comment: Thanks. This is true, but I was asking something a bit different: $given\:two$ arbitrary operators, can one find the function?, instead of having one and proving that there exist another one, which is what I understand you proved. Also, I'm considering the cases where both operators are not linear combinations of each other.


Method of characteristics - geometrical interpretation

Question: I am currently studying the method of characteristics. I feel like missing a fundamental part, which I am not understanding.
Consider for instance the Burgers equation, $u_t  + uu_x = 0$ in $\mathbb{R}$, $t > 0$ with $u(x,0) = u_0(x)$, $x \in \mathbb{R}$.
Here is a plot of the characteristics:

I do understand that when doing the methods of characteristics, that I introduce one new parameter, call it $s$, for changing to a suiting coordinate system where my PDE becomes an ODE. The characteristics should be exactly be these lines. Mostly, there is a second parameter, call it $y$, for choosing the suiting characteristic curve. In the figure given, there are plots where $u(x,t) = 1$ (lines with slope $1$, $x<0$) and $u(x,t) = 0$ (vertical lines ($x > 1$).
In the figure above, we can see projections of these characteristics.
How can I plot the characteristics on my own?
EDIT: Already understood that: It works when looking at $(t,x(t,x_0))$. Looking at $\frac{dx}{dt}$ and inverting it, will yield the slope $\frac{dt}{dx}$, which are the characteristic curves.
Remaining questions:
Can I reconstruct $u(x,t)$ from plots like the above one? If yes, how do I do that?
What is the geometrical interpretation of the connection between $u(x,t)$ and the projections to the $(x,t)$-plane of the characteristics?
Any help is greatly appreciated.
What I have already tried:
If it is possible to get back on an open set (for using the inversion theorem) from the introduced two parameters $(s,y)$ to $(t,x)$, then it must be possible to reconstruct $u(x,t)$ locally due to the third equation of the characteristic equations ($\frac{du}{ds} = c(t,x,u)$ for a differential equation of the form $a(t,x,u)u_t + b(t,x,u)u_x = c(x,y,u)$). I think this should answer the questions above. Is this correct or are there misunderstood parts? Due to people having favoured this question, I will not delete it.
Comment: Anecdote: When asked if it was okay to name the equation Burgers' equation, Burgers is supposed to have answered, "so long as it's not called Burger's equation". I wasn't going to edit the question over such a nitpick, but then I noticed you had a derivative wrong, so it became necessary to do so.
Comment: I have written an answer here that maybe could be useful: https://math.stackexchange.com/a/4547413/601797
Answer: Not sure if this answers your question, but it's best to think of the characteristics as curves in $(t,x,u)$ space. The characteristic equations (including $dt/dt=1$) is just a regular system of ODEs, and the solution curves never cross in this space. Your initial data will be given by a curve, typically of the form $t=0$, $u=u_0(x)$, and all the characteristics starting from this curve will form a two-dimensional surface which is going to be the graph of the solution. Except, of course, the projection to the $(t,x)$ plane will have singularities, and then it will be many to one, so you're not really looking at a function graph anymore, except sufficiently close to the initial data. But locally, the surface will always be the graph of a solution, except where the projection to $(t,x)$ has rank less than $2$.
I find it useful to use a computer algebra system to visualise this for a simple example. For example, Burgers' equation with initial data $u_0(x)=\arctan x$. Plot the solution as the parametric surface (with parameters $(\xi,t)$): $x=\xi+t\arctan\xi$, $u=\arctan\xi$, $t=t$. Then play around with the three-dimensional plot, rotating it with the mouse and studying it from all angles.


What is "The Problem of Counterfactuals?"

Question: From Wikipedia:

The PROBLEM of counterfactuals
According to the material conditional analysis, a natural language
conditional, a statement of the form 'if P then Q', is true whenever
its antecedent, P, is false. Since counterfactual conditionals are
those whose antecedents are false, this analysis would wrongly predict
that all counterfactuals are vacuously true.
https://en.wikipedia.org/wiki/Counterfactual_conditional#The_problem_of_counterfactuals

Is this really a "problem?"
Consider the counterfactual conditional: "If the release valve had been working properly, the explosion would have been contained." (Maybe this is not a good example?)
We have: $ValveFailure \implies Explosion~~~$ (for logical propositions $ValveFailure$ and $Explosion$)
This implication is vacuously true if the antecdent, ValveFailure, is false. In that case, we cannot determine the truth value of Explosion since the antecedent is false. Without introducing any inconsistencies, Explosion could be either true or false. Other possible causes of an explosion are not ruled out. It seems that, in this case anyway, the material condition will suffice.

Another possible approach...
From propositional logic, we know that $(A\land B)\implies (\neg A \implies \neg B)$:

The original "counterfactual conditional" suggests that both $ValveFailure$ and $Explosion$ are true.
Therefore, we have: $\neg ValveFailure \implies \neg Explosion$
This looks suspiciously like our original "counterfactual conditional." What, if anything, are we to make of this?
Comment: The point is that, in terms of the Wikipedia article's analysis, if your statement is in fact a counterfactual then that means that, in reality, the release valve wasn't working properly, and the explosion wasn't contained. That means the antecedent is false, so the material conditional is vacuously true, and hence is not making a meaningful claim about "what would have happened if the antecedent had been true."
Comment: How did you get from "If the release valve had been working properly, the explosion would have been contained." to your formula? Isn't it $ValveWorking \Rightarrow ExplosionContained$? Or, at best, reading more into it $(Explosion \wedge ValveWorking) \Rightarrow ExplosionContained$
Comment: We can assume that a valve failure will result in an explosion. It was not stated that valve failure is the only possible cause of an explosion. It would not be reasonable to assume this in any  case. So, if the valve did not fail (antecedent is false), no meaningful claim can be made about there being an explosion or not.
Answer: There are various Problems with Counterfactuals.
I will give only 2 Classes :
Class 1 :
(1A) If "Historical Event X" had not occurred , we would have no Poverty all over the world.
(1B) If "Historical Event X" had not occurred , we would have Poverty over the world.
Both are valid , because "Historical Event X" did occur.
(2A) If "World war 3" had occurred in 1955 , we would have no Poverty all over the world.
(2B) If "World war 3" had occurred in 1955 , we would have Poverty over the world.
Both are valid , because "World war 3" did not occur.
Class 2 :
(3A) If "1=3" , "42 is the answer to all queries"
(3B) If "1=3" , "42 is not the answer to all queries"
(4A) If "$4 \in \{1,2,3\}$" , "42 is the answer to all queries"
(4B) If "$4 \in \{1,2,3\}$" , "42 is not the answer to all queries"
All Counterfactuals are valid.
With your Example :
"If the release valve had been working properly, the explosion would have been contained."
Imagine a terrorist attack on a Petrol Station & the Security Company ( which did not secure the Petrol Station ) trying to evade responsibility : "Hey , you gave us 10,000,000 Dollars & we did our best : We put in the 100 Dollar CCTV camera to deter terrorists. When our agents went for the 2-hour lunch break , somebody broke in to throw a bomb. Now , your release valve did not work. If the release valve had been working properly, the explosion would have been contained. That is not out fault"
During the bombing with a release valve failure , that is vacuously true , but invalid.
During the bombing with no release valve failure , the Security Company can even claim : "If the release valve had been not working properly, the explosion would have been contained." which is still vacuously true + still invalid.
Class 3 :
I had a look at your given Article now , hence I am including a new Class. I think , "Non-monotonicity" is a Class which uniquely occurs in Counterfactuals.
Let $A:1=0$
If $ A $ , then $ Z $
If $ A \land A1 $ , then $ \lnot Z $
If $ A \land A1 \land A2 $ , then $ \lnot Z $
If $ A \land A1 \land A2 \land A3 $ , then $ Z $
If $ A \land A1 \land A2 \land A3 \land A4 $ , then $ \lnot Z $
If $ A \land A1 \land A2 \land A3 \land A4 \land A5 $ , then $ Z $
Even though we are adding more Conditions , the Conclusion is toggling.
All this because $A$ is not true.
Comment: @DanChristensen The reason it is considered a problem is simply because the material conditional represents "if P is true, then Q is true", whereas counterfactual conditionals have the form "if P was true, then Q would be true". With material conditionals, $\lnot P$ makes $P \to Q$ true, but that doesn't reasonably for counterfactuals, which are common in natural language but not truth-functional.

For an example, contrast "If Lee Harvey Oswald didn't kill JFK, someone else did" with "If Lee Harvey Oswald didn't kill JFK, someone else would've".
Comment: Thank you for your thoughtful answer. If $A$ is false, then $A\implies B$ is always true (or valid) regardless of the truth value of $B$. Likewise, $A\implies \neg B$ is also then true (or valid) regardless of the truth value of $B$. This may seem counter-intuitive, but there is no inconsistency here. We will not be able, for example, to prove that $B \land \neg B$ is true. There is no need to concoct a different kind of conditional to handle such situations. The material condition is quite sufficient in these cases.
Comment: Correct : When $A$ is not true , all variations [[ "if $A$ , then $B$" , "if $A$ , then $\lnot B$" , "if $A$ , then $B \land \lnot B$" , "if $A$ , then $B \lor \lnot B$" ]] are vacuously true , which is consistent though not useful. In Mathematical Logic , when variation 3 arises , the Automatic Conclusion is that $A$ is not true.


Transform differents dates format to one format - Oracle SQL

Question: I have a column with two date format :

DD/MM/YYYY
YYYY-MM-DD

I want to transform all date format of this column to only one date format, it is 'DD/MM/YYYY'
How can i do it in Oracle SQL ?
Thanks in advance
Comment: DO NOT store dates as strings. Use an appropriate DATE / TIME data type.  You will format dates any way you want in UI layer.
Answer: NEVER store dates as strings; always use a DATE or TIMESTAMP data type.

From Oracle 12, you can use multiple calls to the TO_DATE function with different format models and use DEFAULT NULL ON CONVERSION ERROR to prevent errors being raised and COALESCE them to find the match:
SELECT date_string_column,
       COALESCE(
         TO_DATE(
           date_string_column DEFAULT NULL ON CONVERSION ERROR,
           'fxDD/MM/YYYY'
         ),
         TO_DATE(
           date_string_column DEFAULT NULL ON CONVERSION ERROR,
           'fxYYYY-MM-DD'
         )
       ) AS date_value
FROM   table_name

Which, for the sample data:
CREATE TABLE table_name (date_string_column) AS
SELECT '2021-01-01' FROM DUAL UNION ALL
SELECT '31/12/2022' FROM DUAL;

Outputs:

DATE_STRING_COLUMN
DATE_VALUE

2021-01-01
2021-01-01 00:00:00

31/12/2022
2022-12-31 00:00:00

db<>fiddle here
Answer: Assuming you only have those 2 formats, you can do something like:
select (case when instr(columnName, '/') > 1 then
             to_date(columnName, 'DD/MM/YYYY')
        else to_date(columnName, 'YYYY-MM-DD')
        end) field_as_date
 from tableName;

This should give you columnName as a Date (without the time part ofc).
Answer: Here is another way.
String data is horrible for storing anything important.  According to one of the database I work with, there are over 4000 counties in Washington State.  There are also about 15 ways to spell "3M".  You'll probably also need to find ways to cleanse your data or handle non-date data in that column.
with dt (dt) as (
  select cast('2021-01-31' as varchar2(50))
  from dual
  union select cast('31/01/2021' as varchar2(50))
  from dual
)

select
  dt
, to_date(
    regexp_replace(
      regexp_replace(
        dt
        , '([[:digit:]]{2})/([[:digit:]]{2})/([[:digit:]]{4})'
        , '\3-\2-\1'
      )
      , '([[:digit:]]{4})-([[:digit:]]{2})-([[:digit:]]{2})'
      , '\1-\2-\3'
    )
    , 'yyyy-mm-dd'
  ) "dt"
from dt;


How to obtain the value through the nested objects in Reactjs

Question: I am new to the Reactjs development and currently working on a personal fun personal project. So I have JSON file and the contents are:
{
  "btcinr": {
    "base_unit": "btc",
    "quote_unit": "inr",
    "low": "479200.0",
    "high": "509949.0",
    "last": "500003.0",
    "type": "SPOT",
    "open": 493000.0,
    "volume": "48.0567",
    "sell": "503000.0",
    "buy": "500003.0",
    "at": 1584867246,
    "name": "BTC/INR"
  }
}

I have following code in my render method:
import React from "react";

class App extends React.Component {
constructor(props){
  super(props);
  this.state = {
    items : [],
    isLoading: true,
  }
}

  componentDidMount() {
    fetch('JSON API LINK')
    .then(res => res.json())
    .then((data) => {
      this.setState({
         items: data,
         isLoading: false,
        })
    })
    .catch(console.log)
  }

  render() {

const list = this.state.items.btcinr && Object.keys(this.state.items.btcinr);
console.log(list);

    return (

        {this.state.isLoading ?
Fetching data
 :

            list.map(
              (ticker) =>

{ticker}

              )
        }

    );}
  }

export default App;

What I want the output is the value of last. But when I go through list.last I get error that

cannot read the proparty "last" of undefined.
Comment: You need to build the component by passing properties to it. Or to build the values in the state, but leave that for later, look here how to pass props to components. [How to pass props from one class to another in React.js](https://stackoverflow.com/questions/40662893/how-to-pass-props-from-one-class-to-another-in-react-js)
Comment: Can you paste the full code of your JSX file with state etc?
Comment: `list` is an array of the **keys**. you'd probably want to use `this.state.items.btcinr.last`
Comment: @MuhammadHaseeb I have edited the code and inserted full code.
Answer: Your condition is not correct since you have the JSON as a response and you need to check if btcinr key exists in your items state then you need to make a list of keys available in btcinr.
This code should solve your problem:
render() {
const { items } = this.state;
let list = [];
if(items.hasOwnProperty('btcinr')){
  list = Object.keys(items.btcinr);
}
return (

    {list.map(ticker => (

{ticker}

    ))}

);}

If you want to get the last property of btcinr you can use this code:
if(items.hasOwnProperty('btcinr')){
      const last = items.btcinr.last;
  }

And if you want to get the value of the last index from the list of keys, then you can use this code:
if(items.hasOwnProperty('btcinr')){
      list = Object.keys(items.btcinr);
      const last = list[list.length];
  }

Comment: Hey there, thanks for replying. What I want to do is obtain the value of last property in btcinr, and still using the solution you provided i cannot retrieve that value. What can be done?
Comment: I have Eddited my answer as per your requirement. Hope this solves your problem


os.walk giving non existent directories

Question: I have a folder in which there are subfolders corresponding to 10 different classes, and the names of these subfolders are my labels. I came up with the following code to read the images into a Numpy array and save the labels.
import numpy as np
import pandas as pd
import cv2
import glob
import os

x=np.empty([28,28])
y=np.empty([1,0])

for root, dirs, files in os.walk("filepath"):
    for roots in root:
        os.chdir(roots)
        images = np.array([cv2.imread(file) for file in glob.glob(roots+"/*.jpg")])
        num_of_images=images.shape[0]
        if num_of_images == 0:
            continue
        else:
            x = np.concatenate((x,images),axis=0)
            labels = np.empty([num_of_images,1])
            labels = labels.astype(str)
            #labels = get from last part of file name in roots
            #y=np.concatenate((y,labels),axis=0)

The error I'm getting is

os.chdir(roots)
  FileNotFoundError: [Errno 2] No such file or directory: 'U'

When I print(root) it gives the correct subfolder paths. How do I handle this error?
EDIT :
Got it working by removing for roots in root since os.walk returns a 3 tuple for each directory where root gives us the directory paths.
Answer: As docs on os.walk() say, first item in each 3-tuple it returns is a string.
As such, for roots in root: iterates over characters of the string.
You need to read carefully what kind of data structure os.walk() returns and restructure your script accordingly.
Answer: Others already pointed out what is wrong, so I will not repeat it.
I'll just add that you should use
help(os.walk)

or whatever function isn't working as you expect it to, inside the interpreter before asking a question.
You handle this error as follows:
import os

for root, dirs, files in os.walk(path):
    for thedir in dirs:
        p = os.path.join(root, thedir)
        os.chdir(p)

Answer: root will be a string; the name of the current directory of os.walk.
for roots in root:

will iterate over that string; roots will iterate over root one character at the time... os.chdir(some character) will not work.
Comment: Ah. So I should use dirs instead?
Comment: i suggest you print out `root, dirs, files` so see what they are and then proceed with what you need. i'm not sure calling `os.chdir` while iterating over `os.walk` will work as expected...

os.walk giving non existent directories


Marginal distributions of two linear transformations of two correlated Gaussian (Normal) distributions

Question: Considering this entry the distribution of the sum of non i.i.d. gaussian variates is also gaussian.
$$
\begin{align*}
V = aX + bY &\sim N(a\mu_X + b\mu_Y,\; a^2\sigma_X^2 + b^2\sigma_Y^2 + 2ab\sigma_{X,Y})
\end{align*}
$$
What if we have another transformation like W as below:
$$
\begin{align*}
W = cX + dY &\sim N(c\mu_X + d\mu_Y,\; c^2\sigma_X^2 + d^2\sigma_Y^2 + 2cd\sigma_{X,Y})
\end{align*}
$$
Knowing that X and Y are identically distributed and correlated Gaussian r.v.s what are the marginal distributions of V and W?
Besides, how to get the correlation coefficient of V and W?
Answer: You have already written out the marginal distributions for $V$ and $W$ above -- they are normal with means and variances as you expressed. To find their correlation, we can write:
$$\text{cov}(V,W) = \text{cov}(aX+bY,cX+dY)$$
which in turn can be decomposed as $$\text{cov}(aX,cX) + \text{cov}(aX,dY) + \text{cov}(bY,cX) + \text{cov}(bY,dY).$$ Notice that $\text{cov}(aX,cX) = ac \cdot \text{var}(X)$ and $\text{cov}(bY,dY) = bd \cdot \text{var}(Y)$. We also know that $\text{cov}(aX,dY) = ad \cdot \text{cov}(X,Y)$ and $\text{cov}(bY,cX) = bc \cdot \text{cov}(X,Y)$. So, you can compute $\text{cov}(V,W)$ by just plugging in these values, which you already know from the joint distribution of $X$ and $Y$.
Finally, to get the correlation coefficient, you can just divide your value of $\text{cov}(V,W)$ by the square root of the variance of $V$ and the square root of the variance of $W$.
Comment: I may get confused about the marginal distribution here. Thanks.


How do I edit resolv.conf?

Question: I need to setup OpenDNS, but I can't edit resolv.conf
Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.1.1
search gateway.2wire.net

Comment: `sudo vi resolv.conf`
Answer: Your system uses resolvconf, so the resolv.conf file is replaced by a symbolic link to /etc/resolvconf/run/resolv.conf and resolvconf dynamically generated the file. That's why DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
To properly update the information in the file, you can put the dns-* parameters in /etc/network/interfaces e.g.
auto eth0
iface eth0 inet static
     address 184.108.40.206
     netmask 255.255.255.0
     gateway 18.104.22.168
     dns-nameservers 220.127.116.11 184.108.40.206
     dns-search example.com

Then, you can update the dns-* info by
$ resolvconf -d eth0
$ resolvconf -a eth0

Or you can do ifdown & ifup and resolvconf -d, -a will happen behind the scenes.
Note: sometimes I find resolvconf -u doesn't work. I don't know why
You should read man resolvconf. There's more information about all this.
TIP: if you want to update /etc/resolv.conf manually, you can remove the symlink and create /etc/resolv.conf by hand. This way, the file won't get updated from resolvconf ever.
    $ rm /etc/resolv.conf         ;# to remove the symlink
    $ vi /etc/resolv.conf         ;# to create a regular file

Comment: I went for the TIP at the end, seems to work like a charm. But just in case, as a first step I preferred `mv /etc/resolv.conf /etc/resolv.conf.disabled` instead of `rm`. Just in case I need to put the simlink back :)
Comment: The last one worked for me. While probably not ideal solution, this one at least works. Thank you, I tried like 4 or 5 different solutions until I found this one. You saved me a lot of headache.
Answer: This usually requires editing /etc/resolvconf/resolv.conf.d/base(depending on your distro this placement may vary slightly) or other files in this directory. They are added by the resolvconf process itself. The format of those files is the same as a standard resolv.conf.
After you have made those edits then you can force resolvconf to update using the command resolvconf -u.
Comment: Linux rwilson-Inspiron-1318 3.8.0-31-generic #46-Ubuntu SMP Tue Sep 10 19:56:49 UTC 2013 i686 i686 i686 GNU/Linux

My system has the file "/etc/resolvconf/resolv.conf.d/base" but it's
empty
Comment: it just includes what is in that file along with other entries it calculates dynamically.  add your entry there as you would for normal `resolv.conf` file and after you run the command it should update what you see in resolv.conf and do what you need.

How do I edit resolv.conf?


Consultar páginas de terceiros

Question: Problema:
Consultar uma página em outro site, passando parâmetros via POST e recebendo o resultado no PHP.
Eu tenho o seguinte site:

http://www.ciiagro.sp.gov.br/ciiagroonline/Listagens/BH/LBalancoHidricoEDR.asp

No console quando uma pesquisa é feita aparece os seguintes parâmetros:
EDR
Inicio

Existe algum comando no PHP em que você faz o POST para uma página qualquer e ele faz o "download" dessa página?
Comment: Sua pergunta está um pouco confusa. Você quer simular um POST usando PHP?
Comment: Download em que sentido?
Comment: Sim simular o post usando php. Download no sentido de salvar o código da página em uma variável por exemplo
Comment: Quer simular um POST naquela página e que retorne o código da página?
Comment: @JorgeB. Exato .
Answer: Você pode enviar uma solicitação de POST usando cURL;
Primeiro Passo
Vamos verificar se ele está instalado, em seu php.ini verifique essa linha:
;extension=php_curl.dll

Caso esteja comentada, tire o ;.
Uso Básico
  // Inicializamos o cURL informando um site;
  $requisicao = curl_init('www.seusite.com.br');
  // Definimos que deverá retornar o resultado;
  curl_setopt($requisicao, CURLOPT_RETURNTRANSFER, true);
  //Executa e salva o conteúdo na variável;
  $resultado = curl_exec($requisicao);
  // Encerramos a conexão;
  curl_close($requisicao);

Usando POST
  // 'Input' => 'Valor'
  $parametros = [
    'id' => 1,
    'relacao_id' => 234
  ];
  // Setamos POST como true
  curl_setopt($requisicao, CURLOPT_POST, true);
  // Parâmetros que serão enviados pelo POST [array]
  curl_setopt($requisicao, CURLOPT_POSTFIELDS, $parametros);

Fonte: http://blog.thiagobelem.net/tutorial-basico-de-curl-instalacao-configuracao-e-uso/

Exemplo de cURL informando headers para recuperar o captcha do site da Receita Federal:
$ch = curl_init("http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/captcha/gerarCaptcha.asp");
$options = [
    CURLOPT_COOKIEJAR => 'cookiejar',
    CURLOPT_HTTPHEADER => [
        "Pragma: no-cache",
        "Origin: http://www.receita.fazenda.gov.br",
        "Host: www.receita.fazenda.gov.br",
        "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0",
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
        "Accept-Encoding: gzip, deflate",
        "Referer: http://www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/ConsultaPublica.asp",
        "Cookie: $cookie",
        "Connection: keep-alive"
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => 1,
    CURLOPT_BINARYTRANSFER => TRUE
];

curl_setopt_array($ch, $options);
$img = curl_exec($ch);
curl_close($ch);

Exemplo utilizando a API Guzzle para consulta de CEP:
$client = new Client();
$urlCurl = 'http://www.buscacep.correios.com.br/servicos/dnec/consultaEnderecoAction.do';
$request = $client->createRequest('POST', $urlCurl, [
    'body' => [
        'relaxation' => $param,
        'tipoCep' => 'ALL',
        'semelhante' => 'N',
        'cfm' => 1,
        'Metodo' => 'listaLogradouro',
        'TipoConsulta' => 'relaxation',
        'StartRow' => 1,
        'EndRow' => 100
    ],
    'headers' => [
        'Host' => 'www.buscacep.correios.com.br',
        'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36',
        'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language' => 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4',
        'Accept-Encoding' => 'gzip, deflate',
        'Referer' => 'http://www.buscacep.correios.com.br/',
        'Connection' => 'keep-alive'
    ],
]);
$body = $client->send($request)->getBody();

Documentação: http://php.net/manual/pt_BR/book.curl.php
Outros Exemplos: http://php.net/manual/pt_BR/curl.examples-basic.php
Guzzle é uma API que ajuda você nos processos de requisições, no link ao lado você pode achar a documentação, exemplos de uso e demais requerimentos para o funcionamento correto.
Comment: André e Jorge, desculpe o erro.. já foi arrumado
Comment: @JorgeB. alterei :)
Comment: @RafaelWithoeft Acho que ele está falando que `curl_setopt($cURL...` deveria ser `curl_setopt($requisicao...`
Comment: @RafaelWithoeft Obrigado
Comment: @RafaelWithoeft O código funcionou,mas eu não consegui acessar o resultado da página.Você tem alguma dica para eu chegar nele?
Comment: @RodolfoOliveira O resultado retornou na variável como você esperava? O que falta é conseguir capturar da variável o que você precisa, é isso?
Comment: @RafaelWithoeft Retornou uma página html,ou seja,o que eu esperava,entretanto a página que retornou não é o fim da busca e sim o começo da busca.Para entender melhor entre nesse site: http://www.ciiagro.sp.gov.br/ciiagroonline/Listagens/BH/LBalancoHidricoEDR.asp e faça a consulta(são duas telas apenas).No meu post eu estou passando os parâmetros:  $dados = array(
 'EDR'=>'Araraquara',
 'Inicio'=>'16%2F2%2F2015',
 'Consultar'=>'Consultar'
  );,se não for muito em comodo analise e veja no que estou errando,pois não achei o erro
Comment: @RodolfoOliveira vou fazer alguns testes
Comment: @RafaelWithoeft Obrigado Amigo,aguardo.
Comment: @RodolfoOliveira Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/21442/discussion-between-rafael-withoeft-and-rodolfo-oliveira).
Comment: @RodolfoOliveira disponibilizei aqui -> http://pastebin.com/xbZD5PsE o código funcionando, utilize Guzzle;

Consultar páginas de terceiros


Adding payment model to Sold to Model in hybris

Question: I want to integrate my Hybris system with Paymetric for credit card payment for B2b implementation and store the token information got from Paymetric against the Sold to to which the user is associated.How can i add the payment model to sold Model for this implementation.
Comment: Which version of Hybris are you using? Paymetric now comes integrated in the latest version of Hybris. Please see this link:
https://www.hybris.com/ja/partner/hybris-extend/paymetric
Also you can buy the extension from Hybris.
Comment: I'm using Hybris 6.0
Answer: Hybris doesn't come Out of the box for Paymetric it is for Cybersource. You need to get extension from Paymetric for Hybris integration and they will also provide the documentation for Integration. Paymetric will provide you extension by name cispaymentpaymetric. You need to place it in /bin/custom folder .
Add the extension in \hybris\config\localextensions.xml. Then run ant clean all.
eCommerce Payment Integration for hybris® uses the XiPay® Connector for hybris (XPC4 hybris)
solution to facilitate connectivity from your hybris system to the Paymetric XiPay On-Demand Service to
perform authorization and settlement functions.

The Paymetric CIS Payment Extension Module (PEM) component is
installed and configured in the hybris local.properties file on the
same application server (or VM) running your hybris Storefront.
The Paymetric CIS Payment Service Gateway (PSG) component is
installed and configured in the paymetric-hybris.properties file on
a separate Tomcat application server (or VM) that is running the
hybris Payment Service.
The XPC4 hybris components are independent of the database and will
work with any DB that you have implemented with your hybris
solution.


grunt browser sync not injecting changes

Question: I'm trying to get grunt-browser-sync to inject any css changes into an open browser when a file is updated/changed. But for some reason, I can seem to get it to work and grunt is not giving me any errors to let me know it's not working.
I'm currently using MAMP since it's a Wordpress based project.
Here's my Gruntfile.js:
module.exports = function(grunt) {

// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
  build: {
    src: '_/js/libs/*.js', //input
    dest: '_/js/functions.min.js' //output
  }
},
sass: {
  dist: {
    options: {
      loadPath: require('node-bourbon').includePaths,
      loadPath: require('node-neat').includePaths,
      style: 'compressed'
    },
    files: {
      'style.css': 'scss/style.scss'
    }
  }
},

autoprefixer: {
dist: {
  files: {
    'style.css': 'style.css'
  }
 }
},
browserSync: {
        dev: {
            bsFiles: {
                src : 'style.css'
            },
            options: {
                watchTask: true
            }
        }
    },

watch: {
  options: {
    livereload: true
},
js: {
files: ["_/js/libs/*.js"],
tasks: ["ugilify"],
},
sass: {
files: ["scss/*.scss"],
tasks: ["sass", "autoprefixer", "browserSync"],
},
php: {
files: ['*.php']
  },
 }
});

grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-autoprefixer');
grunt.loadNpmTasks('grunt-browser-sync');

// Default task(s).
grunt.registerTask('default', ['uglify', 'sass', 'browserSync', 'watch', 'autoprefixer']);

};

and here's the output when I save/update a file:
Running "watch" task
Waiting...
>> File "scss/global.scss" changed.
Running "sass:dist" (sass) task
File style.css created.

Running "autoprefixer:dist" (autoprefixer) task
File style.css created.

Running "browserSync:dev" (browserSync) task

Done, without errors.
Completed in 1.478s at Wed May 07 2014 18:47:40 GMT-0500 (CDT) - Waiting...

But then I have to physically refresh the browser to see the changes.
I'm not sure if I am missing something within the grunt file or what.
Comment: All looks right... try a Gruntfile that includes only browserSync.  If that works, add watch.  When that works add sass.
Comment: i have the same exact problem and a gruntfile.js which is very similar to yours. as i type grunt watch, i modify say the.html file i get a successfull build but.. no browser is opened or anything :\ any ideas?
Answer: The only version of grunt-browser-sync that works for me with this code is 1.9.1. So, un-install your current version and
npm install firstname.lastname@example.com --save-dev

Comment: This works for me too. Newer versions just don't work the same.
Answer: I encountered the same issue and have opened an issue here
Github grunt-browser-sync repo with issues 58
Comment: One thing I did notice is that if I took my current Gruntfile that I pasted above and just ran `grunt` then I noticed that it would work, and output the JS injection script that I needed to add into my project. Once I did that, it was working. If if run `grunt watch` it doesn't work. So, yeah. I guess I'm getting confused on whether or not I need to even have grunt watch with browser sync or what.

This is still all new to me. And I'll probably be moving to gulp after a while, but there is more development for grunt currently, so I'll be sticking with grunt for a bit.
Comment: I was encountering a similar issue where BrowserSync would see that a file had changed, but would not refresh the page. In my case, I had moved the `` tag to an include file named header.html, so it was unable to inject the necessary script. After moving my opening `` tag to index.html the problem was resolved.

Thought I'd mention for anyone else who may find themselves in a similar scenario.


LEFT JOIN com WHERE em campo da primeira tabela OR campo da segunda tabela

Question: SELECT COALESCE(tb2.numero_novo, tb1.numero_original) as numero
FROM
tb1
LEFT JOIN tb2 ON tb2.id = tb1.id
WHERE
tb1.numero_original = <PARAM> OR tb2.numero_novo = <PARAM>

A query acima gera um full table scan. Como otimizar esta query?
EXPLAIN:
+----+-------------+-------+-------+----------------+----------------+---------+------+----------+----------------------------------------------------+
| id | select_type | table | type  | possible_keys  | key            | key_len | ref  | rows     | Extra                                              |
+----+-------------+-------+-------+----------------+----------------+---------+------+----------+----------------------------------------------------+
|  1 | SIMPLE      | tb1   | index | numero_original| numero_original| 5       | NULL | 11683843 | Using index                                        |
|  1 | SIMPLE      | tb2   | ALL   | PRIMARY        | NULL           | NULL    | NULL |        2 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+-------+----------------+----------------+---------+------+----------+----------------------------------------------------+

O problema que preciso resolver é:
tb1 é uma tabela que contém o campo numero_original. Quero criar a tabela tb2 para armazenar um novo valor para este campo, (que chamei de numero_novo). Fiz isso pois não posso alterar o valor do campo numero_original, e não gostaria de criar o campo numero_novo na tabela tb1, pois ele seria NULL em mais de 95% da tabela de 11 milhões de registros.
EDIT:
Como falaram sobre índices, estou colocando mais informações:

tb1 possui como chave primária o campo id;
O campo numero_original da tabela tb1 possui índice;
tb2 possui como chave primária os campos tb1_id e numero_novo;
A tabela tb1 possui 11mi+ registros;
A tabela recém-criada tb2 possui 2 registros de testes.

.
mysql> show indexes from tb1;
+-------+------------+-------------------+--------------+-----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name          | Seq_in_index | Column_name     | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-------------------+--------------+-----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tb1   |          0 | PRIMARY           |            1 | id              | A         |    11066164 | NULL     | NULL   |      | BTREE      |         |               |
| tb1   |          1 | numero_original   |            1 | numero_original | A         |     5533082 | NULL     | NULL   | YES  | BTREE      |         |               |
+-------+------------+-------------------+--------------+-----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

mysql> show indexes from tb2;
+-------+------------+------------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name   | Seq_in_index | Column_name    | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+------------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tb2   |          0 | PRIMARY    |            1 | tb1_id         | A         |           2 | NULL     | NULL   |      | BTREE      |         |               |
| tb2   |          0 | PRIMARY    |            2 | numero_novo    | A         |           2 | NULL     | NULL   |      | BTREE      |         |               |
+-------+------------+------------+--------------+----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

EXPLAIN selecionando com WHERE somente na primeira tabela (tb1):
+----+-------------+-------+------+----------------+----------------+---------+-------+------+----------------------------------------------------+
| id | select_type | table | type | possible_keys  | key            | key_len | ref   | rows | Extra                                              |
+----+-------------+-------+------+----------------+----------------+---------+-------+------+----------------------------------------------------+
|  1 | SIMPLE      | tb1   | ref  | numero_original| numero_original| 5       | const |    4 | Using index                                        |
|  1 | SIMPLE      | tb2   | ALL  | PRIMARY        | NULL           | NULL    | NULL  |    2 | Using where; Using join buffer (Block Nested Loop) |
+----+-------------+-------+------+----------------+----------------+---------+-------+------+----------------------------------------------------+

EXPLAIN selecionando com WHERE somente na segunda tabela (tb2):
+----+-------------+-------+--------+---------------+---------+---------+-------------------------+------+-------------+
| id | select_type | table | type   | possible_keys | key     | key_len | ref                     | rows | Extra       |
+----+-------------+-------+--------+---------------+---------+---------+-------------------------+------+-------------+
|  1 | SIMPLE      | tb2   | ALL    | PRIMARY       | NULL    | NULL    | NULL                    |    2 | Using where |
|  1 | SIMPLE      | tb1   | eq_ref | PRIMARY       | PRIMARY | 4       | sistema.tb2.tb1_id      |    1 | NULL        |
+----+-------------+-------+--------+---------------+---------+---------+-------------------------+------+-------------+

Comment: Preciso das linhas da `tb1`, mesmo que não existam linhas na `tb2`
Comment: É MySQL? SQL Server? Não se esquece de [edit] as tags da sua pergunta.
Comment: MySQL. Já atualizei, obrigado.
Comment: Só te interessam as linhas da `tb2` onde há correspondência de ID com a `tb1`? Nesse caso você poderia usar um `INNER JOIN` em vez do `LEFT`.
Comment: @RaulBaldnerJunior como fica o explain de somente `SELECT COALESCE(tb2.numero_novo, tb1.numero_original) as numero
FROM
tb1
LEFT JOIN tb2 ON tb2.id = tb1.id
WHERE
tb1.numero_original = `
Comment: @gmsantos editei a pergunta para adicionar esta informação
Answer: Olá, Baldner
Verifique se isso lhe ajuda:
/* Adquirindo os registros da tb1 que possuem registros na tb2, ou seja, os 5% */
SELECT tb2.numero_novo AS numero
  FROM tb2
 INNER JOIN tb1 ON tb1.id = tb2.id
 WHERE tb2.numero_novo = <PARAM>
/* Realizando união com os registros da tb1 que NÃO possuem registros na tb2, ou seja, os 95% restantes */
 UNION
SELECT tb1.numero_original AS numero
  FROM tb1
 WHERE tb1.numero_original = <PARAM>
   AND NOT EXISTS(SELECT TOP 1 1 FROM tb2 WHERE tb2.id = tb1.id)

A minha ideia foi de trabalhar com os 5% que possuem registros na tb2 utilizando o INNER JOIN que é  mais rápido que LEFT JOIN.
Os outros 95% registros da tb1 que não possuem registros na tb2 basta utilizar o NOT EXISTS ao invez do LEFT JOIN.
A União teria como papel do OR melhorado.
Nos avise se isso melhorou ou piorou.
Espero ter ajudado :)
Comment: Obrigado pela resposta!
Infelizmente, não pretendia usar UNION pois preciso utilizar outros parâmetros de pesquisa na tb1. Eu precisaria duplicar os parâmetros nos 2 SELECTS ou então colocar este UNION como subquery e filtrar uma vez só depois (o que acho que seria muito ruim).
Comment: Eu não sei quais outros parâmetros você está precisando mas, dependendo do caso, vale a pena duplicar nas duas consultas. Por que você não tira a dúvida realizando um teste de performance ?


Javascript PHP retornos

Question: Esse aqui e o HTML

          <textarea  cols="150" rows="7" class="input-xxlarge" type="text" id="login" name="login" placeholder="Sua lista"></textarea>

          <button class="btn btn-mini btn btn-success" id="submitValidacao"  type="submit">Iniciar teste</button>
          <button class="btn btn-mini btn btn-danger" type="button">Cancelar e limpar</button>

Retorno

Emails Validos

no textarea eu coloco uma lista grande de email:nome
ficando assim.
email:nome
email2:nome2
email3:nome3

assim por diante
e envio o post pro javascript

agora no  $('.testEmail').html("Testando agora = "val); mostra apenas o Testando agora = email:nome que e o primeiro valor da lista que foi adicionada no textarea, e quando finaliza ação ele chama o  $('.testEmail').html("Teste finalizado com sucesso!");
substituindo o Testando agora = .
o problema e que não consigo passa os valores certinho no Testando agora = , ficando email:nome e quando termina ele já vim o email2:nome2 , pois o php já retorna 1 por 1 ..
Comment: poderia me mostrar o link ?
Comment: Creio que o teu problema aqui é o mesmo que na outra pergunta que marquei como duplicada. Ou seja, tens de ter esse `if (counter === loginsSplitedCount){` dentro de `function(retorna){` porque o ajax é assincrono. http://pt.stackoverflow.com/questions/60852/return-em-each-getjson-jquery
Comment: Isso eu já fiz e não funciono e essa pergunta ai não responde a minha . mesmo assim obrigado
Comment: Acho que não compreendeste a natureza assincrona ainda. Reabri para eu ou otros te explicarem melhor. Mas o problema é de assincronia como na outra pergunta.
Comment: Irei tenta aqui Sergio, irei ler aqui.
Comment: O que quero na verdade e apenas enviar o post e receber as informação que o php retorna :(  se eu carregar uma lista grande ele conta qual ta testando  acho que estou errando em algum lugar .
Comment: Testa isto: http://jsfiddle.net/z1qtj621/
Comment: Do meu ponto de vista o motivo é que por padrao o javascript é assíncrono, o que eu sugiro é alterar para síncrono, assim ele vai executar o `ajax` e so apos terminar que executara o `if` logo abaixo.
Comment: Segue link com resposta sobre síncrono. http://stackoverflow.com/questions/5821380/how-to-make-a-jquery-post-request-synchronous
Answer: O que está a acontecer é que esse ciclo $.each está a correr e terminar sozinho. A cada iteração tens counter++, ele vai somando e chega ao fim. Depois dele vai ser corrido o que o servidor retorna.
Depois?? sim, depois.
O AJAX é assíncrono, e por isso mesmo que ele esteja dentro do seu $.each ele vai chamar a função callback com o resultado que o servidor retorna quando o $.each já tiver acabado certamente.
Como posso controlar o fluxo da aplicação?
Tens de ter como ponto de partida a callback do ajax, pois é aí que o código vai ficar à espera e vai ser chamado quando o servidor responder.
Sugestão:
    $.each(loginsSplited, function (i, val) {
        $('.testEmail').html("Testando agora = " + val);
        $.post('pages/engines/email.php', {
            login: val
        }, function (retorna) {
            $('.resultEmail').show();
            $('.resultEmail').append(retorna);
            counter++;
            if (counter === loginsSplitedCount) {
                $('.returnEmail').html("
Testando " + loginsSplitedCount + " Login...
Pronto!
");
                $('.testEmail').html("Teste finalizado com sucesso!");
            };
        });
    });

Comment: @Wender sugestão: marca esta pergunta como aceite e coloca outra nova pergunta com o problema que ainda falta. Eu confesso que ainda não percebi o que queres fazer. Senão ajudava a encontrar a solução para esse outro problema.
Comment: @Wender a ver se percebi bem. Como está funciona mas querias que mostrasse um a um apagando o anterior. É isso?
Comment: isso mesmo que preciso
Comment: @Wender mas o AJAX é mto rápido.Você nem vai ver os valores a mudar, vai parecer que ele só mostra o ultimo. Estás consciente disso? Se queres assim muda `+ loginsSplitedCount +` para `+ val +` no código que dei na resposta.
Comment: e não existe a possibilidade de colocar um setInterval ?
Comment: @Wender sim, um `setTimeout` assim: http://jsfiddle.net/jsdyjc9u/
Comment: Testando 97 Login...
Aguarde...
Testando agora = email@example.com:1961
não muda :/ e no final Testando 97 Login...
Pronto!
Teste finalizado com sucesso! , Muito Obrigado por te me ajudado , mais irei deixa para la , essa função e muito complicado ...

Javascript PHP retornos


If $|G|\geq 4$ is a planar graph then there are at least 4 vertices with degree at most 5?

Question: The hint given is to transform this into a triangulation and what can you say about the value of $\delta (G')?$.
So add edges to G until G' is a triangulation. Then $3|G'|-6=e(G') \Rightarrow e(G')\geq 6$
What can I say about $\delta (G')?$
I'm lost
Answer: This approach is similar to Willard's, but I'm pretty certain that your formula is fine (you can check both of them against some examples).
Let $n=|G|$. Then $e(G')=3n-6$.
If $G'$ is a triangulation with at least four vertices then $\delta(G') \geq 3$.
You'll probably want to show that bit rigorously, but to convince you that it's plausible:
Every vertex $v$ is in some (potentially unbounded) face of $G'-v$. That face must have at least three vertices, and $v$ must be adjacent to them in $G'$. (It's also a corollary of the $3$-connectedness of maximal planar graphs if you happen to know that fact.)
Rest of the answer:

$6n-12=2e(G')=\sum\deg(v) \geq k\delta(G') + 6(n-k) \geq 3k + 6(n-k)$

(I've split the sum up into the $k$ vertices of degree $\leq 5$ and the $n-k$ remaining vertices.)

Rearranging we get $k \geq 4$.


USB microphones for multi-instrument recording

Question: I have an awesome Korg MKii 1600 recording device with a fairly cheap (I must admit) microphone.
I was recently thinking about getting a USB mic because it seems so easy to record "whenever". It can be cumbersome to attach all the cables then transfer the song to my pc etc.
I play a lot of instruments (sax, guitar, flute) and I also use it for voice acting.
Are USB microphones (for instance condenser mics like Yeti blue) suitable for this or do you recommend a normal condenser mic and possibly an external soundcard (more hassle though).
Answer: It really depends on what type of quality you're looking for. I would highly suggest an audio interface with a good condenser mic, and possibly a pair of cardoid mics.
The convenience of a USB mic is good, but audio interfaces are quite small and are not a hassle at all. It's better to record with the audio interface, because you can potentially record at a higher bit depth and get better quality. The other upside to using an audio interface, is that if you get one that supports multiple mics, you can connect more than one mic and capture your instruments from different points simultaneously, which usually helps to create a richer sound, especially for an instrument like a guitar.
You should look into the focusrite scarlett audio interface series. They have different models that come with a different number of inputs. The focusrite scarlett audio interfaces are affordable and produce excellent results. They're USB powered. As far as condenser mics, good ones will run up high in cost pretty quickly. However, a decent condenser mic paired with an audio interface can still produce some impressive results.
Answer: While is definitely possible to use multiple USB microphones for recording multiple tracks at the same time, this setup is software dependent and may not be very trivial. Here there are some talks relevant to Audacity, for Garage Band you need to create a "composite device" as well.
However may be attractive, as then you do not need a mixer of any kind as long as you have enough USB ports on your machine, and with USB hub probably all mics of symphonic orchestra can be connected no problem.
To lower the risks, I would suggest to get one USB microphone (can be low quality/cheap) and try to combine its input with an audio interface you already have. If this works with your software and hardware, multiple USB microphones should work as well. You will also check if all user interfaces are good enough to work.
Then you can buy first one, then others high end microphones you actually want to use.


Search index as custom view for taxonomy term with hierarchy. Showing all children results in term parent in taxonomy menu

Question: Ok so title is pretty epic, but it goes like this:
Key elements: views, taxonomy_menu, taxonomy, search api, facets.
I created vocabulary "Products" (Drupal Commerce but I don't think it's important), and there term - "Chemistry" - which should be a root of tree of other more specific terms. I added some products. Next I enabled Taxonomy Menu and created a menu, so far so good, but I wanted to use search api, so I created a view of my search index with path:

/taxonomy/term/%

That way I wanted to override view of my taxonomy, and be able to have facets in it. And it perfectly displays indexed products of terms that have them, but it fails to display all products of CHILDREN terms. So if I have my term "Chemistry" - after clicking it - I would like to be able to see every product of its children terms. I cannot see how can I do this with current approach, as it seems that I doesn't have contextual filters for that (as my view is displaying search index).
What can I do?
Comment: Did you try the taxonomy term filter *with depth* ?
Comment: There is no such filter if you created view of search index - there is a problem. I'm open for workarounds also.
Comment: Perhaps [taxonomy entity index](http://drupal.org/project/taxonomy_entity_index) would provide that filter for you.
Comment: I was trying to do this exact same thing last week. I settled for adding the items to the parent terms aswell. It's not a true solution but it works, I guess this could also be done automatically with node save and update hooks.
Comment: @James You might want to check out the module I mentioned above - it's only beta, but it's a true solution :)
Answer: If I'm understanding correctly what you're asking, here are some tips.
Under your defined search index, go to Fields. If you have "Products" taxonomy defined, uncheck the taxonomy term, then go to the bottom and open "Add Related Fields" and add "Products", then save changes. When it reloads, you'll now have more taxonomy options. Check "Products >> All parent terms". You should now have additional facets for parent/child terms.
Use in conjunction with Facet API Pretty Paths for even more powerful usage. Take a look at one of my other response about how to use that.
Answer: Using the following in a custom module will automatically add the parent terms to the node when it is saved.
/*
 * Implements hook_node_presave().
 */
function MYMODULE_node_presave($node) {
  // Get the taxonomy terms.
  if ($terms = field_get_items('node', $node, 'MYVOCABULARY')) {
    $tids = Array();
    foreach ($terms as $term) {
      // Add the term to a list of tids.
      $tids[$term['tid']]['tid'] = $term['tid'];
      // Get the parents of the taxonomy term.
      $parents = taxonomy_get_parents($term['tid']);
      foreach ($parents as $parent) {
        // Add the parents to a list of tids.
        $tids[$parent->tid]['tid'] = $parent->tid;
      }
    }
    // Add the list of tids to the node.
    $node->MYVOCABULARY['und'] = $tids;
  }
}

Answer: The KyleTaylored direction was right.
But I only have to in admin/config/search/search_api/index/product_display/workflow (product_display is my machine name of Product display index DB) check checkbox Index hierarchy. Reindex content admin/config/search/search_api/index/product_display/status.
Thats all.


PHP Session not working, cannot bring value over the next page

Question: need help about session, not sure whats going wrong.
Page 1
    <?php session_start()?>

          <?php
            $_SESSION['name'] = 'John';
            Print_r ($_SESSION);
          ?>

Page 2
    <?php session_start()?>

          <?php
           Print_r ($_SESSION);
          ?>

Page 1 Result
Array ( [name] => John )
Page 2 Result
Array ( )
I did have session_start(); at both pages

Tried IE and Firefox but didnt work

Advices please and thanks :)
Comment: Post your code _with_ `session_start()` in place
Comment: Ensure you have no output (HTML code or any of echo, print_r, etc) before `session_start()`.
Comment: Are the two pages on the same subdomain?
Comment: How does the page flow from Page 1 to Page 2?
Comment: try ``
Comment: @bažmegakapa What do you meant by subdomain, sorry just started doing php recently.
Comment: i suppose this is mistyped?   to
Comment: @user1436885 For example bazmegakapa.com and www.bazmegakapa.com (or even something.bazmegakapa.com). They are not the same.
Comment: @YouQi both pages have Array ( [BCSI-AC-8e905d6ebcb597fe] => 1ED4012A00000004uUrW0SGZ8RScBwfEhZJVJqBlK/lQAAAABAAAAN SEgAgHAAACAAAACXBAAA= ) . what does it means? enlighten me please
Comment: @bažmegakapa http://homes.soi.rp.edu.sg/102223/fypbilly/test1.php to http://homes.soi.rp.edu.sg/102223/fypbilly/test2.php
Answer: As stated by lanzz, you need either to call session_start() in both pages or set the session.auto_start to 1 on yout php.ini.
AFTER EDIT
You seem to have some spaces before the php opening tag (<?php). It must be the first thing to be evaluated. If it isn't, it can't send the headers with the session data, and thus they do not work. It should emit a warning, so you probably have them disabled. To fix it, write the code as follows.
<?php session_start()?>

      <?php
        $_SESSION['name'] = 'John';
        Print_r ($_SESSION);
      ?>

If they still don't work, you'll probably have the file as UTF-8 With BOM, you should disable the BOM. How to do it depends on the editor.
Comment: Sorry, but quoting from the question: `I did have session_start(); at both pages `.
Comment: Still, you can try with `session.auto_start` to check if it's something related with the file or if it has to do with anything else.
Answer: You have to call session_start() on top of all the page
Comment: I just edited and had put session_start() before  on body pages
Answer:
try <?php print_r($_COOKIE);?>. and make sure you have PHPSESSID cookie.
<?php echo phpinfo(); ?> and make sure session.save_path is writable by your apache user.

UPDATE:
it seems obvious your browser did not pass in the required cookies. Can you double confirm your phpinfo whether session.name is PHPSESSID?
To check whether the directory is writable, simply run a php file with script below:
<?php
    $fp = fopen('D:\xampp\tmp\test.txt', 'w');
    fwrite($fp, 'test');
    fclose($fp);
?>

Comment: both pages have Array ( [BCSI-AC-8e905d6ebcb597fe] => 1ED4012A00000004uUrW0SGZ8RScBwfEhZJVJqBlK/lQAAAABAAAAN SEgAgHAAACAAAACXBAAA= ) for print_r($_COOKIE);
Comment: Hi, my session.save_path is at D:\xampp\tmp. How do I know whether is it writable by my apache user. Sorry for the noob quesiton
Comment: Yes it is PHPSESSID, session.name PHPSESSID PHPSESSID. Is it because Im running not on a local host? Meaning like im using my school server. Because before using my school server, my session is working but now suddenly cant work. I had tried changing back to localhost and run but it also couldnt work.  About the script, I run but nothing came up, just a blank screen. Dang this problem hindering the process of my project. :/


Fight against the Hydra - Graph Theory

Question: The following problem is supposed to be a nice application of the basic knowledge of graph theory. I consider it however as difficult and I would be happy if someone could help me find a solution.
Let's consider the Hydra (creature of the greek mythology) :

We can compare it to a tree quite easily: $T = (V,E)$

-The tree has root $r \in V$. The root corresponds to its torso and the leaves of the tree correspond to its heads.
-$p(v)$ gives us the parent node of a node $v \in V − \{r\}$ in the tree.
-If Hercules cuts a head $\ell \in V$ (so that $p(\ell) \neq r$) of the Hydra, it will grow back according to the following rule:
let $T_\ell$ be the subtree with the root $p(\ell)$ after the leaf $\ell$ has been removed (cut in our case), we just add two copies of $T_\ell$ to $p(p(\ell))$.
-The Hydra is considered as defeated when there is just the torso left.
Now the question:

Is it possible for Hercules to kill EACH Hydra?
Comment: Possibly related: http://math.andrej.com/2008/02/02/the-hydra-game/
Comment: How good are you at transfinite arithmetic?
Comment: I guess we're just supposed to use the basics of graph theory, I'm a first semester student in computer science so...
Answer: The nice thing about the hydra game is that Hercules cannot lose. Whatever he does, as long as he keeps cutting the heads, he will kill the hydra (but perhaps after a loooong time). The proof is not complex, but requires a bit more sophisticated machinery than basic graph theory (it is nicely summed up in the article pointed out by @anorton, i.e. here, if you are wondering what the mysterious symbol $\omega$ means, check out the ordinal numbers at Wikipedia).
However, you want to show only that Hercules can kill any hydra, not that any strategy will kill any hydra. The former is much weaker statement and there is a basic proof of that.
Hints:

The height of the hydra tree cannot increase.
Make Hercules cut off any head that is as far from the root as possible.
Hercules can decrease the height of the hydra tree.
Use induction on the tree height to show that for any hydra Hercules can kill it.

If the third step is too hard, find a more detailed explanation below:

 Assume the root is at the top (as in the diagram you supplied) and consider the lowest level of the tree. Group the leaves by the parent, e.g. tree $\Big(\big({\bullet}{\bullet}\big)\big(({\bullet}{\bullet}{\bullet})({\bullet}{\bullet})\big)\Big)$ would give you $({\bullet}{\bullet}{\bullet})({\bullet}{\bullet})$ or $(3,2)$ for short (the first two leaves were not taken into account because they do not belong to the lowest level). Now assign a number $4^3 + 4^2$ to it, or in general $4^{a_1} + 4^{a_2} + 4^{a_3}+\ldots$ for $(a_1, a_2, a_3, \ldots)$. Observe that when Hercules cuts any of the heads, the exponent decreases and we get two new copies. To give an example, if Hercules had cut a head in the first group, we get \begin{align}3\cdot4^{a_1-1}+4^{a_2} + 4^{a_3} + \ldots < 4^{a_1}+4^{a_2} + 4^{a_3} + \ldots \end{align} which means that the natural number we assigned decreases. It cannot decrease forever (it is a natural number), so finally Hercules will manage to cut all the heads of the bottom-most level.

I hope this helps $\ddot\smile$

Fight against the Hydra - Graph Theory


Como diminuir tamanho de array de bytes que representa uma imagem

Question: Tenho um array de bytes na base64 que está numa String em C#. Ele representa uma imagem. O tamanho da String está variando entre 50 e 80 mil caracteres. Queria saber se tem como diminuir esse tamanho , comprimindo e tirando a qualidade da imagem.
Método HttpPost que recebe o array de bytes :
[HttpPost]
    public void Post([FromBody]CreateViewModel model)
    {
        if (String.IsNullOrEmpty(model.PhotoFile))
        {
            Console.WriteLine("Foto não foi selecionada");
            throw new Exception("Foto não foi selecionada");
        }

        _professionalApp.CreateProfessional(model);
    }

Gostaria de ter um método que diminuisse o tamanho de PhotoFile - atributo String de CreateViewModel.
Comment: Não ajudou muita coisa. A melhor coisa é não tratar como Base64 que desperdiça muito. É isto que quer?
Comment: Tem algumas técnicas para fazer isto, mas ficaria muito amplo para responder. Dependendo do que deseja, não é necessário fazer isto. De qualquer forma precisaria de bem mais informações sobre a situação.
Comment: Eu adoraria dar uma resposta completa agora, mas estou tô exausto demais do trabalho pra isso agora, então vou só deixar um link aqui no qual a Microsoft documenta como compactar coisas: https://msdn.microsoft.com/pt-br/library/ms404280(v=vs.110).aspx se alguém quiser elaborar isso em uma resposta completa terá meu voto.
Comment: base 64 nesse caso só serve pra gastar mais espaço ainda.
Comment: Coloquei um exemplo acima.
Comment: Eu como eu poderia salvar a imagem ? O que quero é salvar sem gastar muito espaço, pois como disse a string de bytes tem entre 50 e 80 mil caracteres.
Comment: Então como eu poderia guardar a imagem ?
Comment: Porque você não salva a imagem como binário mesmo ao invés de salvar como Base64 ? Utilizando  System.Drawing.* carregue a imagem, converta para JPEG e diminua ao máximo a qualidade dela, e então salve o arquivo binário (imagem.jpg), se isso não for suficiente para armazenar, utilize algum algoritmo de compressão  como: ZIP/RAR/GZIP
Answer: Eu tenho situações em que o avatar de um usuário é guardado no banco em alta qualidade, mas as vezes para renderizar um thumbnail bem pequeno (e como não tenho uma versão reduzida da imagem salva em nenhum lugar) eu devolvo essa mesma imagem, porém com um tamanho reduzido (para não gastar banda desnecessário do servidor e do client). Para isso, utilizo esse método de extensão (serve apenas para imagens):
public static byte[] ReduzTamanhoDaImagem(this byte[] imageData, int width, int height, Drawing.Imaging.ImageFormat type)
{
    if (imageData == null)
        return null;
    if (imageData.Length == 0)
        return imageData;
    using (MemoryStream myMemStream = new MemoryStream(imageData))
    {
        Drawing.Image fullsizeImage = Drawing.Image.FromStream(myMemStream);
        if (width <= 0 || width > fullsizeImage.Width)
            width = fullsizeImage.Width;
        if (height <= 0 || height > fullsizeImage.Height)
            height = fullsizeImage.Height;
        Drawing.Image newImage = fullsizeImage.GetThumbnailImage(width, height, null, IntPtr.Zero);
        using (MemoryStream myResult = new MemoryStream())
        {
            newImage.Save(myResult, type);
            return myResult.ToArray();
        }
    }
}

Então você poderia utilizar dessa forma:
model.PhotoFile = model.PhotoFile.ReduzTamanhoDaImagem(50, 30, Drawing.Imaging.ImageFormat.Png);

...o que iria reduzir a resolução da imagem para 50x30 (nesse método em particular, se a imagem já tem a largura/altura menor do que o passado por parâmetro, ele manterá o tamanho original).
Não sou expert em manipulação de imagens, mas entendo que o fato de reduzir a resolução não causa perda da qualidade da imagem, no entanto ao tentar redimensioná-la ao tamanho original (que seria maior), aí sim pode ocorrer a perda da qualidade.


Javascript código de redirecionamento URL

Question: eu preciso desenvolver um código em javascript que não está funcionando.
Minha necessidade é a seguinte:
Quando o usuário acessar determinada página, eu gostaria de complementar a URL com alguns parâmetros, exemplo:
Se o dominio for xxx.com.br/index.php, redirecione ele para xxx.com.br/index.php&variavel=1
Lembrando que ele pode entrar também em um subdiretorio, exemplo:
xxx.com.br/pasta/index.php, deve adicionar também xxx.com.br/pasta/index.php&variavel=1
Basicamente, se o dominio coicidir, ele adiciona uma variavel no final.
Detalhe importante, fiz isso e o mesmo ficou em loop, porque ao redirecionar ele identifica o dominio da mesma maneira, portanto, se o dominio bater, deve ter outra verificação pra ver se já não existe o parametro na URL.
Comment: Tentou `document.URL` ??
Answer: Adicionar somente &variavel=1 ao URL parece-me errado, nesse caso devia usar a "query" string que começa com ?. Ou seja usando location.search.
Assim pode ter o seguinte script em todas as páginas que precisar dessa funcionalidade:
location.search = location.search || '?variavel=1';

Combinando isto com o location.hostname pode verificar se o dominio é correto pois o location.hostname dá exatamente essa informação.
Assim o seu código completo poderia ser:
if (location.hostname == 'xxx.com.br') location.search = location.search || '?variavel=1';

Comment: eu não sabia do `location.search`, obrigado!
Answer: Segue uma função que já testa se o parâmetro existe no URL original, e caso não exista, acrescenta.
Esta função está preparada para os casos em que já existem outros valores especificados, e os mantém como estavam:
function setDefaultParameter( url, parameter, value ) {
  if ( ("&"+url.split("?")[1]+"=").indexOf("&"+parameter+"=") < 0 ) {
    url += (url.split("?")[1]?'&':'?') + parameter + '=' + value;
  }
  return url;
}

Basta chamar desta forma para setar todos os parâmetros que quiser:
novoUrl = setDefaultParameter( window.location.href, 'modelo', '1'    );
novoUrl = setDefaultParameter( novoUrl             , 'ano'   , '2014' );

// Redireciona só se mudou algo:
if ( novoUrl != window.location.href ) {
  window.location = novoUrl ;
}

Demonstração:

function setDefaultParameter( url, parameter, value ) {
  if ( ("&"+url.split("?")[1]+"=").indexOf("&"+parameter+"=") < 0 ) {
    url += (url.split("?")[1]?'&':'?') + parameter + '=' + value;
  }
  return url;
}

// Sem nenhum parametro
var url = 'http://example.com';
url = setDefaultParameter( url, 'modelo', '1' );
url = setDefaultParameter( url, 'ano', '2014' );
document.body.innerHTML += url + '
';

// com parametro já existente
url = 'http://example.com?cor=azul';
url = setDefaultParameter( url, 'modelo', '1' );
url = setDefaultParameter( url, 'ano', '2014' );
document.body.innerHTML += url + '
';

// com um dos parâmetros já especificado sendo preservado
url = 'http://example.com?ano=1998';
url = setDefaultParameter( url, 'modelo', '1' );
url = setDefaultParameter( url, 'ano', '2014' );
document.body.innerHTML += url + '
';
Comment: @FabioVieira Se achar necessário, posto uma variante que sobreescreve o parâmetro, mesmo se ele já existir.
Answer: Dessa forma você consegue pegar toda a URL e fazer as verificações nescessárias:
switch(document.URL){
    case 'http://www.meudominio.com/index.html':
        location.href='/index.html?parametros'
        break;
    case 'http://www.meudominio.com/outra.html':
        location.href='/outra.html?parametros'
        break;
  }
}
alert(document.URL); //apenas para ver o que tem em document.URL

Comment: Mas onde está validando o dominio?
Comment: Basta colocar no `case 'minhaURL'`... valida toda a URL de uma vez
Answer: Basta verificar e validar o host e a url(href) do usuário, de forma que deve adicionar se dominio for igual a x porém não adicionar se já houver:
function validaDominio(dominioX){
  var host         = document.location.host;
  var addr         = document.location.href;
  var dominioEnd   = host.indexOf('.');
  var dominio      = host.substring(0, dominioEnd);

  if (dominio == dominioX && (addr.indexOf('&variavel') == -1))
    document.location.href = document.location.href + '&variavel=1';
}

E aí basta adicionar o parâmetro onload=validaDominio('xxx') no  das páginas que você quer verificar, ficando:

Comment: `dominio == dominio` ? Algo errado não? rsrsr
Comment: agora está certo, obrigado @AntonyAlkmim


CQRS Component Roles and Responsibilities with a REST API

Question: There are a lot of opinions out there in terms of CQRS with DDD and what makes up each component. I haven't began to look into Event Sourcing yet, so the list below doesn't include anything related to that. Although insight into ES would be interesting.
So far I have the following components with associated responsibilities (see below). I have inlined some questions in the points below.
REST Endpoints / Application

Receive request from user / ui / etc
Construct and dispatch relevant Command
If the command requires values from other bounded contexts, then perform the relevant Finder calls required to instantiate the command correctly (e.g. Order requires User ID)
In the case of a GET: the relevant Finder is called
Finders sit at this level of the application. The Bounded Contexts write side (command handler, aggregate, factory, domain service, etc) should not be calling Finders. This will maintain encapsulation and by passing into the commands only the required data (instead of full DTOs) it becomes a modest Anti-Corruption layer.
For example:

AggregateId orderId = AggregateId.get();
AggregateId userId = finder.findUserAggregateIdByEmail(email);
dispatcher.fire( new CreateOrderCommand( orderId, userId, orderItems ) );
Command

Changes to the domain are made by dispatching commands
Commands are immutable and contain the data necessary for a Bounded Context to alter it's state or throw an exception
The command input can be validated on object creation in order to avoid invalid commands being sent
For example: new CreateOrderCommand( orderId, userId, orderItems );

Command Handler

The handler can either successfully apply the command or raise an exception
There can only be one command handler for each command
The handler will load or create the Aggregate Root (Repository or Aggregate Factory)
The handler will apply the command to the aggregate root
The handler deals with the repository
Should not fire commands (in or out of it's bounded context)
Should the command handler dispatch Events? For example after successfully saving to the Database? Or is this solely the Aggregate's responsibiity?

Aggregate Factory

Encapsulates the logic required to initialise an Aggregate Root correctly
The factory can access the repository
Should the factory access Domain Services?
For example: factory.createOrder( orderId, userId, orderItems );

Aggregate Root / Aggregates

Contains the domain logic, state and behaviour
Responsible for dispatching Events
Aggregate Root encapsulates access to Aggregates
Aggregate Root should have an ID that uniquely identifies it
Should not interact with external services (other than an event publisher)
For example: order.cancel();

Domain Service

This contains what doesn't quite fit in an Aggregate Root
What components can the domain service interact with?
Should the domain service fire commands / events?
For example: Not sure what to use here, the first point above is vague at best. Most behaviour sits nicely in the Aggregate or can be achieved through Sagas / Events / Commands. What would be a valid example here?

Repository

Takes care of loading / saving / updating / etc our Aggregates
For example: repo.load(orderId);

Event

Represents something that took place in an aggregate (or command handler, etc if they can also fire events)
Events are immutable
Other bounded contexts in the system can use an event to make decisions
For example: new OrderCancelledEvent( orderId );

Event Handler

Reacts to an event that took place
There can be multiple event handlers for a single event in the same or different bounded contexts
Can interact with Infrastructure services: OrderCancelled => OrderCancelledHandler => EmailService.sendEmail()
Can fire new commands
Can talk to Finders
As the event handler fires commands, talks to Finders and interacts with the infrastructure, it is similar in nature to the Saga (or the REST Enpoint behaviour). Except it is the reaction to a single event rather than a chain / set of events.

Saga

Maintains a business process which sits across the same or multiple bounded contexts (co-ordinates)
Receives Events
Maintains the state of a chain / set of events
Normally the state is persisted
Timeouts can be set to check / alter state (can have notion of time)
States can have side effects, such as: firing commands, talking to Finders, interacting with the infrastructure services (e.g. email)
For example:
Wait for OrderShipped and OrderReceived events => fire CancelOrderCommand
Wait for OrderCancelled => fire order cancelled email

Finder

Used to retrieve a readmodel of the context(s)
Generally returns Data Transfer Object (DTO) type objects
Finder should not be found in the write side of our application (less coupling)
Single (read+write) Normalized Database Model: the Finder can call other Finders (across contexts) to satisfy nested objects
Read Specific De-normalized Database Model: the Finder will get the data all in one Database call
For example: finder.findOrdersOnDate( date );

Infrastructure Services

Deals with infrastructure: db access, send emails, message queues, etc

Question
Is this an accurate summary of the components vs. responsibilities?
What's missing and what should be moved around?
I can update the list with relevant answers.
Comment: ["Implementing Domain-Driven Design"](https://vaughnvernon.co/?page_id=168) by Vaughn Vernon provides technical details that cover each of these components. I'd recommend it as a very useful resource in addition to Eric Evans' Domain-Driven Design.
Comment: Coincidentally I found an article by Vaughn Vernon last night. Very interesting! I'll be buying the book. Anything you would add to the list based on the book?
Answer: Like you said, there are many opinions out there, and you need to filter them as most of the time people are giving opinions without any experience on the matter. CQRS is a big topic so I don't think that without prior experience you should jump into DDD and ES altogether. Services should be well contained and with well defined boundaries and if you follow these principle you'll be able to have different implementations in your domain, so start with just CQRS now and add DDD/ES to the following services once you have mastered CQRS.
I would advice you so start building the CQRS part of your architecture, a gateway for the commands and one for the queries because that is common and just on that there are so many decisions to be made:

Rest API
Message contracts/validation
Read models
...

and start implementing your service in a more traditional way without DDD, just using the repository pattern. When you start feeling confident then maybe you can jump into DDD in terms of aggregates and later on to ES. You can always change the initial services at a later stage.
My advice would be not to try to do it all at once, because you will fail; I have seen it happening many times before.

For example: Wait for OrderShipped and OrderReceived events => fire CancelOrderCommand Wait for OrderCancelled => fire order cancelled email

Sagas should not publish events (saga pattern), sagas aggregate events and submit commands. The fact that frameworks like NServiceBus allow sagas to publish events does not help, so be aware.

Single (read+write) Normalized Database Model: the Finder can call other Finders (across contexts) to satisfy nested objects

What other contexts you want to have in your read models?

Infrastructure Services

Deals with infrastructure: db access, send emails, message queues, etc

Not sure what you mean by this, but it sure does not look right. Message queue or database service??
Comment: I got the idead that you were saying that sagas publish the events, s my bad. Read models should have all the information necessary for a given screen or screen section as to avoid multiple round trip calls, and yes that should be the way to go, but that is independent on what you use within the services, as long as you publish the right events and aggregate them into a properly defined view. I always use guids when referencing data that belong to diferent services, and you can use that with our without proper DDD agregates, you are on the safe side if for every entity you have a private id...
Comment: and a public id. As for the queue, when building a cqrs system, which most of the times has a asyn backend, commands are always sync, until the command is accepted (think of xml xcheme), and if it is valid the gateway (command part of the crqs pattern) places the command in the queue and usually returns a 202 http code, either way even if you end up working on top of something like ASP.net WEB API, never return bussiness logic from a commands handler... dont know if this helps.
Comment: A system does not have to have queues to be distributed, this is a very common misunderstanding. You do need queues for asyn systems not to make them distributed, in fairness you can have distributed systems without using any queues at all.
Comment: Hi Marco, thanks for the reply. I agree with breaking up the implementation into phases. I've already redesigned the system to be more DDD oriented. However, the interaction between contexts was always done with direct call to another context's Facade. This obviously links everything tightly together. With the CQRS approach, decoupling becomes much easier. The main thing is how you now coordinate the communication between contexts: i.e. using Events and Sagas (where necessary).
Comment: Let me answer the three extracts you pulled out of the list: 1) The Saga does not publish any events, it waits for events and then fires commands or interacts with the infrastructure.
Comment: 2) Normalized DB: for example, I might have a screen which has a user and information about interactions the user has had with the system. Rather than make two calls and piece them together, I would expect to call a single Finder which will return the data I need for that screen. This is easy with a denormalized model, but for normalized the data may be spread in different contexts it implies I need to use another Finder (if it were different aggregates in the same context, then I could simply use the relevant repository).
Comment: 3) Infrastructure services: primarily these are interfaces to external services. So if i want to queue something I could do Queue.add(something) where Queue is the service interface. Does that make sense?
Comment: Yes, definetely, each Aggregate Root has a uniquely identifying ID. I've got an AggregateId object I use for that. The underlying implementation of the ID is the BSON ObjectId, but GUID will produce the same effects.
Comment: Agree with the process of incoming commands. At the moment the system isn't distributed, so no queueing, but once it is, that will be the process.