Pandas DF referencing the same slice twice in the same computation

Question: I have a huge data set to process and I am trying to optimize the most costly line, processing wise.
I use a df with 3 columns, A, B and C.
I have 2 values, a and b, which are used to update the value of C in a subset of the df.
Before I continue, let me define a textual substitution to increase readability:
filter(_X) -> df.loc[df['A'] < a, _X]

Every time I type "filter", please substitute it with the text on the right (applying the correct argument in place of the parameter _X - think C/C++ macros).
The line of code in question is:
filter('C') += a * np.minimum(filter('B'), b)

What I'm not sure about is if python will process "filter" twice when evaluating the expression, or if it will use a "reference" (a-la C++) and only do it once.
In the former case, is there a way for me to rewrite the expression in a way to avoid the double execution of the code of "filter"?
Moreover, if you have suggestions on how to rewrite the "filter" itself, I'd be happy to test them.
EDIT:
Expanded version of the code:
df.loc[df['A'] < a, 'C'] += a * np.minimum(df.loc[df['A'] < a, 'B'], b)

Comment: is your textual substitution strictly for Stack Overflow purposes? as someone who only codes in Python the relation to C++ makes me lose my train of thought. This may be the case for others
Comment: Yeah, it was meant to help. I'm editing with an expanded version
Comment: So by your code, are you trying to filter your dataframe where `A` is less than some value `a`, then add the current values of column `C` with the minimum of column `B`? You may want to add a sample dataframe to show exactly what you want to accomplish as well :)
Comment: is `b` an array of some kind? [`np.minimum()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.minimum.html) returns the minimum value between two arrays.
Comment: For future reader reference: no, **b** is a scalar. I perform multiple passes (execution of the line in my post) over the df, each time **b** changes, but within a single pass it is a single, constant, scalar. np.minimum is able to handle the case of df-column vs scalar too.
Answer: If I understand correctly, you may not need to "filter twice" after the +=. see my example below:
np.random.seed(5)
df =  pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD'))

    A   B   C   D
0   99  78  61  16
1   73  8   62  27
2   30  80  7   76
3   15  53  80  27

Now if you wanted to add the values of the minimum of columns C and D to the current value of B that would simply be: df.loc[df['A'] < 80, 'B'] += np.minimum(df['C'], df['D'])
    A    B      C   D
0   99  78.0    61  16
1   73  35.0    62  27 #<--- meets condition 8+27=35
2   30  87.0    7   76 #<--- meets condition 80+7=87
3   15  80.0    80  27 #<--- meets condition 53+27=80

Notice how when A < 80. the B value changes with whichever value in C or D is smaller. One thing to note is that B turns to a float. Not sure why.
Comment: In my case the minimum is between df['C'] and a single scalar, but this detail does not change the solution. You answer is what I was looking for. Thanks!
Comment: I just tested your suggestion against my original code. Apparently it's faster to leave the code the way I initially wrote it, as without the second filter the code is way slower (I had to gave up on the processing after waiting 5 times the time, seeing it was still not done).
Comment: @Dirich, hmmm that's interesting! in my testing my solution tends to be faster. what is your `df.shape`?
Comment: I tested with a dataframe with 11 columns and ~20000 rows if I remember correctly (can't check until monday). Using a smaller dataframe (~5000 columns I think) resulted in a speed down of 1.5.


Why does the 7th of a dominant 7th chord have to resolve down in voice leading?

Question: To properly resolve a dominant 7th chord the 7th usually resolves down by step but by doing this I am not able to have a complete tonic chord. See here please:

In voice leading that D in the E7 chord would go down to C in the next Am chord but that would not give me a complete triad as I would have 3 roots so I did it this way and it sounds fine to me. Why does the same voice have to move to the C? the ear still gets to hear the C so  does it matter that the tenor is singing it?
Comment: The issue is less that the seventh resolves down and more the resolution of the tritone between the third and seventh. In this case, the tritone is an augmented fourth (between D and G#), which is expected to resolve "outward" to a sixth.
Comment: Also, if you consider how a singer would find this, it feels quite awkward to be the alto and bring that D up to E.  They will naturally prefer to resolve down and they might actually to it despite what you write because it's such a strong tendency tone.
Comment: In this case, I'd make the last chord A-A-C-A from the bottom.  You don't need the 5th in the final tonic chord.  Another possible resolution would be to omit the B in the E7 chord, doubling the E in the alto, and let the tenor voice move A-D-C
Comment: @Aaron... in writing it doesnt resolve as you say but the two resolved tones are still present in the chord just not in the same voices so the ear still gets what it wants. I doubt thay we perceive the difference. Am I wrong?
Comment: @armani Imagine one voice is cello and the other is violin or piano or trumpet. The difference would be clearly audible. There are circumstances where a dissonance can resolve in a different voice, but, in Common Practice voice leading, this isn't one of those circumstances.
Comment: Echoing nuggethead - try to actually sing that voice while playing the other ones - you'll likely find it quite awkward yourself.
Comment: ok Aaron so if the voices are played by different instruments but if they arent?
Comment: @Armani - then they aren't really different voices.  The whole idea of voice leading is learning to write for an ensemble of one note at a time instruments or voices.  What's happening on the piano is that you're really hearing a 5 voice texture where different notes are being doubled for different chords, and then it's fine.
Comment: @Alexander. I thought the idea of voice leading was to learn how music works. I have no intention of writing for an ensamble. Should I stop learning?
Comment: @armani - Music is a human, artificial, cultural phenomenon that is in no need of explanation besides perhaps an anthropological one.  What Western music theory - keep in mind all this theory is mostly useless for, say, Javanese gamelan - does is to give vocabulary for describing - not explaining - describing in detail most of the pieces of music written in Europe between roughly 1600 and 1900.  Most of that music is written for ensembles of one note at a time instruments (or voices).
Answer: The current answers have already addressed the issue, but I want to present a way of thinking about it that may be new:
The leading tone wants to resolve up, and the chordal seventh resolves down. These opposite tendencies actually work out such that, in order for both the V7 and the tonic to be complete chords, the leading tone must skip down to scale-degree 5. The only way for this to happen is if the leading tone is in an inner voice. In other words, if the V7 is complete and the leading tone is in in the soprano, the tonic must be incomplete.
Otherwise, all other possible combinations that begin with a complete V7 will lead to an incomplete tonic chord (meaning that it lacks a chordal fifth).
The corollary to this is that an incomplete V7, on account of its doubled tonic and missing chordal fifth, can lead to a complete tonic without having to skip the leading tone down.
Comment: This is a good observation. However, I do think music theorists tend to allow "frustrated leading tones" in inner voices mainly because of the obsession with Bach chorales, where Bach frequently prefers a complete chord at authentic cadences. Outside of this specific style, but I think we probably have "frustrated seventh" resolutions upward in inner voices about as frequently as we have "frustrated leading tone" resolutions, which is to say *not very much at all* on both counts. In keyboard textures and other textures without emphasis on individual parts, both are possible, though.
Answer: To amplify some of the comments: resolving the 7th downward uses a half-step movement between diatonic tones. Traditionally (for Western music over the last Millenium), the half-step movement has been considered very "strong." In general, the shorter movements are preferred to longer (but still avoiding parallels.) As pointed out in the comments to the original question, the tritone in a seventh chord is resolved outward if it's an augmented fourth and inward if a diminished fifth(B-F=>C-E and F-B=>E-C). One gets from the Medieval tradition, simultaneous half-step and whole-step movement in contrary motion, tritone resolution, and (from a more modern perspective) one gets root movement by fifths (or fourths depending on which direction one counts in.) Composers have considered that omitting the fifth in the final chord is less important acoustically.
Comment: The example is in A minor, so the resolution of the seventh of V7 to the third of the tonic chord is not a half step.
Comment: I can only imagine that this is why the major 3rd ends so many pieces of music in minor... that whole step is just not as a satisfying
Answer:
Why does the 7th of a dominant 7th chord have to resolve down in voice leading?

Because it is a tendency tone. The really strong tendency tones are FA and TI resolving respectively to MI and DO.
You can either accept they are handled this way by convention, or you can explain it as they must resolve this way, because these two movements are the half step movements in V7 I. (If you want a rationale of FA to ME in minor, consider it to be following the half step voice leading model of major with the minor third of tonic i being a modal modification after the fact.)
But that isn't your real question. The real question is how to get fully voiced chords in V7 I with good voice leading, or turned around, why strict voice leading for V7 I results in incomplete chords.
It may help to first look at the voice leading for triads only and then the implications of adding the seventh to the V chord.
The way to voice lead V I is ideally hold one voice move the other two by step, or possibly you could move all voices in the same direction. If we add basses in contrary motion we have:

For the V chord the E3 in the bass is a given so that means the E4 in the tenor is the duplicate. If we move one voice to get the seventh of a fully voiced V7, we will move the duplicate E of the tenor.
If we make that change, and strictly resolve the tendency tones, we get doubled tones and incomplete tonic chords:

If one of the tendency tones is not strictly resolved, we could move FA up to SOL or TI down to SOL:

I'm not really sure how "acceptable" the first one is, the second is more normal. In either case, burying the unconventional, undesirable movement in the inner voices is the normal way to disguise it. You would not want to put, for example, TI to SOL in the soprano.
Another way to approach the problem is work backwards from where you want to end.
Start at a fully voiced tonic chord, then build the V7 chord, first add the two tendency tones, then add the two remaining voices as step-wise motion:

Notice that none of the voices move E to A or SOL to DO. That means that no matter how you try to invert those voices you will not be able to get both chords in root position! That's a detail you didn't add in the question, but is an essential aspect of the voice leading "problem." There really isn't a voice leading problem until both chords must be root position.
A particular issue is the held tone from the ideal, triadic voice leading, which is SOL held to SOL. If you put that in the bass, you will get a I6/4 tonic chord:

If we "fix" the bass by moving it to A or DO:

...we have two root position chords, and good voice leading, but arrive at the incomplete chord problem through a different process. The "solution" to making that I complete will be the same as above, move one of the tendency tones against its tendency and bury it in the inner voices.
Answer: The  D - G♯ tritone that is the essence of the E7 chord ideally resolves with the G♯ leading note rising to the tonic, the D falling to C.    You could achieve this in your example like this - and in a test I'd suggest you did!
In real life, your version breaks that voice-leading rule, and also has rather a lot of similar motion - all three upper voices move in the same direction -  but the vocal lines are more interesting.  Also, an 'incorrect' resolution seems to hurt less when (mis)-resolving to a minor tonic than to a major one.    I'd be tempted.
Answer: In you example you have a G# that is led to the A you also have a chordal seventh (the D) that is led down to the c. Just by following the two tendencies of a four note chord you already have a easy chord progression laid out for you. This is true for all tetrads, you often go four steps forward in resolution.
Another example is the supertonic seventh chords, it has the tonic note of the scale for its seventh, which leads back to the leading tone which then resolves back up to the tonic. This is the essence of the ubiquitous ii-V-I chord progression. It just all makes good music and is the essence of good voice leading.
Answer: Hum hum.  It seems to me that all of the answers are "correct" by their lights.  Intuitive voice leading, resolving the tritone with contrary stepwise motion, is one tendency.  Wanting to have a particular set of tones for the final chord is another.  Which predominates depends on the circumstances.  Don't think there's any defensible "right" answer here.
Comment: This seems more like a long comment.


Is there a t-test equivalent to Stouffer's z-test?

Question: I have $k$ pairs of samples from different distributions. For each pair of samples I want to check if the samples are taken from a normal distribution with the same mean and variance. I assume the normal distributions for each pair is different and independent of other pairs. I do not know the mean and variance of any of the distributions.
I am doing a two sample t-test for each of the pairs. I want to combine the $k$ resulting p-values.
I could use Fisher's method but I am wondering about the distribution of the average t-value. If these were z-values rather than t-values I would use Stouffer's z-test. I could also approximate the t-distribution with a z-distribution and than use Stouffer's z-test, but I am not sure if that is a good approximation.
Is there a test like Stouffer's z-test for t-values?
Is there a better way to combine the t-values?
Comment: I cannot figure out what this question is asking, because it begins with the objective of checking whether samples have the same *three* properties--normality, means, and variances--but then proceeds to describe a procedure (a t-test) that accomplishes only one of those comparisons. After that it appears to abandon all the preceding context to focus on something else somehow related to "combining t-values." Could you edit it to clear up these uncertainties?
Comment: How about converting t-values into z-values?
Comment: @whuber The OP is away for over a  year and is therefore unlikely to edit. However, I think I can see what they were asking: they wanted to apply Stouffer's z-score method of combining p-values to the results from a bunch of t-tests; and they were worried that applying $z$-something-something method to $t$-tests is not a good idea because a $t$-test is not a $z$-test. So they asked for a suitable alternative. The answer to this specific confusion is that one can of course proceed with Stouffer's method. (But that other approaches make probably *much* more sense for the overall analysis goal.)
Comment: Hi! Still here :) Thanks for your answers.
Donda, I tried to avoid using z-values because that could be inaccurate for small sample sizes.
@amoeba, that was exactly my intension. Which other approaches would you suggest?
Answer: According to Becker's chapter on combining $p$-values in Cooper and Hedges book you can use
$$
\frac{\sum {t_f}_i (p_i)}{{\sqrt{\sum\frac{f_i}{f_i-2}}}} > z(\alpha)
$$
where ${t_f}_i$ is Student's $t$ with $f_i$ the degrees of freedom $p_i$ the p-value and $\alpha$ is the desired significance value.
She does not give a reference for the method which she attributes to Winer. The resemblance to the formula for Stouffer's method is clear though.

Cooper, H and Hedges, L V
A handbook of research synthesis 1994 (Russell Sage, New York)
Comment: Could you edit this answer to make it readable?  I am unable to fix up the formula because it is ambiguous and you haven't explained what "$t$" might mean.
Comment: Sorry about that, at the fourth attempt I realised that I cannot use double subscripts for some reason so I have removed them. Now at least it formats OK.
Comment: Double subscripts require braces, as in `$t_{i_j}$` for $t_{i_j}$.
Comment: Now sorted thanks to @whuber. I have added the citation to the book too.
Comment: @mdewey, thanks for your answer! Isn't the suggested method equivalent to Stouffer's z-test?
Comment: As all $f_i$ tend to infinity, yes, it is equivalent to Stouffer's method.


Concatenar Javascript com PHP

Question: Eu estou tentando concatenar PHP com Javascript, mas não estou conseguindo.

<button onclick="gravaDados('/" . <?php echo nomeCliente; ?> . /"')" class="btn-playpause">Play</button>

Obrigado
Answer: Aqui vamos nós:
<button onclick="gravaDados('<?= $nomeCliente; ?>')" class="btn-playpause">Play</button>

As tags <?= ?> querem dizer a mesma coisa que <?php echo ...; ?>.
Diferença entre tags do php <?php e <?=
Pensando melhor, você não precisa de contra-barras. Use apenas as aspas simples, que você vai ter o resultado que busca.
Caso o seu Apache ou IIS, enfim, CGI, não tenha habilitada a permissão ou o uso das tags curtas do PHP, você pode usar:
<button onclick="gravaDados('<?php echo $nomeCliente; ?>')" class="btn-playpause">Play</button>

Não se esqueça de usar $ antes do nome da variável para indicar variáveis no PHP.
Comment: Desculpa, mas minha resposta foi dada. Eu não preciso de um ensaio acadêmico para responder uma pergunta tão simples. As configurações default do PHP sim, permitem que a partir da versão 5.4 as tags nessa forma sejam usadas, mas por conta de problemas com XML, alguns servidores desabilitam no Apache o seu uso.
Comment: Você manda, @AndersonCarlosWoss!
Comment: @AndersonCarlosWoss Toda a razão mas nem todo o servidor tem a versão mais atualizada do php ainda existem hospedagem com php 5.3 o que é 3 vezes mais lento que php 7
Answer: Uma outra alternativa talvez seja utilizar o printf (ou sprintf dependendo do caso):
printf('<button onclick="gravaDados(\'%s\')" class="btn-playpause">Play</button>', $nomeCliente);

Não acredito que seja a melhor opção, mas é um outra opção.

Dependendo do contexto acredito que convém codificar o HTML do $nomeCliente afim mitigar XSS, neste caso algo como:
printf('<button onclick="gravaDados(\'%s\')" class="btn-playpause">Play</button>',
htmlentities($nomeCliente, ENT_QUOTES | ENT_HTML5, 'UTF-8'));

Sem utilizar o htmlentities, do jeito que as outras respostas fizeram, se o valor do $nomeCliente for );alert('XSS irá injetar um alerta (ou qualquer outro código malicioso que o usuário quiser, óbviamente) no website, veja aqui.
Answer: O problema é que não precisas de escapar as aspas ate porque para espaca-las é com \  e ao mesmo tempos estas a fazer concatenação fora do PHP
Basta assim:
<button onclick="return gravaDados('<?php echo $nomeCliente; ?>');" class="btn-playpause">Play</button>

Concatenar Javascript com PHP


Prove by induction that $(x+1)^n - nx - 1$ is divisible by $x^2$

Question: Prove by induction that $(x+1)^n - nx - 1$ is divisible by $x^2$
Basis step has already been completed. I've started off with the inductive step as just $n=k+1$, trying to involve $f(k)$ into it so that the left over parts can be deducible to be divisible by $x^2$ but getting stuck on this inductive step.
Comment: To be *precise* you should specify if $x$ is an integer or an "indeterminate" (even though a uniform proof can be given for both cases (integers & polynomials); in fact a proof that works in any commutative ring).
Answer: By the Binomial theorem, $(x+1)^n$ ends in $nx+1$, so that the remaining terms are multiples of $x^2$.

By induction, $(x+1)^n$ ends in $nx+1$. This is true for $n=1$, $(x+1)^1$ ends in $x+1$.
Now assume that $(x+1)^n$ ends in $nx+1$. Multiplying by $x+1$, we get $nx+x+1$ and higher order terms, hence $(x+1)^{n+1}$ ends in $(n+1)x+1$.
Comment: @mathreadler: you are right, I forgot that. Let's add an inductive proof of the Binomial theorem :)
Comment: This is a short and nice one, but it isn't induction.
Comment: @mathreadler: fixed.
Comment: Downvote, uh ??
Comment: I upvoted you. Someone else must have downvoted.
Answer: Hint:
$$(x+1)^{n+1}-(n+1)x-1=(x+1)(x+1)^n-nx-x-1$$$$=(x+1)((x+1)^n-nx-1)+(nx+1)(x+1)-nx-x-1$$$$=(x+1)((x+1)^n-nx-1)+nx^2$$
Comment: you need to use induction
Comment: @Babai: Indeed. That's why the hint tries to point out how to prove the induction step.
Comment: okay, great, I understand.
Answer: Lets say the statement is true for $n=k$ i.e., $(1+x)^k-xk-1$ is divisible by $x^2$  (Lets say, $(1+x)^k-xk-1=mx^2$  )
To show $(1+x)^{k+1}-x(k+1)-1$ is divisble by $x^2$
$(1+x)^{k+1}-x(k+1)-1$
$=(1+x)^k(1+x)-xk-x-1$
$=(1+x)^k+x(1+x)^k-xk-x-1$
$=\{(1+x)^k-xk-1\}+x(1+x)^k-x$
$=mx^2+x \{(1+x)^k-1\}$ =
$=mx^2+x \{(1+x)^k-1-xk+xk\}$
$=mx^2+x \{mx^2+xk\}$
$=mx^2+x .x\{mx+k\}$
$=x^2\{m+\{mx+k\}\}$
Hence it is divisible by $x^2$ and hence it finishes the induction.
Answer: The base case is trivial. Suppose the result holds for $k$; then
$$
(x+1)^k-kx-1=x^2f_k(x)
$$
for some polynomial $f_k$. Therefore $(x+1)^k=1+kx+x^2f_k(x)$ and
\begin{align}
(x+1)^{k+1}-(k+1)x-1
&=(x+1)(x+1)^k-kx-x-1\\[6px]
&=(x+1)(1+kx+x^2f_k(x))-kx-x-1\\[6px]
&=\color{red}{x}+kx^2+x^3f_k(x)+\color{red}{1}+\color{red}{kx}+
  x^2f_k(x)-\color{red}{kx}-\color{red}{x}-\color{red}{1}\\[6px]
&=x^2(k+xf_k(x)+f_k(x))
\end{align}
This, by the way, says that
$$
f_{k+1}(x)=k+(x+1)f_k(x)
$$
but it's irrelevant for the proof.
Answer: The induction step is arithmetically clearer if done $\!\bmod \color{#c00}{ x^2},\,$ i.e. using modular arithmetic, i.e. using $\,\rm\color{#0a0}{CPR} =$ Congruence Product Rule), and induction hypothesis $P(n)$   the induction step is
$$\begin{align}{\rm mod}\,\ \color{#e00}{x^2}:\,\  (1+ x)^n\, \ \  \equiv&\,\ \ 1 + \color{#0af}n\:\!x\qquad\qquad\ \ \ \  {\rm i.e.}\ \ P(\color{#0af}n) \\[1pt]
{\rm\color{#0a0}{CPR}}\Longrightarrow\ \ (1+x)^{\color{}{n+1}}\! \equiv &\:\!\  (1+nx)(1 + x)\quad\,\ \text{by $\,1\!+\!x\,$ times prior}\\[1pt]
\equiv &\,\ \ 1+ nx+x+n\:\!\color{#e00}{x^2}\\[1pt]
 \equiv &\,\ \ 1\!+\! (\color{#0af}{n\!+\!1})x\qquad\ \ \ \ \ {\rm i.e.}\ \ P(\color{}{\color{#0af}{n\!+\!1}})\\[2pt]
  \end{align}\qquad\qquad$$
Remark $ $ Note how the use of modular arithmetic greatly clarifies the arithmetical essence of the matter, i.e. the inductive step of incrementing $\,n\,$ amounts to scaling the induction hypothesis congruence by $1+x$ then reducing that $\!\bmod {\color{#c00}{x^2}}.\,$ This arithmetic would be obfuscated if done instead using divisibility relations (vs. above (congruence) equations). This highlights the power of modular arithmetic - to focus on the remainders (and ignore the unneeded quotients).
This first $2$ terms (order $2$) truncation of the Binomial Theorem often proves useful in number theory, e.g. see here (and compare to Bernoulli's inequality).
The same proof works for $\,(a+x)^n,\,$ i.e.
$$\begin{align}{\rm mod}\,\ \color{#e00}{x^2}:\,\  (a+ x)^n\, \ \  \equiv&\,\ \ a^n + \color{#0af}n\:\!a^{\color{#0af}{n-1}}x\qquad\qquad\ \ \ \  {\rm i.e.}\ \ P(\color{#0af}n) \\[2pt]
{\rm\color{#0a0}{CPR}}\Longrightarrow\ \ (a+x)^{\color{}{n+1}}\! \equiv &\:\!\  (a^n+na^{n-1}x)(a + x)\quad\,\ \text{by $\,a\!+\!x\,$ times prior}\\[2pt]
\equiv &\,\ \ a^{n+1}+ na^nx+a^nx+na^{n-1}\color{#e00}{x^2}\\[2pt]
 \equiv &\,\ \ a^{n+1}\!+\! (\color{#0af}{n\!+\!1})a^{\color{#0af}n}x\qquad\ \ \ \ \ {\rm i.e.}\ \ P(\color{}{\color{#0af}{n\!+\!1}})\\[2pt]
  \end{align}\qquad\qquad$$
Generalization $ $ Using the above idea it is easy to generalize, e.g. from this answer
$\!\begin{align}\rm{\bf Theorem}\ \  \forall n\in\Bbb N\!:\ d\mid f(n) = a^n\! + b\:\!n + c  &\rm \iff d\mid \color{blue}{(a\!-\!1)^2},\, \color{brown}{a\!+\!b\!-\!1},\, \color{darkorange}{1\!+\!c}\\ &\rm \iff d\mid f(0),\,f(1),\,f(2)\end{align}$
Comment: that's a good use of colours! (+1)
Comment: If congruences are not familar then see [here](https://math.stackexchange.com/a/1119509/242) for how to rewrite the proof without them.


What is the difference between a Set, a Vector, and, a Vector Space?

Question: What is the difference between a Set, a Vector, and a Vector Space?
Please, explain without using formal math notations. Because if you use formal math notations, I wouldn't understand anything.
Comment: there was actually a very nice discussion on the topic of [definition of a set](http://math.stackexchange.com/questions/742105/definition-of-set)
Answer: A set is what's called a primitive notion.  That means we don't actually define it, we just assume that everyone has roughly the same idea in mind when we say it.  Think what a set of objects means outside of math.  Same definition should work here.  A set is a group(/ collection/ assortment/ assemblage/ ... gaggle -- maybe that one only works for geese) of objects.  Those objects are called members or elements of the set.
A vector is a member of a vector space.
A vector space is a set of objects which can be multiplied by regular numbers and added together via some rules called the vector space axioms.

An example of a set is $\{1,2,3\}$.  This is just a collection of three numbers.  Another example is $\{banana, orange, taco, oatmeal\}$.  This set contains $4$ foods.  Neither one of these sets comes pre-equipped with any notion of addition or multiplication -- they're just groups of objects.
An example of a vector space is the set of all real numbers, $\Bbb R$, along with the usual kind of multiplication and addition.  This is a set of numbers, but we also can talk about adding them and multiplying them by other numbers.  You can check that they satisfy all of those rules that adding and multiplying have to satisfy and thus this set is also a vector space.
The number $3$ is an example of a vector in the above vector space.  So is $\pi$.  So is $\dots$
A less trivial (and more typical) example of a vector space is the set of all continuous functions defined on the interval $[0,1] \subset \Bbb R$.  Addition of two functions $f$ and $g$ is defined by $(f+g)(x) = f(x)+g(x)$ and multiplication is defined by $(af)(x) = a\cdot f(x)$, for $a\in \Bbb R$.  You can verify that this is also a vector space.
The function $f$ given by $f(x)=x^2-2$ is a vector is this vector space.
Comment: If vector-space is a set, doesn't it already incorporate those axioms from the set theory?
Comment: If u update the answer with this information and add some examples, I would accept your answer. Coz, it is almost complete.
Answer: A vector space is a set in which you can add its elements with one another and in which you can "stretch" its elements, in other words multiply them by a real number. The elements of the vector space are the vectors. Some people would say vector spaces are sets with "more structure".
On the other hand vector spaces are different from most sets in the sense that their elements might be arbitrary and it might no be able to add them with each other.
Answer: A set is a collection of objects. For example, the set of integers from $1$ through $5$.
A vector space is a set of elements (called vectors) which is defined "over a field" in the sense that if you multiply by a number in the field (think real numbers), you still get an element in the vector space. It is also possible to add things together in a vector space, and there is a special element called '$0$' which has the property that $\vec{v}+0=\vec{v}=0+\vec{v}$ for every element (same thing as a vector) $\vec{v}$ in the vector space.


Font style isn't applied on PDF (entity print)

Question: I'm using Entity print with my webforms. I've followed those steps https://www.drupal.org/node/2706755 to add the css into my PDF.
My classes are applied (color, padding...), but for some reason, the fonts are never applied on the generated PDF, but is applied on the debug : https://.../print/pdf/webform_submission/10/debug
Font are not applied with CDN @import url('https://fonts.cdnfonts.com/css/aphont');
or with local font files
@font-face {
  font-family: "APHont";
  font-style: Italic;
  font-weight: 700;
  //URLs are OK
  src: url("./font/aphont-bold-italic.woff2") format("woff2"), url("./font/aphont-bold-italic.woff") format("woff");
}

body {
  font-family: 'APHont', 'Arial', serif; //even Arial is not applied
}

I'm using drupal 9.5.1, entity print 9.11 and DomPDF (i've been digging into others issues on entity print, but could'nt find any matching solution)
Comment: Pretty sure asset includes have to be full URLs / paths on the server and not relative.
Comment: https://github.com/dompdf/dompdf/issues/1401#issuecomment-589543115
Comment: It helps. Works with relative, see my answer, thanks a lot
Answer: Works by doing this (thanks to this https://github.com/dompdf/dompdf/issues/1566#issuecomment-591955876) :

Using ttf
not apply font-family to the body
add font-weight to each tag you want to apply the font (h1, p...)

The result in css :
@font-face {
  font-family: "APhont";
  font-style: normal;
  font-weight: bold;
  src: url("./font/aphont-bold.ttf") format("truetype");
}

h1 {
  font-family: APhont, serif;
  font-weight: bold; //very important
}


OroCRM Version upgrade from 4.0.0 to 4.1 Possible Errors

Question: May i know what are all the issues occurred OroCRM Version upgrade from 4.0.0 to 4.1.
Server Information : Centos7, Ngins, PHP 7
Answer: It depends on the customization you have. The plain application can be upgraded with a few commands, and no issues, see
https://doc.oroinc.com/backend/setup/upgrade-to-new-version/
If you have any code customizations, please follow the official upgrade guide. You can start from https://github.com/oroinc/crm-application/blob/master/UPGRADE.md


How to call abstract class method in java

Question: I want to call a method of an abstract class in my own class. The abstract class is:
public abstract class Call {

    public Connection getEarliestConnection() {
         Connection earliest = null;

         ...

         return earliest;
    }
}

I want to call the above method, and the calling class is:
public class MyActivity extends Activity {

    Connection c = new Connection();

    private void getCallFailedString(Call cal)
    {
        c = cal.getEarliestConnection();

        if (c == null) {
            System.out.println("** no connection**");
        } else {
            System.out.println("** connection");
        }
    }
}

Whenever I try to run the above class, it throws a NullPointerException on the line c = cal.getEarliestConnection().  Can anyone tell me how to resolve this problem?
Comment: how and where you call the getCallFaildString() of MyActivity class?
Comment: Pratik is right: the problem isn't that the class is abstract. The problem is that the value of "cal" is null when you are passing it in.
Comment: Why do you need such a horrible mechanism? Looking like it makes no sense to use that `abstract` class.
Comment: Not enough code I'm afraid. We need to see if/how Call is instantiated and where getCallFailedString is invoked.
Comment: thx a lot for ur quick rply. I will edit my above code.
Comment: "Can anyone tell me how to resolve this problem?" Make sure you are not passing `null` for the `cal` variable, I guess...
Comment: there is no subclass of abstract class Call?? plz post the complete code
Comment: @Lion yes u right it doesnt make any sense.. may be he's just doing it for some kida prctice.. ;)
Comment: @Lion: I need to use android source code. that's why i am using abstract class
Answer: Firstly, Call an abstract class, therefore you cannot instantiate it directly. You must create a subclass, say MyCall extends Call which overrides any abstract methods in Call.
Getting a NullPointerException means that whatever you are passing in as an argument to getCallFailedString() hasn't been initialized. So after you create your subclass of Call, you'd have to instantiate it and then pass this in to your method, so something like:
class MyCall extends Call
{
     //override any abstract methods here...
}

Wherever you are calling getCallFailedString() would then require something above it like:
Call cal = new MyCall();
Activity activity = new MyActivity();
activity.getCallFailedString(cal);

Answer: Looks like the Call cal is null before it is passed into the function getCallFailedString.  Make sure you extend Call and instantiate the extended class and pass it into getCallFailedString.
Answer: Make sure your object "cal" is initialized and not null. Also, you won't be able to instantiate a Call object(as its an abstarct class). Instead, declare class Call as an interface and implement its method getEarliestConnection(), in your class.
Comment: You can have an instantiated variable of type `Call` by assigning it a value of an instance of any of its child classes.


Question about measure on set that is not in $\sigma$-algebra

Question: I think I have problem with badly written book, or I just can't understand statement.

Let $(X,\mathcal{A},\mu)$ be any measure space and $\mu^*$ be outer and $\mu_*$ inner measure inner measure generated by $\mu$. Then it's true for any $A\subseteq X$:$$\mu_*(A)\leq \mu(A)\leq\mu^*(A)$$

*line under this one is $\mu_*(A)=\mu(A)=\mu^*(A)$ if $A\in\mathcal{A}$
And it's nowhere defined what is $\mu(A)$ for set $A$ that is not from $\mathcal{A}$.
What would be definition? How should I "treat" it?
(This inequality is used to prove theorem that A is from completion of $(X,\mathcal{A},\mu)$ if and only if $\mu_*(A)=\mu^*(A)$, so if someone has link to proof f that theorem (since proof from mine book obviously has flaws)I would be grateful =))
Comment: From the brief quotation (from a secret source) we cannot guess what is going on.
Comment: Probably they mean "$μ_*(A) ≤ μ^* (A)$ and $μ_*(A) ≤ μ(A) ≤ μ^*(A)$ if $A ∈ \mathcal{A}$".
Comment: It's book in Croatian so I think source wouldn't help :P
But I added some info.
Answer: The assertion would be correct if instead of $A\subset X$ it would say $A\in\mathcal A$. As you say, the way it is written makes no sense.
Comment: line under this one is $\mu_*(A)=\mu(A)=\mu^*(A) $ if $A\in\mathcal{A}$ so I still think they somehow "expanded \mu". This is also used for proving one theorem so it bugs me even more...
Comment: That's expected.  If you construct an outer and an inner measure out of $\mu$, you would expect them to agree with $\mu$ on $\mathcal A$.


CentOS tmpfs mount doubling up?

Question: Everytime I mount a ramdisk with the following command, I get two instead of one ramdisk?
mount -t tmpfs -o size=1024M tmpfs /home/site/public_html/var/cache

Mount shows no ramdisks mounted prior, and after running the command it shows:
tmpfs on /home/site/public_html/var/cache type tmpfs (rw,size=1024M)
tmpfs on /home/site/public_html/var/cache type tmpfs (rw,size=1024M)

If I unmount, both disappear, and when remounting, both appear.
Answer: This can happen if you have a bind mount in your home directory.
Type this:
mount | grep bind

You can also check the contents of /etc/mtab, though I doubt you will see duplicate entries there.

CentOS tmpfs mount doubling up?


MVC RedirectToAction through ajax jQuery call in knockoutjs is not working

Question: I am building a MVC3 web application and I am using knockoutjs. There are two views in the application. SetUpNewCompany and ManageAccount. To Set up a new company the user first enters the account number and clicks search. If the account number already exists the user can click on a button to go to the ManageAccount view. In the SetUpNewCompanyController I redirect using the RedirectToAction method. However, when the Index2 action in ManageAccount is executed the view is not displayed. If I type in the complete URL the view is displayed.
SetUpNewCompanyController.cs
[HttpPost]
 public RedirectToRouteResult RedirectToManageAccount(string accountNumber)
 {
        return RedirectToAction("Index2", new RouteValueDictionary(new {controller=
            "ManageAccount", companyId = "7e96b930-a786-44dd-8576-052ce608e38f" }));
 }

This above is called by the function below when a button is clicked
self.redirectToManageAccount = function () {
        var accountNumber = "7e96b930-a786-44dd-8576-052ce608e38f";
        $.ajax({
            type: "POST",
            url: "/SetUpNewCompany/RedirectToManageAccount",
            data: { accountNumber: accountNumber },
            success: function (data) {
            },
            error: function () {
            }
        });
 }

ManageAccountController.cs
public ActionResult Index2(String companyId)
    {
        var viewModel = new Models.Index();

        List<String> compList = new List<String>();
        compList.Add("MyCompany");

        List<String> usersList = new List<String>();
        usersList.Add("User1");

        viewModel.Users = usersList;
        viewModel.Companies = compList;
        viewModel.CompanyId = companyId;
        viewModel.Role = "Role1";

        return View("ManageAccount",viewModel);
    }

The URL that is generated is
http://localhost:53897/ManageAccount/Index2?companyId=7e96b930-a786-44dd-8576-
052ce608e38f

The console window in Firebug shows
GET http://localhost:53897/ManageAccount/Index2?companyId=7e96b930-a786-44dd-8576-
052ce608e38f 200 OK and the spinner keeps spinng

Also, how do I get the URL below instead of the one with querystring
http://localhost:53897/ManageAccount/Index2/7e96b930-a786-44dd-8576-052ce608e38f

Answer: Since you use AJAX to call the RedirectToManageAccount action method, you are responsible for handling its response yourself and as your success handler function is empty, you are effectively ignoring whatever arrives as a response.
If you want to force a redirect from within the AJAX response handler, I suggest

Modifying your action method as follows
[HttpPost]
public ActionResult RedirectToManageAccount(string accountNumber)
{
    var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index2", "ManageAccount", new { companyId = "7e96b930-a786-44dd-8576-052ce608e38f" });
    return Json(new { Url = redirectUrl });
}

Updating your AJAX call in this way
self.redirectToManageAccount = function () {
  var accountNumber = "7e96b930-a786-44dd-8576-052ce608e38f";
  $.ajax({ type: "POST",
           url: "/SetUpNewCompany/RedirectToManageAccount",
           data: { accountNumber: accountNumber },
           dataType: 'json',
           success: function (response) {
               window.location.href = response.Url;
           },
           error: function () {
           }
  });
}

As for your second question:

Also, how do I get the URL below instead of the one with querystring
  http://localhost:53897/ManageAccount/Index2/7e96b930-a786-44dd-8576-052ce608e38f

You just have to define an appropriate route entry for this URL in your RegisterRoutes() function:
routes.MapRoute(null,
                "ManageAccount/Index2/{companyId}",
                new { controller = "ManageAccount",
                      action = "Index2" }
);

EDIT: As your AJAX call only serves to call an action method which causes a redirect, you can simplify it in a following way, provided you in this point (on the client side) know the companyId already:
self.redirectToManageAccount = function () {
    var companyId = "12345";
    window.location.href = '@(Html.ActionUri("Index2", "ManageAccount"))?companyId=' + companyId;
}

where I used this extension method
public static string ActionUri(this HtmlHelper html, string action, string controller)
{
    return new UrlHelper(html.ViewContext.RequestContext).Action(action, controller);
}

Comment: Is there another way to redirect to the ManageAccount/Index2 also i added the route as you suggested but I still got the ?companyId=xxxxx in the URL
Comment: It depends on the specific scenario, really. I updated my answer with one possible simplification of the redirection process. As for the route: are you sure you did not add it __after__ some more general rule?
Comment: i changed the companyid to id and used the default routing route to remove the querystring


Importing Test Database to Main Database

Question: My problem is that I decided to have a Test Database where I put the data I'm testing and where I can play around without any issue. When everything seems ok I migrate the data to the "official" database, where I plan to migrate different Test DBs.
The problem are child tables. I have:
Table1:          Table2:          Child:
- id             -id              -idTable1
- name           -name            -idTable2
- url            -type            -quantity

To migrate Table1 and Table2 I thought to create a temporaryID on the "official" Database. When I want to migrate the table "Child" the only thing I can think of is to check every single row and update it with the corresponding new ids.
Isn't there a better way to do this?
I also thought to simply forget about Test DB and work only with the "official" one, but I am afraid of having to start again from scratch every time I make a mistake.
I think I've seen a couple of examples here on SO, but they seems much more complicated than what I need.
Answer: if the problem is that you don't want to avoid duplicate ids on the 2 (or more) databases,
you should read about "auto-increment-increment" and "auto-increment-offset".
if server 1 have:
auto-increment-increment                        = 4
auto-increment-offset                           = 1

then id number generated on that server is going to be: 1,5,9,13...
and the 2nd server configed like
auto-increment-increment                        = 4
auto-increment-offset                           = 2

the id numbers on the 2nd server is going to be 2,6,10,14..
that alow you to copy data, inlcuding the id number, between the servers
Comment: That would be nice if I have two Test Db, but I don't know how many I will have. :(
Comment: the exemple was for a up to 4 config, so set auto-increment-increment to 100, 1000 or higher :-)


Concatenation, Haskell

Question: Hi I am currently trying to concatenate two lists in Haskell similar to this:
l1 = [[aa,adb,adc], [aa,dd,gg]]
l2 = [[cc,abd,hh], [hh, cc, vvvv]]
result:
l3 = [[aa,adb,adc], [aa,dd,gg], [cc,abd,hh], [hh, cc, vvvv]]
here is my Haskell code:
Length-Ordered Lists over "character type" a (aka "strings over a")
Invariant: In LOL n xs, n == length xs
Note that automatically-derived Ord instance correctly orders LOLs
data LOL a = LOL Int [a] deriving (Eq,Ord)
instance Show a => Show (LOL a) where
show (LOL n xs) = show xs

-- Empty list (epsilon)
eps :: LOL a
eps = LOL 0 []

establish invariant
lol :: [a] -> LOL a
lol xs = LOL (length xs) xs

Normalized lists of LOLS
Lang a implies xs is ordered with no duplicates
type Lang a = [LOL a]

establish invariant
lang :: Ord a => [[a]] -> Lang a
lang xs = norm $ map lol xs

Here is where I am having a problem down below. I can't seem to connect the constructor Lang properly to establish a concatenation.
cat :: Ord a => Lang a -> Lang a -> Lang a
cat (ws) (zs)  = [ws:zs | ws++zs, ws <-Lang, zs <-Lang]

Any help will be greatly appreciated!
Comment: But you already concatenate it: `cat` is simply `cat = (++)` here.
Comment: I wish it was that simple. There is quite a few steps involved since I had to establish normalcy through the invariants described above. I attempted:cat [] a = [];
cat a [] = [];
cat (x:xs) (y:ys) = (xs++ys);but still to no avail. I recognize I have to use recursion to get my required output but... I can't figure out how to implement recursion to include both lists. (; although not syntactically correct - I used it to clarify endings)
Comment: LOL is used to both describe the length of the string and to hold the string aka: LOL 3 "lol". Lang is a list of these items.
Answer: cat :: Ord a => Lang a -> Lang a -> Lang a
cat (ws) (zs)  = [ws:zs | ws++zs, ws <-Lang, zs <-Lang]

This has several syntactic and type errors.

[… | ws ++ zs, …] tries to use ws ++ zs as a filter for the list comprehension, but ws ++ zs is of type Lang a, not Bool

[… | …, ws <- Lang, zs <- Lang] shadows the parameters ws and zs with new local variables bound inside the comprehension; in addition, Lang is a type constructor, not a list, so you can't iterate over it

ws : zs assumes ws is an a and zs is a [a], since the (:) operator prepends an element to a list, but you're trying to work with LOL a values

The Ord constraint is unnecessary, since you don't use any comparison functions in the definition of cat

If you're trying to concatenate every list (of type LOL a) from one Lang with every list from the other Lang, you need to do something like the following:
cat :: Lang a -> Lang a -> Lang a
cat ws zs = [catLol w z | w <- ws, z <- zs]

catLol :: LOL a -> LOL a -> LOL a
catLol (LOL m xs) (LOL n ys) = LOL (m + n) (xs ++ ys)

That is:

w :: LOL a is bound to each element of ws

Within that loop, z :: LOL a is bound to each element of zs

The two LOL a values are concatenated using catLol

catLol pattern matches on both its arguments to extract the length and list fields

catLol returns a combined LOL with a length equal to the sum of the lengths of its operands, and items resulting from concatenating their list fields

This can of course be written without the catLol helper function:
cat :: Lang a -> Lang a -> Lang a
cat ws zs = [LOL (m + n) (xs ++ ys) | LOL m xs <- ws, LOL n ys <- zs]

But if you're trying to just concatenate the two Lang a values, cat is equal to (++), since they're lists already:
-- Identical to: cat :: [LOL a] -> [LOL a] -> [LOL a]
cat :: Lang a -> Lang a -> Lang a
cat ws zs = ws ++ zs

If you want to normalise the result, then the Ord constraint makes sense to add back in, and you can just call your norm function, assuming it has type (Ord a) => Lang a -> Lang a:
cat :: (Ord a) => Lang a -> Lang a -> Lang a
cat ws zs = norm (ws ++ zs)

Concatenation, Haskell


SQL Server Agent was not running on Server Dynamics CRM 2013

Question: I'm trying to install Dynamics CRM 2013 on a server. This server is on a VM. There are several other VMs, an ADDS & DNS, a MSSQL and a WebServer VM.
Each server is a Windows Server 2012 R2. The SQL Server is 2012 Enterprise.
Each VM is part of the main Domain, set by the ADDS & DNS. NSLookup confirms I can see the computer at the right IP address.
Each separate VM has its own static IP, the DNS is set to the ADDS & DNS. I use the domain administrator to log into all the servers, and make the that domain administrator a local administrator.
I've set up all the domain users for the CRM and gave them appropriate permissions, I have also added the accounts to the appropriate places, such that the CRM Deployment user is in the SQL security.
The SQL Agent is running. SQL server configuration manager has SQL server network configuration TCP/IP enabled to allow remote connections. The SQL server has the domain user as a administrator, which is the same user being used to install the CRM.
In the CRM setup i point to the [Servername]\[Instance] and I have also tried just the [Servername]. to make this easier I called the server MSSQL and left the instance name to the default. I even install the MSSQL instance as the domain administrator.
CRM can find the ReportServer url. I have enable all the ports required, including: 135, 1433, 1434, 2382, 2383, 4022. 1434 UDP.
I feel like I have absolutely done everything, I have google many times and tried all the different methods, and for the life of me I cant seem to get the CRM setup to find the SQL server agent. It passes everything else perfectly fine. I can even ping the MSSQL server.
What is the problem, why does the CRM still keep giving the error:
SQLSERVERAGENT (SQLSERVERAGENT) service is not running on the server MSSQL

On the MSSQL server, the name of the sql server agent service is:
SQL Server Agent (MSSQLSERVER)

Answer: I needed to have opened port 445 on the MSSQL server machine. That was all....
Answer: We had something very similar...except opening the ports, ensuring permissions and other advised steps did not help. The error still persisted.
By pure chance - we stumbled across the file shares not being accessible. By allowing "File and Printer Sharing for Microsoft Networks" on the SQL server's LAN connection, we were able to solve the problem.
I am including this here purely as reference for the above solution... as we were unable to solve the problem via search engines/forums/q & a sites etc.
Comment: Not sure why this was down voted. The answer given did not resolve our issue. The above did.


Bootstrap - Fluid navbar items

Question: I'm a newbie bootstrap user, currently I want to create a fluid navigation bar, but when I shrink the browser the navigation bar becomes weird.
Before shrinking:

After shrinking further:

As you can see, the second image is pretty bad.. One possible way I thought is to separate the words into 2 lines (e.g. line 1 - goto, line 2 - Hello_World!). Can anyone give me a better approach for this issue? Thanks in advance.
Current HTML code:

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>

goto Hello_World!

goto About_Me

goto Life_Graph

goto Skill_Trees

goto Feat_Stacks

goto Codetact_Me

HERE IS MY FIDDLE...
Comment: Did you somehow overlook http://getbootstrap.com/components/#callout-navbar-overflow ?
Comment: Not yet, but going to look over that
Answer: If my understanding for your quesetion is correct you can use .row & .col to block menu to new row

        ...

          ...

You can change col-md-xx to make it wider or smaller
for more info
http://getbootstrap.com/css/#grid
Comment: Can you create jsfiddle

Bootstrap - Fluid navbar items


How to avoid rendering of same node in two different view blocks on same page ?

Question: One of my page shows two different view blocks. Suppose View-block-1 and view-block-2.
Both renders and display nodes from same content type, say products. Node display Limit is set to 1 in both view and ordered by random.
Products:
Product 1
Product 2
Case 1
View-block-1  |   View-block-2
Product 1     |  Product 2
Case 2
View-block-1  |   View-block-2
Product 1    |    Product 1
Problem is that (case 2) sometimes both block shows same node since ordering is set to random.
Is there any way to ensure that both view do not show same node ?
Answer: Install Views exclude previous module.Then your views filter criteria will have a option like this
Views: Views Exclude Previous (<> Exclude nodes that where loaded in any node based view.)
This will restrict the same content to be displayed in page more than one time.
Hope this answers your question.
Comment: I saw if there is any option to it, but I think there is some module available 'views exclude previous'. I need to install it first. I'll make a try :)
Comment: Well, Yes. Thank You so much. This worked. But I installed Views exclude previous module prior to use that filter. Please update your post so that I can accept it. :)


$base_url and $THEME_ARRAY using together

Question: I have this in settings.php:
<code>$THEME_URLS = array(
  array('/optoelectronics','sky'),
);
foreach ($THEME_URLS as $info) {
  if (strpos($_SERVER['REQUEST_URI'], $info[0]) === 0) {
    $conf['theme_default'] = $info[1];
  }
}
</code>
I have two domains each based on a different theme. The issue is that I'm trying to use part of the old theme for just these two sections but the other theme is entirely based on SKY and if I make any modifications to the css or create a page-optoelectronics.tpl.php, then both sites receive the modifications, which I don't want.
So I duped the theme "sky" and changed all appropriate names and such to 'optotemp' but as I mention above, Drupal still disregards the "http://www.site.com" part and switches to 'optotemp' when it sees /optoelectronics.
So I found $base_url which returns the full path, including the host.
I'm a little rusty with the combination of an if/else command and including the array above in one fell swoop.
I want to say: If the absolute path is http://www.sitea.com/optoelectronics use theme optotemp. Otherwise, use the default theme. This command would then mean by default that http://www.siteB.com/optoelectronics would still use the theme assigned to that domain via the domain access module, which is Sky.
In other words, www.sitea.com has a new entire theme, but two sections of www.sitea.com will need to use optotemp but www.siteb.com uses sky.
I need help on knowing the syntax to get this right.
<code>var $usOrEuro = $base_url;
if ($usOrEuro == 'http://www.sitea.com/optoelectronics'){
  $appliedTheme = 'optotemp';
}

$THEME_URLS = array(
  array($usOrEuro, $appliedTheme),
);
foreach ($THEME_URLS as $info) {
  if (strpos($_SERVER['REQUEST_URI'], $info[0]) === 0) {
    $conf['theme_default'] = $info[1];
  }
}
</code>
Answer: This should do it:
<code>$hosts = array('sitea.com', 'www.sitea.com');
if (in_array($_SERVER['HTTP_HOST'], $hosts) && $_SERVER['REQUEST_URI'] == '/optoelectronics') {
  $conf['theme_default'] = 'optotemp';
}
</code>
Comment: well, no go. I put this in the settings.php file:

$hosts = array('sitea.com', 'www.sitea.com');
if (in_array($_SERVER['HTTP_HOST'], $hosts) && $_SERVER['REQUEST_URI'] == '/optoelectronics') {
  $conf['theme_default'] = 'optotemp';
}

substituting the real domain of course. But, I stuck a  little span at the bottom and the template within the optotemp style is not being called at the url.
Comment: Hmm, not sure why - I tested the same thing locally (with a different domain obviously) and it worked just fine
Comment: I think it's the darn Domain Access module. It seems powerful until you hit the specific user case where one of two sites, each with different themes, has to share a theme from the other. The IP doesn't have anything to do with this, does it? Because of the Domain Module, the other domain (siteb) is pointed to the main site(sitea), so within Drupal the IP is the same for both sites.
Comment: The IP wouldn't make any difference, no...have you tried [ThemeKey](http://drupal.org/project/themekey)?
Comment: Yes, but as I'm in 6.28 there seems to be conflicts as Domain Access is overriding anything there. It seems like there should be an easy way using something in Settings.php because that's the last stop before index.php, right? Anyway, thanks for help.
Comment: Did you put this in settings.php or theme.php?
Comment: Straight into settings.php


"The echo" module in reason only plays the feedback sound

Question: When I use the "the echo" plugin in Reason (using Reason 11) and turn up the delay time, I do not get a sound immediately when pressing a key but, but after that delay time. That means I only hear the echo, not the sound that is "echoed".
I expect to be able to hear both.
How is that done?
Comment: There has to be some sort of dry/wet knob.
Comment: From the pictures i found on the internet, the dry/wet knob is in the top right corner of the plugin. With this knob you can adjust the mix between the dry input signal and the processed output signal. If you point it in between, you will get a mix of both.
Answer: In the top right corner of your plugin you will find a dry/wet knob. With this knob you can adjust the mix between the dry input signal and the processed output signal. If you point it in between, you will get a mix of both.


htaccess replace part of url based on condition

Question: I'd like to redirect from a URL like http://www.example.de/this.xml
To the .xml with the right language, eg. http://www.example.de/this-www.example.de.xml
The same with every other language i.e. (de|com|eu ...)
Right now I've got this, but I don't know how to set the right language in the RewriteRule:
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.(de|at|ch|com|nl|be|fr)$
RewriteCond %{REQUEST_URI} ^/this.xml$
RewriteRule ^(.*)$ /this-www.mydomain.$1(de|at|ch|com|nl|be|fr)$2.xml [R=301,L]

Answer: Do you need to specifically check for the ccTLD? It looks like you are simply copying the host into the target URL-path?
Try something like the following:
RewriteRule ^(this)(\.xml)$ /$1-%{HTTP_HOST}$2 [R=301,L]

This will permanently redirect a request for http://www.example.de/this.xml to http://www.example.de/this-www.example.de.xml.
Note that if you've previously been testing with 301s you will need to make sure that any intermediary caches are cleared since any earlier erroneous 301s will have been cached. (Testing with 302s can sometimes be beneficial for this reason.)

But how would you have checked specifically for the ccTLD?

To allow only a select few ccTLDs and also capture the TLD from the host then you would need to use a RewriteCond directive and check against the HTTP_HOST server variable, similar to what you have done. However, your RewriteRule substitution is wrong.
For example, you could do something like:
RewriteCond %{HTTP_HOST} ^(www\.)?example\.(de|at|ch|com|nl|be|fr)$
RewriteRule ^(this)(\.xml)$ /$1-%2$2 [R=301,L]

This will redirect http://www.example.de/this.xml to http://www.example.de/this-de.xml. But not do anything with http://www.example.us/this.xml, since the ccTLD does not match one of those in the CondPattern.
$1 and $2 are backreferences to the captured groups in the RewriteRule pattern. Whereas %2 is a backreference to the 2nd captured group in the last matched RewriteCond CondPattern.
NB: You should canonicalise the domain (ie. redirect to www or non-www) earlier in your config, so that making www. optional in the above regex (ie. (www\.)?) should not be necessary.
Comment: Yes, I simply copied the host into the target URL-path.

Thank you for help, it works like intended.

But how would you have checked specifically for the ccTLD?


How to tell Swift which function signature to use between default optionals

Question: I want to instantiate the root view controller of a Storyboard I created.
To do so I was used to calling -instantiateInitialViewController() from a storyboard.
The thing is since iOS13 there's a new method signature that takes a new optional argument: (creator: ((NSCoder)->ViewController?)?)

The annoying thing is that Xcode thinks I want to use that new API, which makes my app incompatible with older OS.

And I can't get around it, even with a version check.

My question is: How to tell the compiler to use the method signature without the parameter?
Comment: Try deleting your derived data. I just created a new project with compatibility to iOS 10 and the line is perfectly-recognized by Xcode (Version 11.5)
Comment: Hey, regardless of the Xcode bug, I have answered your bolded question **How to tell the compiler to use which method signature** [here](https://stackoverflow.com/a/63504077/5623035). Did you check that?
Answer: Quick Answer for your issue: Xcode BUG
First of all, as your screenshots show, it's a bug. (try removing driven data or restarting stuff to make it work). The following is the answer to your question.

Explanation: How to tell the compiler to use which method signature
Swift infers the function signature based on the used Types in the expression. So imagine this:
class ViewController { }
class UIViewController { }

func instantiateInitialViewController() -> UIViewController? {}
func instantiateInitialViewController() -> ViewController? {}

So calling this would be ambiguous use of instantiateInitialViewController():
let theController = instantiateInitialViewController()

The solution for this is to tell the compiler what is the expected type explicitly:
let theController: ViewController? = instantiateInitialViewController()
let theOtherController: UIViewController? = instantiateInitialViewController()

The new instantiateInitialViewController return type is a protocol (ViewController) that constrained to UIViewController. So it should infer the type and have no logical difference from the old one. So just keep calm and just let it infer ;)
Answer: Ok this became patently a bug from Xcode.
After restarting my mac, it works fine.
Why did I thought the error could came from me… ♀
Thank you all!
Answer: UIViewController objects can be saved to disk and restored upon request (ie, battery down, memory warning issues).
The new iOS13 method
instantiateInitialViewController { (coder:NSCoder) -> MyViewController? in
    return MyViewController(coder: coder)
}

allows the view controller instance come to life by restoring some of its state.
This method call invokes initWith(coder:) in MyViewController, where one can, in this example, restore "name" property.
class MyViewController: UIViewController {

    var name:String?

    required init?(coder: NSCoder) {
        name = coder.decodeObject(forKey: "name") as? String
        super.init(coder: coder)
    }
}

Answer: Actually, I don't know the answer on your question, but maybe you just want to init your ViewController from Storyboard for iOS version less than 13.0? Try this:
UIStoryboard(name: "storyboardName", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerID")

Comment: I already tried it and unfortunately there's the optional parameter on that signature too.
Comment: Did you try to unwrap your instantiateViewController result ?
guard let myVC = UIStoryboard(name: "storyboardName", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerID") as? MyViewController else { return UIViewController() }

or you also can use 'as!'


How do I test my app when it's dependent on Google sign in after publishing app on the Google Play Store?

Question: So when I published my app on the Google Play Store, I had to change the SHA1 key on Firebase and Google Play API Console to the new one that the Google Play Console generated.
The problem now is if I want to test my app from Android Studio, I need to change the SHA1 key back to the original one. If I do that, then the current users who have already logged in my app will no longer be able to log back in.
How do I test my app when it's dependent on the Google sign in and not affect current users?
Answer: Multiple SHA1 fingerprints can be added to a single firebase project. Add your debug key (Android studio SHA1 fingerprint) to your firebase project along with your app's production key. Then download the latest Json file and add it to your project in Android studio.
Comment: What about the Google API Console? That only accepts one SHA1 key, not multiples.
Comment: Download the json file after adding both debug key and production key to your firebase project. Include it in your project. Make sure that Google signin feature works. Finally, generate the signed apk using your production key (Production key cannot be changed once it is generated or linked to an app). Upload it to Google play console.
Comment: In this way, you will be able to use signin feature in both debug apk and production apk. Good luck.
Answer: Sarweshkumar C R's answer is perfect, just adding visualization for total newbies. Both keys can coexist with no problems, in the image I added 3 SHA certificate fingerprints to demonstrate and you can add by clicking 'Add fingerprint'


How can one determine order of execution of ChannelInterceptors in Spring messaging?

Question: The problem I'm having is with the execution order of ChannelInterceptors.I tried setting up websocket security. Defined a ChannelInterseptor to implement jwt token based authentication and added its ChannelRegistration. Also added @EnableWebsocketSecurity annotation to enable security for websocket. At the same time, interceptor chains are added that define security rules.Here is my class implementing WebSocketMessageBrokerConfigurer. My ChannelInterceptor was being added later than the security interceptor chain, resulting in an authorization error.
<code>@Configuration
@EnableWebSocketMessageBroker
@EnableWebSocketSecurity
@Slf4j
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private final JwtDecoder jwtDecoder;

    public WebSocketConfig(JwtDecoder jwtDecoder) {
        this.jwtDecoder = jwtDecoder;
    }

    @Bean
    public ChannelInterceptor csrfChannelInterceptor(){
        return new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                return ChannelInterceptor.super.preSend(message, channel);
            }
        };
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor =
                    MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    List<String> authorization = accessor.getNativeHeader("Authorization");

                    String accessToken = authorization.get(0).split(" ")[1];
                    Jwt jwt = jwtDecoder.decode(accessToken);
                    JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
                    Authentication authentication = converter.convert(jwt);
                    accessor.setUser(authentication);
                }
                return message;
            }
        });
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new AuthenticationPrincipalArgumentResolver());
    }

    @Bean
    public AuthorizationManager<Message<?>> messageAuthorizationManager(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
        messages
            .anyMessage().authenticated();
        return messages.build();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat")
            .setAllowedOrigins("http://localhost:8080", "http://localhost:4200");
        registry.addEndpoint("/chat")
            .setAllowedOrigins("http://localhost:8080", "http://localhost:4200")
            .withSockJS();
    }
}
</code>
The problem is that the order in which ChannelInterseptors are registered depends only on the insertion order, since everything is implemented through a regular ArrayList. There is one way - to determine the order of configurations that implement the WebsocketMessageBrokerConfigurer interface. They are injected via a setter in the DelegatingWebSocketMessageBrokerConfiguration. And the order of implementation of collections can be changed using the @Order annotation, placing it above our configuration class.
This solved the problem in my case, but I wondered if there would be a need to explicitly define the order of interceptors, such as wedging into a chain of security interceptors. An analogy can be drawn with SecurityFilterChain, when configuring it you can use the addFilterAt, addFilterBefore, addFilterAfter methods.
I couldn't find a way, but maybe I'm missing something.
Comment: I have the same issue as well, do you solve that?
Comment: Sorry, but I left this question since no one commented. At the moment, the only way I know of is to define the order of the configurations themselves, using the @Order annotation on your websocket configuration class. if you find a more flexible solution, it would be nice if you shared it.
Answer: After some time I returned to this issue and made one decision. Perhaps not the best, but quite functional.
First of all, we need to mark our configuration with the @Order annotation without a parameter, by default it is Integer.MAX_VALUE, which means that our configuration will be processed last, which means that all other configurations will already be processed and all interceptors will be added, which allows us to implement order manually.
Here's how I implemented it:
<code>@Configuration
@EnableWebSocketMessageBroker
@EnableWebSocketSecurity
@Order
@Slf4j
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private final JwtDecoder jwtDecoder;

    public WebSocketConfig(JwtDecoder jwtDecoder) {
        this.jwtDecoder = jwtDecoder;
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        ChannelInterceptor securityInterceptor = new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor =
                    MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    List<String> authorization = accessor.getNativeHeader("Authorization");

                    String accessToken = authorization.get(0).split(" ")[1];
                    Jwt jwt = jwtDecoder.decode(accessToken);
                    JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
                    Authentication authentication = converter.convert(jwt);
                    accessor.setUser(authentication);
                }
                return message;
            }

            @Override
            public String toString(){
                return "SecurityInterceptor";
            }
        };
        ChannelInterceptor csrf = new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                return ChannelInterceptor.super.preSend(message, channel);
            }
            @Override
            public String toString(){
                return "csrfChannelInterceptor";
            }
        };
        addInterceptorBefore(registration, securityInterceptor, AuthorizationChannelInterceptor.class);
        addFilterAt(registration, csrf, XorCsrfChannelInterceptor.class);
    }

    private void addInterceptorBefore(ChannelRegistration registration, ChannelInterceptor interceptor, Class<? extends ChannelInterceptor> before) {
        List<ChannelInterceptor> interceptors = getChannelInterceptors(registration);
        int index = findInterceptor(interceptors, before);
        interceptors.add(interceptors.get(interceptors.size()-1));
        for(int i = interceptors.size()-2; i > index; i--){
            interceptors.set(i, interceptors.get(i-1));
        }
        interceptors.set(index, interceptor);
    }

    private void addFilterAfter(ChannelRegistration registration, ChannelInterceptor interceptor, Class<? extends ChannelInterceptor> after) {
        List<ChannelInterceptor> interceptors = getChannelInterceptors(registration);
        int index = findInterceptor(interceptors, after);
        interceptors.add(interceptors.get(interceptors.size()-1));
        for(int i = interceptors.size()-2; i > index + 1; i--){
            interceptors.set(i, interceptors.get(i-1));
        }
        interceptors.set(index+1, interceptor);
    }

    private void addFilterAt(ChannelRegistration registration, ChannelInterceptor interceptor, Class<? extends ChannelInterceptor> at) {
        List<ChannelInterceptor> interceptors = getChannelInterceptors(registration);
        int index = findInterceptor(interceptors, at);
        interceptors.set(index, interceptor);
    }

    private List<ChannelInterceptor> getChannelInterceptors(ChannelRegistration registration) {
        Field field = ReflectionUtils.findField(registration.getClass(), "interceptors");
        Objects.requireNonNull(field);
        field.setAccessible(true);
        List<ChannelInterceptor> interceptors =
            (List<ChannelInterceptor>) ReflectionUtils.getField(field, registration);
        Objects.requireNonNull(interceptors);
        return interceptors;
    }

    private int findInterceptor(List<ChannelInterceptor> interceptors, Class<? extends ChannelInterceptor> interceptor) {
        int index = -1;
        for(int i = 0; i < interceptors.size();i++){
            if(interceptors.get(i).getClass().equals(interceptor)){
                index = i;
                break;
            }
        }
        return index;
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new AuthenticationPrincipalArgumentResolver());
    }

    @Bean
    public AuthorizationManager<Message<?>> messageAuthorizationManager(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
        messages
            .anyMessage().authenticated();
        return messages.build();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat")
            .setAllowedOrigins("http://localhost:8080", "http://localhost:4200");
        registry.addEndpoint("/chat")
            .setAllowedOrigins("http://localhost:8080", "http://localhost:4200")
            .withSockJS();
    }
}
</code>
This implementation may be far from ideal, but it is simpler than implementing some BeanFactoryPostProcessor and proxy to override behavior. I will be glad if you share your ideas.


Como converter para base64 em C#?

Question: Eu estou utilizando o WebForms. Tem uma determinada parte dessa aplicação onde eu envio, através do Ajax, uma string base64, que se trata do código de uma imagem.
Eu estou acostumado a usar o PHP e utilizo as funções base64_encode e base64_decode para fazer as conversões para base64.
Mas em C# não faço a mínima ideia de como se faça isso.
Como decodificar um base64 em C# (e vice-versa)?
Não sei se é duplicada, não achei nada referente a isso no site
Comment: Você quer decodificar um Base64 em Imagem?
Answer: Se o código se trata da manipulação de imagens então em C# não vai usar string, vai usar byte[] provavelmente, então o uso de:

System.Text.ASCIIEncoding.ASCII.GetBytes

E

System.Text.Encoding.UTF8.GetString

Não fazem muito sentido, supondo que vá ler a imagem assim:
byte[] imagem = System.IO.File.ReadAllBytes(@"<caminho da imagem>");

Então basta passar a variável assim:
string imagebase64 = System.Convert.ToBase64String(imagem);

Não tem por que usar string para isto.
Para decodificar deve usar System.Convert.FromBase64String que irá retornar em byte[] e depois pode salvar os valor disto em um arquivo, assim como desejar, exemplo:
string imagecodificadaembase64 = <valor em string do arquivo ou requisição em bas64>;
byte[] imagemdecodificada = System.Convert.FromBase64String(imagecodificadaembase64);

Answer: Peguei daqui
Encode
public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

Decode
public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

Comment: Supondo que esteja em UTF8 e for string esta ok ... se estiver em outro formato terá que ter cuidado com isto, não é uma solução que funciona magicamente, por exemplo, para não unicode provavelmente seria `System.Text.ASCIIEncoding.ASCII.GetBytes`, para dados binários provavelmente já usaria os bytes diretamente (afinal, base64 geralmente é para fazer transporte de dados binários)

Como converter para base64 em C#?


MySql - No changes detected

Question: Toda vez que altero uma procedure no MySql Workbench e tento gravar (Apply) e eu recebo a seguinte mensagem (No changes detected) ai para contornar o problema eu deleto e recrio a procedure.
Isso é muito chato alguém sabe como resolver?
Abaixo tem duas imagens que mostra que depois de alterar a procedure ele não identifica alteração e não grava.
Obrigado.
Comment: Posta o código de como você tentava alterar a procedure.
Comment: O que você esta alterando ??????????
Comment: Posta o código não a imagem.
Comment: Coloquei duas imagens, acho que fica mais fácil entender, deve existir alguma opção para desabilitar essa identificação de código alterado, mas eu não consegui encontrar.
Comment: O código é esse da imagem. um simples select e ele não identifica a alteração.
Comment: @MarconcilioSouza talvez você não tenha visto a diferença nas imagens na segunda imagem eu acrescentei uma linha, não importa quantas linhas eu altere ou adicione ele não grava. É isso o que eu estou alterando.
Answer: O Mysql apresenta essa mensagem MySql - No changes detected, uma vês que o script já tenha sido executado ou nada tenha sido alterado no Script.
O que pode ter acontecido é você ter clicado no Apply uma ver e depois continuar clicando.
Altere seu select e veja que vai se alterado.
E seu DEFINER=root@%
Abra uma nova guia com seu scrip da procedure da seguinte forma e execute.
USE `seu banco`;
DROP procedure IF EXISTS `procedureTeste`;

DELIMITER $$
USE `seu banco`$$
CREATE DEFINER=`root`@`%` PROCEDURE `procedureTeste`()
BEGIN

select 'teste';
select 'teste2';
select 'teste3';
select 'teste4';

-- altera o que for preciso e execulta.
END$$

DELIMITER ;

Comment: Já alterei diversas vezes e já cliquei no Apply diversas vezes e a procedure sempre volta para a forma com o conteúdo com qual foi criada a primeira vez, vc sabe se existe uma forma de desativar esta identificação se a procedure foi alterada ou não? Tipo não me interessa se a procedure foi alterada ou não, se eu cliquei no gravar e para gravar e pronto igual o world.
Comment: Tentei com root e também não grava.
Comment: Tente altera através do script .
Comment: Dessa forma funciona mas perde a praticidade que a ferramenta oferece, acredito que o que esteja acontecendo seja um bug do próprio workbench. De qualquer maneira muito obrigado pela ajuda.

MySql - No changes detected


Existence of continuous sections of a continuous open surjection.

Question: Let $f : X \to Y$ be a continuous open surjection between Hausdorff spaces.
Does there always exists a continuous section $s: Y \to X$ of $f$?
If not, under what conditions does one exist?
For the problem I'm considering I have a few additional assuptions available, but they may be red herrings:

$X$ and $Y$ are compact/locally compact, and
$\sup_{x \in X} \# f^{-1}(x)<\infty$.
Comment: Generally the answer is no; consider any nontrivial covering map of Hausdorff spaces, e.g. the double cover $S^1 \to S^1$. See also https://qchu.wordpress.com/2014/11/29/topological-diophantine-equations/ for some discussion.
Comment: @QiaochuYuan Thanks for that example. I think what I actually want is the existence of local sections. Do you know if anything prevents that?
Answer: Consider the map $f(z)=z^2$ of the complex plane and try to construct a local section near zero.


Prove that if $a, b, c \geq 0$ then $(a + b)(b + c)( a + c) \geq 8abc$

Question:
Prove that if $a, b, c\ge 0$, then $(a + b)(b + c)(a + c)\ge 8abc$.
Comment: Hint: $a+b \ge 2 \sqrt{ab}$ for $\forall a,b \ge 0\,$.
Answer: Note that $$a+b \ge 2 \sqrt{ab}$$ By $\text{AM-GM}$.
So we have  $$(a+b)(b+c)(c+a) \ge 2\sqrt{ab} \times 2 \sqrt{bc}  \times 2 \sqrt{ca}=8abc$$
Answer: The ArithmeticMean-GeometricMean (AM-GM) Inequality states that for non-negative real numbers $a$ and $b$ one has:
$$\frac{a+b}{2}\geq \sqrt{a\cdot b}$$
Proof:
$0\leq^{\color{gray}{\star}} (\sqrt{a}-\sqrt{b})^2 = (\sqrt{a})^2-2\sqrt{a}\cdot\sqrt{b}+(\sqrt{b})^2 = a-2\sqrt{ab}+b$
The inequality marked $\star$ is valid since the square of any real number is non-negative (noting that $\sqrt{a}-\sqrt{b}$ is a real number).
Rearranging: $2\sqrt{ab}\leq a+b$
Using this inequality three times (once for $(a+b)$, again for $(b+c)$ and once more for $(c+a)$) the original problem is proven.
Answer: Observe that $LHS - RHS = a(b-c)^2 + b(c-a)^2 + c(a-b)^2 \ge 0$.


angular2 after upgrade Error encountered resolving symbol values statically

Question: i had upgraded to the latest angular cli and now i get this error:

Error encountered resolving symbol values statically. Reference to a local (non-exported) symbol 'dictionary'. Consider exporting the symbol (position 12:7 in the original .ts file), resolving symbol TRANSLATION_PROVIDERS in C:/xampp/htdocs/milesofmusic/src/app/translate/translation.ts, resolving symbol AppModule in C:/xampp/htdocs/milesofmusic/src/app/app.module.ts, resolving symbol AppModule in C:/xampp/htdocs/milesofmusic/src/app/app.module.ts

the code it refers to is this:
// all traslations
const dictionary = {
    [LANG_EN_NAME]: LANG_EN_TRANS,
    [LANG_HE_NAME]: LANG_HE_TRANS,
};

// providers
export const TRANSLATION_PROVIDERS = [
    { provide: TRANSLATIONS, useValue: dictionary },
];

and in my app module i import
import { TRANSLATION_PROVIDERS } from './translate/translation';
and have it in the providers array
how to fix it?
Answer: const dictionary  = {
    [LANG_EN_NAME]: LANG_EN_TRANS,
    [LANG_FR_NAME]: LANG_FR_TRANS,

};

I am also getting the same error, so do one thing: directly write the language value instead of the brackets.
const dictionary  = {
    "en-US": LANG_EN_TRANS,
    "fr-FR": LANG_FR_TRANS,
};

Enjoy Happy Coding
Answer: I believe you got this example from an old guide somewhere on the world wide web. As far as I remember, this one is outdated and it's not the appropriate way anymore to handle translations within angular2. I suggest you take a look at the
i18n internationalization cookbook of angular.
Comment: yeah, that was the first thing i tried. but then i get still: Error encountered resolving symbol values statically. Expression form not supported (position 13:2 in the original .ts file), resolving symbol dictionary in C:/xampp/htdocs/milesofmusic/src/app/translate/translation.ts, resolving symbol TRANSLATION_PROVIDERS in C:/xampp/htdocs/milesofmusic/src/app/translate/translation.ts, resolving symbol AppModule in C:/xampp/htdocs/milesofmusic/src/app/app.module.ts, resolving symbol AppModule in C:/xampp/htdocs/milesofmusic/src/app/app.module.ts
Comment: thanks for the answer. i will need to convert it to use the built in i18n. but this answer did work for me [link](http://stackoverflow.com/a/40643715/587579)
Comment: I was looking for that one! I remembered I saw the same question before :) nice find.


Model selection with low N?

Question: I've got a study which is kinda messed up by the design...Turns out I ended up with about 50 patients of which 80% have the outcome and 20% don't (binary outcome).
I've been turning in my bed for the last month trying to figure out what to do with this. The only real answer is "don't" but I have to deliver something in the next days as it's part of a master's thesis.
I have about 10 predictors of interest for the outcome (various variable types) and the research question is whether any of these predictors can predict the outcome. Some already have an established correlation in the literature while some are original hypothesis. Several are significant with a univariate logistic regression, but it doesn't look good in any other way than the actual p-value.
Now obviously I'm not going to be able to answer this research question sufficiently but if you were in my shoes, what sort of statistical analysis would you perform to relay to your supervisors?
EDIT: Link to my (anonymized) data (CSV): https://gofile.io/?c=vwH9PS
Comment: What goes wrong if you have adequate power to get significant p-values?
Comment: See for yourself. Edited to include data. Outcome variable is labelled outcome. The rest is predictors.
Comment: I think I'd go for a form or regularized logistic regression such as elastic net. But as you rightly acknowledge: It's hard to learn much from small samples.
Comment: I've been working with Lasso, would that be the same thing?
Comment: Also which of these variables would you include in which bracket of the regularization? I'm interested in all the variables, which makes it hard to choose which go in "interested" and which go in the "picks from" column.
Answer: For biomedical studies, a general rule of thumb to avoid overfitting in an unpenalized logistic regression model is to have on the order of 10-20 minority-class cases per evaluated predictor. You have about 10 cases in the minority class, so without penalization you should only be evaluating 1 predictor. That predictor would need to be pre-selected based on your knowledge of the subject matter, as using the data to identify the predictor invalidates the assumptions needed to calculate p-values and confidence intervals.
If you did multiple association tests of outcome against each predictor as you propose you would at least have to correct for multiple comparisons and you would not be able to control for the values of the other predictors.
LASSO tends to return a number of predictors similar to the number that would be allowed under the rule of thumb in the first paragraph: so maybe only 1 or 2 in this case.
Logistic ridge regression (L2 penalty) might be the best way to start working with this small data set. All of your predictors would be included in the model, but their coefficients would be heavily penalized to avoid overfitting.
Comment: @Paze in logistic regression I use that to mean the class with the smallest number of cases. So it isn't the 50 total cases that matters. With 40 in one class and only 10 in the other, the rule of thumb would be based on the 10 cases in the smaller class.
Comment: @Paze it's generally good to start with your understanding of the subject matter rather than just throwing everything blindly at penalized regression software. That said, if predictors are linearly related to outcome then penalized regressions will emphasize the strongest associations _in your data sample_ regardless of how many predictors you include. A risk in throwing everything in is finding spurious associations due to peculiarities of your data sample. A risk of not throwing everything in is missing a true, novel finding. As always: tradeoffs of Type I and Type II errors.
Comment: To be able to correctly understand your answer, which thus far is quite illuminating, I'd like to ask what you mean by the nomenclature "minority-class case"? I've heard the rule of thumb being 10 independent variables per dependent variable but I've never heard of "minority-class cases" and I want to make sure we are on the same page.
Comment: Thank you. Is there a similar rule for penalized regressions or can you simply throw as much as you want at them?

Model selection with low N?


How to find and fix fragmented MySQL tables

Question: I used MySQLTuner which pointed out some tables were fragmented.  I used
mysqlcheck --optimize -A
to optimize all tables.  It fixed some tables but MySQLTuner still finds 19 tables fragmented.  how can I see which tables are in need of defragmenting?  Maybe OPTIMIZE TABLE will work where mysqlcheck didn't?  Or what else should I try?
Comment: I have a similar problem. I'm setting up a new DB with MySQL 5.5 and certain InnoDB tables never unfragment.  I'm wondering if the Data_free check (shown in KayakJim's answer) is incorrect with InnoDB tables.
Answer: the short answer:
select  ENGINE, TABLE_NAME,Round( DATA_LENGTH/1024/1024) as data_length , round(INDEX_LENGTH/1024/1024) as index_length, round(DATA_FREE/ 1024/1024) as data_free from information_schema.tables  where  DATA_FREE > 0;

The "You must know" answer
first at all you must understand that Mysql tables get fragmented when a row is updated, so it's a normal situation.
When a table is created, lets say imported using a dump with data, all rows are stored with no fragmentation in many fixed size pages. When you update a variable length row, the page containing this row is divided in two or more pages to store the changes, and these new two (or more) pages contains blank spaces filling the unused space.
This does not impact performance, unless of course the fragmentation grows too much.
What is too much fragmentation, well let's see the query you're looking for:
  select  ENGINE, TABLE_NAME,Round( DATA_LENGTH/1024/1024) as data_length , round(INDEX_LENGTH/1024/1024) as index_length, round(DATA_FREE/ 1024/1024) as data_free from information_schema.tables  where  DATA_FREE > 0;

The DATA_LENGTH and INDEX_LENGTH are the space your data and indexes are using,  and DATA_FREE is the total amount of bytes unused in all the table pages (fragmentation).
Here's an example of a real production table
| ENGINE | TABLE_NAME               | data_length | index_length | data_free |
| InnoDB | comments                 |         896 |          316 |         5 |

In this case we have a Table using (896 + 316) = 1212 MB, and have data a free space of 5 MB.
This means a "ratio of fragmentation" of:
5/1212 = 0.0041

...Which is a really low "fragmentation ratio".
I've been working with tables with a ratio near 0.2 (meaning 20% of blank spaces) and never notice a slow down on queries, even if I optimize the table, the performance is the same. But apply a optimize table on a 800MB table takes a lot of time and blocks the table for several minutes, which is impracticable on production.
So, if you consider what you win in performance and the time wasted in optimize a table, I prefer NOT OPTIMIZE.
If you think it's better for storage, see your ratio and see how much space can you save when optimize. It's usually not too much, so I prefer NOT OPTIMIZE.
And if you optimize, the next update will create blank spaces by splitting a page in two or more. But it's faster to update a fragmented table than a not fragmented one, because if the table is fragmented an update on a row not necessarily will split a page.
I hope this helps you.
Comment: Although this is an answer from several years ago, I thought I'd point out that the data_free is a stat for the whole tablespace, not for the respective table. If you store multiple tables together in one tablespace, the data_free can mislead you to believe the table needs defragmenting, when it just means there are free extents in the tablespace. Running optimize table won't reduce the free extents. Defragmenting the table may even *increase* the free extents.
Answer: Just to add to the answer from Felipe-Rojas you can calculate the fragment ratio as part of the query:
select ENGINE,
  concat(TABLE_SCHEMA, '.', TABLE_NAME) as table_name,
  round(DATA_LENGTH/1024/1024, 2) as data_length,
  round(INDEX_LENGTH/1024/1024, 2) as index_length,
  round(DATA_FREE/1024/1024, 2) as data_free,
  (data_free/(index_length+data_length)) as frag_ratio
FROM information_schema.tables
WHERE DATA_FREE > 0
ORDER BY frag_ratio DESC;

If a table is fragmented a small percentage (less than 5%?) then you can probably leave it alone.
Anything larger and you will need to assess based on your db usage, locking tables etc as to how important it is to defragment the table.
Answer: Optimize Table will indeed resolve the issue you are having.
If you only have a few databases, then you could go use PHPMyAdmin to go through all of your databases. Select the tables with overhead and then select to optimize.
If you have a lot of databases then another method would likely be preferable.
I use the following PHP script setup in cron to run every hour.
$DB = new mysqli ('localhost', 'DbUser', 'DbPassword');
$results = $DB->query('show databases');
$allDbs = array();
while ($row = $results->fetch_array(MYSQLI_NUM))
{
    $allDbs[] = $row[0];
}
$results->close();
foreach ($allDbs as $dbName)
{
    if ($dbName != 'information_schema' && $dbName != 'mysql')
    {
        $DB->select_db($dbName);
        $results = $DB->query('SHOW TABLE STATUS WHERE Data_free > 0');
        if ($results->num_rows > 0)
        {
            while ($row = $results->fetch_assoc())
            {
                $DB->query('optimize table ' . $row['Name']);
            }
        }
        $results->close();
    }
}
$DB->close();

Comment: I'm pretty sure that `mysqlcheck --optimize -A` is the same as the SQL `OPTIMIZE TABLE ;`
Answer: I came across this page and found the queries by Felipe-Rojas and sysadmiral to be very helpful. But in my case, I was running the query in WHM's phpMyAdmin and getting only TABLE_NAME was not as helpful since the database was not listed, and several databases have the same table names. So, simply adding TABLE_SCHEMA will provide that column as well.
select  ENGINE, TABLE_SCHEMA, TABLE_NAME, Round( DATA_LENGTH/1024/1024) as data_length , round(INDEX_LENGTH/1024/1024) as index_length, round(DATA_FREE/ 1024/1024) as data_free, (data_free/(index_length+data_length)) as frag_ratio from information_schema.tables  where  DATA_FREE > 0 order by frag_ratio desc

Shows DB
ENGINE  | TABLE_SCHEMA  | TABLE_NAME    | data_length   | index_length  | data_free | frag_ratio

InnoDB  | db_name       | db_table      | 0             | 0             | 8         | 170.6667

To "fix" I used the Defragment table link in phpMyAdmin for each of the tables that resulted in high "frag_ratio" for which phpMyAdmin executes:
ALTER TABLE `table_name` ENGINE = InnoDB;

Answer: A table using MySQL's InnoDB Engine essentially never needs to be OPTIMIZEd.
The value of Data_free from either information_schema.tables or SHOW TABLE STATUS is very often non-zero, even when you think you have done all you can do defrag your table(s).  Furthermore, that metric is only one of several fragmentations that can and do occur.  (Also, wasted space in blocks, undo lists, index BTrees vs data BTrees, etc, etc.
And innodb_file_per_table complicates the use of Data_free.  If the table is in ibdata1, then Data_free refers to the entire tablespace; a rather useless number.  If the table is in its own .ibd file, it is likely to be a few MB or a few percent of the table size, whichever is larger.
Only if you have deleted lots of rows and don't intend to refill the table, might it be worth running OPTIMIZE TABLE.
PARTITIONs also show a disturbing amount of Data_free, since each partition typically shows 4-7MB "free".  And this will not go away.
Why Defragment?

To return space to the OS?  Well, you might achieve this briefly if you had innodb_file_per_table=1.  But as you add rows, you will take it back from the OS.
To speed up access?  Forget it.  The layout of blocks on disk is relatively random, and has been for the last few decades.  Half a century ago, it was somewhat important to rearrange blocks.
To rebalance BTrees?  So?  They will promptly become unbalanced again.  The steady-state for BTrees that are randomly inserted into is 69%.  And that is not even factored into Data_free.
MySQLTuner says to?  That product needs to chill.

A history note.  When I was helping DBAs with mostly MyISAM tables, I discovered perhaps 2 out of 1000 tables that were helped by a monthly OPTIMIZE.  Since then, I have worked with thousands of InnoDB tables, have yet find a performance problem that was likely to be helped by OPTIMIZE.  (Sure, there have been disk space problems for which OPTIMIZE might help, but that gets tricky -- usually the DBA does not have enough disk space to run OPTIMIZE!)