Independence of increasing limits

Question:
If $\{E_n\}_{n\ge1}$, and $\{F_n\}_{n\ge1}$ are increasing and independent for each $n$, show that their limits are independent.

Here is my attempt:
Note that $\{E_n \cap F_n\}$ is also increasing. Then,
\begin{align}
    P(E \cap F) &=P\left(  \lim_{n \to \infty}\{ E_n\} \cap \lim_{n \to \infty}\{ F_n\}  \right)\\
     &=P\left(  \bigcup_{n=1}^{\infty} \{ E_n \}\cap  \bigcup_{n=1}^{\infty} \{ F_n \} \right)\\
     &= P\left(  \bigcup_{n=1}^{\infty} \{ E_n \cap F_n\} \right)        \\
     &= P(\lim_{n \to\infty} \{E_n \cap F_n \}) \\
     &=\lim_{n\to\infty}  P(E_n \cap F_n )\\
     &=\lim_{n\to\infty}P(E_n)P(F_n)\\
     &=P(E)P(F)  \hspace{5mm} \blacksquare
\end{align}
Answer: What you did is essentially correct. Here are some remarks.

It is not necessary to write the $\lim$ of a sequence of sets (unless it has been properly defined with the equality of $\limsup$ and $\liminf$ of the corresponding sequence). All we actually need is that if $\left(A_n\right)_{n\geqslant 1}$ is a non-decreasing sequence of sets, then $\lim_{n\to +\infty}\mathbb P\left(A_n\right)=\mathbb P\left(\bigcup_{j=1}^{+\infty}A_j\right)$.
The place where the assumption that the sequences $\left(E_n\right)_{n\geqslant 1}$ and $\left(F_n\right)_{n\geqslant 1}$ are non-decreasing is used should appear more clearly. It is used to justify the equality
$$
  \left( \bigcup_{j=1}^{+\infty}E_j\right)\cap \left( \bigcup_{k=1}^{+\infty}F_k\right)=  \bigcup_{n=1}^{+\infty}\left(E_n\cap F_n\right).
 $$
The last equality is not true in general (take $E_{2i}=\emptyset=F_{2i+1}$, $E_{2i+1}=F_{2i}=\Omega$ for example.

Independence of increasing limits


Evaluate $\int_0^{\pi/2} \frac{1+2\cos x}{(2+\cos x)^2}$

Question: I don't know how to begin solving. Can I get a hint?
My failed attempt
Let $t =\tan (x/2)$
Then $$I =2 \int_0^1 \frac{(3-t^2)}{(3+t^2)^2 }$$
which I am not able to solve
Comment: https://en.wikipedia.org/wiki/Weierstrass_substitution
Comment: @RobertZ yes, I had already tried that, lead me nowhere
Comment: Can you show us what you have tried?
Comment: @TobyMak done!!
Comment: Actually, it should be $\int_0^1\frac{2(3-t^2)}{(3+t^2)^2}dt$. You've forgotten a factor of $\frac{dx}{dt}=\frac{2}{1+t^2}$.
Comment: @J.G. ok, but I still don't know how to solve after after
Answer: $$\int_0^\tfrac{\pi}{2} \frac{1 + 2\cos x}{(2 + \cos x)^2}{\rm d}x \\
= \int_0^\tfrac{\pi}{2} \frac{1 + 2\cos x}{(2 + \cos x)^2}\frac{/\sin^2 x}{/\sin^2 x} {\rm d}x \\
= \int_0^\tfrac{\pi}{2} \frac{\csc^2 x + 2\cot x \csc x}{(2\csc x + \cot x)^2}{\rm d}x \\
= \int_0^\tfrac{\pi}{2} \frac{-1}{(2\csc x + \cot x)^2}{\rm d}(2\csc x + \cot x) \\
= \left[\frac{1}{(2\csc x + \cot x)}\right]_0^\tfrac{\pi}{2}\\
= \left[\frac{\sin x}{(2 + \cos x)}\right]_0^\tfrac{\pi}{2} \\
= \frac{1}{2}$$ Hope it helps.
Comment: Awesome technique
Answer: Since $1=\sin^2x+\cos^2x$, $1+2\cos x=\sin^2x+\cos x(2+\cos x)$, so the integrand is $\frac{\sin^2x}{(2+\cos x)^2}+\frac{\cos x}{2+\cos x}$. By the product rule, one antiderivative of this integrand is $\frac{\sin x}{2+\cos x}$, so $I=\frac{\sin\pi/2}{2+\cos\pi/2}=\frac12$.
If you'd prefer a solution using $t=\tan\tfrac{x}{2}$, follow it up with $t=\sqrt{3}\tan y$, reducing the problem to $\int_0^{\pi/6}\tfrac{2}{\sqrt{3}}\cos2ydy=\tfrac12$.
Comment: I don't understand
Comment: @Aditya You don't say why, but hopefully my edit helps.
Comment: I didn't understand what you wrote after "with anti derivative.." in the third line
Comment: @Aditya I've edited again.
Answer: Continuing from your method is messy but possible:
Let $\frac{(3-t^2)}{(3+t^2)^2 } = \frac{A}{(3+t^2)} + \frac{B}{(3+t^2)^2}$. Then $3-t^2 = (3+t^2)A + B$. When $t = 0, 3 = 3A + B$, and when $t = 1, 2=4A+B$, so $A = -1, B= 6$. Thus:
$$I = -2 \int_0^1 \frac{1}{3+t^2} \ dt + 12 \int_0^1 \frac{1}{(3+t^2)^2} \ dt $$
For the second integral, substitute $t = \sqrt{3} \tan u, dt = \sqrt{3} \sec^2 u$. Then $(3+t^2)^2$ $ =(3(1 + \tan^2 u))^2 = 9 \sec^4 u$, and so:
$$I_2 = \frac{\sqrt{3}}{9} \int_0^1 \cos^2u \ du = \frac{\sqrt3}{18} \int_0^1 1+\cos2u \ du= \left[\frac{\sqrt3}{18} (u+\frac{1}{2} \sin 2u)\right]_0^1 = \left[\frac{\sqrt3}{18} (\tan^{-1} \frac{t}{\sqrt3}+\frac{1}{2} \sin(2(\tan^{-1}\frac{t}{\sqrt3}))\right]_0^1$$
and therefore:
$$I = -2 \left[\frac{1}{\sqrt 3} \tan^{-1} \frac{t}{\sqrt3}\right]_0^1+12\left[\frac{\sqrt3}{18} (\tan^{-1} \frac{t}{\sqrt3}+\frac{1}{2} \sin(2(\tan^{-1}\frac{t}{\sqrt3}))\right]_0^1$$
$$=-2(\frac{1}{6\sqrt3} \pi - 0) + 12 \cdot \frac{\sqrt{3}}{18}(\frac{\pi}{6}+\frac{\sqrt3}{4}-0) = \frac{1}{2}.$$
Answer: By substitution $u=\tan(\frac{x}{2})$ then $du=\frac{1}{2}\sec^2(\frac{x}{2})$.
Using the trigonometric formula, $\sin (x)=\frac{2u}{1+u^2}, \quad \cos(x)=\frac{1-u^2}{1+u^2}$ and $dx=\frac{2 du}{1+u^2}$.
When  you  do the required substitutions, you find a nice integral with rational expression, which can be solved by decomposition into simple elements.
Comment: Are you familiar with the method of partial fraction decomposition?
Comment: That's what I did. Still not able to solve though
Comment: @asahay yes I am
Comment: Once you have an integral of a rational function (which you seem to have gotten in the current version of your question), you can do a partial fraction decomposition to break into smaller, easier integrals.
Answer: Hint
Like How to integrate $\int \frac{\cos(x) + \sqrt 3}{1+ 4 \sin(x+\frac{\pi}{3}) + 4\sin^2(x+\frac{\pi}{3})}{\rm d}x$,
find $$\dfrac{dy}{dx}$$ where $$y=\dfrac{a\sin x+b\cos x+c}{2+\cos x}$$
Compare the coefficients of $\sin x,\cos x,\sin x\cos x$ and the constant to find the arbitrary constants $a,b,c$


Why would an arranger change a major G6 chord to a major C chord in second inversion?

Question: I am studying Cold Play's "Don't Panic", and in the piano arrangement, the arranger has changed a major6 chord to an inverted chord with the same bass. Here is the score

In the original recording of the song the chord is a G6 chord played on a guitar (about 0:50), so why would the arranger put that C there for the piano arrangement on that particular note? The arranger could have kept that B throughout the whole bar yet he/she decided to use C and change it halfway through the bar. Why?
Comment: Clefs??? why are we supposed to guess and fill in the blanks? update the picture.
Comment: The top staff is a vocal melody, but what are the other staves?
Comment: There's not enough information here to give a good answer to the question. At minimum: what is the song, and what happens in the measure before? (Also, the chords have the same "bass note", but they do not have the same "root". This is a critical distinction.)
Comment: Er, because he can? When there are specific notes at a point in a song, any chord that can fit is fair game. Here there's E and G (I think) so Em, A7, C, G6, Am7 are some options one could use. Or even chords that don't exactly contain both notes.
Comment: @piiperi bass and treble staves... sorry, thought that was obvious
Comment: @Aaron, you are right, I changed the word... my bad. The song is Don't panic by Coldplay and this happens in the bridge section about a minute or two in
Comment: @Tim What do you mean "because he can". The original song uses a G6 chord so there must be a good reason for making the change if the purpose is to arrange the music as faithfuly as possible
Comment: 'If that's the purpose' - but is it? I frequently re-harmonise songs - it's quite fun and sometimes challenging.He's an arranger, and that's what they sometimes decide to do. Arrange something differently. And it's not clear exactly *what* has been changed to what. Please post both editions, with a few bars before and after to help. Song name helps too.
Comment: Is that "fr 3" - like fret three - next to the chord diagram? I assume it is, but the picture is unclear
Comment: @MichaelCurtis - fr3 is standard for 'this is fret 3' in guitar chord windows.
Comment: @Tim, provided I can _read_ it, I can't tell if it's `fr3` or `fr5`
Comment: @MichaelCurtis - O.k., but if it was fr5 that would be a A chord - even more bizarre.
Comment: My point it to the OP to provide a clear to read example.
Comment: Just a brief comment to point out the importance of including 1) The song being asked about; 2) The measure number and/or position in a recording; 3) context beyond the specific note/chord in question. Without that information, Laurence's answer would be near impossible to give.
Comment: Yeah, I need clefs on your sheet music. Although the answers on this question imply a different story, I currently cannot help but think that **all 3 staves on your excerpt use the bass clef**, which would explain all the notes except the passing A in the topmost staff.
Answer: As far as I can see, the arranger has written the following:

Singer, sing these lyrics with this melody
Guitarist, play this chord
Pianist, play these notes

I don't recall any rule that states that if a guitarist plays a G6 chord, then a pianist absolutely must not play a C note, even for a fraction of a second.
Chord symbols are not a harmonic analysis: What is the relation of guitar chords to actual notes in the measure?
It would be unrealistic to demand the C note to be reflected in the accompaniment chord symbols. It is perfectly fine to have a backing band play a chord - however they feel appropriate - and write other notes for other instruments. For example, for harmonizing a melody with a fixed sixth or third.
Edit. From the OP's comment I see that the real question is: why wasn't the arranger faithful to the original recording, which only has a guitar in that part, and the guitar does not play a C note. Well, who knows why that is, but it's an arranger's job and even duty to make some kind of a creative contribution. Without further information I have to assume that the arranger liked the sound of the added C note, and thought that it felt appropriate to have a piano play it at that point.
Edit2. After listening to the recording posted by Laurence, on the first "yeah" word, the lead guitar and the melody together play a distinct C chord, and the bass plays a G. The acoustic guitar in the background may or may not play a C on the first "yeah", it sounds like muted notes to me. The G or G6 chord, with a B note, is played only on the "do" word. The transcription or arrangement is OK, so your claim that it's not faithful to the recording must be based on a different version of the song, or something.
Comment: Who knows? Maybe the arranger liked the sound of that? Maybe it was a mistake? That's what arranging is - deliberate modification or adaptation of a piece. If you don't make any sort of creative contribution, you shouldn't even deserve arranger credits.
Comment: There is no pianist in that part of the song! The piano arrangement is an interpretation of the piece so that someone playing this on a piano can play the song. That is why I don't understand why the arranger has not been faithful to the G6 chord for the full measure.
Comment: Not when your task is to arrange it as faithfully as possible to the original recording. Anyhow, it still doesn't explain why for have the bar it is arranged faithfully while for the first few notes there is a C/G chord
Comment: Who says an arrangement must be faithful to the original? I read arrangements every day and few are that faithful.
Comment: Maybe Armani confused arrangement and transcription? :) Really, arranging means deliberate modification, adaptation, adjustment.
Comment: @armani, the point is to _not_ consider the group of tones `G C E` in beat one a proper chord. Just because the tones coincide don't make them a chord. If your point is the arrangement is _inaccurate_, then it's off topic, question to faithfully transcribe/arrange a song.
Comment: In this case, on the recording there are two distinct chords played.  It's easy to notate them properly with chord symbols.
Comment: @LaurencePayne After listening to the recording, I have to agree, there's a C/G chord hit before the G (or G6). I would even write accent marks for the hits, because it feels important for the arrangement that all players hit them in the same rhythm. Though the C chord is played by the electric lead guitar, and it's unclear if the acoustic guitar plays the C or just muted notes at that point. The transcription or arrangement posted in the question looks OK to me, if the piano is supposed to play the lead guitar's part and the guitar chords are what the acoustic is doing.
Answer: Listen to the track.  This phrase occurs at 0'50".     I'm sure I hear two different chords.   Which means the piano part is correct.  The chord symbol is wrong.  Or, if you want to be polite, an over-simplification.
Now, what the actual intention was is another matter!  When that section returns near the end of the song the guitar plays something a bit different.  Maybe deep artistic intention, maybe just sloppiness.
Comment: Sounds to me at that point there's an awful edit been made!
Comment: And when that section returns at the end of the track it's played differently.
Comment: Can't listen to it for that long!
Answer: If I follow your question's concern, I think you are expecting the chords symbols to be...
C/G then G6 or
Gsus4 then G6
...because of the C in middle staff, first beat.
But the chord symbols are there to show what a guitarist should play rather than some kind non chord tone label or analysis.
The chord in this section is G6 and their is a non-chord tone C resolving to a B.
Another way to think about this situation is a very old idea from figured bass harmony. A chord in second in version like C/G is a harmonic idea, basically dealing with chord roots. But figured bass looked at it as a double appoggiatura over a G bass, it look at it as a contrapuntal thing, it would be called a "chord of the sixth", but the G bass was the fundamental thing rather than a theoretical root of C.
From the figured bass, contrapuntal perspective the C is an embellishment to resolve, not really a proper chord tone.
If you go with the modern, harmonic, chord root perspective you should be identifying 6/4 chords in the four categories: cadential, passing, pedal, or arpeggiated. The example doesn't include before/after one chord so we can't really explore it this way.
This seem like a lot of theory to throw around. I think the simple idea is don't casually identify 6/4 chords. First suspect them as non-chord tone, contrapuntal elements, unless you can fit them clearly into one of the four harmonic categories.
Comment: Michael, you are right about what I was asking and I understand the different historical ways of looking at these non chord tones but I was more concerned as to why there is a non chord tone there in the piano arrangement if the G6 chord is played for the whole bar on the guitar and the guitar is what drives the track? Could there be a melody part that has altered that G chord in the 1st beat and because of that the arranger voiced the piano part so to include this melodic part?
Comment: also, when you say modern harmonic chord root perspective, I assume you don't really mean "modern" as in "today" since in real modern music there are other 6/4 chords other than these right?
Comment: My "modern" I mean the chord root theory from Rameau. That's from 1722, so not "today", but it's the origin of the theory of chord used right up til now. The four 6/4 chord types is taught in today's textbooks.
Comment: We're really "getting into the weeds" with questions about the arrangement. It may be good or bad. The important take away is the guitar chord are instructions for _what to play_ not analysis of harmony and NCT... at least they shouldn't be. Lots of Hal Leonard song books have chord symbols that clearly are trying to account for the NCTs of the melody. IMO that is a _terrible idea!_ The result is a song sheet that usually _sounds wrong_ if you play all the sus and add chords cluttering up the page.
Comment: A suggestion from my experience: use the arrangements you find as an _aid only_, then mod or write your own. Songbook arrangements can help you with transcription by ear of tricky parts. Usually the melody is correct. But the accompaniment won't be accurate. That's to be expected, these are arrangements not transcriptions of the original recordings. From the chord symbols I usually pay attention to only the _root_ and _major/minor_ quality, sometimes seventh chords. The rest I get by ear from a recording.
Answer: First, I guess the author meant "... in particular that  CHORD...", instead of "... that NOTE...".
Second, the chord IS ACTUALLY a CMaj⁹ chord.  It's easier for a guitarist (guessing he's not proficient in harmony) to place the fingering shape of a G⁶ chord, finger 2 on 3rd fret.  However, for a full PIANO part, and much more if to improvise, the note "c" should be present to understand the SOUND of the moment.  (I play professionally both jazz guitar and piano, and am an arranger also).


How change "user menu" to current username

Question: I'm looking for a way to change the label "user menu" to be the current user's username. I am using the default Drupal 7 theme, Bartik, if that makes any difference.
Answer: You could do that with hook_preprocess_block
e.g, in template.php
function MYTHEME_preprocess_block(&$vars){

  global $user;
  $block =& $vars['block'];

  if ($block->module == 'system' && $block->delta == 'user-menu') {
    if (user_is_logged_in()) {
      $block->subject = check_plain($user->name);
    }
  }

}

Clear theme registry cache after adding new preprocess function.
Comment: upvote especially for using check_plain, and not t() in $block->subject :)
Comment: I actually have a subtheme. I created a file called templates.php and template.php and tried the code but it doesn't change. I deleted the cache per your instructions too. Any ideas?
Comment: Make sure you rename "mytheme" to your theme name.
Comment: Still nothing, does this file just sit directly in my subtheme's folder? Should it be named template.php or templates.php?
Comment: template.php in your subtheme folder, clear all caches at admin > performance > clear caches. If that doesn't work, try copying block.tpl.php from base theme to sub theme folder and clear cache again.
Comment: @keith, please try again, I had &= vs =& around the wrong way for the assignment by reference. Answer corrected.
Answer: You could use the Menu Token module along with the Token module to achieve this.

Menu Token module provides tokens, that could be used in title or in path of menu items (links).

A detailed step by step procedure to achieve the use case can be found at the answer here.
Answer: No need for Menu Token; as long as you have the Token module enabled, just set the User Menu Block title to [current-user:name]


After a sleep on Windows 11, Docker Desktop containers disappear

Question: I am using Docker Desktop on Windows 11 to start and stop containers. When I close Docker Desktop and the computer goes to sleep, whenever I come back and relaunch Docker Desktop, the containers are gone. If I then restart the computer, they reappear. I have observed this consistently. Why are the containers lost after a sleep ?
If I don't close the Docker Desktop application, then after a sleep the containers remain there. I also have a hard time restarting Docker Desktop from the mouse menu. It just hangs there displaying : "Docker Desktop stopping..."
Comment: Me too. It is unbearable!
Answer: I have found a simple way to bring back the containers. In a windows power shell or terminal, I do
<code>docker ps -a
</code>
Then when I reopen Docker Desktop, the containers are back !


Conditional probabilities of a chain of variables depending on one another

Question: Suppose there are $T$ variables $\{x_1, x_2, ..., x_T\}$, and they have the following relationship
$$
p(x_t|x_{t-1}) = N \big( x_t; \sqrt{1-\beta_t}x_{t-1}, \beta_tI \big)
$$
that means there is a Gaussian distribution relationship between 2 adjacent variables. Then how to derive $p(x_t|x_1)$?
My question originates from the DDPM paper, in which equation (2) and (4) state the distributions, I wonder how equation (4) is derived.
Comment: Eq (2) contains another multiplicative assumption.  Use that too and integrate out $x_{1:{t - 1}}$.
Comment: You only need to specify mean and variance, since the distribution remains Gaussian.
Comment: @Zhanxiong can you give more details please?
Comment: @avocado After applying the multiplicative assumption, a better way to circumventing explicit integration is following Xi'an's suggestion.  See my answer below.
Answer: By assumption (Eq (2) in the cited paper), the joint distribution of $X_1, \ldots, X_T$ given $X_0 = x_0$ (from now on, I will drop this conditioning qualifier for simplicity because it does not have impact on the derivation) is
\begin{align}
f(x_1, \ldots, x_T) = (2\pi)^{-T/2}(\beta_1\cdots\beta_T)^{-1/2}
\exp\left[-\frac{1}{2}\sum_{t = 1}^T\frac{1}{\beta_t}(x_t - \sqrt{\alpha_t}x_{t - 1})^2\right], \tag{1}
\end{align}
where $\alpha_t = 1 - \beta_t$ as in the cited paper. $(1)$ implies that the joint distribution of $(X_1, \ldots, X_T)$ is Gaussian
$^\dagger$. Hence the marginal distribution of $X_T$ is Gaussian, whence to determine the distribution of $X_T$, it suffices to determine its mean and variance.  By $X_t|X_{t - 1} = x_{t - 1} \sim N(\sqrt{\alpha_t}x_{t - 1}, \beta_t)$ for $t = 1, 2, \ldots, T$ and repeated application of the law of iterative expectations:
\begin{align}
E[X_T] = E[E[X_T|X_{T - 1}]] = \sqrt{\alpha_T}E[X_{T - 1}] = \cdots = \prod_{t = 1}^T\sqrt{\alpha_t}x_0.
\end{align}
Similarly, by the law of total variance:
\begin{align}
& \operatorname{Var}(X_T) = E[\operatorname{Var}(X_T|X_{T - 1})] +
\operatorname{Var}(E[X_T|X_{T - 1}]) \\
=& E[\beta_T] + \operatorname{Var}(\sqrt{\alpha_T}X_{T - 1})
= \beta_{T} + \alpha_T\operatorname{Var}(X_{T - 1}).
\end{align}
Plugging in $\beta_T = 1 - \alpha_T$, this gives the recursive relation
\begin{align}
\operatorname{Var}(X_T) - 1 = \alpha_T(\operatorname{Var}(X_{T - 1}) - 1),
\end{align}
which together with the initial condition $\operatorname{Var}(X_1) = \beta_1
= 1 - \alpha_1$ yields
\begin{align}
\operatorname{Var}(X_T) - 1 = \prod_{t = 2}^T\alpha_t(\operatorname{Var}(X_1) - 1) = -\prod_{t = 1}^T\alpha_t,
\end{align}
i.e., $\operatorname{Var}(X_T) = 1 - \prod\limits_{t = 1}^T\alpha_t$. This shows that $X_T|X_0 = x_0 \sim N(\sqrt{\bar{\alpha}_T}x_0, 1 - \bar{\alpha}_T)$.  The multivariate case can be derived analogously.

$^\dagger$ One way to see it is considering the following 1-to-1 non-singular affine transformation:
\begin{align}
\begin{bmatrix}
Y_1 \\ Y_2 \\ \vdots \\ Y_T
\end{bmatrix} =
\begin{bmatrix}
\beta_1^{-1/2} & 0 & \cdots & 0 \\
-\beta_2^{-1/2}\sqrt{\alpha_2} & \beta_2^{-1/2} & \cdots & 0 \\
\vdots & \vdots & \ddots & \vdots \\
0      & 0      & \cdots & \beta_T^{-1/2}
\end{bmatrix}
\begin{bmatrix}
X_1 \\ X_2 \\ \vdots \\ X_T
\end{bmatrix} +
\begin{bmatrix}
-\beta_1^{-1/2}\sqrt{\alpha_1} \\ 0 \\ \vdots \\ 0
\end{bmatrix} \tag{2}
\end{align}
By $(1)$ and $(2)$, the joint density of $(Y_1, \ldots, Y_T)$ is
\begin{align}
g(y_1, \ldots, y_T) = (2\pi)^{-T/2}\exp(-(y_1^2 + \cdots + y_T^2)/2),
\end{align}
which is clearly Gaussian.  Hence the joint distribution of $(X_1, \ldots, X_T)$ must be Gaussian too (as $(X_1, \ldots, X_T)$ is an affine transformation of $(Y_1, \ldots, Y_T)$ by $(2)$).
Comment: This is amazing, math is so beautiful. To make sense of your answer, I had to re-study a few things, such as why product of gaussian pdfs is still a gaussian, and why a subset of variables of multivariate gaussian still follows a gaussian distribution, law of total expecation and vairance etc.


inverse trigonometric functions with plus minus sign

Question: $$  \cos\left(\theta_{} \right) =  \pm  \frac{  1  }{  \sqrt{ 3 }   }  $$
$$  \theta_{} = \pm \cos^{-1} \left( \pm \frac{  1  }{  \sqrt{ 3 }   }  \right)       $$
I can't get why the leftmost $~ \pm  ~$ of the right term of the second equation should be needed?
I thought as
$$  \cos\left(\theta_{} \right) =  \pm  \frac{  1  }{  \sqrt{ 3 }   } ~~ $$
is held,
$$  \theta_{} = \cos^{-1} \left( \pm \frac{  1  }{  \sqrt{ 3 }   }  \right)       $$
must be held.
misprint?
Comment: Note that $\cos(\theta)=\cos(-\theta)$.
Comment: Ah, I may got the conception.
Answer: $$  \cos\left(\theta_{} \right) =  \pm  \frac{  1  }{  \sqrt{ 3 }   }   $$
$$  \theta_{} ~~ \leftarrow~~ \text{constant angle }  $$
As this argument is thrown to the cosine function ,the 2 way return values exist and it are $~ \pm \frac{  1  }{  \sqrt{ 3 }   }  ~$
$$  \theta_{} =  \cos^{-1} \left( \pm \frac{  1  }{  \sqrt{ 3 }   }  \right)       $$
$$  \cos\left(\cos^{-1} \left( \pm \frac{  1  }{  \sqrt{ 3 }   }  \right) \right) = \pm \frac{  1  }{  \sqrt{ 3 }   }  $$
By the way,
$$  \theta_{} = - \cos^{-1} \left( \pm \frac{  1  }{  \sqrt{ 3 }   }  \right)       $$
$$  \cos\left(-\cos^{-1} \left( \pm \frac{  1  }{  \sqrt{ 3 }   }  \right) \right)  $$
$$ = \cos\left(\cos^{-1} \left( \pm \frac{  1  }{  \sqrt{ 3 }   }  \right) \right)  =  \pm \frac{  1  }{  \sqrt{ 3 }   }  $$
$$  \therefore ~~ \theta_{} = \pm \cos^{-1} \left( \pm \frac{  1  }{  \sqrt{ 3 }   }  \right) \ni \cos\left(\theta_{} \right) = \pm \frac{  1  }{  \sqrt{ 3 }   }  $$


Abstract algebra,polynomial rings

Question: I recently took my first abstract algebra class and I'm loving it, so here I am asking for some help studying
The professor mentioned how in polynomial rings, if $x$ is the ordered sequence $(0,1,0,0,...)$, then $x^2$ is $(0,0,1,0,...)$ etc. Although I get why that is, I can find no book mentioning it. Can you recommend any book or resource online with a really detailed, theoretical approach to rings, that requires no background in abstract algebra?
Thanks in advance
Comment: This approach to define polynomials using sequences which are zero almost everywhere are quite common. It is also mentioned in the fabulous beginner's book "Algebra" by Michael Artin. Thomas Hungerford ("Algebra") defines the polynomial ring exactly with those sequences and then develops the "ordinary" (well known) representation of polynomials.
Answer: You will definitely find the claim that $k[x]$ is a $k$-vector space, and basic linear algebra is the only thing needed to understand this situation.
There is a particularly natural basis for $k[x]$: $\{1, x, x^2, x^3,\ldots\}$. Using this basis, you have the obvious isomorphism $k[x]\cong \bigoplus_{i=0}^\infty k$.
The coordinates with respect to this ordered basis are precisely the sequences you mention.
Comment: Thanks for the response.It was pretty helpful

I'd like to make another question that bothers me is what's the reason for polynomial functions.I get polynomials as an extension of a ring,but why would one wet another function from R[x]->R?(Although the definition says that it's from R->R).This topic really confuses me
Comment: @FotisRokanis for each $r\in R$, you can assign f(r)\in R$. This defines a function, but I wouldn't say the polynomial *is* a function.

Abstract algebra,polynomial rings


C# Embed QEMU Into panel - how to get/generate QEMU window handle?

Question: I am trying to embed QEMU into Panel in .NET 4.5.
...and I found Application panel example, which is using the WinAPI SetParent function.
Great, but how to get QEMU window's handle, or generate it?
I looked at (maybe discontinued?) QEMU Manager, and I found, that the Manager is executing the QEMU emulator with -hwnd parameter, and passing number (maybe int pointer?) after it.
I tried using Process.MainWindowHandle as window handle, and waiting for it with WaitForInputHandle() function, but I got exception, since QEMU is console app...
So, final question is: How to get/generate window handle of QEMU window?
...please keep in mind, that I need multiple instances of QEMU.
Thanks for any help,
Vít "VitekST" Staniček
Answer: Translation of user5154346's answer for anyone who comes accross this:
private IntPtr WaitForMainWindowHandle(Process proc, int maxIntent = int.MaxValue)
{
    IntPtr hwnd;
    do
    {
        hwnd = proc.MainWindowHandle;
        if (hwnd != IntPtr.Zero)
            return hwnd;
        System.Threading.Thread.Sleep(25);
        maxIntent--;
    } while (hwind == IntPtr.Zero && maxIntent > 0);
    return hwnd;
}

Use:
IntPtr hwnd = WaitForMainWindowHandle(procQEMU, 50);
StringBuilder message = new StringBuilder(256);
SendMessage(hwnd, WM_GETTEXT, message.Capacity, message);
Console.WriteLine(message);

Answer: in VB:
Private Function WaitForMainWindowHandle(proc As Process, Optional maxIntent As Integer = Integer.MaxValue) As IntPtr
    Dim hwnd As IntPtr
    Do
        hwnd = proc.MainWindowHandle
        If hwnd <> IntPtr.Zero Then Return hwnd
        Application.DoEvents() // or:
        Threading.Thread.Sleep(25)
        maxIntent -= 1
    Loop While hwnd = IntPtr.Zero AndAlso maxIntent > 0
    '**********
    Return hwnd
End Function

Use:
    Dim hwnd As IntPtr = WaitForMainWindowHandle(procQEMU, 50)
    Dim message As New StringBuilder(256)
    SendMessage(hwnd, WM_GETTEXT, message.Capacity, message)
    Console.WriteLine(message)


Round a number down (not half down)

Question: I'm looking for a round mode like PHP_ROUND_HALF_DOWN but always down :
$number = 76.5 // I want 76
$number = 76.6 // I want 76
$number = 77.0 // I want 77
$number = 0.0165 // I want 0.0160
$number = 0.0166 // I want 0.0160
$number = 0.0170 // I want 0.0170

There is a solution ?
Answer: You can use the floor function, e.g.:
floor(76.5) = 76

But for rounding decimals to a decimal place you will need to multiply/divide, e.g.:
floor(0.0165 * 1000) / 1000 = 0.016

http://php.net/manual/en/function.floor.php

Round a number down (not half down)


Derivative of an inverse

Question: Let $f(x)=2x^3+7x−1$, and let $g(x)$ be the inverse of $f(x)$. Then find $g′(191/4)$. I know only one way of doing this. Solving the cubic equation for x and then differentiating it. This is too too long. How to solve it more easily?
Comment: Hint: $ \frac{d}{dx} f^{-1} = \frac{1}{f^{\prime}\left(f^{-1}\left(x\right)\right)} $.
Comment: Will you please elaborate? How? Why?...
Comment: Take a look at this question http://math.stackexchange.com/questions/231801/question-about-derivatives-of-inverses-functions?rq=1
Comment: consider user103828's initial comment while referring to the 2nd diagram at this webpage. http://mathuprising.comlu.com/inverse-functions.html
Answer: $g(x)$ is the inverse of $f(x)$ means that $f \circ g(x)=f(g(x))=x=g(f(x))$
You take the derivative and get
$g'(x) \times f'(g(x))=1$ and also $f'(x) \times g'(f(x))=1$
Answer: In order to not confuse the variables of the inverse function with the variables of the function itself, let :
$y=f(x)=2x^3+7x−1=X$
$Y=g(X)=x$
One little picture says more than a long speech! : See below

$\frac{dg}{dX}=\frac{1}{\frac{df}{dx}}$
For $X=\frac{191}{4}$ we have $y=\frac{191}{4}=2x^3+7x-1$ which real root is $x=\frac{5}{2}$
$\frac{1}{\frac{df}{dx}}=\frac{1}{6x^2+7}=\frac{1}{6\left(\frac{5}{2}\right)^2+7}=\frac{2}{89}$
$\frac{dY}{dX}=\frac{1}{\frac{df}{dx}}=\frac{2}{89}$
where $X=y=\frac{191}{4}$  and $Y=x=\frac{5}{2}$
One see on the graph on right, which represents the inverse function, that the point considered is at abscissa $\frac{191}{4}$ as specified in the wording of the question.
Answer: Hint: First solve for $x_0$ such that: $2x^3 + 7x - 1 = \frac{191}{4}$, then apply inverse function theorem for derivative: $g'(f(x_0)) = \dfrac{1}{f'(x_0)}$

Derivative of an inverse


O que é o PHP Injection? Qual a diferença dele para o SQL Injection? E como evitá-lo?

Question:
O que é o PHP Injection?
Qual a diferença dele para o SQL Injection?
Como evitar o PHP Injection na minha aplicação?
Quais são as principais formas de ataque do tipo PHP Injection?

Atualização
Observação: Lembrando que o SQL injection não é a mesma coisa que o PHP Injection.
Code Injection in PHP
What is SQL Injection?
Comment: PHP injection, vc quer dizer abusos de `eval()`, `extract()` e coisas piores como o register globals, magic quotes?
Comment: Wallace não é exatamente/completamente o mesmo assunto mas deve ajudar: http://pt.stackoverflow.com/a/10931/3635
Comment: @rray O que um `extract()` pode fazer de mal?
Answer: Devido a inúmeros comentários publicados (na época que a pergunta foi feita por mim), creio que há alguma dúvida quanto ao PHP Injection.
Então vou explicar alguns pontos.
O que é PHP Injection?
É uma forma de ataque onde o atacante se utiliza de um script PHP para atacar uma aplicação escrita em PHP.
De acordo com o Google:

[...] PHP Injection é uma técnica utilizada na internet que consiste em
injetar scripts maliciosos, fazendo com que a página vulnerável fique
a controle do atacante [...]

Geralmente, esse tipo ataque se consolida quando o desenvolvedor deixa brechas em formulários de upload. Por exemplo, a pessoa má intencionada pode enviar um script PHP através desse formulário e, em seguida, executá-lo.
O resultado poderá ser desastroso se o atacante conseguir listar diretórios, deletar arquivos, roubar dados sensíveis, etc...
Send assim, PHP Injection não tem relação com SQL Injection, como alguns haviam apontado nos comentários anteriores.
E o SQL Injection?

SQL Injection é um ataque que consiste na inserção (conhecido como injeção) de uma query via aplicação web.

Ou seja, não há relação direta com o PHP Injection.
Formas de evitar o PHP Injection
Cuidado na hora de fazer upload!
Como dito anteriormente, uma das maiores formas desse ataque é através de formulários de upload, onde o atacante manipula o conteúdo enviado (geralmente, enviando um script PHP não esperado no servidor) e, através dele, tem acesso a informações do servidor.
Evite o eval
Outra coisa perigosa em relação ao PHP Injection é a utilização da função eval, que tem o poder de tornar uma string em um código PHP válido.
Veja mais informações sobre o eval na pergunta abaixo:

Eval é mocinho ou bandido?

Cuidado como o modificador e da função preg_replace
Recentemente, o PHP depreciou o modificador e da função preg_replace, pois esse modificador poderia utilizar um código PHP válido como retorno, sendo também utilizado por atacantes.
Veja que o preg_replace e o modificador e nessa pergunta causou alguns problemas para o desenvolvedor:

O que o código abaixo (escrito por um cracker) faz?

Nessa pergunta feita pelo @RodrigoBorth, fica claro que o código foi injetado por um cracker no servidor onde fica a aplicação dele.
Apesar de ter sido depreciada, é bom ficar atento em versões antigas de bibliotecas ou aplicações legadas que possam usar esse modificador.
Null Byte Attack
Parece que o Null Byte Attack também já foi um problema no PHP em versões anteriores também.
Veja mais sobre isso aqui:

O que é Null Byte Injection? Como evitá-lo?

SQL Injection tem relação com o PHP Injection ?
Não. São assuntos diferentes e, em cada caso, o cuidado em relação à segurança deverá será diferente.
Veja sobre SQL Injection na pargunta abaixo para tirar as suas conclusões sobre as diferenças:

Como prevenir injeção de código SQL no meu código PHP?

O que mais não confundir?
Outra coisa é confundir Ataque XSS com PHP Injection.
XSS pode ser feito em qualquer outra linguagem que não tome os devidos cuidados.
PHP Injection é algo específico do PHP.
Comment: @KaduAmaral, ainda tem muito código assim, é so ver algumas perguntas ...
Comment: Como eu disse *"não é exatamente/completamente o mesmo assunto mas deve ajudar"*, não discordo da sua pergunta e resposta, tanto que dei +1 pra ambas, o dificil é aturar estes votos pra baixo "roboticos" :( -- parabéns pela resposta!
Comment: Antigamente era comum a prática de fazer includes com base na URL, exemplo `meusite.com/?page=contato` onde `contato` era um arquivo do site, então essa brecha era aproveitada colocando ali o caminho para arquivos maliciosos...
Answer: Apenas para contribuir com a discussão e tendo em vista que passei por esta má experiência em um site que administro vou detalhar o ocorrido.
Neste site é permitido pelo usuário o envio de arquivos ZIP e imagens (JPG/PNG). Pois bem, um infeliz subiu um arquivo JPG que na verdade não era uma imagem e sim um script PHP, ele simplesmente alterou sua extensão, subiu o arquivo com um cabeçalho de imagem obviamente mas no final do arquivo existe um script php que criava um console de acesso remoto com o nome de copyright.php , de lá ele conseguia listar os arquivos do servidor e consequentemente ver eles em detalhe (com direito a conexão ao banco de dados).
Deu trabalho para identificar isso, corrigir foi simples, mas ver a php injection acontecendo foi trabalhoso, e cá para nós nunca que você vai imaginar isso. O interessante é que ele tambem usou um browser de texto para visitar a imagem, para vir um cabeçalho binário e na sequência o código ser mostrado no navegador.
Comment: Nem precisa alterar a extensão, dependendo do cenário. Isso é muito comum se o mime magic do apache estiver habilitado, pq ai a extensão é ignorada e são usados metadados para determinar a ação do servidor. Em outras postagens eu já recomendei (ao próprio autor da pergunta, inclusive) justamente desabilitar este recurso. https://httpd.apache.org/docs/current/mod/mod_mime_magic.html
Comment: O @Bacco tem um caso de amor com esse `mime_magic`, só pode, kkkkk.
Comment: Valeu pela dica @Bacco , nao sabia dessa fragilidade


Como fazer skins em ASP.NET MVC

Question: Como faria skins em MVC? onde o cliente(usuário) poderia escolher o skin (mudaria CSS, html, imagens, etc)?
OBS¹: O Skin seria para todas as páginas e cada cliente pode ter apenas 1 único skin. Mas eu teria uns 10 skins diferentes. Esses skins podem ser apenas um css diferente ou todo um site diferente.
OBS²: Imaginando que Somente a Controller pode ser igual para diferentes skins, Ex: public ActionResult MostrarProduto() vai retornar sempre a mesma coisa, somente a view ou o _Layout poderão ser diferentes.
Imagino de 3 formas, porém como não tenho experiência grande em MVC preciso de FATOS sobre vantagens e desvantagens de cada uma, claro que pode ser que nenhuma das 3 formas que imagino seja a melhor.
1 - Filtros na controller:
[VerificarSkin]
public ActionResult MostrarProduto()
{

2 - Mudando o arquivo de Layout pela Controller ou View
@{Layout = ViewBag.SkinAtual;}

3- Mudando a Pasta da View [Vídeo explicando essa solução]
public ActionResult MostrarProduto()
{
    var skinAtual = "skin12";
     return View("../Views/" + skinAtual + "/Home/index.cshtml");

Soluções:
1 - Vantagens: Limpeza no código,
2 - Vantagens: aproveito a mesma view para todos os skins mudo apenas os layout, porém dai também pode ser uma desvantagem não pode personalizar a view?
3 - Vantagem: Posso mudar tudo, view e Layout, porém daria mais trabalho?
Cenário: Hoje tenho 300 clientes(usuários) onde cada um possui seu site, esses sites são compartilhados da minha ferramenta, onde ele pode escolher os skins (que são desde mudanças de cores a layout totalmente diferentes)
Comment: Sua ideia e trocar os skins por usuário, página, por permissão? Melhor, se escolher um skin será o mesmo para todas as páginas, ou eu posso escolher um para cada página, etc?
Comment: cada cliente teria apenas um único skin que seria aplicado para todas as páginas!
Comment: Quando você diz cliente você se refere a cada usuário que acessar o sistema ou seu sistema tem vários clientes e cada clientes pode ter vários usuários? Estou fazendo essas perguntas, pois o contexto de seu sistema, pode alterar alguns fatores. Mas, a terceira forma me parece inviável, até o momento.
Comment: boas perguntas vou atualizar a pergunta.  cliente = usuário.
Comment: Qual o método de autenticação, Identity?
Comment: nenhum, identifico o cliente pela url dele, assim sei qual site é qual ClienteId é. O site é de usuário anonimo, é um site e não um admin.
Answer:
Não tem uma forma de falar qual é a melhor, pois vai depender do que você irá realmente precisar, explicarei melhor abaixo. Então, apontarei os pontos fortes e fracos dessas abordagens.

Primeira Forma
A primeira forma, como você mesmo disse, deixa o código muito mais limpo, e sem redundância, pois irá criar um filtro para obter as a Skin necessária e retornar ao usuário. Creio que seria algo parecido com isso:
 public class LayoutInjecterAttribute : ActionFilterAttribute
    {
        private readonly string _masterName;
        public LayoutInjecterAttribute(string masterName)
        {
            _masterName = masterName;
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            var result = filterContext.Result as ViewResult;
            if (result != null)
            {
                result.MasterName = _masterName;
            }
        }
    }

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

Fonte: How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?
Claro, aplicando as suas necessidades. A desvantagem desse método é que você não poderá modificar as Views com informações diferentes, ou seja, as Views serão as mesmas, o que irá mudar será o layout das mesmas.
Obs.: Se isso não for um problema, acho a melhor solução para seu caso.
Segunda forma
Essa forma tem as mesmas desvantagens da primeira, você irá poder alterar somente o Layout, mas ainda conta com mais uma desvantagem, terá que criar a ViewBag a cada Action, pois o ciclo de vida da ViewBag não é utilizada em Actions distintas. Você pode fazer no OnActionExecuted ou OnCreate do controller, mas mesmo assim, terá que fazer em cada controler, ou na View, mas tenho certeza que você sabe que não "deve" fazer nada nela.
Terceira forma
Essa é a forma que irá te dar mais trabalho para implementar, pois terá que replicar o código para cada Skin que possuir, e como disse que terá uns  10... Acho que você não quer esse trabalho todo.
Porém, se você precisa alterar algo, além do layout, em suas Views, essa será a única forma de conseguir fazer o que deseja.
Lembrando também, que você irá precisar obter a Skin em cada View, e isso pode não ser viável, dependendo da forma que busca esse Skin.
Conclusão (Pessoal)

Antes de concluir, devo lembrar que quando eu falo em "não mudar nada da View, me refiro à código que esteja naquela View em específico, mas se for algo que pode ser compartilhado para todos, você sempre terá o Shared _Layout para isso.

Das formas apresentadas, creio que a primeira seria a indicada. Além de não ter que reescrever o código, você conseguirá manipular cada Action diferentemente, caso deseje. Mas se precisa alterar algo em uma View ou outra, as duas primeiras formas não irá lhe servir.
Mas, dependendo do seu contexto, nada impede que você utilize mais de uma forma, utilizando a terceira somente onde for necessário.
Comment: @Dorathoto Eu discordo. Com HTML/CSS você consegue personalizar o site todo, a primeira opção só não iria servir se você tiver comportamentos diferentes. Visual e até mesmo mostrar ou não algo, pode ser feito por apenas por CSS, caso queira.
Comment: A forma mais correta é, de fato, a primeira. Não apenas especificar o nome fixo no código do atributo, mas também fazer um tipo de filtro cujo layout está de alguma forma associado ao usuário.
Comment: a sua resposta me fez pensar, e acho que infelizmente a primeira opção não vai ser a melhor, pois ai eu teria que ter Views Iguais para todos os skins e creio que não irei consegui personaliza tanto o site apenas pela _Layout e css diferentes.
Comment: Mas como eu disse, não tem como dar certeza sem conhecer o seu contexto. Então o que da para fazer é apenas falar um pouco sobre cada forma apresentada.
Comment: Acho q vou utilizar a primeira forma, porém nda impede de caso precise de uma view exclusiva ou crie uma nova ou use o terceiro método.

Como fazer skins em ASP.NET MVC


Java Spring form tag question

Question: I am using JSPs, and this is my contacts.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

    <title>Spring 3.0 MVC series: Contact manager</title>

Contact Manager

<form:form method="post" action="addContact.html">

            <form:label path="firstName">First Name</form:label>	 // LABEL
            <form:input path="firstName" />

            <form:label path="lastName">Last Name</form:label>
            <form:input path="lastName" />

            <form:label path="lastName">Email</form:label>
            <form:input path="email" />

            <form:label path="lastName">Telephone</form:label>
            <form:input path="telephone" />

                <input type="submit" value="Add Contact"/>

</form:form>

My questions is, that when i change form:label path="firstName" into form:label path="firstname", why tomcat starts throwing errors? Doesn't the model only need the input path, since the value inside input path, is the value it will use?
EDIT:
should i even use the form:label tag , why is it used?
Comment: The form:label tag needs a path attribute so that it can generate the "for" attribute of the label tag.
Comment: The value of using labels is that they allow the user to click on the label to select the control to which the label is attached (via the label's "for" attribute).
Comment: You should always use labels; they make your code more accessible to screen readers and other alternative user agents.
Answer: It's because firstName is either used literally, or is translated into the method getFirstName().
Either way, the capitalization matters when the lookup is performed.

For your question on whether or not you need the path in the label: If you provide the path, then the label will know which input it belongs to. In HTML, that allows you to click on the label and have the input field gain focus. I assume the output HTML for your code is something like this:

  <input type="text" id="firstName">

Comment: But should i use the `form:label` tag anyways, when it does not matter if it is there, or it is not?
Comment: I am wondering, why should i use the `form:label` tag, when it is not used anywhere?
Comment: I assume the output is a ``, so if you don't want that, then don't use it. I'm not quite sure what the other option is? You either want a label or you don't. It's not required.
Comment: Yes I can have label and I can't, but my initial question was this: Why does my label need a path?
Comment: Sorry, but it was not clear that was your original question. If you provide the path, then the label will know which input it belongs to. In HTML, that allows you to click on the label and have the input field gain focus. I assume the output HTML for your code is something like this: ``
Comment: Oh great, yeah i was confused and tried to ask many questions in same time, but thanks for your answer, that was exactly what i wanted to know!

Java Spring form tag question


Where is RxJS 6 static merge?

Question: In RxJS 6, how do I import a static merge function for merging a list of Observables?
I want to be able to do:
const merged$ = merge(
    obs1$,
    obs2$,
    obs3$
);

I've tried:
import { merge } from 'rxjs/observable/merge'; and
import { merge } from 'rxjs/operators';
but neither seems to give me what I want.
Comment: See that example in the doc : https://www.learnrxjs.io/operators/combination/merge.html#example-1-merging-multiple-observables-static-method
Answer: Importing has been made easy in RxJS 6:
 import { merge } from 'rxjs';

You may want to read the official migration guide.
Another useful resource regarding importing in RxJS 6 is this talk by Ben Lesh who is the RxJS lead.
Comment: how to use this with the new pipe operator?
Comment: Link invalid 404
Answer: I believe now when the "creation" classes were removed the recommended way is importing directly from 'rxjs':
import { merge as mergeStatic } from 'rxjs';

Previous alpha version of RxJS 6 used to have 'rxjs/create' file but this has been removed already: https://github.com/ReactiveX/rxjs/blob/master/CHANGELOG.md#600-alpha3-2018-02-06
However this expects you to use path maps correctly otherwise you'll import a lot of things you don't need. If you don't use path maps or the build process hidden from you you can import directly the correct file:
import { merge as mergeStatic } from 'rxjs/internal/observable/merge';

Answer: RxJS 7.X
In RxJS v7.X the merge() method is deprecated and will be removed from RxJs v8.X, use mergeWith() instead.
See:
https://rxjs.dev/api/operators/mergeWith
https://rxjs.dev/api/operators/merge (deprecated)
import { fromEvent } from 'rxjs';
import { map, mergeWith } from 'rxjs/operators';

const clicks$ = fromEvent(document, 'click').pipe(map(() => 'click'));
const mousemoves$ = fromEvent(document, 'mousemove').pipe(map(() => 'mousemove'));
const dblclicks$ = fromEvent(document, 'dblclick').pipe(map(() => 'dblclick'));

mousemoves$.pipe(
  mergeWith(clicks$, dblclicks$),
)
.subscribe(x => console.log(x));

// result (assuming user interactions)
// "mousemove"
// "mousemove"
// "mousemove"
// "click"
// "click"
// "dblclick"

(example from api docs)
Answer: As of RXJS 6. The merge is in the rxjs/operators
import { map, take, merge, switchMap, filter } from 'rxjs/operators';

Comment: Not exactly. There are two merge functions:

from 'rxjs': https://rxjs-dev.firebaseapp.com/api/index/function/merge and
from 'rxjs/operators': https://rxjs-dev.firebaseapp.com/api/operators/merge
Comment: The difference: import { merge } from 'rxjs' -> Creates an output Observable which concurrently emits all values from every given input Observable. || import { merge } from 'rjxs/operators' -> Deprecated in favor of static merge.  You are correct; start using just 'rxjs' https://github.com/ng-bootstrap/ng-bootstrap/issues/2394

Where is RxJS 6 static merge?


how to play an open Bm on the 7th fret of the guitar

Question: I am trying to work out what the chords are to a song by the band Oasis which uses an open string Bm chord up on the 7th fret but I can't figure out the fingering. I know how to play a Bm chord as a barre chord but I want to learn this version of it. Can anyone please help with some possible fingerings of the chord?
Here is a link to the video

 and you can see the chord at 1:21
Comment: Presumably you've already noticed he's not in standard tuning?
Comment: Nope, never noticed that but that E chord he plays seems like a pretty standard E chord shape so if you could please tell me why you think he is not using standard tuning
Comment: Ah, now I'm awake… he's just got his thumb over the top of the neck.
Comment: ok so thumb plays B on 7th fret?
Comment: Hmmm, it doesn't look like the thumb is doing any pressing down... what about it maybe being a 2nd inversion Bm chord so in other words no bottom string?
Answer: it's more of a Bm add4 (or add11).
fingering:
with thumb to mute: x99700
with thumb to fret: 799700
and, of course, that can be tactically muted/strummed to mute the e at the top, making it a straight Bm too and giving a little melodic interplay between the d (7th fret g string) and e (open e string) at the top of the chord.  Their spacing apart (separated by the open b) makes it not too tricky to target these notes and highlight them while strumming, which is what your man does here.
To mute the ringing e string entirely for a straight Bm chord, you can let the inside of your left hand fingers touch the bottom of the guitar neck.  You don't have to, but if you want to it's a good tip for how.
Abcjs transcription of the 4 possibilities just for fun:
X: 1
T:
M: 4/4
L: 8/8
R:
K: Bmin
%%annotationfont Times-Italic *
|"^no thumb" "_Bm add4/F#"[FBBde]| "^thumb""_Bm add4"[B,FBBde]|"^muted top w/o thumb""_Bm/F#"[FBBd]| "_Bm""^muted top w/ thumb" [B,FBBd]|

the first is the one most employed here
Answer: Simply play an open E minor shape at 9 (and 7 fret on 3rd string). There's an open top string sounding too.The open B string will be in tune! Bottom string is up to you - maybe thumb over, or leave it out.


A straight line parallel to the base of a triangle divides it into parts whose areas are 2 : 1.

Question:
A straight line parallel to the base of a triangle divides it into parts whose areas are 2 : 1. In what respect, counting from the top, does it divide the sides?

So what I understand here is that the ratio of the area of two similar triangles are equal to the square of the ratio of their corresponding sides. Applying this to the question will give me $\sqrt2 : 1$, which is not same as the answer given.
Answer given : $(\sqrt6 +2) : 1 $ or $(\sqrt3 +1) : 2$.
Somebody help me here. Thanks.
Comment: Note that you need to sum the areas, otherwise you end up with a trapezium.
Answer: $$
\frac{x^2}{1-x^2}=2\implies x=\sqrt\frac23\implies \frac x{1-x}=\frac{\sqrt\frac23}{1-\sqrt\frac23}=\frac{\sqrt\frac23\left(1+\sqrt\frac23\right)}{\frac13}=\sqrt6+2.
$$
and similarly for the case
$\frac{x^2}{1-x^2}=\frac12.$
Answer: If the trapezium is larger than the small triangle, then The ratio of the areas of the similar triangles is 3:1
The ratio of the lengths of the triangles are rt3:1
The ratio of the sides are then rt 3 -1 : 1.
Multiplying both sides by rt 3 +1, we get 2:rt3 +1.

Now do the same if the trapezium has area smaller than the inner triangle.


react-media-recorder not Stopping recording in deployment

Question: I am using react-media-recorder to record audio. It works fine on localhost but when deployed to a server and accessed, the onStop method stops working. It doesn't get invoked.
this is my file:
import { useReactMediaRecorder } from "react-media-recorder"

const { status, startRecording, stopRecording, error, mediaBlobUrl, clearBlobUrl } = useReactMediaRecorder({
        audio: true,
        type: "audio/wav",
        onStop: (blobUrl, blob) => {
            console.log("onStop recording")
            const url = URL.createObjectURL(blob)
            let formData = new FormData()

            //person_name-person_id-language_id-sentence.id-date
            const today = new Date()
            // const file_name = `${id}-${language_id}-${sentence.id}-${today.toISOString()}.wav`
            const file_name = `${name}-${id}-${language_id}-${
                sentence.id
            }-${today.toDateString()}-${language_name}.wav`

            console.log("-------------------------------------------------------")
            console.log("file_name :>>", file_name)
            console.log("-------------------------------------------------------")

            formData.append("file", blob, file_name)

            let upload_url
            if (sample) {
                upload_url = "sentence/upload_audio_sample"
            } else {
                upload_url = "sentence/upload_audio"
            }

            console.log(`upload_url`, upload_url)
            axios
                .post(upload_url, formData)
                .then((d) => console.log("after post blob :>>", d))
                .catch((e) => console.log("error in post blob :>>", e))
        },
    })

    const handleStartRecording = () => {
        setRecording(!recording)
        if (!recording) {
            clearBlobUrl()
            startRecording()
        } else {
            stopRecording()
        }
}

any help is much appreciated
Answer: for this to work both the frontend and backend need to be on https.
Make sure your backend server is running on https


Is SPF record necessary for single domain IP?

Question: My question is simply this - I have a domain where all the DNS records to a single box. Do I need to setup an SPF record in this instance as SPF is designed for where a different IP is sending emails on behalf of that domain. Is there any extra benefit of doing it?
Comment: You are wrong about what SPF is for; it is still perfectly applicable if only a single system handles all your mail (your DNS settings are irrelevant for SPF record purposes save inasmuch as your DNS servers will need to serve the record).  I strongly recommend you read [our canonical question on SPF](http://serverfault.com/questions/369460/what-are-spf-records-and-how-do-i-configure-them) and then either edit or delete this question.
Answer: Yes!
It's not necessary per se, but highly recommendable. It's not so much about overcoming the ability to send email, but about protecting domain reputation.
With no SPF record in place, receiving parties have little information to go on when determining validity and authenticity of messages claiming to originate from your domain. By publishing a restrictive SPF record, you can actively let recipients know that they should not trust email coming from other MTA's than your single box (or maybe not trust ANY email claiming to come from your domain).
In a scenario where mail is occasionally sent from that single IP:
v=spf1 a -all

In a scenario where no mail will ever be sent from your domain:
v=spf1 -all


ODE transformation for Midpoint Implicit method

Question: I need to transform my ODE to an update scheme for the midpoint implicit method and I can't get the right answer.
The ODE is $\frac{du}{dt} = -3t^2(u-2)$
Which I think means $f(u(t),t) = -3t^2(u-2)$
The initial condition is $u(0) = 2.18$ although that's not too important for the context of this question.
The equation for the midpoint implicit method is $u_{i+1} = u_i + hf(\frac{1}{2}(u_i+u_{i+1}),t_i+\frac{h}{2})$
I think I need $u_{i+1}$ in terms of $h$, $t_i$ and $u_i$ without the function $f$ being there anymore but I can't do it.
Thanks
Answer: If you parametrize $u_{i+1}=u_i+2k$, then you get the equation
$$
k=\frac{h}2f(u_i+k,t_i+\frac h2)
$$
which you could recognize as an implicit Euler step. So if you have methods to solve that, or just use this equation in a Newton method or similar to solve for $k$, you also get a solver for the midpoint method.

In this specific case as the ODE is linear in $u$ this equation can be solved directly as
$$
(1+\tfrac32ht_{i+1/2}^2)k=-\tfrac32ht_{i+1/2}^2(u_i-2),~~~t_{i+1/2}=t_i+\frac h2,
$$
so that
$$
u_{i+1}=u_i-\frac{3ht_{i+1/2}^2}{1+\tfrac32ht_{i+1/2}^2}(u_i-2)
=2+\frac{1-\tfrac32ht_{i+1/2}^2}{1+\tfrac32ht_{i+1/2}^2}(u_i-2).
$$


If $q^{n+1}$ doesn't converge, then why $\frac{1-q^{n+1}}{1-q}$ doesn't converge either?

Question: Suposse $q^{n+1}$ doesn't converge (I know this happens only when $|q|\geq 1$ and $q \neq 1$ ). Then why $\frac{1-q^{n+1}}{1-q}$ doesn't converge either? Should I use the definition of "no convergence" ie divergence.
Answer: $\dfrac {1-q^{n+1}}{1-q}={\dfrac{1}{1-q}}\times({1-q^{n+1}})$.
If $q^{n+1}$ does not converge then $1-q^{n+1}$ also does not converge and, more generally, $a\times({1-q^{n+1}})$ also does not converge if $a$ is real number different from zero.
In your example $a=\dfrac {1}{1-q}$.
Answer: Negation, addition of a constant ($1$) and division by a nonzero constant ($1-q$) are continuous operations on $\overline{\mathbb R}=\mathbb R\cup\{-\infty,+\infty\}.$
Answer: Taking @user236182 's suggestion,
$q^n$ diverges if and only if $q=-1$ or $|q|>1$.
i) $q>1$
$$\frac{1-q^{n+1}}{1-q}=\sum_{k=1}^n q^k > q^n$$
$$\lim_{n\to\infty}\frac{1-q^{n+1}}{1-q}\ge\lim_{n\to\infty}q^n=\infty$$
ii) $q<-1$
$$\left|\frac{1-q^{n+1}}{1-q}\right|>\frac{|q^{n+1}|-|1|}{|1-q|}$$
$$\lim_{n\to\infty}\left|\frac{1-q^{n+1}}{1-q}\right|\ge\lim_{n\to\infty}\frac{|q^{n+1}|-|1|}{|1-q|}=\infty$$
iii) $q=-1$:
$$\frac{1-q^{n+1}}{1-q}=\sum_{k=0}^n q^k=\sum_{k=0}^n (-1)^k=\frac{1-(-1)^{n+1}}{2}$$
Therefore if $q^n$ doesn't converge, $\frac{1-q^{n+1}}{1-q}$ doesn't converge either.
Comment: This argument won't work if $q=-1$.
Comment: The assumption is "If $q^n$ diverges". Ah I got your point.
Comment: $(-1)^n$ diverges.
Comment: $q=-1$ can be treated as a separate simple case. If $q<-1$, then $q^n$ gets arbitrarily large, but you can't say that $\lim_{n\to +\infty}q^n=+\infty$ in that case.
Comment: Yeah, I think the @Justpassingby 's statement is more than enough for this question.
Comment: Though you could make a little edit to make yours correct. $q^n$ diverges if and only if either $q=-1$ or $|q|>1$. $q=-1$ is a simple case, where $\frac{1-q^{n+1}}{1-q}$ oscillates between $0$ and $1$, and if $|q|>1$, then $q^n$ gets arbitrarily large, and $q^n<\frac{1-q^{n+1}}{1-q}$.
Comment: @user236182 Thanks. I made edits.
Comment: The expression is defined if $q=-1$. It equals $0$ when $n$ is odd and $1$ when $n$ is even.
Comment: Hey, you're right :0). I fixed it.


Dojo versions and Intern compatibility

Question: This should be an easy question for the Dojo and Intern gurus our there.
What versions of dojo do the different versions of Intern work with without any core configuration changes required?
For example I had come up against an issue recently where I used dojo 1.9 with intern 1.7 and had an issue where the default AMD loader that Intern expects was not correct. Whilst this type of problem can be fixed with some Intern configuration values, it would be good to get a clear understanding of what versions work out of the box (by default) with each other without any core configuration changes like the AMD loader issue for example?
Answer: The recommended way to install Intern now is via npm. As such, the correct version of each Intern dependency will be fetched and installed for you - including Dojo - so there's no need to manually manage these anymore. Simply run npm install intern and you can rest assured the correct version of Dojo will be internally installed and used by Intern.

Dojo versions and Intern compatibility


Need to append forward slash but only when href doesn't have a .aspx in the value

Question: This is what i have so far and it works fine:
$("a[id=terminalNode]").each(function() {
    var _href = $(this).attr("href");
    $(this).attr("href", _href + '/');
});

However, there are some instances where the value could have a ".aspx" in the href. Is there an easy way to filter these out of my each loop?
Answer: $("a[id=terminalNode]").each(function() {
    var href = $(this).attr("href");
    if (href.toLowerCase().slice(-5) != '.aspx')
        $(this).attr("href", href + '/');
});

or
$("a[id=terminalNode]").each(function() {
    var href = $(this).attr("href");
    if (href.toLowerCase().test('.aspx'))
        $(this).attr("href", href + '/');
});

or
$("a[id=terminalNode]").each(function() {
    var href = $(this).attr("href");
    if (href.toLowerCase().indexOf('.aspx') != -1)
        $(this).attr("href", href + '/');
});

however why would you have a foreach on a[id=terminalNode]? Something with an id should only appear once on the page.
Answer: You can use .indexOf() to check if a string contains a specific string. It is case-sensitive so .toLowerCase() might be a good idea:
$("a[id=terminalNode]").each(function () {
    var _href = $(this).attr("href");
    if (_href.toLowerCase().indexOf(".aspx") == -1) {
        $(this).attr("href", _href + "/");
    }
});


$\frac{23x - 11x^2}{(2x-1)(9-x^2)}$ when resolved into partial fractions is equal to?

Question: $\frac{23x - 11x^2}{(2x-1)(9-x^2)}$ when resolved into partial fractions is equal to?
I solved it using $\frac{23x - 11x^2}{(2x-1)(9-x^2)} = \frac{A}{2x-1} + \frac{B}{3-x} + \frac{C}{3+x}$, but this is very long method to solve, as after comparing I will get three variables equations. Please tell me any shorter method to do it.
Answer: $$\frac{23x-11x^2}{(2x-1)(9-x^2)}=\frac{23x-11x^2}{(2x-1)(3-x)(3+x)}$$
The denominator of $A$ vanishes when $x=\frac12$, omit the vanishing term, we have
$$A=\frac{23\left( \frac12\right)-11\left( \frac12\right)^2}{(3-\frac12)(3+\frac12)}$$
The denominator of $B$ vanishes when $x=3$, again, we have
$$B = \frac{23(3)-11(3)^2}{(2(3)-1)(3+3)}$$
Similarly for $C$.
The main idea is
$$23x-11x^2 = A(3-x)(3+x)+B(2x-1)(3+x)+C(2x-1)(3-x)$$
By using the terms that the other two terms vanishes, we can solve a variable easily.
For example, by letting $x=\frac12$, the last two terms on the right vanishes and we are left with
$$23\left( \frac12\right)-11\left( \frac12\right)^2=A\left( 3-\frac12\right) \left( 3+\frac12\right)$$
This is known as Heaviside cover-up method. Refer to case $2$ of the wikipedia if the factors of the denominator include powers of one expression
Comment: I think many would appreciate a short justification for why this works at all. It seems like black magic, and people unfamiliar with the trick have no reason to trust it, nor any help remembering the details of it, nor any hope of figuring out what to do if we have a square factor in the denominator.
Comment: oops, thanks for pointing that out.


The requested PHP extension json and mbstring is missing from your system

Question: I am installing a PHP script in my Cpanel. it's showing an error

ERROR: The requested PHP extension json is missing from your system.
ERROR: The requested PHP extension mbstring is missing from your system.

while I have double-checked and enabled these two extensions from my PHP version's what should I do to solve this issue please guide me.
Answer: Use the Output of phpinfo() to determine whether the Extensions are really active. Depending on your infrastructure a restart of either your webserver and/or the php-fpm may be necessary.


Why does this function not invoke the move constructor?

Question: I am following the video lectures of Stephan T. Lavavej, namely this one on move semantics: http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-9-of-n
In the lecture, Stephan gives an example class named remote_integer and defines a global function as follows:
remote_integer square(const remote_integer &r) {
  const int i = r.get();
  return remote_integer(i*i);
}

The class remote_integer contains a move constructor, however, I've noticed that when the function square is called when trying to initialize a new object, the move constructor does not work as intended.
Here's the code:
  remote_integer a(8);
  // Expect move constructor to be called
  remote_integer b = square(a);

When I change the function definition of square as follows, the move constructor does work as intended.
remote_integer square(const remote_integer &r) {
  const int i = r.get();
  remote_integer local(i*i);
  return local;
}

Why is the move constructor called in the second case, but not in the first case? Obviously in the modified square function, the remote_integer is local the the scope of the function, so it's pretty clear that the move constructor is called when the variable local is returned. But why does this not occur when I return an anonymous object as in the first function definition?
Answer: First one: RVO - return value optimization, construct in place in the call site
Second one: Copy elision - elide copies / moves and construct in place
Third one: Inhibits RVO, moves the object out of the function
Comment: You can actually optimize out moves/copies even if it *does* change semantics.  Copy elision is one of the very few exceptions (and the only exception i can think of) to the as-if rule.  Even if the copy/move constructor has side effects, the compiler isn't required to call it.
Comment: Good Description +1 for the answer
Comment: BTW, RVO is a form of copy elision.
Comment: Note that `NRVO` may apply in third case.


How to programmatically create an exposed filter?

Question: Is there a way to create programmatically exposed filters in Drupal 7?
I searched a lot but I found only topics related remove or alter exposed filters already available in a view.
By instance my view doesn't provide any exposed filter.
I must create it through the code in my module.
I have a view but I can't change it via Views administration interface.
I must achieve the result by implementing hook_views_pre_view() and add_item().
Unfortunately add_item is not very well documented or, at least, not the part concerning the $options array structure.
Given 'field_status' a "select list" with 3 items defined in the field configuration, and the following piece of code:
 function hook_views_pre_view(&$view, &$display_id, &$args) {
   $field = field_info_field('field_status');
   if (!empty($field)) {
    $filter = array(
     'identifier' => 'field_status',
     'exposed' => TRUE,
     'is_grouped' => FALSE,
     'table' => 'field_data_field_status',
     'type' => 'list_text',
     'expose' => array(
       'operator_id' => 'field_status_value',
       'label' => 'Status',
     )
   );
   $view->add_item($view->current_display, 'filter', 'field_data_field_status', 'field_status_value', $filter);
   $view->display_handler->set_option('css_class', 'view-status');
}

what should be the structure of the array $options (in my case $filter)?
As a result of this I can see the submit button 'Apply' and the label "Status" in an empty widget 'div'.
Here is the code edited following suggestions in comments:
function my_module_views_default_views_alter(&$views) {
  if (array_key_exists('my_view_name', $views)) {

    $options = array (
      0 => 'Blocked',
      1 => 'Active',
    );

    $display = $views['my_view_name']->display['my_view_page'];

    $display->display_options['filters']['field_status']['id'] = 'field_status';
    $display->display_options['filters']['field_status']['table'] = 'field_data_field_status';
    $display->display_options['filters']['field_status']['field'] = 'field_status';
    $display->display_options['filters']['field_status']['exposed'] = TRUE;
    $display->display_options['filters']['field_status']['expose']['operator_id'] = 'field_status_value';
    $display->display_options['filters']['field_status']['expose']['label'] = 'Status';
    $display->display_options['filters']['field_status']['expose']['operator'] = 'field_status_value';
    $display->display_options['filters']['field_status']['expose']['identifier'] = 'field_status';
    $display->display_options['filters']['field_status']['value'] = $options;

    $views['my_view_name']->display['my_view_page'] = $display;
  }
}

--- ALTERNATIVE SOLUTION ---
Since this problem seems to be hard to fix (@ least for my specific case) I have used a workaround to achieve the goal.
The solution consists basically on a Views Block Clone with Exposed Filters which overrides the Views Block (without exposed filters) according to specific cases (Is User LoggedIn, Content Type, Contextual Filters ecc..).
Answer: Can you please try with hook_views_default_views_alter function. This function should be defined in MODULE_NAME/views/MODULE_NAME.views.inc file. And don't forget to include this file on .info file as files[] = views/MODULE_NAME.views.inc.
 function MODULE_NAME_views_default_views_alter(&$views) {
        if (array_key_exists('MY_VIEW_NAME', $views)) {
          $options = array(
          0 => 'Blocked',
          1 => 'Active',
          );
          $display = $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'];
          $display->display_options['filters']['field_status']['id'] = 'field_status';
          $display->display_options['filters']['field_status']['table'] = 'field_data_field_status';
          $display->display_options['filters']['field_status']['field'] = 'field_status';
          $display->display_options['filters']['field_status']['value'] = $options;
          $display->display_options['filters']['field_status']['exposed'] = TRUE;
          $display->display_options['filters']['field_status']['expose']['operator_id'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['label'] = 'Status';
          $display->display_options['filters']['field_status']['expose']['operator'] = 'field_status_value';
          $display->display_options['filters']['field_status']['expose']['identifier'] = 'field_status';
          $views['MY_VIEW_NAME']->display['MY_VIEW_PAGE'] = $display;
          }
    }

Comment: Great, thanks for precious information. I will make a test and will return to you with a feedback for this solution.
Comment: Welcome. Please try and confirm if it got worked..
Comment: Hi, the solution looks good in terms of cleanliness. Unfortuantely I got the same result with label and submit 'Apply' but no select list field. I also got the Notice: Undefined index: field_tags in views_handler_filter->accept_exposed_input(). Moreover, as far as I understood, this hook must be implemented streight in .module file otherwise it doesn't work. Any idea about that? Thank you anyway for your help!! I really appreciate
Comment: Can u please include below code in to the above statement. I will edit my answer.                                                                                $options = array(
          0 => 'Blocked',
          1 => 'Active',
        );                                                              $display->display_options['filters']['field_status']['value'] = $options;
Comment: Hi, I have added the snippet of code on my comment above.
Comment: The problem is that I'm still getting the same result... I don't know if it depends by Organic Groups module. I will make a test on a simple Drupal instance just to have a more clear picture and will return to you with a feedback of course! :) Thanks!!


How to configure an additional field for a bundle that is created by a custom module

Question: In Drupal 8 have a custom module for which bundles are created via yaml files in its config/install folder. I need to add an additional field to the 'schema.'
My steps were:

pm-uninstall the module
delete the content type via the ui
rebuild cache
add the new yaml file (a clone of an existing file with the field name changed)
re-enable the module

This gave me an unmet dependencies error.
If I remove the file and enable the module, the bundle is created, without the field of course.
I can create the field via the ui, but then its yaml file is not present in the install folder, so the module isn't deployable as-is.
Answer: You have to add the field via the UI.
Then you can export the yml config files required by the field by

Using drush cex sync
Navigating to admin/config/development/configuration/single/export and export the changed/new files on admin/config/development/configuration manually.

Copy the new/changed files to your config/install folder and you are good to go
Comment: Hi. Thanks for the reply. Copy them to config/install as in docroot, or overwrite the module's?
Comment: Add/override them in your_module/config/install


Getting user photo url and profile url using views_json

Question: I'm using the views_json module in Views Datasource to send some information in JSON format to a related website.  I've got a bunch of content views built, but now I'm trying to build staff pages.  I've got most of it working fine, but when I try to add the user picture I end up with an empty field, When trying to find a url for the user's profile page (using User: Link), I got the text "view", leading me to believe that when drupal tries to output the content as a link, views_json returns the link text.  I just want the url in plaintext, I don't need the html for a link.  How can I get the user picture, and the absolute url to the user profile in views_json?
Image fields for my node views work just fine, I get field_image.src and field_image.alt elements in the JSON that is returned, with the Use picture I get a blank field or a series of \n´s
Answer: To get the user pic url, you can do it using Image URL Formatter. Once enabled, when you click on the user picture field, you will now see a formatter option, select image url.
For the user, assuming this is a user view, in FIELDS add the User: Uid as a field and checkmark ☑ exclude from display.
Now, add Global: Custom text as a field. In the text box, put http://ultrabob.com/user/[uid]
I got [uid] from replacement patterns. Side note, in order for fields to appear as a replacement pattern, they must be above the current field.
Else, if you're using pathauto so the user pages are /user/[username] then add the User: Name field instead and use the [name] token.
Now, if your view is a content view, ex: shows articles, then you will need to add a relationship of node author first, once you do that, the user fields will become available to be added as a field.

OK, that issue got me sorted with the pictures, I'm now working on the
  solution for profile page link. Can you think of a good way to get the
  domain part of the url (http://ultrabob.com/) in your example
  dynamically in views from the site configuration. I would like this to
  continue to work without modification as it is deployed across test
  servers and onto production

You can using php. Ex: <?php echo $_SERVER['HTTP_HOST']; ?>
Either you could enable the Views PHP module, but remember to turn it off on production, or use a template file.
views-view-field--[view-name]--views-data-export--[field-name].tpl.php
<?php

$fields["field_name"]->content = 'http://' . $_SERVER['HTTP_HOST'] . '/user/' . $fields["field_name"]->content;

echo $fields["field_name"]->content;

Comment: hmmm, I've enabled the Image URL Formatter module, cleared cache and reloaded the view, but I'm still not seeing any formatter option.  I wonder what I'm missing.
Comment: I clicked back over to my node view and confirm I get the formatters on my node image field.  It seems not to work for user picture.  I found an [open issue](https://www.drupal.org/node/2396813) which I'll go investigate.
Comment: This is a great answer and got me working toward the right answer for this particular situation.  In the end I managed to get it all solved in a `hook_preprocess_views_views_json_style_simple` call, so I'll put up an answer with that solution in it.  Thanks as always for your great help!
Comment: @UltraBob oh cool, didn't know about that hook.
Answer: UPDATE: There was a follow up comment on the drupal.org thread where someone suggested using Views User Picture URL.  Since the solution below already works for me I haven't tried it, but this solution seems easier and reasonable. /UPDATE
@no-sssweat provided a superb answer, but it turned out that my problem was the result of a bug in views_datasource in that thread, @tyler-frankenstein provides a really useful solution.  Based on that I was able to get both the url path and profile link issues resolved:
/**
 * Implements hook_preprocess_views_views_json_style_simple().
 * solution for user pictures not showing up properly in views_json
 * via https://www.drupal.org/node/2396813#comment-10461959
 */
function MY_MODULE_preprocess_views_views_json_style_simple(&$vars) {
    $views_to_process = array(
        'user_view' => array(
            'uid_column_name' => 'uid',
            'picture_column_name' => 'picture',
            'image_style' => 'medium',
            'url_column_name' => 'url',
        ),
        'my_other_user_view' => array(
            'uid_column_name' => 'uid',
            'picture_column_name' => 'picture',
            'image_style' => 'medium',
            'url_column_name' => 'url',
        )
    );
    if (!in_array($vars['view']->name, array_keys($views_to_process))) { return; }
    $uids = array();
    $uid_column_name = $views_to_process[$vars['view']->name]['uid_column_name'];
    $picture_column_name = $views_to_process[$vars['view']->name]['picture_column_name'];
    $image_style = $views_to_process[$vars['view']->name]['image_style'];
    $url_column_name = $views_to_process[$vars['view']->name]['url_column_name'];
    foreach ($vars['rows'] as $i => $row) {
        $uid = $row[$uid_column_name];
        $uids[] = $uid;
    }
    $users = user_load_multiple($uids);
    foreach ($vars['rows'] as $i => $row) {
        $uid = $row[$uid_column_name];
        $vars['rows'][$i][$url_column_name] = url(drupal_get_path_alias('user/' . $uid), array('absolute' => TRUE));
        if (!$users[$uid]->picture) { continue; }
        $vars['rows'][$i][$picture_column_name] = array(
            'src' => image_style_url($image_style, $users[$uid]->picture->uri)
        );
    }
}

replacing user_view and my_other_user_view with the names of views this needs to work on and putting the label names in the uid_column_name, picture_column_name and url_column_name as well as filling in the value for the image style you've chosen for your picture field will result in your picture and url fields being filled with data like so:
"url" : "http://link.to.the/users/profile",
"photo" : {
  "src" : "http://link.to.the/users/profile/picture/with/styles/applied/properly.jpg?itok=ipLMAws_"
},


How to set horizontal scroll position react

Question: I'm trying to make a page set it's horizontal scrolling position in the middle on load.
I've tried calling window.scrollBy (and the others like scrollTo etc) in the componentDidMount function (which I confirmed is being called).
I can't get it to work for horizontal nor vertical scrolling.
The npm package 'react-scroll' did work but only for vertical scrolling.
EDIT:
tech_amity is right that these functions take two arguments: the x and y coordinate.
In my case however the problem was solved by accessing the window.scrollTo() function from the onLoad event on a new parent container div. I'm still not really sure why.
so:
function moveLeft()
{
  window.scrollTo(300, 0);
}

//and then in the JSX/html:

//... stuff i want to scroll

Answer: You should give proper co-ordinates in scroll function.
window.scrollTo(x-coord, y-coord);
window.scrollTo(scroll-to-middle, 0);

give x-co-ordinates according to you.


List of vectors multiplied by one matrix with numpy einsum

Question: I have a 3x3 matrix and I would like to multiply each vector in a list by this matrix.
This can be done easily with a loop:
import numpy as np

a = np.array([[0,1,0],[-1,0,0],[0,0,1]])
b = np.array([[1,2,3],[4,5,6]])

for elem in b:
   print(a.dot(elem))

To make it quicker I have tried using numpy.einsum but I am not able to do the correct formulation.
I have tried  np.einsum('ij,ji->ij', a, b) but this results in ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (3,3)->(3,3) (2,3)->(3,2)
Any advice ?
Comment: Why not simply `a @ b.T` (`@` is same as `.dot`) No need for fancy `einsum` here.
Answer: In [489]: for elem in b:
     ...:     print(a.dot(elem))
     ...:
[ 2 -1  3]
[ 5 -4  6]

first step - you are iterating the first dimension of b, and expecting that in the result as well:
np.einsum(',i->i', a, b)

dot pairs the last dim of a with the only dim of elem, the 2nd dim of b - and sums them:
np.einsum(' j,ij->i', a, b)

Now fill in the first dimension of a, which passes through as the last dim of the result:
In [495]: np.einsum('kj,ij->ik', a, b)
Out[495]:
array([[ 2, -1,  3],
       [ 5, -4,  6]])

Switch the arguments around, and a regular 2d dot product appears:
In [496]: np.einsum('ij,kj->ik', b, a)
Out[496]:
array([[ 2, -1,  3],
       [ 5, -4,  6]])
In [497]: b.dot(a.T)    # b@(a.T)
Out[497]:
array([[ 2, -1,  3],
       [ 5, -4,  6]])


How to 'normalize' data to account for level at baseline?

Question: In the beginning of an experiment, subjects are required to report on their initial emotions / mood using Questionnaire#1. After the experiment is conducted, the subjects fill another mood questionnaire#2.
How do we interpret these two sets of data (from the initial questionnaire and the final questionnaire)?
Since it is not possible for every participant to have the same initial emotions or level on the Likert scale (which goes from strongly disagree to strongly agree) at the start of the experiment, how do we analyze the data to "normalize their emotions" from questionnaires.
Comment: I still don't understand your question. What are you trying to get at? **What's your specific research question?** For example, I don't know if the interest is: in questionnaire #2 but accounting for the fact that there were pre-existing differences in emotions at time 1; in change over time in emotions scores; or in having the two sets of scores on a same scale (though it sounds like they both were measured on the same Likert scales).
Comment: 1) Why did you add the `missing-data` tag? 2) I still don't understand your question. In my very first comment, I offered 3 possible research questions, and you didn't pick either of them. What is your **research** question? Why did you measure emotions? What's your experiment? What are you trying to get at?
Comment: seems to me that the word "normalize" in the title and question is the wrong word and confusing people. You want to analyze the data in a way that takes into account differences among individuals on the first questionnaire. Is it correct to say that your goal is to describe/quantify how much the reported emotions change between the two questionnaires?
Comment: Let me clarify. Since there are initial data about baseline emotions and final data, I don't believe that I should ignore the initial data, and consider the final data of how the participants were feeling at the end of the experiment. My question is how do we analyze the data - given that we should account for the initial data that relate to baseline emotions as well. My reasoning is that not all participants are on the same level on the mood scale or have the same emotions at the start of the experiment, that is why they have to indicate their baseline emotions.
Comment: Can you please advise what is the best statistical method I should apply in this scenario to obtain their resultant or net emotions, at the end of the study. This has been referred to as normalizing data by some researchers, which is beyond the scope of my understanding. Thanks –
Comment: At this point, the goal of this study is to evaluate (measure) emotional responses of participants using subjective instrument like self-report questionnaire, in a controlled experiment. This forms part of the bigger picture to answer my main research question on user experience. At this point, I would like to know how the initial data of baseline emotions and the post-experiment data of emotional responses should to be treated. I cannot ignore the baseline emotions, and solely consider the post-experiment data, as I am afraid I won't be reporting the "true emotions" accurately.
Comment: I apologize if I used the wrong term "normalize" however when I read a research article, the author mentioned that he had to normalize the data before proceeding to the analysis of initial (baseline emotions reported) and the post-experiment data.I believe you have a sense of what I imply by now. How do I proceed with those two sets of pre-test and post-test data, as it is clear that initial baseline emotions are not necessarily neutral or similar for all participants. In fact, the post-test emotional responses are affected by the stimuli, and by their baseline emotional state (initial data).
Comment: My pertinent question is whether performing an ANCOVA will help me analyze the above data, as it will take care of the initial (baseline) emotions data. Or is there another statistical method I should use to obtain an accurate "resultant" emotional responses (post-test). If I ignore the baseline data, I am afraid that the just analyzing the post-test data won't be true and accurate, due to the influence of the baseline mood or emotion of the subject, prior to the experiment.
Comment: When you say "experiment", what do you mean? You have 2 groups, treatment vs. control? If so, then yes, ANCOVA with factor=experimental group, covariate=baseline emotion, and dv=post emotion. If all your participants took part in the experiment (i.e. you have an experimental group and no control), then matched-pairs t test.
Comment: Indeed, The same subjects will be taking part in two different experimental conditions: controlled experiment and manipulated experiment. Thanks
Answer: The analysis method you are looking for is called Mixed Models for Repeated Measures. See this similar question Which statistical analyses should I use?
Briefly, the data are model as:
$$\mathbf{Y} = \mathbf{X}\beta + \mathbf{Z}\mathbf{u} + \varepsilon$$
Where $\beta$ is a vector of fixed effects, and $\mathbf{u}$ is a vector of random effects. The random errors $\varepsilon$ have have covariance matrix $\mathbf{R}$ and the random effects $\mathbf{u}$ have covariance matrix $\mathbf{G}$. The variance of $\mathbf{Y}$ is then $\mathbf{ZGZ' + R}$. A brief overview can be found in its Wikipedia entry. An introduction to Mixed Models is typically a one semester course at a university.
This model addresses your problem because each subject has their own $\mathbf{R}$ matrix (which can have many different covariance structures - such as unstructured, compound symmetry, autoregressive, and more - a structure that is common for all subjects).
Comment: This is a good suggestion, but given the OP's evident level of statistical sophistication is likely to be too advanced.
Comment: Thanks for prompting me to the right direction. Is mixed model different from ANOVA?
Comment: You might think of it as an extension to ANOVA.
Comment: Is it a Mixed ANOVA of within-subject test that I need to carry out?
Comment: So I understand that I should conduct an ANCOVA; need to treat the baseline emotional responses as a covariate. Kindly advise
Answer: I don't think the Mixed Models for Repeated Measures and include the the baseline emotional responses as a covariate is a right way to solve your question, since it seems that you do not have a control group. only you have two groups, you can treat the baseline emotional response as a covariate to adujst the this potenial confounding factors between groups.
Comment: It seems from the OP's last comment on his question that he does have a control group, and that the design is in fact a repeated-measures one, where all subjects did both the experimental and the control condition.
Comment: Thank you for your explanation. and I want to consult you a question that can I adjust some confounding factors using some statistical methods for a uncontrolled prpspective study design.
Comment: I want to consult you a question whether I can adjust some confounding factors using some statistical methods for a uncontrolled prpspective study design. For example, I found the patients with depression had a lower serum BDNF levels after 8 weeks antidepressant treatment, and how can I adjust some confouding factors such as baseline severity, the length of disease to interpret the treatment effect. Thanks!


admin/content/comment/approval -> 410 Gone error (linked from content -> comments -> unapproved comments)

Question: I have no idea when this happened (I've been trying to fix Mollom + PostgreSQL, to the point where I tried, and removed, some core patches), but when I go to Content / Comments / Unapproved Comments (which leads to admin/content/comment/approval) I get a 410 Gone error.
Was this supposed to be a view? How does one recreate such core views? Is the link the result of some module long since uninstalled?
Answer: You could try installing the module
admin_views
As well as converting core administration pages (admin/content/node, admin/people etc.. ) to use VBO, it will add a view to admin/content/comment/approval
Recommended.
Comment: So *perhaps* I ended up with the `admin/content/comment/approval` link because I had VBO in the past (but uninstalled it at some point)? Note, I'd be perfectly content to restore the "Unapproved Comments" link to whatever it was before VBO
Comment: Finally got around to testing. VBO doesn't fix the problem; additionally a pristine installation has the same URL working. So this answer does not work
Answer: The problem was a RewriteRule (written by me) attempting to get rid of the non-numeric comment error (https://drupal.org/node/1838338). I didn't count on the admin/comment/approval path


Parse.com always returns a maximum of 100 records, same having "limit = 1000"

Question: I have an iOS app that receives data from the PARSE.COM.
How did not know nothing about 'parse.com' , I used the tutorial "http://www.raywenderlich.com/15916/how-to-synchronize-core-data-with-a-web-service-part-1".
The synchronization occurs only from the server to the device (iOS), and one time the object is added to the device, it should not be inserted again.
Turns out I got 131 objects in a class and 145 in another, but the Parse.com always returns me the first 100 items, even those already are in the device (iOS).
The worst thing is that in my code I have a variable "limit" in "request" that should work, but does not work for me.
I need your help, please ...
Code:
- (NSMutableURLRequest *)GETRequestForAllRecordsOfClass:(NSString *)className updatedAfterDate:(NSDate *)updatedDate
{
    NSMutableURLRequest *request = nil;
    NSDictionary *paramters = nil;
    if (updatedDate) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.'999Z'"];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

        NSString *jsonString = [NSString
                                stringWithFormat:@"{\"updatedAt\":{\"$gte\":{\"__type\":\"Date\",\"iso\":\"%@\"}}}",
                                [dateFormatter stringFromDate:updatedDate]];

        //That's line of 'paramters' is from original tutorial Raywenderlich
       // paramters = [NSDictionary dictionaryWithObject:jsonString forKey:@"where"];

        //This line was add for the autors of tutorial in a comment from your blog, and he say that has work, but not for me =(
        paramters = @{@"where" : jsonString, @"limit" : @(1000)};

    }
    request = [self GETRequestForClass:className parameters:paramters];
    return request;
}

The print of variable "request" after this method is this:
URL: https://api.parse.com/1/classes/Substancia?where=%7B%22updatedAt%22%3A%7B%22%24gte%22%3A%7B%22__type%22%3A%22Date%22%2C%22iso%22%3A%222014-09-23T02%3A13%3A01.999Z%22%7D%7D%7D&limit=1000

Why do same having the variable "LIMIT = 1000", the parse.com every returns me 100 items?
And even that returns 100 items, why do in the next time he does the "request" he it does not catch the next 100 since the other 100 registers earlier have already been entered?
Can anyone help me?
Comment: I have to ask: why are you using the REST queries in iOS? You could simply use the built-in iOS query system instead.
Comment: Generally speaking "limit" will only limit the number of results returned. There is probably another parameter to use to tell the server your offset.
Comment: Ryan, bacause i used an tutorial (raywenderlich)... =S
Comment: Ian. But if the limit is 1000 (for example) and I have 150 items in the server of PARSE.COM, this 150 items does not exceed the limit, then the "request" should bring 150 items, right?
The problem is that he always behind 100, and items are the same. =(
Comment: there are nice solutions in amany languages here: [How to retrieve more than 1000 rows from Parse.com?](https://stackoverflow.com/questions/17246991/how-to-retrieve-more-than-1000-rows-from-parse-com?noredirect=1&lq=1)
Answer: (Answering here since I don't have enough reputation to comment.)

For the limit=1000 not seeming to work: perhaps the "where" clause (i.e. constraining to items with updatedAt value >= 2014-09-23T02:13:01.999Z) is limiting results to less than 1000?
(To Ian's point) There is a 'skip' parameter that tells the API how many items to skip ahead, for pagination. i.e. limit=100&skip=100 to see page 2.
Comment: Gabby, thank you for your help.
- Apparently  not is this, because the date of the "last update" that I use in the "where" is lower than the "update date" of all 131 or 145 items I have in PARSE.COM.
So should be bring all, because they have not been updated yet on the device...
- I saw the clause "skipe" but it does not work for me because in my case I got the limit in 1000 on the "request" and only 145 items on PARSE.COM, then it is not overflow the limit. = (
Comment: Hmm some things to try: 1) Can you try LOWERING the limit to 50 and seeing if you indeed see fewer results? 2) Can you post the code for "GETRequestForClass:parameters" and also the code that handles the response from parse (if that is different); just to rule out that there's something going on there that applies a 100 limit
Answer: I'm not sure, but I think this is what you're looking for. A great solution on how to retrieve all the objects from Parse instead of the max limit i.e. 1000.