Product of functions of class $C^r$

Question:
Let $f,g:\mathbb{R}^n\rightarrow\mathbb{R}$ be of class $C^r$. Show that the function $h(\textbf{x})=f(\textbf{x})g(\textbf{x})$ is of class $C^r$.

I'm posting this as a reference for myself, so I'm answering my own question.
Answer: So I'm looking at $r=1$ first. That $f$ is of class $C^1$ means that for each $i=1,2,\ldots,n$, $$\lim_{t\rightarrow 0}\dfrac{f(\textbf{a}+t\textbf{e}_i)-f(\textbf{a})}{t}$$ exists and is continuous. The same goes for $g$. Then we must prove  the same for $h=fg$. The limit in question may be rewritten as $$\lim_{t\rightarrow 0}\dfrac{f(\textbf{a}+t\textbf{e}_i)(g(\textbf{a}+t\textbf{e}_i)-g(\textbf{a}))+g(\textbf{a})(f(\textbf{a}+t\textbf{e}_i)-f(\textbf{a}))}{t}$$ which is equal to $$f(\textbf{a})\lim_{t\rightarrow 0}\dfrac{g(\textbf{a}+t\textbf{e}_i)-g(\textbf{a})}{t}+\lim_{t\rightarrow 0}\dfrac{f(\textbf{a}+t\textbf{e}_i)-f(\textbf{a})}{t}g(\textbf{a}) = f(\textbf{a})D_ig(\textbf{a})+D_if(\textbf{a})g(\textbf{a})$$ so it exists and is continuous.
Now perform induction on $r$. Assume the statement holds for values less than $r$, and we'll prove it for $r$. We must show that $D_ih$ is of class $C^{r-1}$ for all $i$. But we know $D_ih(\textbf{a})=f(\textbf{a})D_ig(\textbf{a})+D_if(\textbf{a})g(\textbf{a})$. These terms are of class $C^{r-1}$, so by the induction hypothesis, their product is $C^{r-1}$, and their sum is also $C^{r-1}$ (not hard to prove), so the total is $C^{r-1}$, as desired.

Product of functions of class $C^r$


Textbook vs real world explanation of loudness perception

Question: I read that if you double the number of instruments playing, i.e double the amount of acoustic energy, then the perceived loudness rises by 3 dB. I've also read that a 3 dB change is almost imperceptible.
However, two trumpets playing at the same time seems considerably louder than just one.
Can someone explain?
At least one of these three statements must be false:

Double the acoustic power and the sound volume rises by 3 dB
A 3 dB change in volume is imperceptible
two trumpets playing exactly the same thing are considerably louder than just one trumpet playing alone.

I wouldn't be surprised if I'd mixed up physics, which is about experiments and actual physical measurements, with psycho-acoustics which is about the perception of sound, and hence not measurable in the same way.
Comment: I suspect you've confused  3dBA, an absolute (and very faint) sound level, with a 3dB **change** in sound level.
Comment: This question needs some work on rewording.  You are citing several sources of information that seem contradictory.  Please state where you found this info.  Is one a physics book and the other a sound system or recording magazine?
Answer: First of all you have to have a technical definition of "loudness" before the question makes sense.  I will try to add to this with some "textbook" info and I hope it clarifies things but the question may need modification as more info comes in.
From a purely physics based point of view we define, or associate, the loudness of a set of acoustic sources with amplitude or power of the vibrating sources.  Power is proportional to the square of the amplitude.  Since sound is actually a wave the amplitudes add producing an interference pattern.  In an acoustic environment where there is reverb and background noise we add power to get the total power produced by the sources.
The Decibel scale is based on taking the logarithm of the total power, scaled by a reference power (in music this is usually the threshold of human hearing).  The formula is 10*log(P).  If you double the power (or more generally the argument of the log) you get ~3.0*(The dB of the original power).  This is a purely mathematical measure of the objective relative strength of two equal strength sources.  So the first problem in the question is "double the number of players".  To conclude that the loudness level is 3dB higher you are implicitly assuming that they are (1) all playing the same strength, (2) that the combination is incoherent, and (3) that you are in an environment where you are not sitting in a place of destructive interference.
The next point is that the human ear and brain work non-linearly.  For you to perceive that the situation is 3dB higher (twice the power) the combined music sources need to trigger your audio detectors (ears+brain) to perceive the change.  This is partly objective and related to the response curve of the ear, and partly subjective related to the ability of someone to judge what is "loud" relative to a set of linear devices set up to measure power.  So it is entirely possible to set up a controlled experiment where a person sits in a room listening to 1, 2, 4, 8, equal sources and doesn't necessarily judge the results as increasing by 3dB each time.
Factors that affect perception of loudness include (1) saturation of of ear and its lack of ability to respond to increased amplitude, (2) placement of the sources (you could be sitting in a dead spot), (3) psycho-acoustic effects, (4) the actual frequency of the instruments.  The last one is very interesting.  If you produce tones with a scientific device, one low pitch and the other high pitch (say 55Hz, and 1500Hz) both at exactly the same power, most humans will say the bass note is quieter than than treble note.  So the second issue with your proposed question is the comparison of "two trumpets" versus "3dB is almost imperceptible".  Without knowing the situation the statements about doubling trumpets and 3dB is imperceptible are meaningless.  The later could be true when the instruments are not perceptible over background reverb in a room, or if the situation is 2 basses playing in low register at piano or mezzo-piano (not perceptible in the first place, relative loudness is very hard to judge).
So in short scientific measure of loudness and human perception of loudness do not match in general.  Even when they should (in frequency bands where most humans perception matches objective measure) environmental factors can cause wild variations in response to the question.  Since acoustics is a field that travels through space the "power" at the sources will not equal "power" at the ear.
Edit (addition).  Another cause of ambiguity is that the power that reaches your ear will attenuate, 1/R^2 loss.  This is geometric spread.  So when you "add a trumpet" to the band if one of them is farther way from you than the other the combination will not be twice as powerful at your ear.  This is part of the wave nature of sound.  To get the correct combination a person needs to weight the powers by the inverse of the distance squared.  Even if they blow the same note with equal strength the combined power at the ear will not be 3dB higher.  Again, there is a bit of ambiguity in the distillation of the items you have presented.
Comment: "power that reaches your ear will attenuate, 1/R^2 loss" - that is *not true* in most real-world listening situations. For example, in a room, almost all the sound that you hear is *reflected from the walls, floor and roof*, not coming direct from the instrument. Even out of doors, you get reflections from the ground and from buildings, trees, etc, and refraction of sound energy radiated "upwards" into the air, because air temperature and wind speed both vary with the  height above the ground.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/79874/discussion-between-jdjazz-and-ggcg).


How can I print out "AB\nCD" on the console without going to a new line?

Question: I want to print these things on the console

AB\nCD
AB\tCD
AB\bCD
Comment: Did you try anything?
Comment: You can print literal ```\n``` using ```\\n```. etc.
Answer: Escape the backslash:
System.out.println("AB\\nCD");
System.out.println("AB\\tCD");
System.out.println("AB\\bCD");

Testing:
public class Test {
     public static void main(String []args){
        System.out.println("AB\\nCD");
        System.out.println("AB\\tCD");
        System.out.println("AB\\bCD");
     }
}

Output:
$javac Test.java
$java -Xmx128M -Xms16M Test
AB\nCD
AB\tCD
AB\bCD

Edit:
Code available here:
http://tpcg.io/3KKGIP
Comment: Yes it does....
Comment: @ThisuraThenuka How are you using it? https://ideone.com/uRajCd seems to confirm it works.
Comment: My bad bro. I am sorry. You are right
Comment: If I had a penny everytime I heard someone say that to me......................


Border radius em tabela com border collapse

Question: Tenho o seguinte código:

table {
  border-collapse: collapse;
}

.item1, .item2, .item3 {
  border-top:1pt solid black;
  border-bottom:1pt solid black;
}
.item1 {
  border-left:1pt solid black;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}
.item3 {
  border-right:1pt solid black;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}

   I
    X
    Y
    Z
    K

   X
    A
    B
    C
    Y

   I
    X
    Y
    Z
    K

Resultado obtido:

Resultado desejado:

Perceba que minha tabela usa border-collapse: collapse o que tem impedido de deixar as bordas arredondadas com border radius. Como posso resolver esse problema?
Answer: Utilize border-spacing:0 ao invés de border-collapse: collapse.

table {
  border-spacing:0;
}

.item1, .item2, .item3 {
  border-top:1pt solid black;
  border-bottom:1pt solid black;
}
.item1 {
  border-left:1pt solid black;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}
.item3 {
  border-right:1pt solid black;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}

   I
    X
    Y
    Z
    K

   X
    A
    B
    C
    Y

   I
    X
    Y
    Z
    K


The equation of a line reflected about another line

Question: I need to find the equation of this reflected line:
Comment: Use orthogonal projection matrices and reflection matrices. Hint: the orthogonal projection of a point $x$ onto a vector $v$ is $\frac{vv^T}{v^Tv}x$. The reflection of the point $x$ about the vector $v$ is $2\frac{vv^T}{v^Tv}x-x$.
Answer: The General Formula for finding the equation of the line when the line $Ax+By=C$ is reflected at the line $Dx+Ey=F$.
$$y-k=\left(\frac{AE^2-AD^2-2BDE}{BE^2-BD^2+2ADE}\right)(x-h)$$
where
$$h=\frac{CD-AF}{BD-AE}$$
$$k=\frac{CE-BF}{AE-BD}$$
Where $(h,k)$ is the intersection of the lines.
If the lines are parallel, the slope becomes:
$$\frac{AE^2-AD^2-2BDE}{BE^2-BD^2+2ADE}=-\frac{A}{B}=-\frac{D}{E}$$
With equation:
$$y=-\frac{D}{E}x+\left[\frac{2F}{E}-\frac{AC\left(E^{2}+D^{2}\right)}{ED\left(A^{2}+B^{2}\right)}\right]$$
For horizontal lines $(A,D = 0)$:
$$y=\frac{2F}{E}-\frac{C}{B} $$
For vertical lines $(B,E = 0)$:
$$x=\frac{2F}{D}-\frac{C}{A} $$
This is easily derived by the use of perpendicular slopes and midpoint formula.
Comment: Are you sure of this formula? It nearly works, when applied to this situation https://math.stackexchange.com/a/4852511/109021, but the reflected lines don't have exactly the right slope (see the reflection of the orange line on the dashed orange axis)
Comment: *if the two lines are parallel then it $h=0$,$k=0$* -- But then the claimed reflection line is

$$y=\frac{AE^2-AD^2-2BDE}{BE^2-BD^2+2ADE}x$$

and so goes through the origin? This doesn't seem right? E.g. the reflection of $x=5$ in $x=3$ is $x=1$ which doesn't go through the origin. Please correct me if I'm mistaken or misinterpreted what you're saying.
Comment: The formula was incomplete. The premise was to use a arbitrary line perpendicular to the parallel lines to obtain points of intersection that would be used in the midpoint formula to get a point within the reflected line. Additionally, the initial error was that $k$ was used with $x$ and $h$ with $y$. I've corrected it now.
Answer: The equation for your reflected line can be constructed using the point-slope form, $y=m(x-x_Q)+y_Q$. The point $(x_Q,y_Q)$ is easily obtained as the intersection of your "mirror" line (the blue one) and the line to be reflected (the solid red one). This leaves the problem of the slope. To get you started, recall that if a line has slope $m$ and is at an angle $\phi$ from the $x$-axis, then $m=\tan\,\phi$. You can try using the sum/difference formulae for the tangent to derive the slope of the reflected line (the dashed red one) from the slopes $k_n$ and $k_m$.
Answer: Let's observe picture below. First of all note that $k_1=\tan\theta_1$ ; $k_2=\tan\theta_2$ and $k_3=\tan\theta_3$
Since dashed red line is reflection of the solid red line we may write next equality: $\alpha=\beta$ $\Rightarrow \theta_2-\theta_1=\theta_3-\theta_2$ . Now, if we apply $\tan$ on the both sides we get following: $\tan(\theta_2-\theta_1)=\tan(\theta_3-\theta_2)$ $\Rightarrow \frac{\tan\theta_2-\tan\theta_1}{1+\tan\theta_2\tan\theta_1}=\frac{\tan\theta_3-\tan\theta_2}{1+\tan\theta_3\tan\theta_2}$$\Rightarrow \frac{k_2-k_1}{1+k_2k_1}=\frac{k_3-k_2}{1+k_3k_2}$, so we can find $k_1$ from the last equation. Since $y_1=k_1x_1+C_1$ and we know that point $Z(x_q,y_q)$ belongs to the dashed red line we may write $y_1=k_1x_1+C_1$ and find $C_1$.
Answer: The parametric equation of the blue line is $Z+tr_b$, where $t\in \mathbb R$ and
$r_b=(1,k_n)$, the parametric equation of the red line is $Z+tr_r$, where $t\in \mathbb R$ and
$r_r=(1,k_m)$. Then the parametric equation of the red dotted line is $Z+tr_d$, where $r_d=(r_1,r_2)$ is symmetric to $r_r$ with respect to $r_b$ and $t\in \mathbb R$. Then
$|r_d|=|r_r|$ and $(r_d,r_b)=(r_r,r_b)$. That is $r_1^2+r_2^2=1+k_m^2$ and $r_1+r_2k_n=1+k_nk_m$.
Then $(1+k_nk_m-r_2k_n)^2+r_2^2=1+k_m^2$. This is a square equation with respect to $r_2$ and
one of its roots is $k_m$. Vieta's formula implies that the other root is $r_2=\frac{k_n^2k_m+2k_n-k_m}{1+k_n^2}$. Then $r_1=1+k_nk_m-k_nr_2$.
The canonical equation of the red dotted line is $(y-Y_q)r_1=(x-X_q)r_2$.
Answer: I'm going to write a proof of the formula written by William II.
When $l : Ax+By=C$ is reflected at $L : Dx+Ey=F$, the equation of the reflected line $l_r$ is given by $$\begin{cases}p(y-h)=q(x-k)&\text{if $AE\not=BD$}
\\\\x=\dfrac{2AF-CD}{AD}&\text{if $B=E=0$}
\\\\y=-\dfrac{D}{E}x+\dfrac{2BF-EC}{BE}&\text{if $AE=BD$ and $BE\not=0$}\end{cases}$$
where
$$k=\frac{CE-BF}{AE-BD},h=\frac{AF-CD}{AE-BD}$$
$$p=BE^2-BD^2+2ADE$$
$$q=AE^2-AD^2-2BDE$$
Proof :
Case 1 : $AE\not=BD$ and $B\not=0$
The intersection point of $l$ with $L$ is given by $P(k,h)$.
$Q(0,\frac CB)$ is a point on $l$. Let $R(s,t)$ be the reflection point of $Q$.
Since the midpoint of $QR$ is on $L$, we have
$$D\times\frac{s}{2}+E\times\frac{\frac CB+t}{2}=F\tag1$$
Since the line $QR$ is perpendicular to $L$, we have
$$\frac{-D}{E}\times\frac{t-\frac CB}{s}=-1\tag2$$
Solving the system $(1)(2)$, we have
$$s = \frac{2 (B D F - C D E)}{B (D^2 + E^2)},t = \frac{2 B E F + C D^2 - C E^2}{B (D^2 + E^2)}$$
The equation of $l_r$, i.e. $PR$ is given by
$$y-h=\frac{t-h}{s-k}(x-k)$$
We have
$$\begin{align}\frac{t-h}{s-k}&=\frac{B(D^2+E^2)(AE-BD)(t-h)}{B(D^2+E^2)(AE-BD)(s-k)}
\\\\&=\frac{(AE^2-A D^2 - 2 B D E) (BF-C E)}{( BE^2- B D^2 +2 A D E) (B F - C E)}
\\\\&=\frac{AE^2-A D^2 - 2 B D E}{BE^2- B D^2 +2 A D E}\end{align}$$
Therefore, we finally get
$$(BE^2-BD^2+2ADE)(y-h)=(AE^2-AD^2-2BDE)(x-k)$$
(this works even when $BE^2-BD^2+2ADE=0$)
Case 2 : $AE\not=BD$ and $B=0$
In a similar way as the one in Case 1, we see that the equation of $l_r$ is
$$2DE(y-h)=(E^2-D^2)(x-k)$$
Case 3 : If $B=E=0$, then the equation of $l_r$ is $ADx=2AF-CD$.
Case 4 : If $AE=BD$ and $BE\not=0$, then the equation of $l_r$ is $BDx+BEy=2BF-EC$.
Comment: (1) Are you assuming the reflection of a line in a line is a line? (2) Don't you also have to deal with the case where $B=0$?
Comment: (3) Don't you also have to deal with the case where $l$ and $L$ don't intersect?
Comment: @user182601 : Thanks. I edited the answer.
Answer: Let $l$ be the line $ax+by+c=0$. Let $m$ be the line $dx+ey+f=0$. Let $r$ be the reflection of $m$ in $l$.
When we reflect an equation in $l$, to get the new equation, simply replace each $x$ with $x-2a\frac{ax+by+c}{a^{2}+b^{2}}$ and each $y$ with $y-2b\frac{ax+by+c}{a^{2}+b^{2}}$ (see here).
So, $r$ is $$d\left(x-2a\frac{ax+by+c}{a^{2}+b^{2}}\right)+e\left(y-2b\frac{ax+by+c}{a^{2}+b^{2}}\right)+f=0.$$
Or (doing a bit of algebra), $r$ is
$$\left[\left(b^{2}-a^{2}\right)d-2abe\right]x+\left[\left(a^{2}-b^{2}\right)e-2abd\right]y+f\left(a^{2}+b^{2}\right)-2c\left(ad+be\right)=0.$$


Prove $\{0, 1\}^{\mathbb{N}}$ is uncountable.

Question: Prove that $\{0, 1\}^\mathbb{N}$ (the product of countably many copies of the two-point set) is uncountable.
Comment: ....$\,2^{\aleph_0}\,$ ...?
Comment: Binary numbers?
Comment: @Michael: If you're correcting the braces, why did you leave the ones after the `\mathbb`? It works perfectly well without any braces: $\{0,1\}^\mathbb N$.
Answer: Hint: Show that $\{0,1\}^A$ is the same thing as $\mathcal P(A)$; and use Cantor's theorem to show that $|A|<|\mathcal P(A)|$. Deduce the wanted conclusion.
Comment: this is a similar question to the one above: how would you  prove that the set of infinite sequences $\{0,1\}^{\mathbb{N}}$ that doesn't contain the continuum ${00}$ are not countable?

I was thinking that this question seems to be answered by Cantor's Diagonal by I can't think of the way to define the set  in order to defiantly have a function that won't be a in the set, in order to get a contradiction.
Comment: @Jneven: Do you know what a "base 1 representation" of a number is?
Comment: unfortunately, no
Comment: @Jneven: It's simply counting how many "1" appear in a row. So $5$ would be $11111$ and $10$ would be $1111111111$, and so on. If you have no consecutive $00$, that means you can use $0$ as a separator as encoding of stuff in base $1$. (In fact, even if you do have $0$, you can still do that.) So your binary sequence is really a sequence of natural numbers. Just note that some sequences will have a tail of $1$s, and you need to take care of these separately. But those are countable.
Comment: @Jneven: More to the point, diagonalization does not have to *really* follow a diagonal. You just need to make sure that at some point, your information is different from a given member of the countable sequence.
Comment: @Jneven: In particular, if $f_n$ is a sequence of binary sequences with no $00$, you can define $f$ to be $1$'s only, and change the $2^n+3$th coordinate to $0$ if and only if $f_n(2^n+3)=1$. This will ensure enough space is lying between the $0$s, and still let you perform the diagonalization.
Answer: Hint: Cantor's Diagonal argument.
Answer: $$\left|\{0, 1\}^\mathbb{N}\right| = \left|\{0, 1\}\right|^{|\mathbb{N}|} = 2^{\aleph_0} = \left|\mathbb{R}\right|$$
Comment: See also [Cantor's Diagonal Argument](http://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument) if you haven't yet encountered it.
Comment: Do any of these answers make sense, Cornelius?


Cyclic Quintic Polynomial Family

Question: Is there another known cyclic quintic family other than Lehmer's simplest quintic, which is well known? For instance, in this pdf, in section (4.2) when the parameters $(s_1, s_2, s_3, s_4)$ are set to $s_1=n+1, s_2=n+2, s_3=1, s_4=n+3$, Lehmer's simplest quintic is obtained. What is the two parameter polynomial when $s_1=n-1, s_2=-1, s_3=-1, s_4=n$? Thanks in advance.
Comment: see   http://math.stackexchange.com/questions/1996552/any-more-cyclic-quintics  That is a nice article. Gauss periods are done in modern terms in Galois Theory by Cox.
Comment: many, many examples in https://books.google.com/books?id=wt7lgfeYqMQC&pg=PR1&lpg=PR1&dq=reuschle++tafeln+complexer+primzahlen&source=bl&ots=VGZFPrfUBn&sig=MlQ667PqXaQ9rAvLWkG3_F1rwsk&hl=en&sa=X&ved=0ahUKEwiIwtSvm9TQAhUJ-2MKHXJIA_kQ6AEIODAE#v=onepage&q=reuschle%20%20tafeln%20complexer%20primzahlen&f=false
Answer: Such families are easily construct able now.
In this paper, specializing the parameters $v = 2n+1, w = 1, u = 0$ leads to
$p = n^4 + 2n^3 + 14n^2 + 13n + 11$
Certain linear transformations of the Gaussian Quintic of conductor $p$ lead to the family
$x^5 + (n^2 + n + 4)x^4 + (-2n^2 - 2n + 2)x^3 + (-n^4 - 2n^3 - 10n^2 - 9n - 5)x^2 + (-3n^2 - 3n - 2)x + n^2 + n + 1$
The discriminant of this polynomial is
$(2n + 1)^4(n^2 + n + 1)^2p^4$

Cyclic Quintic Polynomial Family


custom ui autocomplete edit to url

Question: i want to edit this code please:
the original code: (taken from http://designshack.net/?p=40354 )
$(function(){
var currencies = [
{ value: 'Afghan afghani', data: 'AFN' },
{ value: 'Albanian lek', data: 'ALL' },
{ value: 'Algerian dinar', data: 'DZD' },
];

$('#autocomplete').autocomplete({
lookup: currencies,
onSelect: function (suggestion) {
var thehtml = 'Currency Name: ' + suggestion.value +'
 Symbol: ' + suggestion.data;
$('#outputcontent').html(thehtml);
}
});
});

my edited code looks like:
$(function(){
var mydata = [
{ value: 'google exmple', url: 'http://google.com/' },
{ value: 'yahoo exmple', url: 'http://yahoo.com/' },
{ value: 'bing exmple', url: 'http://bing.com/' },
];

$('#autocomplete').autocomplete({

// edit here
// i want that when i click on suggestion = redirect me to url
// and the maximum number of suggestion that shown = 7

});
});

thanks.
Comment: Did you try something in place of `// edit here` ?
Comment: Create a jsfiddle please
Answer: Not tested
$('#autocomplete').autocomplete({

    lookup: mydata,
    onSelect: function (suggestion) {
      window.location.href = suggestion.url;
    }

});

Answer: Following your example you can simply redirect to the site on select. There does not seem to be any way to set the results limit.
var mydata = [
  { value: 'google exmple', url: 'http://google.com/' },
  { value: 'yahoo exmple', url: 'http://yahoo.com/' },
  { value: 'bing exmple', url: 'http://bing.com/' },
];

$('#autocomplete').autocomplete({
  lookup: mydata,
  onSelect: function(data) {
    window.location.href = data.url;
  }
});

custom ui autocomplete edit to url


How to prevent auto scroll in RecyclerView after notifyDataSetChanged?

Question: I have a RecyclerView with several items types. It looks like this:

07/21/2017
Message 1
Message 2
Message 3
07/22/2017
Message 4
New messages header
Message 5
Message 6

When new messages arrived I sort it by date and call notifyDataSetChanged(). It works well, but it automatically scroll my RecyclerView on new item(s) height. In this case I cannot use notifyItemInserted() because I don't know item position after sorting.
How to force RecyclerView do not scroll after notifyDataSetChanged() without call notifyItemInserted()?
Comment: Just wonder Why you don't want to call notifyItemInserted() ?
Comment: Because I sort items by date and don't know inserted item position(s) after sorting.
Comment: And your views can be changed from the beginning item, is that right?
Comment: Yes, if new item has smallest date.
Answer: There are 4 ways you can try. Because I don't know what is the height of your view, so I can't sure if it really works. But let give it a try
I. You don't which specific item could be changed. But you know the range of that change
mAdapter.notifyItemInserted(position);
mAdapter.notifyItemRangeChanged(0, list.size());

II. Clear list before call notifyDataSetChanged()
yourList.clear();
mAdapter.notifyDataSetChanged();

III. Save/Reset state of ReyclerView before/after adding new item
    // Save state
    private Parcelable recyclerViewState;
    recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();

    // Restore state
    recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);

IV. Use this function
mAdapter.notifyItemRangeChanged(0, list.size());

Comment: Bingo! solution # III worked for me while also using DiffUtil in my adapter. Thanks!
Comment: First method is great, exactly what I need!
Answer: Have you played with myRecView.getLayoutManager().setStackFromEnd(boolean) ?
If you can determine if the new item has been inserted after sorting above or below the visible part and in function of this call setStackFromEnd () with true or false maybe you can avoid the scroll.
I do not know if it will really work ....
Answer: You can know where the new item has been inserted using list.indexOf(yourItem) on your list of items. Then you can call notifyItemInserted()


Replace para html

Question: Daí Galera, vejam meu código:
<--php-->
$nomeusuario = print($_SESSION['nome']);
$html = str_replace('#NOMEUSUARIO#', $nomeusuario, $html);

<--html-->
Olá, #NOMEUSUARIO# seja bem vindo

O nome do usuário fica no topo da página, e não na tag  que gostaria. Como que substituo o #NOMEUSUARIO# para pegar a string 'nome' do print($_SESSION['nome'] não posso deixar o arquivo html em php, pois uso MVC.
Vejam abaixo como fica.

Obrigado.
Comment: Não entendi.
O que tem no $html antes do str_replace?
E a forma correta para atribuir o valor à variável $nomeusuario é:
$nomeusuario = $_SESSION['nome'];
Answer: Irei listar dois erros existentes:
1. Print():
Primeiramente neste caso o print não é correto, apenas remova.
<--php-->
$nomeusuario = $_SESSION['nome'];
$html = str_replace('#NOMEUSUARIO#', $nomeusuario, $html);

<--html-->
Olá, #NOMEUSUARIO# seja bem vindo

O motivo disso é simples.
Quando se usa o print estará literalmente exibindo o conteúdo.
Não entendeu?
Veja este exemplo:
$qualquer_coisa = print('meu_nome');

Isso irá exibir meu_nome no arquivo, geralmente no inicio uma vez que o html está depois dessa função. Mas, o resultado irá ser exibido onde é chamado.
E a variável $qualquer_coisa? Essa irá possuir o valor 1, CASO estivesse funcionando perfeitamente, o #NOMEUSUARIO# seria substituído por 1.
2. $html?!
Existe um detalhe, que não sei se foi criado por você ao postar a pergunta, mas estarei considerando um erro.
O que a variável $html possui? Nada.
Para solucionar aconselho fazer dois arquivos, por exemplo:
Um arquivo para salvar puramente o HTML:

/public_html/html_index.html ~ Exemplo, mas deixe antes do public_html!

Olá, #NOMEUSUARIO# seja bem vindo

/public_html/index.php

$nomeusuario = $_SESSION['nome'];

$arquivo = 'html_index.html';
// Caminho de exemplo!

$html = file_get_contents( $arquivo );
// Carrega o HTML, do outro arquivo.

$html = str_replace('#NOMEUSUARIO#', $nomeusuario, $html);

echo $html;
// Exibe o HTML, já alterado.

Por que isso?
O file_get_contents() irá obter o HTML do outro arquivo, que é puramente HTML, por isso o str_replace() irá justamente substituir o conteúdo que foi carregado anteriormente.
Comment: Não compreendi o porque fazer isso. Já tenho os arquivos html, só preciso fazer um replace de uma variável do php e jogar no html. Tipo assim.

No php --------------------------------------------------------------------------------

$nomeusuario = $_SESSION['nome'];

$html = str_replace('#NOMEUSUARIO#', $nomeusuario);

No html---------------------------------------------------------------------------------
#NOMEUSUARIO#
Comment: Você pode ter o HTML, mas ele não é mencionado. O PHP só pode manipular o que está setado. Não há como fazer a substituição sem que antes carregue o texto. Por exemplo: "Eu falo biscoito", se quiser trocar por "biscoito" por "bolacha" terá que PRIMEIRO definir alguma variavel para ter a frase "Eu falo biscoito". Caso contrario não há como definir. Logico, se tiver noção minima poderá fazer um `file_get_contents` no próprio arquivo e então "encontrar" o html (até mesmo fazer um `explode` básico no `<--html-->`) e então uma variável irá ter o HTML do arquivo. Mas isso vai depender de você.
Comment: Valeu pela ajuda amigo. Estou iniciando em php. Consegui fazer de outra maneira, com o menu sendo feito no php direto, na classe Menu. Não precisando carregar um arquivo html. Obrigado.
Answer: Olá. Você pode fazer para exibir o nome do usuário com o próprio php, desta maneira:

php

$nomeusuario = $_SESSION['nome'];

html

Olá, <?php echo $nomeusuario; ?> seja bem vindo

Comment: Não funciona no modo MVC, não posso alterar a estrutura do html.

Replace para html


Como alterar a legenda de um gráfico de linhas do Primefaces?

Question: Estou querendo mudar o tamanho da fonte e o quadrado da legenda de um gráfico do Primefaces via JavaScript.
Meu código:

Answer: Consegui, apenas acrescentei o código:
this.cfg.legend = {
    how : false,
    show : true,
    border : 'none',
    location : 'n',
    fontSize: '150%',
    renderer : $.jqplot.EnhancedLegendRenderer
}

Comment: Mas ainda não consegui aumentar o tamanho do quadrado da legenda


How can I compare performance of two logistic regression models after splitting into two the combined datasets relating to hospital mortality?

Question: I have data on patients with candidaemia and have analysed a range of predictor variables  associated with 30-day in hospital mortality using binary logistic regression in STATA version 14. I can also use SPSS Version 24.
One of the predictor variables  is location of this set of patients, i.e. hospital (Hospital A, Hospital B), referring to the hospitals where these patients were first seen and managed up to 30 days. These two hospitals function separately in terms of patients' management but are managed admistratively by one organisation (UK NHS Trust).
The analysis I have done is for all patients combined.
What I want to see is if the final models would remain the same(in terms of the vector of coefficients/predictabilty)  when I split the data into hospital A and Hospital B, according to the difference in  likelihood ratio tests performed on the two split samples. Would the patients in Hospital A versus Hospital B  behave the same in terms of mortality as defined?
I read around nested models and full models, less restrictive and more restrictive models, etc. But I am not sure how they can help me answer my question: As an example, what is the estimated probability of dying at 30-day for a patient aged 70 in Hospital A, and Hospital B? Are the probabilities the same or different according to the final models of the respective Hospitals?
Thank you for your help.
Answer: The most direct way to evaluate this is to include an interaction term for the hospital predictor with each of the other predictors, in a model of all the data. (I assume that hospital is already included as a predictor on its own in the model.)
Each interaction term will tell you how much the hospitals differ with respect to that predictor's association with outcome. For an overall test, you can do a likelihood-ratio test on two nested models, one with all the interaction terms and one without.
Doing separate models on the two split data sets isn't an efficient use of the data. You end up with less precision in the models because each only uses half the data. The two models aren't nested, as nested models mean that one model contains a proper subset of the predictors in the other model and both models are fit to the same data. Split models have identical predictors and different data.
If you do need separate results for the two hospitals, use the predictions from the combined model including the interaction terms. With binary coding of hospital, the single-predictor coefficients will be those for the reference hospital; you add each hospital interaction coefficient to the corresponding single-predictor coefficient to get the coefficients for the other. Be careful, as SPSS doesn't choose the same default reference levels for categorical predictors as other software (like R) does.


How Much Time spent on websites of user

Question: In website have many AUTHENTICATED USER. I want to how many times spent of each user on site.
I use login history module, it show only every login time of all user.
I use time spent module, but not track all time of every page.
Please suggest how to calculate time spent of each user on every login.
Comment: What do you mean by "time spent" exactly? If a user opens up a web page, then leaves it open for 24 hours, is that "time spent" on your site? If not, where's the cut-off? I think you need to define this a lot better if you want an answer that's going to address your actual problem. Otherwise people are just going to guess what you mean
Answer: Seems the Time Spent  module is what you're looking for

This module tracks, by Ajax, how long a registered user took to read a page and the amount of time he spent on the entire site.
You can configure which content type and role should be tracked and view the report, exhibiting the total hours (or minutes/seconds) a user spent reading a page and at the entire site.

Similar module -Time Tracker

Features

Track Time on any entity and or comments
Activities and Time Entries are now both fieldable entities.
Track time using time intervals (start and end times) or durations    (admin/settings/time_tracker)
Integrated Timer to track time as you go
Time estimating
User Time Sheets to display weekly logged time (user/%uid/time_sheet)
View for reporting on tracked time (time/report)
Comment: Time Tracker module only handle any node or any nodes comments
Comment: that what i say
Comment: @RiturajKumar Time Spent is that what you need but if you are very visitor it cause too load on your website performance.
Comment: Krishna Mohan, you solution is good. vote up. but he should care about performance.
Comment: @KrishnaMohan you're welcome,yes, you right

How Much Time spent on websites of user


Finding the structure of a group without using sylows theorem.

Question:
If$ |G|=pq $ and $p $ doesnt divide $(q-1)$ and $p <q$ then $G$ is cyclic.

My proof stands as this .I have used the fact that
$(i)$ If $|G|=pq$ then I showed that there will only be one element of order $p$ and one element of order $q$.
My approach in proving this part has been to show that if there are two elements of order $p$ say $x_1$ and $x_2$ , then say $H_1$ is a group of order $p$ generated by $x_1$ and $H_2$ is a group of order $p$ generated by $x_2$ .We assume that the intersection is {e} if not then we can get $H_1$=$H_2$(by property of subgroup).
Proving that the elements are distinct .
We assume that the elements $(x_1)^{i}.(x_2)^j$ are not distinct then $(x_1)^{i}.(x_2)^j =(x_1)^{i'}(x_2)^{j'}$.From here we can arrive at a contradiction as $H_1 \cap H_2 =e$.So if there are $p^2$ elements then we can arrive at a contradiction as $p$ and $q$ are both primes.
Similar results will hold in the case of $q$.
$(ii)$ Now  there is only one subgroup of order $p$ and one subgroup of order $q$ so they are both normal
$(iii)$ let $H$ and $K$ be two subgroups of order $p$ and order $q$.Then we know that $H \cap K={e}$.$H$ and $K$ are both normal .Then I showed that $x^{-1}y^{-1}xy \in H \cap K$ and $xy=yx$. So the order of the element $xy$ is $pq$.Where am I going wrong in my proof and since I have not used the fact that $p $ doesnot $q-1$.
Comment: You use the fact that $p \nmid q -1$ when you prove the uniqueness of the subgroups of order $p, q$ initially. You have to make use of the Third Sylow Theorem.
Comment: $p \lt q$ should be added.
Comment: While proving that  $H_1$ is the only subgroup of order $p$ did I use it ? I tried doing the proof without using sylows theorem.could you just tell me if my proof in the part where I am trying to show that there is only subgroup of order p is correct or wrong?
Comment: In cases like this it my be most instructive to look at a small example where your argument fails. Consider the case $p=2, q=3$ and the group $S_3$ of order $2\cdot3$. It has three subgroups of order two that I am sure you can describe. What happens for example when $x_1=(12)$ and $x_2=(13)$? The elements are $x_1^ix_2^j$ are distinct all right. There is room for these $4$ elements. But what is the contradiction with there being four distinct elements in a group of order six?
Comment: Yes right so is there a better way to use show that there is only one subgroup of order p without using sylows theorem or centre of the group?
Comment: I was trying to prove that if such a thing happens then we can have a subgroup of order $p^2 $generated by$ x_1,x_2$ , which is a contradiction
Comment: There is no reason why that subset of $p^2$ elements would be a *subgroup*.
Comment: @JyrkiLahtonen , Do you find a way in which I can improve my argument  to use the fact that $p  $ doesn't divide $q-1$ and come to a contradiction.I dont want to use Sylows theorem
Answer: As Gerry Meyerson pointed out, it does not hold in general as it is stated. You need to infer that $p \lt q$. Choose $Q$ a subgroup of $G$ of order $q$ (you can use Cauchy's Theorem for its existence!). Then $|G:Q|=p$ is the smallest prime dividing $|G|$ (ah yes here we are using $p \lt q$), hence $Q \lhd G$ (I hope you know this theorem ... see here for example).
Now $P$ acts on $Q$ by conjugation, but since $p \nmid q-1$ and Aut$(Q) \cong C_{q-1}$ (here we use that $q$ is prime), the action must be trivial: $P$ centralizes $Q$ and the other way around. Since $G=PQ$, $G$ must be abelian and the Chinese Remainder Theorem does the rest: $G \cong C_p \times C_q \cong C_{pq}$.
Bonus remark if $|G|=n$ and gcd$(\varphi(n),n)=1$, then $G$ is cyclic (as a matter of fact the only group of order $n$).
Comment: Yes true, Jyrki provided an answer there, but the point is if you are doing group theory and "blocking" yourself away from some well-known theorems, it will, not always, encompass some difficulties. But do not get me wrong: if you can do it simple(r) and non-conventional, I strongly support that!! As such your question is very good and I upvoted it! And the answer of Jyrki too!
Comment: I appreciate your answer but I think I have mentioned I dont want to use group actions and the 1st theorem you will not be able to prove without group actions...
Comment: @smita In a sense my answer runs along similar lines. Other than I don't invoke Cauchy nor that theorem :-) I just outline how you can reach essentially the same conclusions. As Nicky explained, $p\nmid q-1$ comes from the order of the group of automorphisms of $C_q$. I tried to write it in more elementary language, but the idea is the same (so +1).
Comment: Thanks a lot , I just wanted to see if there's another way to think about the problem . However I find I am making some basic mistakes ..
Comment: This is not a problem, that is why this site exists: you showed some original thinking of your own and people helped. You got at the time I wrote this 5 upvotes for your post. Excellent job and keep asking more questions like that!
Answer: An argument close to the OP's idea could proceed as follows. Fill in the details.

If $x$ and $y$ are elements of order $q$, then among the products $x^iy^j$, $0\le i,j<q$, there must be repetitions. This is because $q^2>|G|$. Show that this implies that the subgroup $H$ of order $q$ is unique. Let's fix a generator $x$ of $H$.
If $z\notin H$ has order $pq$ then $G$ is cyclic. Therefore the remaining possibility is that all such elements $z$ have order $p$.
Because $H$ is a unique subgroup of its order, $H\unlhd G$. Why does it follow that $zxz^{-1}=x^i$ for some $i, 1\le i<q$?
Why do we have $z^pxz^{-p}=x$?
On the other hand we also have $z^pxz^{-p}=x^{i^p}$, why? Why does this imply the congruence $$i^p\equiv1\pmod q?$$
It follows that the coset of $i$ in the multiplicative group $\Bbb{Z}_q^*$ has either order $1$ or order $p$. Why?
If the order of the coset of $i$ is equal to one, then $zx$ has order $pq$. Why?
If the order of the coset of $i$ is equal to $p$, why does it follow that $p\mid q-1$?
Comment: Basically using the known structure of the group of automorphisms of $C_q$.
Comment: @smita Correct. Or may be just the group $\Bbb{Z}_q^*$. You do know the order of that group from an earlier course, don't you?
Answer: If $|Z(G)|=p$, then the class equation yields: $pq=p+kq$, a contradiction because $q\nmid p$.
If $|Z(G)|=q$, then the class equation yields: $pq=q+lp$, again a contradiction because $p\nmid q$.
If $|Z(G)|=1$, then the class equation yields:
$$pq=1+mq+np \tag1$$
So, there are $np$ elements of order $q$, grouped in $n'$ subgroups of order $q$, and then:
$$np=n'(q-1) \tag2$$
Since by assumption $p\nmid q-1$, from $(2)$ follows $p\mid n'$, say $n'=n''p$, whence:
$$n=n''(q-1) \tag3$$
which plugged in $(1)$ gives: $$pq=1+mq+n''p(q-1)\tag4$$
But, from $(1)$:
$$1+mq=m'p \tag5$$
which plugged in $(4)$ yields:
$$q=m'+n''(q-1) \tag6$$ which implies $m'=n''=1$ and then, from $(5)$:
$$1+mq=p \tag7$$
a contradiction, because $q>p$.
Therefore $Z(G)=G$, namely $G$ is abelian, and hence (Cauchy) cyclic.
Answer: Consider the center $Z(G)$ of G. The center $Z(G)$ is a normal subgroup of $G$. In particular the order of $Z(G)$ divides the order of $G$ by Lagrange's theorem. So the possible orders of $Z(G)$ are $1,p,q $  or $pq$. Now look at the order of the quotient group $G/Z(G)$.
Comment: You need to explain how you rule out $Z(G)=\{1\}$.
Comment: Your reasoning makes perfectly sense, but you need to prove that $G$ *is* cyclic. You cannot assume that beforehand.
Comment: If $Z(G)=\{1\}$, then this means that $G$ is not an abelian group. Since every cyclic group is abelian,  $G$ is non-abelian implies that it is not cyclic. Does that make sense?
Comment: Yes, you are right. I need to employ third Sylow theorem. If $P$ and $Q$ are Sylow p-subgroup and Sylow $q$-subgroup of $G$ respectively, then by the given condition in question $P \trianglelefteq G$ and $Q \trianglelefteq G$. Furthermore $P \cap Q =\{1\}$. So $G\cong P \times Q  \implies G\cong C_p \times C_q $ which is abelian. So $Z(G)\neq \{1\}.$


DB2 - Foreign key constraint length generated by juplo/hibernate4-maven-plugin is too long

Question: I get the error below:
DB21034E  The command was processed as an SQL statement because it was not a
valid Command Line Processor command.  During SQL processing it returned:
SQL0107N  The name "FK_11CCTW7HP8CNTIYTKPMYGNBF" is too long.  The maximum
length is "18".  SQLSTATE=42622

when i run:
db2 'alter table adviserMediaContent add constraint FK_11cctw7hp8cntiytkpmygnbf foreign key (mediaContentId) references mediaContent;'

Sql is part of schema generated by juplo/hibernate4-maven-plugin.
Any idea how to shorten the constraint in the plugin?
Comment: You must be running a really old version; the 18 byte restriction on most object names was lifted I think in DB2 9.5 (if you are using DB2 for LUW).
Answer: Such names are generated by Hibernate. You can specify a constraint name with a @ForeginKey annotation (not JPA, but a Hibernate annotation).
In Hibernate 5 you can use a naming strategy to generate constraint names.


AWS Boto3 No Credential Error IAM role K8S

Question: I have a python script in our K8s cluster that is run as a k8s Cronjob every few minutes. The script checks the nodes in the cluster and if a node is unhealthy for more than 5 minutes, it terminates the node.
To connect to AWS I use Boto3.
requirement.txt
boto3==1.16.11
botocore==1.19.11

and the permissions are passed as pod annotations.
Annotations:  iam.amazonaws.com/role: arn:aws:iam::123456789:role/k8s-nodes-monitoring-role

The IAM role has arn:aws:iam::aws:policy/AmazonEC2FullAccess policy and a valid trust policy.
{
   "Version": "2012-10-17",
   "Statement": [
{
  "Effect": "Allow",
  "Principal": {
    "Service": "ec2.amazonaws.com"
  },
  "Action": "sts:AssumeRole"
},
{
  "Sid": "",
  "Effect": "Allow",
  "Principal": {
    "AWS": "arn:aws:iam::123456789:role/nodes.my-domain.com"
  },
  "Action": "sts:AssumeRole"
}
]
}

The problem that I facing is that on some occasions the script throws NoCredentialsError('Unable to locate credentials') error. This behaviour is not consistent as on most occasions the script has successfully terminates the unhealthy node and I can cross-check it against AWS CloudTrail events.
I can see in kub2iam logs that the Get request receives 200 but the Put request receives 403.
ime="2020-12-21T12:50:16Z" level=info msg="GET /latest/meta-data/iam/security-
credentials/k8s-nodes-monitoring-role (200) took 47918.000000 ns" req.method=GET
req.path=/latest/meta-data/iam/security-credentials/k8s-nodes-monitoring-role
req.remote=18.104.22.168 res.duration=47918 res.status=200
time="2020-12-21T12:52:16Z" level=info msg="PUT /latest/api/token (403) took 19352999.000000
ns" req.method=PUT req.path=/latest/api/token req.remote=22.214.171.124
res.duration=1.9352999e+07 res.status=40

Any help or idea about how to debug this will be highly appreciated.
Comment: There is some drama related to IMDSv2 [in #241](https://github.com/jtblin/kube2iam/issues/241); do you have a newer version than that, and have you already followed their troubleshooting steps?
Answer: I dont know kube2iam in detail, but maybe you should switch to a AWS native way called IRSA (IAM Roles for Service Accounts). You can find all necessary information in this blog post: https://aws.amazon.com/de/blogs/opensource/introducing-fine-grained-iam-roles-service-accounts/
Comment: thanks, will look into it and provide update.


Zabbix installed from package, but no SNMP or Web Scenarios?

Question: I'm new to Zabbix but I'm loving the capabilities.  I installed on a fresh server (Debian Jessie) using the package and from following the instructions here.  Today I just realized I don't have the capability to use the Web Scenario and SNMP functionality.  It looks like if I had downloaded and compiled from source, I could have enabled this using the arguments on the configuration step.
My question is:
Do I have to uninstall my current installation and compile from source to get this functionality? If so, should I expect having to start fresh (new db, configuration, templates, triggers, etc..)?
Also, am I correct in assuming that if I compile from source without uninstalling from package, not all files from the previous installion would be overwritten and I would have two side-by-side installations?
Answer: Most likely, both of those features are available. To verify, check your server logfile when it has been just started up - the feature entries should say YES.
Note that there is no separate menu entry for web monitoring since Zabbix 2.2 - this is now available in host & template listings.
Comment: You are correct - I see that everything is enabled but I don't have any options for web scenarios or monitoring... Weird.  I'll have to get back to Googling to try and figure out why.
Comment: You might have been looking at some older manuals and expecting the main menu entry, maybe? Included that bit in the answer, too :)
Comment: You were correct. I was looking in all of the wrong places..


Content:author Relationship Not Showing Fields for Comments View

Question: I have created a view to show a nodes comments in a block.
Authors on my site have different roles, and they can create a single business page. On that page, other users can leave comments.
For site authors that have a "Free Listing" role, I want to hide the ability for other users to post comments.
To do this, I have added a view to display comments, then added a relationship for Comment:Content, then a relationship for Content:Author.
In my previous experience, this should give me a field (Content)Author:Role to filter results by. Instead, I get no additional fields, just the standard Content:Author ID field, which then tells me..."If you need more fields than the uid add the content: author relationship", I have!!!
Have I uncovered a bug? Or am I missing something?

Any advice appreciated.
Answer: You need to filter for a User fields if I understand correctly (i.e. you want to display only comments on the current node when the node author has a certain role).
Select User: Roles as the filter and make sure the Relationship select box is set to the identifier for Content: Author. That will let you filter the comments by the node author's role.
Comment: Ah! I am a moron! That was staring me right in the face, but I just assumed it was for the role of the comment author. Thanks!


Is it possible to make R^n a field for n>2

Question: I know that real line is a field. And we can make $\mathbb R^2$ a field by defining complex operations. But can we extend this process? Is there any way to  make $\mathbb R^n$ field, at-least for some positive integer '$n$'?
In particular, using similar constructions, which we used to get complex field from $\mathbb R^2$, can we make $\mathbb C^2$ field? If yes, this means we converted $\mathbb R^4$ in to a field.
Comment: No. But see https://en.wikipedia.org/wiki/Quaternion and https://en.wikipedia.org/wiki/Frobenius_theorem_(real_division_algebras) .
Comment: Note that if $\Bbb C^2$ were a field properly containing $\Bbb C$, it would be a non-trivial algebraic extension of $\Bbb C$, thus contradicting the Fundamental Theorem of Algebra.
Answer: A division algebra is a ring in which every non-zero element has a multiplicative inverse (here multiplication is not necessarily commutative like in a field).
According to http://mathworld.wolfram.com/DivisionAlgebra.html the only finite-dimensional real division algebras occur for dimensions $n=1,2,4,8$.
If $n=4$ (quaternions) or $n=8$ (octonions) multiplication is noncommutative and there is no field structure. The proof of these facts are not simple.
However there is a short proof that if $n>1$ and $\mathbb{R}^n$ is a division algebra (or a field) then $n$ is not odd.
In fact, by the linearity of the multiplication, we can consider the map
$$L:\mathbb{R}^n\to \mbox{GL}(n,\mathbb{R})\cup \{0\}$$
such that $v\cdot w=L(v)w$. We have that $L(v)=0$ iff $v=0$. Moreover $L$ is linear and therefore continuous ($\mbox{GL}(n,\mathbb{R})$ is finite-dimensional).
Let $u$ be the neutral element of the multiplication and take a continuous path $\varphi:[-1,1]\to \mathbb{R}^n$ from $\varphi(1)=u$ to $\varphi(-1)=-u$ such that $\varphi(t)\not=0$ for any $t\in [-1,1]$ (use the fact that $n>1$).
Notice that $L(\pm u)=\pm I$ where $I$ is the $n\times n$ identity matrix.
Let $f(t)=\det(L(\varphi(t))$ then $f:[-1,1]\to \mathbb{R}$ is continuous, $f(1)=1$, $f(-1)=(-1)$ and by the Intermediate Value Theorem there is $t_0\in (-1,1)$ such that $f(t_0)=0$ that is $L(\varphi(t_0))\not\in \mbox{GL}(n,\mathbb{R})$. Contradiction.


jQuery print JSON element whose key value equals name of li class

Question: I retrieve a JSON object which contains the keys "options" and "message", whereas each options value has a corresponding li element in the document, for example [{"opt" : "12", "msg" : "red"}] exists a list element with class="12".
Now I want to do the following, when a user clicks the link inside on of the list elements, the value of the corresponding "msg" key should be displayed.
I have got it working up to the point that the message value of the first element of the JSON object is displayed on click, but it always displays message value of the first element in the JSON, no matter which link is clicked. I think has to do with the .attr(), but I am not sure.
What am I doing wrong?
Here is my code and the fiddle:
http://jsfiddle.net/F7PuA/1/
HTML

 Option 1

 Option 2

JS
$("#list li a").click(function () {

   var liclass = $("#list li").attr("class");

   var json = [{
       "opt": "12",
           "msg": "Red"
   }, {
       "opt": "37",
           "msg": "Green"
   }];

   $.each(json, function (key, value) {
       if (json[key].opt == liclass) {
           $(".message").empty().append(json[key].msg).fadeIn();
       }
   });
});

Comment: A better approach would be to use the data attribute to associate a unique numeric value to a DOM element.  Class attributes are intended for classifications.  ID could also work though it could get in the way of styling
Comment: Here is an approach that uses data attributes directly on the li elements: http://jsfiddle.net/m2jHt/
Comment: Thanks for the suggestion and the example, unfortunately I can't change the server side code but I will keep it in mind for future use.
Answer: You need to find the li in relation to the clicked a element, in this case you need to find the parent li of the clicked a.
You can use .closest() to do that
var liclass = $(this).closest('li').attr("class");

Demo: Fiddle
Answer: Your liclass initialization is always running on the list of li elements under #list, not the specific li that was clicked.  attr is returning the first class it finds.
Try:
var liclass = $(this).closest('li').attr("class");

Answer: You need to change the liClass to point to the clicked hyperlink.
var liclass = $(this).parent().attr("class");

Updated jsFiddle example.
EDIT: Perhaps you could just grab the number off of the href attr instead:
var liclass = $(this).attr('href').substring(1);

2nd jsFiddle example


Service to interface with sessions table?

Question: In my module, I need greater session control, beyond simple max_lifetime and other parameters taken from PHP config. What I did was to add a column to the sessions table that gives me the effective session expiration, which I can compare against to know if to revoke the session. (I also want to "cache" this in the local session, but this is unrelated to the question).
The question is, what is the best way to retrieve the new data from the sessions table? I can just send a direct DB query, such as:
Database::getConnection()->query('SELECT expires_at FROM {sessions} s WHERE s.uid = :uid', [':uid' => $uid]);

However, is there a built-in service for accessing this table, for greater abstraction?
Answer: You can make use of Dynamic Queries
instead of Database::getConnection()->query('SELECT expires_at FROM {sessions} s WHERE s.uid = :uid', [':uid' => $uid]);
You can do:
  // Create an object of type Select.
  $database = \Drupal::database();
  $query = $database->select('sessions', 's');
  // Add extra detail to this query object: a condition, fields and a range.
  $query->condition('s.uid', $uid, '=');
  $query->fields('s', ['expires_at']);
  $result = $query->execute();

Comment: Thanks for the answer :) I assume this means that there is no built-in service I can use specifically for the sessions table?
Comment: No i don't think so, as far as i now there is only **Database abstraction layer** you can check it here https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21database.api.php/group/database/8.2.x


Why doesn't specificity formula work for ten enclosed tags?

Question: According to the specification, second rule has more specificity and text must be blue, but it's red.

/** specificity =  10 */
.my{
     background-color: red;
}

/** specificity =  12 */
html body div b i strong em span font strike ul li{
      background-color: blue;
}

SUPER

Comment: Because `0,0,1,0 ` is NOT 10.
Comment: Specificity is more of a matrix and **not** a point system you can add up. Early on in web dev I made this same mistake. Selectors fit into four categories with higher weight give to those moving from the right to left. The total of one does not outweigh the total to the left unless that number is `0`, i.e. `0, 1, 0, 0` > `0, 0, 150, 0`.
Answer: See these rules from CSS Tricks:

For each class value (or pseudo-class or attribute selector), apply 0,0,1,0 points
For each element reference, apply 0,0,0,1 point

https://css-tricks.com/specifics-on-css-specificity/

Therefore your first example has 0,0,1,0 points. Whereas your second has 0,0,0,12 points.
0,0,1,0 > 0,0,0,12
Basically it doesn't matter how many elements you have referenced in your selector, if you don't have an ID or class referenced then your class selector will always win.

CSS Tricks
Answer: Second rule has more specificity only if the rule has the same hierarchy selector. If you have a class (which is more specific) it will take over.
You can use li.my:

/** specificity =  10 */
.my{
     background-color: red;
}

/** specificity =  12 */
html body div b i strong em span font strike ul li.my {
      background-color: blue;
}

SUPER


How to quantify the fluctuation of an error?

Question: First of all sorry for the bad title, but unfortunately, I can't think of a better one at the moment. Hopefully, that will change when my question is answered.
Let's say I have two sets of values:
The target values $T_i$ and the actual values $X_i$ and I want to quantify the errors $E_i=X_i-T_i$ using a single number. Due to the fact that I don't want negative and positive to compensate each other and the fact that I'd like to punish outliers, I decided to use the Root Mean Square Error $\text{RMSE}$.
Now the question: How can I quantify the fluctuation of the errors in a way that can be compared with the $\text{RMSE}$? My first idea was to use the standard deviation. After all, the $\text{RMSE}$ is a mean value and it is a plausible assumption, that the errors $E_i$ are normally distributed. However, I think the standard deviation is "incompatible" with the $\text{RMSE}$, because unlike the $\text{RMSE}$ it does not operate on the squared errors.
What are your recommendations?
EDIT: I'll try to make things clearer. What I want to do is to quantify the error of the $\text{RMSE}$. After all it is a mean, so there must be a way to tell how much the values, this mean is based on, fluctuate. Let's say I would use the $\text{MAE}$ instead of the $\text{RMSE}$. Then I could easily quantify the fluctuation of the absolute errors using their standard deviation. However, to apply the same approach to the $\text{RMSE}$, I would have to calculate the square root of the standard deviation of the squared errors, which seems a little odd to me.
Answer: From what I can make out, you have two requirements:

Ensure that positive and negative errors don't cancel out. So, you square the errors.
You want to punish the models which have large errors for some predictions (but possibly lower errors elsewhere) more than models which have no large outlier errors(but possibly higher errors elsewhere). This is done by, again, squaring the errors. The square really amplifies the outliers. (For example, a model with errors 10 and 0 has squared-sum-of-errors of 100 whereas a model with errors 5 and 5 has squared-sum-of-errors of 50).

If you notice, both your requirements imply the use of squared errors. Whether or not you take the root after summing the squared-errors has no impact on meeting the above requirements.
Comment: Thank you for your quick reply. Apparently, I did not describe my interest well enough. What I want to do is to quantify the error of the RMSE. After all it is a mean, so there must be a way to tell how much the values, this mean is based on, fluctuate. I'll edit my question a little to make things clearer.


How to give a 404 error for a http request to an ip address

Question: I have a fairly basic question.  Please be patient with me.
As an example, say I host "www.example.com" and "www.another-example.com" on a single server with an ip address of "22.214.171.124".
Here would be a typical apache configuration:
Listen 80
NameVirtualHost *:80

<VirtualHost *:80>
ServerName www.example.com
# Other directives here
</VirtualHost>

<VirtualHost *:80>
ServerName www.another-example.com
# Other directives here
</VirtualHost>

How do I return a 404 error code for a request to "http://126.96.36.199" without blocking all websites on the server?
Could you please include an example of an apache configuration directive I should be using?
Answer: First virtual host definition will be used as "catch all" in case if domain name in not known to Apache.
I know 2 solutions:

Create one more <VirtualHost> pointed into empty folder and make it listed above all other virtual host definitions.
Using mod_rewrite create a rule in first virtual host to return 404 response if %{HTTP_HOST} is an IP address.

Approach #1 is more logical and widely used. Approach #2 I would not use unless under some special circumstances.
Comment: I tried out solution #1.  It worked as advertised.  Thanks.
Answer: The first defined virtual host will answer queries for the bare IP address. You can also just include a named virtual host for the IP address itself and point that at a directory with whatever you'd like to return in it.


Pulling HTTP codes from a F5 Load Balancer

Question: My environment is 4 Ubuntu 14.04 servers running Nginx sitting behind an F5 Load Balancer. They are sending metrics to Datadog and also pulling metrics from the F5 via SNMP to send to Datadog as well.
The Dev team has a requirement to be able to monitor HTTP codes. I cannot pull them from Nginx on the server side, as that is only possible with Nginx Plus. I had thought about building out some in house solution with reading the access logs and what not, but don't really want to go down that road. So next I looked to the F5, but have been unable to grab them their either.
This OID returns a value of 0: sysStatHttpRequests::18.104.22.168.4.1.33184.108.40.206.2.1.56
Which I know is incorrect as I was sending about 1000 HTTP requests at the VIP a second. The following also returns values of 0:
sysFastHttpStatResp2xxCnt   220.127.116.11.4.1.33184.108.40.206.2.14.16
sysFastHttpStatResp3xxCnt   126.96.36.199.4.1.33188.8.131.52.2.14.17
sysFastHttpStatResp4xxCnt   188.8.131.52.4.1.33220.127.116.11.2.14.18
sysFastHttpStatResp5xxCnt   18.104.22.168.4.1.3318.104.22.168.2.14.19

SNMP is working as I am able to pull other metrics, such as throughput, connections, etc... Anybody have any ideas on how to pull HTTP code metrics in this environment? Or maybe I am completely missing something I need to setup on the F5 in order to do this.

F5 Big-IP 3900
Version: 12.1.1

EDIT: Solved my own problem. Had to provision AVR on the F5 then apply an HTTP profile to the virtual servers.
Answer: If you don't have the fastHTTP profile applied you won't see stats on that oid. Normal HTTP profiles use these oids:
[root@ltm3:Active:Standalone] mibs # snmptranslate -On F5-BIGIP-SYSTEM-MIB::sysHttpStatResp2xxCnt
.220.127.116.11.4.1.33126.96.36.199.2.4.3
[root@ltm3:Active:Standalone] mibs # snmptranslate -On F5-BIGIP-SYSTEM-MIB::sysHttpStatResp3xxCnt
.22.214.171.124.4.1.33220.127.116.11.2.4.4
[root@ltm3:Active:Standalone] mibs # snmptranslate -On F5-BIGIP-SYSTEM-MIB::sysHttpStatResp4xxCnt
.22.214.171.124.4.1.33184.108.40.206.2.4.5

And if I run ab 10k times against a local vip after resetting the stats and check the 2xx oid, I see:
[root@ltm3:Active:Standalone] mibs # snmpget -v 2c -c public localhost .18.104.22.168.4.1.33188.8.131.52.22.214.171.124
F5-BIGIP-SYSTEM-MIB::sysHttpStatResp2xxCnt.0 = Counter64: 10000

Comment: That was the main issue, I didn't have the HTTP profile applied =)
Answer: In order for the F5 to start gathering metrics in regards to HTTP response codes I had to provision the AVR module on the F5. Then I just need to simply apply the default HTTP profile to my pool of virtual servers. Statistics regarding HTTP codes we're then being tracked and I could pull those stats via SNMP and send them to Datadog.


How to perform a "left join" in Redis?

Question: Say I have a structure similar to reddit or stack overflow.
e.g. assuming that i have a json structure like
posts = [{id: 1, title: "foo", pages: 300}, {id: 2, title: "bar", pages: 300}]

votes = [{user_id: 1, post_id: 1, vote: "upvote"}]

how can i get a result similar to this (getting a post and attaching the users vote for this item, assuming it is known that the user_id is 1):
posts = [{id: 1, title: "foo", pages:300, vote: "upvote"}]

currently i am using an sql left outer join, but am trying to implement this using redis. i'm just having a hard time wrapping my mind around how to express this effectively in redis.
Answer: You could store the votes as a sorted set per user (with e.g. a score 1 for up and a score -1 for down):
# Register upvote for post 1
ZADD votes:user:1 1 1
# Register downvote for post 2
ZADD votes:user:1 -1 2

Fetching user 1:s vote for post 1:
ZSCORE votes:user:1 1
# => "1"

If you need to reference the votes the other direction (all votes for a given post) you could simply keep a similar set, e.g. votes:post:1, with the votes for that post. Or if you just need to keep track of the accumulated score, just keep a counter.

How to perform a "left join" in Redis?


Processar no servidor e retornar em um Input PHP

Question: Olá, eu estou fazendo uma calculadora em PHP e HTML, e eu queria que quando o usuário apertasse no submit, seja calculado no servidor, e o resultado retornasse no Input resultado, se você não entendeu, vou tentar explicar de uma forma mais básica:
Usuário Adiciona os números no primeiro e segundo campo de texto (Input) o resultado será calculado e irá aparecer no terceiro campo.
Queria fazer isso usando PHP, agradeço desde já.
Comment: O que você quer fazer deu pra entender perfeitamente, o que não dá pra entender é em qual parte você está com a dificuldade.
Comment: Qual a dúvida? Tem um problema com código específico?
Comment: Sim, eu queria saber como fazer isso
Comment: É uma tarefa relativamente simples, já tentou algo? Está com algum problema em um código que já desenvolveu ou é dúvida de como fazer mesmo? No segundo caso, recomendo dar uma revisada nos conhecimentos que você possui sobre a linguagem, quando estiver melhor acostumado, daí você tenta fazer algo
Comment: Eu estou aprendendo PHP, a minha professora ainda não me explicou sobre isso, mas se é tão fácil assim, vou pesquisar
Comment: Só um lembrete: É fácil se você já tem um base da linguagem, caso não saiba nada, recomendo aprender mais um pouco e depois tentar fazer
Comment: Mas você poderia me falar qual comando eu usaria?
Answer: Acho que uma forma bem simples de fazer isso seria (caso você não conheça muito bem ainda a linguagem), utilizar o xampp com apache para executar os arquivos.
Caso utilize o xampp, depois de instalado, basta adicionar seus arquivos e projetos no diretório C:\xampp\htdocs\ e dar um "start" no apache.
Bem vamos lá.
Crie um arquivo html que terá o seu formulário, como por exemplo:
<!DOCTYPE html>

    <title>Calculadora</title>
    <meta charset="utf-8">

     <form method="POST" action="calcular.php">
        Primeiro número:

        <input name="primeiro" type="text" value="" size="30"/>

        Segundo número:

        <input name="segundo" type="text" value="" size="30"/>

        Operacao:

        <select name="operacao">
          <option value="+">Somar</option>
          <option value="-">Subtrair</option>
          <option value="/">Dividir</option>
          <option value="*">Multiplicar</option>
        </select>

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

Bom o atributo "action" do form está apontando para outro arquivo, no caso um arquivo chamado calcular.php é nele que será feito toda a lógica da calculadora.
<?php
$primeiro = $_POST['primeiro'];
$segundo = $_POST['segundo'];
$operacao = $_POST['operacao'];

$resultado = 0;
if ($operacao == "+") {
    $resultado = $primeiro + $segundo;
} else if ($operacao == "-") {
    $resultado = $primeiro + $segundo;
} else if ($operacao == "*") {
    $resultado = $primeiro * $segundo;
} else if ($operacao == "/") {
    $resultado = $primeiro / $segundo;
}
echo $resultado;
?>

Para adicionar o resultado a um input na mesma tela só utilizando HTML, PHP, uma solução seria criar apenas um arquivo .php, por exemplo calcular.php e nele você terá tanto a lógica da calculadora quanto o formulário html, ficaria mais ou menos assim:
<?php
$primeiro = $_POST['primeiro'];
$segundo= $_POST['segundo'];
$operacao = $_POST['operacao'];
$resultado = 0;
if ($operacao == "+") {
    $resultado = $primeiro + $segundo;
} else if ($operacao == "-") {
    $resultado = $primeiro - $segundo;
} else if ($operacao == "*") {
    $resultado = $primeiro * $segundo;
} else if ($operacao == "/") {
    $resultado = $primeiro / $segundo;
}
?>
<!DOCTYPE html>

    <title>Calculadora</title>
    <meta charset="utf-8">

     <form method="POST" action="">
        Primeiro número:

        <input name="primeiro" type="text" value="<?= $primeiro ?>" size="30"/>

        Segundo número:

        <input name="segundo" type="text" value="<?= $segundo ?>" size="30"/>

        Operacao:

        <select name="operacao">
          <option value="+">Somar</option>
          <option value="-">Subtrair</option>
          <option value="/">Dividir</option>
          <option value="*">Multiplicar</option>
        </select>

        Resultado:

        <input name="resultado" type="text" value="<?= $resultado ?>" size="30"/>

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

Mas vale lembrar que exitem outras soluções como por exemplo utilizar ajax, js etc..
Se você estiver apenas no começo do mundo da programação aconselho a ir pelo simples e ir aprendendo passo a passo as coisas, conforme você for se sentindo mais a vontade pode experimentar outras soluções.
Mas o que foi alterado nesse exemplo comparado ao primeiro?
Vamos lá,
removi o valor do atributo "action" do formulário, pois ele apontará para a mesma página, ou seja será redirecionado ao clicar em "Calcular" para o calular.php novamente, porém como você terá preenchido os dados, é possível pegarmos via POST ou GET. E dessa forma eu consigo exibir o resultado através das tags  no formulário HTML.
Espero ter ajudado !
Comment: @KarenVicente recomendo dar uma lida [nesta](https://pt.meta.stackoverflow.com/a/5485/53279) publicação sobre as imagens
Comment: Certo, estou no aguardo! Muito obrigado mesmo
Comment: Mas tudo bem, embora eu gostaria muito de fazer desse jeito, eu fiz de uma outra maneira, obrigado mesmo assim!
Comment: Muito bom! Mas teria como eu colocar o $resultado dentro de um input no HTML?
Comment: Oláa, siim, só utilizando o HMTL e PHP existe uma forma, por exemplo utilizando o mesmo arquivo, dessa forma você manda o resultado para a própria página, vou postar um exemplo :)
Comment: @KarenVicente foi de grande ajuda! Mas um erro persiste, no input resultado, aparece: , ou seja, o código, e não o resultado :(
O que posso fazer?
Comment: @DetetiveVirtual você poderia mandar o seu código completo?
Já tentou assim?:
Comment: Aqui está o código https://pastebin.com/ePBaj6SS
Comment: @DetetiveVirtual
Olá!!
bom eu acho que o problema está no , você deve passar um atributo chamato "value" para cada option

Ex:
+, desta maneira basta utilizar o atributo "name" para pegar o valor selecionado $_POST["select"];:
Comment: Certo, vou mudar isso
Comment: Infelizmente, o erro persiste :(


Unsure what the elements of the A/R (equivalence class) in this question

Question:
I believe the elements of $A/R$ are $\{0,2\}$, $\{1\}$ and $A/R = \{\{0,2\},\{1\}\}$.  Continuing with the second part of the question, I believe that that set comes out to be
$$
\{ (\{0,2\}, 0), (\{0,2\}, 2), (\{1\}, 1) \}.
$$
But, since I am unsure about the first part, the second part may not be correct.
Comment: It may help to have the questions reworded for you into a bit more plain of English.  The first question is asking you to find the set of equivalence classes.  The second question is asking you to find all ways in which you can pick a single "representative" from each equivalence class.
Comment: that helps me understand it a lot better.  thanks!
Answer: The set of equivalence classes is correct.
Now you have to find the maps $f\colon A/R \to A$ such that $f(x)\in x$. A map $f\colon A/R\to A$ is determined by specifying the image of each element in the domain and there are nine of them.
If we set $e=\{0,2\}$ and $o=\{1\}$, we have some restrictions for a map to be in the set: we need $f(e)\in e$, so either $f(e)=0$ or $f(e)=2$; moreover $f(o)\in o$ is the same as $f(o)=1$. Thus we have just two maps satisfying the requirement.
If you want to describe the maps as sets of ordered pairs, the functions are
$$
\{(e,0),(o,1)\}\qquad\text{and}\qquad\{(e,2),(o,1)\}
$$
so your set is
$$
\bigl\{ \{(\{0,2\},0),(\{1\},1)\},\{(\{0,2\},2),(\{1\},1)\}\bigr\}
$$
Comment: thank you!  I forgot that it was asking for all the functions.


Where to override current_user helper method of devise gem

Question: How can i override current_user of devise gem.
Actually I need to add web services for mobile-app.
Currently devise is managing session and 'current_user' for web-application.
Now Mobile app will send user_id to the server.  I need to override current user like this
def current_user
  if params[:user_id].blank?
    current_user
  else
    User.find(params[:user_id])
  end
end

Should I need to modify devise gem as plugin ? or something else ?
Kindly explain in detail as I am new in rails.
Kind regards,
Comment: yikes... so, are you saying when a mobile agent sends up a user_id you'll just trust it?
Comment: Devise will handle that token_authenticatable - just passing authentication_token up, no need for user_id.
Comment: also some authentication secret key
Answer: According to the module Devise::Controllers::Helpers, current_user (together with all other devise helpers) is added to ApplicationController, which means that you can override it in this way:
# in application_controller.rb

def devise_current_user
  @devise_current_user ||= warden.authenticate(scope: :user)
end

def current_user
  if params[:user_id].blank?
    devise_current_user
  else
    User.find(params[:user_id])
  end
end

Comment: Error on the "alias_method" row: undefined_method 'current_user' for class ApplicationController (NameError), when starting up my environment. If I comment it out, boot up, and uncomment, it works fine. Got a fix?
Comment: Frexuz, try replacing the alias_method with something like:

def devise_current_user { @devise_current_user ||= warden.authenticate(:scope => :user) }
Comment: why alias current_user instead of calling super?
Comment: `alias_method` is better than calling `super` in case you'd actually need to acccess the original `current_user`. You may need it at some point (eg. `if current_user != devise_current_user #etc.`).
Comment: is this thread-safe? I'm getting nil errors in weird points in controllers after authentication on MRI.
Comment: What for @devise_current_user? What is that?
Answer: The other answer suggesting aliasing the method is actually not the best solution. Doug English's comment is the best solution:
# In ApplicationHelper
def devise_current_user
   @devise_current_user ||= warden.authenticate(:scope => :user)
end

Here's the reason:
Suppose you're including your ApplicationHelper in your controller. If you need a method in your ApplicationHelper that relies on devise_current_user, given the alias solution inside the controller, you're out of luck.
But with the explicit method definition above, you can move the definition to the helper and call it from other methods and you still get to include it in the controller.
This is useful, for example, when you're developing a user impersonation solution and you need to show two different users in the view, one for the real admin (devise_current_user) and the other, the impersonated user (current_user).
Comment: Indeed you are right. Please mention that the following should be included in the `ApplicationController `: `include ApplicationHelper`. Otherwise, `devise_current_user` becomes unknown.
Answer: Limbo-Peng's answer is great, but can be improved a little to make sure only admins can do this:
You'll need to also define a is_admin? method or is_admin attribute on the User class.
You may also want to use a different key than user_id, so it will never conflict with your regular parameters.
# to impersonate another user, e.g. for customer support
# only admins can do this..
#
alias_method :devise_current_user, :current_user
def current_user
  if ! params[:user_id].blank? \
     && devise_current_user && devise_current_user.is_admin?
    User.find(params[:user_id])
  else
    devise_current_user
  end
end

Answer: Assuming we can trust our session data (which relies on whether you put user input in there without proper authorization or not), this might work as a Concern:
module Concerns
  module ControllerWithImpersonation
    extend ActiveSupport::Concern

    included do
      helper_method :devise_current_user
    end

    def current_user
      if session[:impersonated_user_id].blank?
        devise_current_user
      else
        User.find(session[:impersonated_user_id])
      end
    end

    def devise_current_user
      @devise_current_user ||= warden.authenticate(:scope => :user)
    end

  end
end

I'm using this in a project for now.
A minor question (in the answer, sorry) ... should I be aware of any changes in Devise or Warden that make devise_current_user above outdated?


Help with a cello cadenza (Boccherini Concerto No 3 in G Maj)

Question: Here's a cadenza my daughter came up with, by mixing parts of the original score and changing them a little bit, e.g changing the key. She is unsatisfied with two things here. Maybe you could give me a hint how to fix this?
Instrument is cello.
The final goal is, starting at the end of measure 10, to move from minor (in fact its phrygian mode, isn't it?) to G major in measure 13. The notes given in green are mandatory and can not be changed, except for articulation of course.
A secondary goal seems to be to add a little bit of bagpipe feel :-) which she likes very much (me too) and Boccherini too. I think thats why she added the quote in measures 11 and 12.
She really loves her cadenza so if I could help her a little bit to fix the following two problems that would be of great help.
The first problem of interest is at the end of measure 10. The blue notes are a transition intended to glue that parts together. This transition doesn't work well.
Do you have some hints how to do this smarter? Can you explain to beginners, why it doesn't work?
The second problem of interest is the transition from minor to major from measure 12 to 13. This transition too doesn't sound smooth. It sounds like it is simply stuck together.
Do you have any suggestion how to improve the situation a tiny little bit here?
The notes in yellowish-olive color are an automatic function of musescore not relevant here, it indicates that these notes are more difficult to play due to their pitch.
Comment: What are the yellow notes? Looks to me like some range warning from the program, since all the notes above that A are yellow, but it would be better if this was explicit in the question, I think. Also you could explain what instrument is this for. And by cadenca you mean cadenza?
Comment: hey @coconochao, thank you for your comment. I edited the question taking all of your points into account. Yellow is kind of a range warning it indicates that the pitch is to high for beginners, but thats not the problem here. Instrument is cello and yes I mean cadenza. thx
Answer: The First Problem: This might just be a notation issue. It's somewhat unclear what is intended by the triplet marking under the group of blue notes. As written, the problem is that since our ears are attuned the preceding A-flats, the sudden appearance of A-natural creates an accent. By itself that's not an issue, but it comes in an especially weak rhythmic position. That intensifies the sense of accent to a jarring degree.
One fix would be to place the A-natural on the downbeat of the following measure. However, that is problematic for two reasons: 1) the preceding four notes would best become sixteenth notes (semiquavers), making for an anticlimax after the sextuplet and preceding the chromatic alteration, and 2) your daughter clearly wants the A-natural to anticipate the following downbeat.
I think the best, simplest solution is to remove the triplet indication, change the E-F-G-Ab to 32nd notes (demisemiquavers), and leave the A-natural as is. Since the preceding several measures have relative emphases on the half-beats, the chromatic anticipation on the half-beat of beat 4 of m. 10 works to my ear.
The second problem: The issue in this case is that the change from minor to major (specifically, B-flat to B-natural) is too abrupt, creating a dissonance. The minor sound is well established, and our ears don't have time to anticipate or adjust to the change to major.
The simplest solution here, I think, is to place a grand pause at the rest preceding the entry to the trill. This will create a sense of anticipation, and the change to major will be received as a pleasant surprise, signaling the end of the cadenza. In performance it will also help to slightly elongate the lead-in to the trill, especially the A immediately before.
Other solutions would require some degree of recomposition in order to create an expectation either of B-natural specifically, or major-minor or chromatic shifting more generally.
Comment: Allowing that your daughter has already come up with a solution, please consider posting it. I, for one, would be very interested to know.
Answer: Something like below may suffice.

You're going from C minor to G major. You want to cancel the flats. Bar 10 is a transition or bridge to G major. It's in modulation.
B11 creating some rhythmic momentum as there has been before, without this momentum will sound too dead. B13 creates an authentic cadence where the modulation to G is very solid.Clef change to bass at b13 might be ommitted looks a little strange. Key signature change after modulation / bridge, not before (otherwise like inviting people to party and no-one home!)


db_set_active() and node_save() not working as expected

Question: I'm writing a module to use on a multisite setup that enables nodes to be published to another site on the same installation.
Suppose I have Site A and Site B. I want this module to provide the ability to save a given node from Site A to Site B. Naturally, the way I have the database info set up in settings.php for Site A is as follows:
$databases['default']['default'] = array (
    'database'  => $db_name,
    'username'  => $db_user,
    'password'  => $db_pass,
    'host'      => 'localhost',
    'port'      => '',
    'driver'    => 'mysql',
    'prefix'    => $db_tables,
);

$databases['site_b']['default'] = array (
    'database'  => 'site_b',
    'username'  => $db_user,
    'password'  => $db_pass,
    'host'      => 'localhost',
    'port'      => '',
    'driver'    => 'mysql',
    'prefix'    => '',
);

...thus giving Site A the info it needs to access Site B's database.
When I execute the following code in the module via the hook_node_insert and hook_node_update hooks:
// Switch to Site B database
db_set_active('site_b');

// Save the node on Site B
node_save($node);

...it attempts to save the node on the current database instead, resulting in an SQL error (duplicate node ID). (Also, as a side note, I'm utilising a boolean property on the $node object to prevent the hooks and node_save() from throwing each other into an endless loop.)
I tried using drupal_get_schema(NULL, TRUE); directly after db_set_active('site_b'), but that made no difference. I've also cleared the cache in between every code change and test. No luck.
I don't know what's preventing it from working... maybe my $databases array is structured incorrectly?
Comment: I've tried to do the same exact thing in D6, with the same result.  After much testing, I came to the conclusion that hooks only work for the local site's DB.  I also couldn't pull data using the variable_get() method either... you might want to try to see if you can get ANY hooks to work on the remote DB.
Comment: Mine is working now (almost) - I can't quite pinpoint which change enabled it to switch database, but at a guess it's the "prefix" array, which I populated appropriately (pointing 'default' to 'site_b.'). I now face an SQL error every time I add a new node - e.g. `Duplicate entry '242-0-all' for key 'PRIMARY': INSERT INTO {node_access}`. Seems to be a conflict with the node ID, which is odd because it generates a new one...
Comment: OK, it turns out that my code wasn't properly updating `$node->nid` and `$node->vid` based on which site's tables were being manipulated at any given time - so basically **Site A** was receiving node IDs used by **Site B**. I think this is why it _looked like_ it wasn't switching DBs. I added in the necessary context-aware handling of the two properties and it seems to be fine now. P.S. I didn't add this as an answer as it isn't really an answer to my original question as such, but it solved a problem further down the line. :)
Comment: i am having the same exact problem, any solutions?
Answer: Here is some help:

The general format for the $databases array is as follows:
 * @code
 * $databases['default']['default'] = $info_array;
 * $databases['default']['slave'][] = $info_array;
 * $databases['default']['slave'][] = $info_array;
 * $databases['extra']['default'] = $info_array;
 * @endcode
 *
 * In the above example, $info_array is an array of settings described above.
 * The first line sets a "default" database that has one master database
 * (the second level default).  The second and third lines create an array
 * of potential slave databases.  Drupal will select one at random for a given
 * request as needed.  The fourth line creates a new database with a name of
 * "extra".

Are you sure Drupal can connect to the second database? Check your login credential, put some dummy table and do a db_query to verify they exist only in the second one.
Comment: It can definitely connect. Both databases are accessed with the same user, which has privileges on them both.

I've been working at it some more since asking the question and something I've done has caused it to semi-work - it now switches database as expected, BUT when I add a node, somewhere along the line it tries to write values to {node_access} on the CURRENT database instead (and fails - duplicate values). Really weird.
Comment: (NB - see my comment on the question for more clarification)
Comment: This is due to the db_transaction() at the top of node_save() firing up the transaction on the default database, unfortunately, you need to hack or patch core here...


Leitura uma matriz de um arquivo

Question: Estou querendo ler de um arquivo que possui uma matriz dentro, a quantidade de linhas e colunas e printar na tela, mas o meu programa não aparece nada, ele simplesmente para e não printa o número de linhas(counterL) e de colunas(counterC).
O programa está logo abaixo:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
A funcao abaixo tem como utilidade a alocacao dinamica de uma matriz
*/

int** alocaMatriz(int linha, int coluna)
{
    int i, j;
    int** matriz = NULL;

    for(i = 0; i < linha; i++)
    {
        matriz = (int**) malloc(linha * sizeof(int*));
        for(j = 0; j < coluna; j++)
        {
            matriz[i] = (int*) malloc(coluna * sizeof(int));
        }
    }

    return matriz;
}

/*
A funcao abaixo tem como utilidade a liberacao de memoria de uma matriz alocada
dinamicamente
*/

void liberaMatrizes()
{

}

int main (void)
{

    int aux, counterL = 0, counterC = 0;
    int** matrizRetorno = NULL;
    char* nomeArquivo = NULL;
    size_t tamanho = 0;
    FILE * ponteiro;

    getline(&nomeArquivo, &tamanho, stdin);

    nomeArquivo[strlen(nomeArquivo) - 1] = '\0';

    ponteiro = fopen(nomeArquivo, "r");

    while(fscanf(ponteiro, "%d", &aux) != '\n')
    {
        counterC++;
        if(fscanf(ponteiro, "%d", &aux) == '\n')
            counterL++;
    }

    printf("%d\n%d\n", counterL, counterC);

    matrizRetorno = alocaMatriz(counterL, counterC);

    fclose(ponteiro);

    liberaMatrizes();

    return 0;
}

Answer: Resultados vericados
Eu compilei o teu programa (depois das minhas alterações) e vou-te dizer que não funciona. A função que deves usar é fgets. Vê isto.
Solução
Para lermos um ficheiro utilizando o fgets fazemos um loop, ela retorna NULL quando não há caracteres para serem lidos ou EOF. O segundo argumento do fgetsé a quantidade caracteres a ser lido, normalmente o tamano da string que se passou. O terceiro é o apontador para o ficheiro. A função para de ler a linha quando encontra um \n, ou \0 ou o final do ficheiro EOF.
Então como fazemos as contas?
A quantidade de linhas vai ser o nº de linhas lido e a de colunas o máximo nº de caracteres lido numa linha. Neste caso escolhi 20, mas você pode mudar.
    char lido[20];
   while(fgets(lido, 20, ponteiro))
   {
       if(counterC < (strlen(lido)-1)) //Pois inclui o \n e o \0
   {
       counterC = (strlen(lido)-1);

     }
     counterL++;

    }

Para acrescentar
A função getline coloca o caractér terminador automaticamente.

getline() reads an entire line from stream, storing the address of
         the buffer containing the text into *lineptr.  The buffer is null-
         terminated and includes the newline character, if one was found.

Basicamente coloca o caráter terminador e um \n, se este for encontrado.
Resultado de compilação
Notar que utilizei um ficheiro que continha o seguinte:
ab
cv
ed

Este foi o output( teste é o nome do executável depois de compilado ):
C:\Users\NAMS\Desktop>teste
3
2

Comment: Mas eu não qual o tamanho de linhas e colunas do meu arquivo, a pessoa insere o arquivo txt e o meu programa conta
Comment: Não sei se leu o segundo link que mandei. Basicamente se o scanf falhar poderá deixar o seu apontador num local desconhecido trazendo problemas futuros. No caso do tamnho das linhas e colunas pode sempre criar uma string com um tamanho como 4098 ou 10240, duvido que alguem escreva tanto numa linha e se houver deve ser um troll.
Answer:     while(fscanf(ponteiro, "%d", &aux) != '\n')
    {
        counterC++;
        if(fscanf(ponteiro, "%d", &aux) == '\n')
            counterL++;
    }

Este é um ciclo infinito. O valor devolvido pelo primeiro fscanf() NUNCA vai ser igual a '\n'.
Cada membro da familia de funções scanf devolve o número de atribuições efectuadas (que pode ser 0) ou EOF em caso de erro. No teu caso, como tens apenas uma atribuição possível o valor devolvido vai ser um dos três { EOF, 0, 1 }
Suponho que o que queres fazer seja ler dois números do principio do ficheiro sem te preocupares com espaços em branco ou quebra de linhas.
Experimenta assim
   if (fscanf(ponteiro, "%d%d", &counterC, &counterL) != 2) /* erro */;

Leitura uma matriz de um arquivo


DropDownList in .NET WebApp - Is it possible to underline one or two items in list?

Question: I have been tasked to underline one or two items in a dropdown... is this possible and to have it display in IE?
Any advice, links, sample would be greatly appreciated.
Answer: You may checkout the following plugin.
Comment: I'll try it out. So far, I haven't been able to access it on my work station because it's a blocked site for some reason. I'll d/l it when I get home and will get back
Answer: You will probably have to hand roll your own javascript solution as this is not possible in the standard  html element it produces.
perhaps this jQuery plugin would do the trick: http://www.marghoobsuleman.com/jquery-image-dropdown
Answer: You can try the following, but not all styles work on list items:
<code>DropDownList1.Items[0].Attributes.CssStyle.Add("text-decoration", "underline");
</code>


Can I perform multiple Kruskal-Wallis tests with different explanatory variables against the same response variable?

Question: My data is observational data, and that's made it all kinds of ugly, and I can't decide what statistical test is needed. I have one response variable, which is categorical (Species 1, Species 2, or None). I have about a dozen explanatory variables, which are numeric (canopy cover, soil moisture content, etc.). I want to know which of the explanatory variables have a significant influence on the response variable. I cannot safely assume that these variables are independent, so I won't be using a multinomial logistic regression. I also don't want to use a principal component analysis, because I don't really care how my explanatory variables interact with each other (example, canopy cover might be correlated with soil moisture content; that's no shocker, and not really what I'm looking for; I want to know how those variables affect the presence or absence of the species). The data are not normally distributed, so that's a no on using anything that assumes normal distribution. I measured all these variables at 140 physical locations, but they are in groups of 20 points nearby each other, so I cannot assume the cases are all independent.
I am really struggling to find a statistical test that fits this situation. I'm thinking I could run a Kruskal-Wallis test comparing the response variable to each of the explanatory variables individually. Someone tell me if that's a big mathematical "no-no." Alternatively, I was thinking about running a PCA and only looking at the relationships that I am interested in (for example, if there is a statistical correlation between canopy cover and soil moisture, I don't really care; but if there is a statistical correlation canopy cover and the presence of Species 1, that is what I am looking for). Or is there another statistical analysis that fits better? Just about every test I find, my data violate at least one of the core assumptions.
Comment: Welcome to Cross Validated! What is your objection to multinomial logistic regression? I would consider that the starting point for seeing how various factors influence a categorical outcome.
Answer: Everyone's data always violates model assumptions! But the model can still be useful.
First, Kruskal-Wallis does not work when the response variable is nominal. Besides, an independent test with each variable will make a stronger assumption of independence than doing a regression.
In general, a regression model will work fine unless the explanatory variables are very highly correlated, and you will be able to tell from the output of the model if this is happening -- the standard errors will be way too big. If you need to convince someone else that this is OK, you can potentially use a diagnostic called the Variance Inflation Factor (VIF). First you run the regression model, then you calculate the VIFs from it and if any of them are really big, it means you have (near-)collinearity.
However, we should note that this isn't a world-ending problem anyways. The predictions made by the model (assuming it is correct and all that other stuff) are still accurate, just not the inference on the coefficients. To borrow an analogy from McElreath's Statistical Rethinking, imagine that the regression model is a robot that does a specific task. The regression robot is very good at fitting the model and figuring out the best linear combination of the variables that predicts the (link-transformed) response. But if the variables are collinear, it is not so good at figuring out which variable is more important, so it will give you some crazy numbers. Then it is up to you as a scientist to determine which variables are most important and how to detangle the effects, the robot can't do any of this part that requires critical thinking and domain knowledge.
Finally, to deal with the clustering. I am no expert on spatial data so I can't say too much about the clusters you have, but you can probably get away with using the cluster-robust sandwich variance estimator, which is very easy to implement in R. I highly recommend this blog post by Andrew Heiss for a thorough treatment of this issue. If you want to account for spatial autocorrelation within clusters, I'll leave that to you, but it can definitely be done in a multiple regression framework.


hook_node_view() is not working

Question: I am building a module for Drupal 8 which needs to use hook_node_view(). I tried the following code
<?php

/**
 * @file
 * Demonstrates the possibilities of forms in Drupal 8.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Node;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_form_alter()
 */
function demo_form_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  drupal_set_message(t('Found a form with ID %form_id', array('%form_id' => $form_id)));
}

/**
 * Implements hook_node_view()
 */
function demo_form_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
   drupal_set_message(t('its working'));
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Only alters the Search form 'search_block_form'.
 */
function demo_form_form_search_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['hello'] = array(
    '#markup' => t('Go ahead, try me ...') . '
',
    '#weight' => -1,
  );
}

I can't see any message from demo_form_node_view(). If the hook was correct, it should have shown the message. I am new to Drupal and I can't figure out why it is not working.
Comment: The hook the OP is using is still invoked from Drupal. It is just documented under `hook_ENTITY_TYPE_view()`.
Comment: Try to set parameters for hook_node_view as (array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode)

If it works, I would be grateful for upvoting :)
Comment: Did you clear your cache after adding that function?
Comment: I haven't found hook_node_view for Drupal 8 in [api documentation](https://api.drupal.org/api/drupal/8.2.x). Hovewer, there is a [hook_entity_view](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_view/8.2.x), which can be used instead hook_node_view.
Comment: @YakimkinRoman I just found out that hook_entity_view is working... But i don't know why is this happening? hook_node is still supported in Drupal 8 AFAIK
Answer: In Drupal 8, the core Drupal hook hook_entity_view() is only called when the entity is "being assembled before rendering". See the documentation at https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!entity.api.php/function/hook_entity_view
After the entity has been rendered, core Drupal will cache the rendered entity and serve the rendered entity from the cache when needed. The entity is not rendered every time it is used. So BY DESIGN hook_entity_view() will not be called again when the rendered entity is loaded from the cache, it will only be called when the entity needs to be re-rendered - that is, when the entity is changed and/or the cache of that entity is invalidated.
This behavior is different from the way it worked in Drupal 7 because Drupal 7 did not cache rendered entities like this.
Comment: Is there an alternative that fires on every pagview for a node_view during development?
Answer: This doesn't answer the question because the OP says he is building a module, but for others who stumble upon this question: I've found that this hook cannot be called from a theme. It must be called from a module. I could be wrong, but this has been my experience.

hook_node_view() is not working