find the average of 2 columns in Tableau

Question: would appreciate help on how to use tableau to show the average of Q1 & Q2 as shown in attached image:
Find AvgeQ1&Q2
Comment: Nice Beattle, do you already has those data inside your Tableau or in an Excel (Access or something of a kind)?
Comment: I already have the data sample in excel but want help on how to do the same in Tableau ... any ideas? Thanks
Comment: how is the data shaped? What are the column headers in Excel? Level of detail?
Comment: CC Date Period Metric
Comment: hello, just 3 columns : CC, Date_Period, Metric  ........ the date period has the last 6 months November to April ... i need to be able to show in tableau an additional field for the average (january, april) thanks
Comment: Did you have any calculation for Jan month or it is coming from database?
Comment: hello, no calculation for January comes from the database ... thanks
Comment: Level of detail? or granularity? meaning one row per month in your data set? one row per day? one row per transaction? Ideal if you have transactional data in your data set and let Tableau generate a query to aggregate it? (If you pre-aggregate the data before making available to Tableau, you limit what you can do)
Answer: Use Connect --> To a File --> Excell then open your file. If data is shown scrambled, check the checkbox located on the left of the window, below the title Sheets --> Cleaned with data. Then, see following image:
1 - click on top right of table field and
2 - select Create calculated field

3 - Find a name for the new field
4 - Enter with the expression: SUM(([End Q1 Jan]+[End Q2 Apr])/2)
5 - Apply

A new field will be created on your sheet with active calculation (if you update values on your Excell file and refresh data in Tableau - or close/open, you will see updated values).
Answer: You'll do better if your Date_Period column is a real date (i.e. it has all three parts - Month, Day, Year) and not just a month name or a string describing the period.
If you do that, i.e. make sure your Date_Period column has the data type date (with a calendar icon next to the field name), then drag Date_Period to the Rows shelf. You'll see it displayed as YEAR(Date_Period), meaning Tableau is extracting the Year date part and treating it as dimension. Click the + sign to the left of the field on the Rows Shelf to also get a row per QUARTER(Date_Period). Click that fields + sign to expand again to get a row per month.
Put Metric onto the text shelf on the marks card. Right click on the Metric field and choose AVG as the Measure aggregation function.
From the Analysis menu, under Totals, show Column Totals. Right click on the fields on the Rows shelf (starting from the left) and choose Subtotals to show the subtotals that you want.
If you want to change the label from Total to Average or something else to reflect the aggregation function you chose, right click on the word Total in the view and choose Format. On the Format pane, under Header, you can choose the label you wish to display


Crystal Reports Primavera V9 "Fazer filtro sobre mapa a partir do form primavera"

Question: [Crystal Reporter]
[]1
Tenho essa tela, preciso construir um mapa que me mostra a Análise Mensal e Anual
ao mesmo tempo, mas, a partir de uma query e não tabelas específicas só que nessa query preciso de um filtro que é o ano (2019) da Imagem acima.
Como faço para pegar o 2019 do form inserir no mapa sem utilizar parâmetros? segue a query( o ano (2019) precisa vir do form):
<code>select *
from (

select a.rubrica,
Jan=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=1 and year(dataac)=2019 ),0) ,
Fev=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=2 and year(dataac)=2019 ),0),
Marc=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=3 and year(dataac)=2019 ),0),
Abr=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=4 and year(dataac)=2019 ),0),
Mai=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=5 and year(dataac)=2019 ),0),
Jun=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=6 and year(dataac)=2019 ),0),
Jul=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=7 and year(dataac)=2019 ),0),
Ago=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=8 and year(dataac)=2019 ),0),
Sept=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=9 and year(dataac)=2019 ),0),
Outb=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=10 and year(dataac)=2019 ),0),
Nov=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=11 and year(dataac)=2019 ),0),
Dez=isnull((select sum(jan.acum) from AcRubricas jan where jan.rubrica=a.rubrica and month(dataac)=12 and year(dataac)=2019 ),0)
from AcRubricas a where year(a.DataAc)=2019  group by a.Rubrica) mensal
inner join
(select rubrica,sum(Acum) as Acumulado,sum(orca) as Orcamento,( sum(orca) - sum(Acum)) as desvio from AcRubricas where  year(DataAc)=2019 group by rubrica) anual on anual.rubrica = mensal.Rubrica
</code>
Answer: Diria que o mais simples,é criar uma view com base nessa query, retirando o filtro por Ano e agrupando os dados por Ano. Depois crias um mapa novo com base no existente. Adicionas a tua View ao mapa, podes fazer o link à tabela existente, por exemplo pela Rubrica, tendo assim o filtro das rubricas seleccionadas na janela. Dentro desse mapa tens lá um campo "Ano" ("formula field"), que é passado pelo Primavera. Usas esse campo para filtrar os dados a apresentar.
Comment: muitas vezes tenho tido problemas ao filtrar os dados a apresentar e evito usar porque ao fazer o somatório usar todos os dados até os não apresentados. obgdo pela sugestão. Percebi que não tenho hipótese sem os parâmetros é isso? fiz um mapa novo e estou tendo um outro erro.  segue o erro:"Esse nome de campo não é conhecido.
Detalhes: errorKind
Erro no arquivo BALS01 {5B2E11DD-6324-4390-8E03-157B7850BFA2}.rpt:
Erro na fórmula Record Selection:
'{AcumuladosRubricas.posto}=1'
Esse nome de campo não é conhecido.
Detalhes: errorKind"


How do I prove that $\sum_{k=0}^n \binom{2n}{k}=2^{2n-1} + \binom{2n-1}{n}$?

Question: I am trying to prove that, for all natural numbers $n\geq 1$, $$\displaystyle\sum_{k=0}^n\binom{2n}{k} = 2^{2n-1} + \binom{2n-1}{n}$$

I have checked it with computer up to $n=1000$. It is always true. But I do not know how to prove it.
I tried to use the identity which I know already.
$$\displaystyle\sum_{k=0}^n \binom{n}{k}^2 = \binom{2n}{n}$$
$$\displaystyle\sum_{k=0}^n \binom{n}{k} = 2^n$$
If you add them up then it looks close to the answer on right side only.
$$\displaystyle\sum_{k=0}^n \left[\binom{n}{k}^2 + \binom{n}{k}\right] = 2^n + \binom{2n}{n}$$
But it is not the same. Off by $1$, should be $2n-1$ not $2n$.
Answer: The calculation $2^{2n}=\sum_{k=0}^{2n}\binom{2n}{k}=2\sum_{k=0}^n\binom{2n}{k}-\binom{2n}{n}$ uses two facts, both with $m=2n$: $2^m=\sum_k\binom{m}{k}$ (partition subsets of a size-$m$ set by their size) and $\binom{m}{k}=\binom{m}{m-k}$ (pair subsets and their complements). So$$\sum_{k=0}^n\binom{2n}{k}=2^{2n-1}+\frac12\binom{2n}{n}=2^{2n-1}+\binom{2n-1}{n},$$since$$\frac12\binom{2n}{n}=\frac{(2n)!}{2\cdot n\cdot (n-1)!\cdot n!}=\frac{(2n-1)!}{(n-1)!n!}=\binom{2n-1}{n}.$$
Answer: $\sum_\limits{k=0}^{2n} {2n\choose k} = \sum_\limits{k=0}^{n-1} {2n\choose k} + {2n\choose n} + \sum_\limits{k=n+1}^{2n} {2n\choose k} = 2^{2n}$
Since ${n\choose k} = {n\choose n-k},$ we can say $\sum_\limits{k=0}^{n-1} {2n\choose k} = \sum_\limits{k=n+1}^{2n} {2n\choose k}$
$2\sum_\limits{k=0}^{n-1} {2n\choose k} = 2^{2n} - {2n\choose n}$
We must show that ${2n\choose n} = 2{2n-1\choose n}$
${2n\choose n} = \frac {(2n)!}{n!n!}$ by definition
Factoring $2n$ from the numerator and $n$ from the denominator.
$\frac {2n(2n-1)!}{n(n-1)!n!} = \frac {2(2n-1)!}{(n-1)!n!} = 2{2n-1\choose n}$
$2\sum_\limits{k=0}^{n-1} {2n\choose k} = 2^{2n} - 2{2n-1\choose n}\\
\sum_\limits{k=0}^{n-1} {2n\choose k} = 2^{2n-1} - {2n-1\choose n}\\
$


Why $f(n) = \frac{1}{(n+1)}+\frac{1}{(n+1)(n+2)}+\frac{1}{(n+1)(n+2)(n+3)}+... = \frac{1}{n} - \frac{1}{n^3} + O(\frac{1}{n^4})$, ($n\in N, n\ge 2$)?

Question: I think we need to prove $\frac{1}{(n+1)}+...+\frac{1}{(n+1)(n+2)(n+3)(n+4)}\le \frac{1}{n} - \frac{1}{n^3} $ and $\frac{1}{(n+1)...(n+5)}+\frac{1}{(n+1)...(n+6)}+...\le \frac{1}{n^5}$. I try to manipulate this formula, but just have another cubersome formula. I think to compare to $\frac{1}{n}+\frac{1}{n^2}+...$ then use geometric series formula, but not see anything.
This is a detail in the solution of problem 1.1 of the book "Problems and Solutions in Real Analysis" by Masayoshi Hata. Here, I change notation $\epsilon_n$ in the book to $f(n)$.
Comment: Put $n=1/x$, expand the left-hand side into a power series about $0$ up to order $x^4$ and replace $x$ by $1/n$.
Comment: @Gary Thank! Details from your hint (correct me if I'm wrong). First, set $f(0)=0$, so $f(x)$ is determined at $0$, and in $f'(x)$, only first term $\bigg(1/(\frac{1}{x}+1)\bigg)'\ne 0$ at $0$, so $2$-th order Taylor expansion is $\frac{1}{n+1}-\frac{1}{(n+3)^3}+O(1/n^2)$ (not $O(1/n^4)$ as in the question), and we has the answer. If nothing's wrong, please turn your comment into the answer.
Comment: More [context](http://meta.math.stackexchange.com/a/9960) should be included or perhaps an application of the hint given by Gary. If not, this question appears to be a [PSQ](https://math.meta.stackexchange.com/q/33854) and may be closed. If the question is improved, I can post an answer that gives the coefficient for each $\frac1{n^i}$.
Comment: @ydhhat: instead of Gary answering a PSQ, which might be closed and deleted, improve the question, as mentioned above, and Gary can post his answer and I will post mine.
Comment: @robjohn , Thank! check my edited question.
Comment: @ydhhat: thank you for providing some context. I still fear that others may want more, and my answering might draw them here, so if there is any more context you can add (e.g. adding the things you have written in comments to the question) it would be useful.
Comment: @Gary This comment continues the above comment about details from Gary's hint, the $O(\frac{1}{n^2})$ part is wrong (somehow, I misuse litle-o as big-O). Now, continues expand to 4-th order Taylor series of $f$, we get the answer.
Answer: We basically want the expansion of $f(n)$ around $n = \infty$. To this end we can take the expansion of $f(1/x)$ around $x = 0$. Note that we only need to go till $x^4$ since we want the expansion of $f(n)$ to end with $O(1/n^4)$. Then \begin{align*}f(1/x) &= \frac{1}{1/x + 1} + \frac{1}{(1/x + 1)(1/x + 2)} + \frac{1}{(1/x + 1)(1/x + 2)(1/x + 3)} + \cdots\\
&=\frac{x}{x+1} + \frac{x^2}{(x+1)(2x + 1)} + \frac{x^3}{(x+1)(2x + 1)(3x+1)} + \cdots\\
&=x\sum_{k=0}^\infty (-x)^k + x^2 \sum_{k=0}^\infty(-x)^k\sum_{k=0}^\infty(-2x)^k + x^3\sum_{k=0}^\infty(-x)^k\sum_{k=0}^\infty(-2x)^k\sum_{k=0}^\infty(-3x)^k + x^4\prod_{i=1}^4\sum_{k=0}^\infty(-ix)^k\\
&=(x-x^2 + x^3 - x^4 + \cdots) + (x^2 - 3x^3 + 7x^4 + \cdots) + (x^3 - 6x^4 + \cdots) + (x^4 + \cdots)\\
&= x - x^3 + O(x^4),\quad \text{as }x\to 0\end{align*}
so $f(n) = \frac{1}{n} - \frac{1}{n^3} + O\left(\frac{1}{n^4}\right)$ as $n \to \infty$.
Answer: $\newcommand{\d}{\mathrm{d}}$
$\newcommand{\e}{\mathrm{e}}$
Note that
$$\begin{split}f(n) &= \sum_{k=0}^{\infty}\frac{n!}{(n+k+1)!} \\
&= \sum_{k=0}^{\infty}\int_0^1 \frac{(1-t)^k}{k!}t^n \d t \\
&= \int_0^1 \sum_{k=0}^{\infty}\frac{(1-t)^k}{k!}t^n \d t \\
&= \int_0^1 \e^{1-t} t^n \d t \\
&= \int_0^{\infty} \e^{1-t-\e^{-t}} \e^{-nt}\d t \text{.}
\end{split}$$
(The sum and integral interchange by the monotone convergence theorem for integrals.) Note that $\e^{1-t-\e^{-t}}$ is analytic and has Maclaurin expansion
$$\e^{1-t-\e^{-t}} = \sum_{k=0}^{\infty}a_k \tfrac{t^k}{k!}\text{,}$$
with coefficients given by OEIS A014182
$$a_{(\quad)} = (1,0,-1,1,2,-9,\ldots)\text{.}$$
Then by Watson's lemma, the integral expression for $f(n)$ has the asymptotic expansion that one would expect by termwise integration:
$$\begin{split}f(n)=\int_0^{\infty} \e^{1-t-\e^{-t}} \e^{-nt}\d t &\sim \sum_{k=0}^{\infty} \frac{a_k}{n^{k+1}}\\
&= \frac{1}{n}-\frac{1}{n^3} +\frac{1}{n^4} + \frac{2}{n^5} -\frac{9}{n^6} + O(n^{-7})\text{.}\end{split}$$
Answer: Expanding as a geometric series gives
$$
\frac1{n+j}=\sum_{i=0}^{m-1}(-1)^i\frac{j^{\,i}}{n^{i+1}}+\frac1{n^{m+1}}O\!\left(j^m\right)\tag1
$$
Using the Heaviside method for partial fractions yields
$$
\frac{n!}{(n+k)!}=\sum_{j=1}^k\frac{(-1)^{j-1}}{(j-1)!(k-j)!}\frac1{n+j}\tag2
$$
With $a_i=e\sum\limits_{j=0}^\infty\frac{(-1)^{i+j}}{j!}j^{\,i}$, we have
$$
\begin{align}
\sum_{k=1}^\infty\frac{n!}{(n+k)!}
&=\sum_{j=1}^\infty\sum_{k=j}^\infty\frac{(-1)^{j-1}}{(j-1)!}\frac1{(k-j)!}\frac1{n+j}\tag{3a}\\
&=e\sum_{j=1}^\infty\frac{(-1)^{j-1}}{(j-1)!}\frac1{n+j}\tag{3b}\\
&=\sum_{i=0}^{m-1}(-1)^i\frac1{n^{i+1}}e\sum_{j=1}^\infty\frac{(-1)^{j-1}}{(j-1)!}j^{\,i}+O\!\left(\frac1{n^{m+1}}\right)\tag{3c}\\
&=\sum_{i=1}^m\frac1{n^i}e\sum_{j=0}^\infty\frac{(-1)^{i+j}}{j!}j^{\,i}+O\!\left(\frac1{n^{m+1}}\right)\tag{3d}\\
&=\sum_{i=1}^m\frac{a_i}{n^i}+O\!\left(\frac1{n^{m+1}}\right)\tag{3e}
\end{align}
$$
Explanation:
$\text{(3a)}$: apply $(2)$ and swap order of summation
$\text{(3b)}$: sum in $k$
$\text{(3c)}$: apply $(1)$
$\text{(3d)}$: substitute $i\mapsto i-1$, multiply by $\frac jj$, include the $j=0$ term
$\text{(3e)}$: apply the definition of $a_i$
Here is a method to compute the $a_i$ without the use of Stirling Numbers of the Second Kind; however, it is not apparent that these coefficients are all integers:
$$
\begin{align}
a_i
&=e\sum_{j=0}^\infty\frac{(-1)^{i+j}}{j!}j^{\,i}\tag{4a}\\
&=\sum_{j=0}^\infty\sum_{k=j}^\infty\frac{(-1)^{i+j}}{(k-j)!j!}j^{\,i}\tag{4b}\\
&=\sum_{k=0}^\infty\sum_{j=0}^k\frac{(-1)^{i+j}}{(k-j)!j!}j^{\,i}\tag{4c}\\
&=\sum_{k=0}^i\sum_{j=0}^k\frac{(-1)^{i+j}}{(k-j)!j!}j^{\,i}\tag{4d}\\
&=\sum_{j=0}^i\sum_{k=j}^i\frac{(-1)^{i+j}}{(k-j)!j!}j^{\,i}\tag{4e}\\
&=\sum_{j=0}^i\sum_{k=0}^{i-j}\frac{(-1)^{i+j}}{k!j!}j^{\,i}\tag{4f}
\end{align}
$$
Explanation:
$\text{(4a)}$: definition
$\text{(4b)}$: $e=\sum\limits_{k=j}^\infty\frac1{(k-j)!}$
$\text{(4c)}$: switch order of summation
$\text{(4d)}$: the $k^\text{th}$ difference of $j^{\,i}$ vanishes for $k\gt i$
$\text{(4e)}$: switch order of summation
$\text{(4f)}$: substitute $k\mapsto k+j$
Using Stirling Numbers of the Second Kind, however, it is easy to see that these coefficients are integers:
$$\newcommand{\stirtwo}[2]{\left\{#1\atop #2\right\}}
\begin{align}
a_i
&=e\sum_{j=0}^\infty\frac{(-1)^{i+j}}{j!}j^{\,i}\tag{5a}\\
&=e\sum_{j=0}^\infty\frac{(-1)^{i+j}}{j!}\sum_{k=0}^i\stirtwo{i}{k}\frac{j!}{(j-k)!}\tag{5b}\\
&=e\sum_{k=0}^i\sum_{j=0}^\infty\stirtwo{i}{k}\frac{(-1)^{i+j}}{(j-k)!}\tag{5c}\\
&=\sum_{k=0}^i(-1)^{i-k}\stirtwo{i}{k}\tag{5d}
\end{align}
$$
Explanation:
$\text{(5a)}$: definition
$\text{(5b)}$: $j^{\,i}=\sum\limits_{k=0}^i\stirtwo{i}{k}\frac{j!}{(j-k)!}$
$\text{(5c)}$: combine terms and switch order of summation
$\text{(5d)}$: sum in $j$
Thus, using $(3)$ and either $(4)$ or $(5)$, we get
$$
\!\!\!\!\!\!\sum_{k=1}^\infty\frac{n!}{(n+k)!}=\frac1n+\frac0{n^2}-\frac1{n^3}+\frac1{n^4}+\frac2{n^5}-\frac9{n^6}+\frac9{n^7}+\frac{50}{n^8}-\frac{267}{n^9}+O\!\left(\frac1{n^{10}}\right)\tag6
$$
Comment: Somewhere you have to address the fact that these are formal manipulations. For example $(1)$ is valid for $n>j$ but $j$ will eventually run through all positive integers.
Comment: @Gary: How about now?
Comment: Looks good now!


Load html in div and then remove it

Question: I'm a beginner in Javascript and I struggle with a problem for a while. I want to open a new content in an existing div from another local html document. So in main content I have a simple list of projects and when I click on one project I want it to open in same the div '#content' as my projects. For this I use code:
$(document).ready(function() {
    $('a.th-link').click(function() {
        var url = $(this).attr('href');
        $('#content').html('
Loading...
').load(url+ '#mynewdiv');
        $.getScript('js/jquery.js');
        $.getScript('js/jquery.horizontal.scroll.js');
        $.getScript('js/jquery.mousewheel.js');
        $(url).remove();
        return false;
    });
 });

The problem is when I want to go back to my main div with projects '#content', with back-button on mouse or with browser, I stuck on other div '#mynewdiv', or I get to the previous open site.
Can anybody help with the code?
I'm still dealing with this problem. I found a rough example that is similar to mine and I have transformed it, to work like I want, but still doesn't work as it should. To refresh my problem.
I want to open in certain div, a new html page and it will work back button.
I also tried benalman bbq but I can't figure out, what I'm doing wrong.
Here is what I'm doing
    <!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>TEST</title>

Test

    Test 1

    Test 2

Thanks for the answer
Comment: Javascript changes will loss, when you press back button in browser
Answer: .load() gets the data and displays it on the same site. The browser is never changing page. So when you click back, the browser will go to the previous open site.
You can use a plugin like jQuery Address to simulate the behavior you want.

Load html in div and then remove it


Fisher exact test for mutation co-occurence

Question: I've a dataset of 492 samples, for each sample I've information regarding if gene X  has a germline mutation and a somatic mutation. I would like to test co-occurence of germline and somatic mutation in the same gene.
What I did is that I counted for each gene the number of patient harboring a germline and somatic mutation and then computed a fisher exact test.
Here is my final dataset :
# A tibble: 716 x 8
   germ_gene somatic_gene only_germ only_som germ_and_som no_germ_no_som f.odd f.pvalue
   <chr>     <chr>            <int>    <int>        <int>          <int> <dbl>    <dbl>
 1 A2M       A2M                 73        9            2            408 1.24    0.519
 2 ABCA1     ABCA1               89       12            1            390 0.366   0.930
 3 ABCA12    ABCA12              39       12            4            437 3.72    0.0424
 4 ABCA13    ABCA13              58       23            4            407 1.22    0.450
 5 ABCA2     ABCA2               68        9            1            414 0.677   0.783
 6 ABCB11    ABCB11              16       10            0            466 0       1
 7 ABCB5     ABCB5               47        9            1            435 1.03    0.645
 8 ABCC1     ABCC1               45        8            2            437 2.42    0.246
 9 ABCC2     ABCC2               36       14            0            442 0       1
10 ABCC3     ABCC3               32       11            0            449 0       1

The fisher exact test is computed as this (example with the gene A2M) :
contingency <- matrix(c(germ_and_som,only_som,only_germ,no_germ_no_som),nrow=2,ncol=2,dimnames=list(c("germ","no_germ"),c("som","no_som")))

#            som no_som
# germ         2     73
# no_germ      9    408

f.test <- fisher.test(contingency,alternative = "greater")

#   Fisher's Exact Test for Count Data

# data:
# p-value = 0.5191
# alternative hypothesis: true odds ratio is greater than 1
# 95 percent confidence interval:
#  0.1890338       Inf
# sample estimates:
# odds ratio
#   1.241402

Is this strategy correct ? and if yes is that correct to put alternative = "greater" or should I let two-tails ?
Thank you
Answer: The statement "I would like to test co-occurrence of germline and somatic mutation in the same gene." doesn't imply a direction for the null hypothesis of independence. So a two-sided alternative would seem more appropriate on the face of it. You should also consider adjusting the p-values for multiple hypothesis testing (since you are testing 716 genes at the same time according to the tibble above). For example, with stats::p.adjust.
Comment: Ok thank you. Other comment : Most of my contingency tables are imbalanced i.e. one field contains most of the events ( no_germ_no_som ) . Is that an issue for the test ?
Comment: Shouldn't be a problem. The Fisher exact test can be used (to test for independence between two categorical variables) on a 2-by-2 contingency table in which some of the cells contain 0s or small numbers.


Nginx configuration doesn't work with wordpress in subdirectory

Question: I have a nginx installation which I need for hosting web sites in development so that other people can test them out.
Right now I've set up a virtual host for a single sub-domain and in that directory I symlink projects which should be open for testing. As you can see have I restricted access to the whole site but enabled for the specific directory, but keeping it private with a simple auth_basic.
The PHP runs but I keep getting 404s for anything other than / or /wp-admin/, all the other permalinks gives 404s. I've done just about everything to get this to work but I have no idea what I'm doing wrong. Please point out my error in the following configuration:
server {
  listen 80;
  server_name dev.example.com;
  client_max_body_size 20m;
  server_tokens off;

  root /srv/dev.example.com;
  index index.php index.html index.htm;

  location / {
    deny all;
  }

  location /my-site {
    allow all;

    try_files $uri $uri/ /index.php?$args;

    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/auth.d/.htpasswd-my-site;

    location ~ \.php$ {
      include fastcgi_params;
      fastcgi_index index.php;
      fastcgi_pass php5-fpm-sock;
      fastcgi_param SCRIPT_FILENAME $request_filename;
      fastcgi_intercept_errors on;
      fastcgi_param HTTPS $https;
    }
  }
}

Thank you!
UPDATE:
This request would work: http://dev.example.com/my-site/, it would result in loading the file /srv/dev.example.com/my-site/index.php.
A request to the wordpress admin interface would work too: http://dev.example.com/my-site/wp/wp-admin, also going directly to an index file: /srv/dev.example.com/my-site/wp/wp-admin/index.php. Everything within the admin interface works since it doesn't use permalinks but the raw GET input.
However, as soon as I attempt to load a permalink (I use the most simple format /%postname%/) it fails in finding it and the try_files directive in location /my-site {} should match them. This means that routes such as the following doesn't work:
http://dev.example.com/my-site/about
http://dev.example.com/my-site/contact
http://dev.example.com/my-site/etc

Comment: Can you provide a sample URL that falls in 404 and the real path on your filesystem to that resource ?
Comment: Xavier Lucas, I added the sample you asked for. Does it help?
Comment: It does, definately.
Answer: I'm gonna assume the following files don't exist on your filesystem :
/srv/dev.example.com/my-site/about/index.{php,html,htm}
/srv/dev.example.com/my-site/contact/index.{php,html,htm}
/srv/dev.example.com/my-site/etc/index.{php,html,htm}

Your issue comes from the fact that your php fallback location is nested within /my-site location and that try_files directive may not work like you are expecting.
Indeed, try_files accepts as a last parameter either :

an URI
a named location
an HTTP code

For options 1 & 2, it will imply an internal redirect to the specified element. In your case /index.php?$args is interpreted as an URI and nginx will internaly redirect to it if $uri, $uri/, $uri/index.php, $uri/index.html, $uri/index.htm are missing.
Now, the other thing is : you use a nested location to handle php files processing. But as your try_files last parameter is the /index.php?$args URI it won't match the apex location /my-site so it's handled by the server block and if the URI can't be resolved to a local file then you end up with an HTTP 404 reply.
Note that the index directive will also imply internal redirects to the specified index files, but as  URIs start with /my-site it will always fall in your php location.
So you must either move this location to the same level than the others or prefix your try_files URI with the prefix of your apex location and make sure the php file is in the right place.
Comment: So what you are saying is that the try_files directive should instead be under `location / {}` or that I change the last element to `/my-site/index.php?$args`? Does it really matter where I put the `location ~ \.php$ {` since I'm not getting "File not found" from php-fpm but 404 from nginx? Are you also saying that I can't have the try_files directive under the `location /my-site {}`, that it must be at the root?
Comment: @Niklas Well, I though I had explained these. Either change the last parameter of try_files or move the php location to the same level than the other locations. The 404 from nginx is exactly what I explained : you don't reach the php location because it's nested in `/my-site` and the URI of `/index.php?$args` doesn't match `/my-site` location.


Factor Levels in a Two-Way ANOVA

Question: I'm trying to figure out the explanations of the Effect Plots below. I believe I have figures out Figure 9a, but the explanation for Figures b, c, and d given in the textbook I do not comprehend.
Any further detail would be greatly appreciated.

Figure 9(a) shows that the means for Factor $A$ are equal (because the three dots are on the same horizontal line), but the response differs for the two levels of Factor $B$ (because the lines are one above the other). Thus, there is no effect of Factor $A$ on the response, but a Factor $B$ main effect is present. In Figure 9(b), the Factor $A$ means differ, but the Factor $B$ means are equal at each level of Factor $A$ (WHY?????). Here a Factor $A$ main effect is present, but no effect of Factor $B$ is present. Figure 9(c) and Figure 9(d) illustrate cases in which both factors affect the response. In Figure 9(c), the mean response between levels of Factor $A$ does not change for the three levels, so the effect of Factor $A$ on the response is independent of Factor $B$. That is, the two factors do not interact. In contrast, Figure 9(d) shows that the differences between mean distances between levels of Factor $B$ varies with the levels of Factor $A$. Thus, the effect of Factor $A$ on the response depends on the levels of Factor $B$, and the two factors do interact.
Answer: You have (a) correct!  The key thing to understand here is that the effects of A and B will look totally different, because they are represented by different things in the diagrams.  Moving a dot higher or lower means that that group mean is higher or lower.  Factor A is split into three points along the x-axis, so a difference between the means across those will mean that the dots on a given line will be moved up or down relative to each other.  I.e. if the line isn't flat: you have an effect of factor A.
Factor B on the other hand is represented by splitting the graph into two lines.  So an effect of Factor B will be seen as moving the whole of one line higher or lower than the other.
It might make more sense to you if (b) had been drawn so that the two lines were directly on top of each other?  That is the purest version of "no main effect of B" -- the two lines land in exactly the same place (neither shifted up or down relative to the other so that we don't really need two lines at all, because B has no effect).  But in reality the lines never land exactly on top of each other (two sample means never come out the same: that's why we need the ANOVA in the first place) and also it wouldn't be easy to draw it.  But the purest version of (b) would have both lines smack bang on top of each other.  That is to say, factor B is having no effect and isn't able to shift the line up or down.
On the other hand in (c), one line is shifted up relative to the other.  So factor B is having an effect (shifting the whole line up).
But notice that in all three graphs so far, the lines are parallel?  Because whatever jump up or down we get as we move along one line, we get the same jump or down on the other.  Those jumps up and down are the effects of factor A.   So, the effect of factor A is the same in both levels of B (i.e. on both lines).
On the other hand, (d) is not even parallel.  There are jumps up and down as we move across the graph to different levels of A, but those jumps up and down are different on the different lines, so not only is there an effect of A, but it differs across the levels of B.  So, basically, we have something more complicated altogether.

Factor Levels in a Two-Way ANOVA


secure cookies when https is done on balancer, but balancer->appserver is http

Question: We're trying to maintain PCI compliance for our application and after an audit, the report was telling us that we need to set the secure flag on our cookies. The site is HTTPS (using pound for https termination) sitting in front of haproxy which serves to a number of backened appservers, as follows:
CLIENT ->(https)-> [Pound]->[HAProxy] ->(http)-> { app001 | app002 | appNNN }

I've done some research (googling) around but haven't been able to find anything definitive about this, but would there be any issue with an appserver setting a secure cookie over http between it and the balancer, and would it make it through to the client over https?
Our staging environment doesn't have SSL set up the same way as production so I'm unable to test this, but I'm trying to come up with a plan of action and see if there's anything I'm missing before we try to move forward with this.
Answer: You can set the secure flag on a cookie regardless of whether the connection made to the origin server was secured or not. The client interprets this flag, and won't actually set the cookie if the connection wasn't secured.
According to RFC 6265:

When a cookie has the Secure attribute, the user agent will include the cookie in an HTTP request only if the request is transmitted over a secure channel (typically HTTP over Transport Layer Security (TLS) [RFC2818]).

See RFC 6265 for more on how this flag works (and cookies in general).
Comment: Ah, sweet, this makes sense. I think I looked everywhere except the RFC. Thanks!


Certain infinite subsets of $k_\omega$-spaces have an infinite closed discrete subspace

Question:
A Hausdorff space $( X , \mathcal{T} )$ is said to be a $k_\omega$-space if there is a countable collection $X_n$, $n \in \mathbb{N}$ of compact subsets of $X$ such that

$X_n \subseteq X_{n+1}$, for all $n$,
$X = \bigcup_{n=1}^\infty X_n$,
any subset $A$ of $X$ is closed if and only if $A \cap X_n$ is compact for each $n \in \mathbb{N}$.

If $S$ is an infinite subset of the $k_\omega$-space $( X , \mathcal{T} )$, such that $S$ is not contained in any $X_n$, $n \in \mathbb{N}$, then $S$ has an infinite discrete closed subspace.

I notice that in order to prove this, it suffices to show that there exists  collection of open sets $U_n \subset X_n$ but $U_n \not\subset X_{n-1}$. However, I can not construct such collection of open sets by just the properties stated above like Hausdorff and $k_\omega$-space.  Can someone give me a hint?
The above information is from the Ebook, Topology Without Tears by Sidney A. Morris around Page 290.
Comment: Using images instead of MathJax makes it much more difficult for others to search for this question. I have transcribed the images, but please check to make sure I have not made any errors. Also including information about the source of those images (book, website, author(s), etc.) would aid others who might have the same question from the same source.
Answer: If $S$ is infinite and not contained in any single $X_{n}$, then the set $\{ n \in \mathbb{N} : S \cap (X_n \setminus X_{n-1} ) \neq \emptyset \}$ is infinite, and we may recursively pick $x_1 , x_2 , \ldots \in S$ such that for each $k \in \mathbb{N}$ there is an $n \in \mathbb{N}$ such that $S \cap X_n = \{ x_1 , \ldots , x_k \}$. (Let $n_1 = \min \{ n \in \mathbb{N} : S \cap X_n \neq \emptyset \}$ and pick $x_1 \in S \cap X_{n_1}$; given appropriate $n_1 < \cdots < n_{k-1}$ let $n_k = \min \{ n \in \mathbb{N} : S \cap ( X_n \setminus X_{n_{k-1}} ) \neq \emptyset \}$ and pick $x_k \in S \cap (X_{n_k} \setminus X_{n_{k-1}} )$.)
I claim that $A = \{ x_1 , x_2 , \ldots \}$ is closed discrete.

Note that as the $X_n$ are increasing, by our choice of the $x_k$ it follows that $A \cap X_n$ is finite, and hence compact, for each $n$, meaning that $A$ is closed in $X$.
In fact, using the same reasoning as above, all subsets of $A$ are closed in $X$. In particular, for each $k \in \mathbb{N}$ as $A \setminus \{ x_k \}$ is closed in $X$, then $X \setminus ( A \setminus \{ x_k \} ) = \{ x_k \} \cup ( X \setminus A )$ is an open neighborhood of $x_k$ whose intersection with $A$ is $\{ x_k \}$.  Thus $A$ is a discrete subset of $X$.


FakeApplication using a specific application.conf?

Question: How can I create a FakeApplication to run my tests using my dev.conf instead of the default application.conf?
My current test consists of the following construct:
Map<String, String> map = new HashMap<>();
map.put("config.file", "/path/to/dev.conf");
FakeApplication fakeApplication = fakeApplication(map);
TestServer testServer = testServer(3333, fakeApplication);
// testServer.start();
running(testServer, HTMLUNIT, new F.Callback<TestBrowser>() {
    public void invoke(TestBrowser browser) {
        //do something
    }
});

This code adapted from the Play Framework Documentation about writing test throws the following Exception, as the default application.conf does not work on my development-system. If I uncomment testServer.start(); I can see it even more clearly.
[WARN] [01/01/2013 18:36:59.505] [pool-4-thread-3] [Dispatchers] Dispatcher [akka.actor.promises-dispatcher] not configured, using default-dispatcher
[WARN] [01/01/2013 18:36:59.521] [play-akka.actor.default-dispatcher-2] [Dispatchers] Dispatcher [akka.actor.actions-dispatcher] not configured, using default-dispatcher
[error] Test test.ApplicationTest.runInBrowser failed: Server is not started!
[error]     at scala.sys.package$.error(package.scala:27)
[error]     at play.api.test.TestServer.stop(Selenium.scala:117)
[error]     at play.test.Helpers.stop(Helpers.java:325)
[error]     at play.test.Helpers.running(Helpers.java:355)
[error]     at test.ApplicationTest.runInBrowser(ApplicationTest.java:74)
[error]     ...

I assume the line
map.put("config.file", "/path/to/dev.conf");

is wrong and has to be adapted. But how?
Comment: Please try `./path/to/dev.conf`.
Comment: That didn't do the trick unfortunately. Actually, I used an absolute path.
Comment: Then try `./conf/dev.conf`.
Comment: Course, I did try this too. ;-) I think I've tried all varieties of writing a path.
Answer: It is impossible to substitute main config with another this way. You only could override specific settings by passing a map to fakeApplication.
I.e. if you config contains:
mongodb.default.uri = ...
logger.root = ERROR

You can override it by placing new values inside a map:
Map<String, String> map = new HashMap<>();
map.put("mongodb.default.uri", "...");
map.put("logger.root", "INFO");

FakeApplication fakeApplication = fakeApplication(map);

Comment: Although this was not the solution I was looking for, I could workaround the problem with it. Thanks a lot!
Answer: I think you might want to run your test command as follows:

play -Dconfig.file=path/to/dev.conf
test

Answer: You may also want to check out this option:
http://alexgaribay.com/2015/02/05/overwrite-settings-for-testing-in-play-framework/
Comment: Do not just add a link, extract the important information from it and add it to your post.
Answer: I have the same issue and I did something like this to solve it:
  private Configuration additionalConfigurations;

  @Before
  public void initialize() {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    Config additionalConfig  =ConfigFactory.parseFile(newFile(cl.getResource("application.dev.conf").getF)));
    additionalConfigurations = new Configuration(additionalConfig);
  }
  @Test
  public void testPropertiesGetLoaded() throws Exception{

    running(testServer(3333, fakeApplication(additionalConfigurations.asMap())), HTMLUNIT, new F.Callback<TestBrowser>(){
      public void invoke(TestBrowser browser) throws InterruptedException {

        String specificProperty = Play.application().configuration().getString("db.ro.url");
        Logger.info("printingVar:" + specificProperty);

      }
    });
  }

where application.dev.conf can be whaterver config file you want to set in there.


AngularJS Multiple drag and drop

Question: I'm writing directive for multiple drag and drop using jQueryUI. Holding CTRL and selecting elements you can do multiple sorting.
It works ok, except when element doesn't change position (I drag it, and then return it on same place).
In that case, element is gone, although model is fine, and it displays all the elements correctly.
Here's the fiddle, for what I've done.
http://jsfiddle.net/ndamnjanovic/swt48/3/
That's why I tried to manually insert HTML node, in case element is returned on same position.
But in this case, after I insert element  with ui.item.after(elements).detach(), elements lose associated actions (clicking on it doesn't trigger alertCity anymore).
Here's the fiddle with other approach.
http://jsfiddle.net/ndamnjanovic/EkVTW/11/
Any ideas what's the problem here?
Comment: Why are you using such an old version of Angular ?
Comment: yes, I add it by mistake, I see now. I'll change it, thanks for noticing. However I don't think that's the problem, cause in my project I have latest version and it's still not working.
Answer: I think you've fooled yourself into thinking that Angular is managing this list for you (and me too, for the past hour ;) ). Because of the jQuery plugins you're using, the DOM for that sortable
 doesn't appear to be under Angular's control anymore.  They probably re-rendered something at some point, wrapped it in a container, etc.  But that means you are responsible for the DOM.  After the drop, you need to re-insert the removed elements (draggedElements) into the correct position in the list.
Alternatively... you can trick Angular into managing the list for you.
First, add ng-if="cities" to your sortable
, then add this code at the end of your drop callback:
                var temp = scope.collection.slice(0);
                scope.$apply(function(scope) {
                    while (scope.collection.length) scope.collection.pop();
                });
                scope.$apply(function(scope) {
                    for (var i = 0; i < temp.length; i++) scope.collection.push(temp[i]);
                });

The ng-if directive causes angular to re-render the inner components (and re-initialize any inner directives) anytime the value changes from false to true.  In this case, we use two calls to $apply to first give the collection a falsy value, and then restore its contents. This trips the ng-if wire and causes the list to re-render.
Example: http://jsfiddle.net/colllin/8dcXB/
Comment: BTW, I don't think the `ngIf` is necessary. `ngRepeat` will do the re-rendering if it detects changes in the list. I removed `ngIf` and it seemd to work file.)
Comment: Without your calls, it was all happening inside the same $digest loop, so `ngRepeat` could not see the difference (the city was removed from the array and then added back at the same index). Without any difference it didn't bother to re-render. But the jQuery (throught the sortable plugin) would have removed the DOM element (but `ngRepeat` just looks at the internal array, not the DOM).
Comment: With your `$apply()`s you first empty the cities array in one `$diget` loop (the first `$apply()`) then in the sacond `$digest` loop you populate it again (second `$apply()`). Thus , `ngRepeat` spots a difference in each cycle and re-renders the DOM. It is not a very efficient solution, but the code is rather complicated to spot the real problem and provide a better fix :D
Comment: Hey, I was stuck with another project, so finally I managed to take a look at this. Trick with $apply worked. Only one thing, instead of pop-ing and push-ing all of the elements of the array, I added $apply only  when I remove dragged elements and return them back to list (places that already existed in code). Thanks again!
Comment: Hey, Collin, thanks a lot for helping me, I'm currently away from my working computer, I'll check this code as soon as I get near one :) Thanks a lot again!
Comment: @ExpertSystem Totally true.  Is this an angular bug then with the changes not being digested properly?  Or is there something asynchronous happening that my additional calls to `$apply()` are somehow solving?

AngularJS Multiple drag and drop


how to remove white space at the top when doing a print styles

Question: How do you remove the white space at the top when you print. I'm doing print styles using print.css files. When i preview the print there is a white space at the top. How do i remove that?
Thanks
Comment: Do you have a live view of your site?
Answer: How about this?
<code>@media print {
body, html {
margin-top:0px;
padding-top:0px;
}
}
</code>
You could write this directly in your default style.css file.
Answer: Css rules, Try this
<code>@ media print{
body{
margin-top:0px;padding-top:0px;
}
}
</code>
Comment: what about a negative margin ?
Comment: i also tried that, but it ends up cutting off the top of the logo
Comment: Where is the whitespace ? above the logo or below ? could you move the logo upwards then add negative margin to the rest of the page to move it up aswell ?
Comment: Billy, the whitespace is above the logo, its like a 50-60px whitespace at the top
Comment: What happens if you move the logo up by 50px, i.e. `#logo{position:relative;top:-50px;}`
Comment: same things, gets cut off. so weird
Comment: try using cm or mm CSS units, I've just seen somewhere that using px may affect print styles
Comment: cm and mm just makes my logo disapear from the print style
Comment: I think you're gonna have to post some of your code, as I'm out at the minute and on a library computer I won't be able to try and muck around with it but others might. I'll have a look later when I'm home. One last idea, Is your logo an image? Does the image have the whitespace?
Comment: yes, my logo is an image. Even when i remove the image the text underneath the still dosen't sit at the top of the page and still has the white space at the top. I checked the code and there is nothing else displaying above the image.
Comment: I think you'll have to post at least the top part of your code
Comment: Back again, on my comp now. Try linking to a different css sheet in the html file with `` To make sure that no other rules are conflicting with the @media print.


Generate large dataset of dates for each user

Question: I'm looking for SQL help generating a large dataset.
I have a list of users (id) and the date they activated with our service (activated_date).
I'm looking to generate a data set that has an entry for every day from the user's activated date to today.
What I Have Today
--------------------
id | activated_date
--------------------
2  | 01/01/2017
63 | 23/04/2018
.. | ...
--------------------

What I want to achieve
--------------------
id | date
--------------------
2  | 01/01/2017 <-- activation date
2  | 02/01/2017
2  | 03/01/2017
2  | 04/01/2017
2  | 05/01/2017
.. | ...
2  | 27/10/2018 <-- yesterday
63 | 23/04/2018 <-- activation date
63 | 24/04/2018
63 | 25/04/2018
63 | 26/04/2018
.. | ...
63 | 27/10/2018 <-- yesterday

Comment: If you got a calendar table (which is very useful anyway) you can simply join to it using `calendar_date between activated_date and current_date)`
Comment: Tag your question with the database you are using.
Comment: Can you share what you've tried so far?
Comment: I'm using PSQL here
Comment: @dnoeth that's a good idea!
Comment: @dnoeth the problem should solve using `RECURSIVE CTE`. Why do create a new table?
Comment: @JamesPatrick create a new table is not a good idea. because you add an extra object that you need it only for one reason in a query.
Comment: @MohammadMohabbati: A calendar table is one of the basic things in a Data Warehouse Enivironment. IMHO it should exist in every database, you can do  lots of things with it.
Comment: @dnoeth it is absolutely correct in Data Warehouse databases, but in OLTP databases it is just a trick.
Answer: You can generate the dates recursively so the problem will solve by RECURSIVE CTE as follow:
create test table:
create table your_table
(
  id    int not null,
  activated_date    timestamp  not null
);

add sample data:
insert into your_table
values
(2, '2017/01/01'),
(63, '2018/04/23');

and final the recursive query:
with
recursive
    cte(id, active_date)
as
(
    select
        id,
        activated_date  as active_date
    from
        your_table
    union all
    select
        t.id,
        active_date + justify_days(interval '1 days')
    from
        cte
    inner join
        your_table t
    on
        cte.id = t.id
    where
        cte.active_date < now()
)
select
    *
from
    cte
order by 1, 2;

try it on: dbfiddle


Accessing user's custom field in html.tpl.php

Question: In my html.tpl.php , I was printing this:
    print $user->name;

which displayed username.
But now I need to print Custom field "First Name" instead of username.
So I tried this:
   print $user->field_first_name[und][0]['value'];

which is not printing anything  although the field "First Name" has some value.
Where am I going wrong ? Am I missing some obvious thing ?
Thank you .
Answer: If you are using the global variable $user, it doesn't always contain a full initialized object. In fact, during the bootstrap, $user is initialized with the data contained in the "users" table, from the following code.
  if ($is_https) {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();
    if (!$user) {
      if (isset($_COOKIE[$insecure_session_name])) {
        $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(
          ':sid' => $_COOKIE[$insecure_session_name],
        ))
        ->fetchObject();
      }
    }
  }
  else {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => $sid))->fetchObject();
  }

  // We found the client's session record and they are an authenticated,
  // active user.
  if ($user && $user->uid > 0 && $user->status == 1) {
    // This is done to unserialize the data member of $user.
    $user->data = unserialize($user->data);

    // Add roles element to $user.
    $user->roles = array();
    $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
    $user->roles += db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = :uid", array(':uid' => $user->uid))->fetchAllKeyed(0, 1);
  }

If you want to be sure to get a fully loaded user object for the currently logged-in user, you should use the following code.
$account = user_uid_optional_load();

After that, you can get the value of any user field.
$fullname = field_get_items('user', $account, 'field_first_name');

You can also get the rendered value of the field using the following code.
$rendered_value = field_view_field('user', $account, 'field_first_name');

The other reason for which $user->field_first_name['und'][0]['value'] could not contain any value is that the language-neutral value of the field is not be set. ('und' is the value of the constant LANGUAGE_NONE, or LANGUAGE_NOT_SPECIFIED in Drupal 8.) If you use field_get_items(), or field_view_field(), you are sure to get the correct value.
As side note, it is preferable to keep the logic in the template.php file, in functions that are called from the template files.
Comment: You need to pass the user object, not the user ID.
Comment: Thank you @Kiamlaluno for the answer.                     I tried doing this: `$fullname = field_get_items('user', $user->uid, 'field_first_name');` in html.tpl  but did not get any value when I printed $fullname or $fullname['value'].
Comment: I tried without `uid` too, using simply `$user` but it also did not print anything.
Comment: And when I print `$user->field_first_name['und'][0]['value']` in `user-profile.tpl.php` it prints the value but it is not printing when used in `html.tpl.php`
Comment: How to you initialize the `$user` variable?
Comment: using
       `global $user;`
Comment: The global `$user` is not always a fully user object. Only the values contained in the "users" table are initially used, and that table doesn't contain the values of the field API fields.
Comment: Thank you very much @kiamlaluno. It worked when I initialised $account and used it as you mentioned. And also thank you for explaining everything :)


Under what conditions is integrating over a series expansion valid for an improper integral?

Question: On stackoverflow, a question was asked about getting Mathematica to evaluate the integral,
$$\int^\infty_0 \frac{e^{-x}}{\sin x} \, \mathrm{d}x$$
which we know is divergent.  In one of the answers, the integrand is replaced with its Taylor expansion, and integrated term by term, and in physics, it is often taken for granted that this works. But, under what circumstances is this valid for improper integrals, in general?  More precisely, what must be done to properly interchange the two limiting processes?
Comment: The integrand has a nasty fence of poles within the interval of integration... why would somebody expect the whole mess to converge?
Comment: It should be at least convergent for $x$ in the integration range (which in this case doesn't seem to be given).
Comment: A sufficient criterion is that the sum converges uniformly.
Comment: @JM, I have no idea, but it did bring up some questions on how to proceed.
Comment: @J.M.: because in physics all functions are well-behaved. (Whatever well-behaved means in context). They are only outside $C^{\infty}$ when it is convenient.  I still (many years later) remember the revolt when the professor talked about the derivative of the delta function...
Comment: @Ross: I know (FWIW, I'm a chemist). On the other hand, part of my training was to look at a graph of a function before it is integrated/differentiated/whatever, and a look at the plot (not even counting the concept of Cauchy principal values), you'd want to make sure first that such an integral is sensible even before you start cracking (numerically). I agree, "well-behaved" is context dependent...
Comment: @J.M.: we are closely aligned.  My degree is physics and now I am an aerospace engineer.  I took my math outside the "math for applications" area.  But looking at graphs is very productive, particularly when the functions are smooth (as most functions are not).
Comment: It's not true. In Physics, it's not taken for granted that it works. Those types of integrals involves 'energy denominators' and the divergence appears since some interaction is neglected. Once that interaction is recovered the energy poles becomes complex and anything works fine. Sometimes, it's quite difficult to include the neglected interaction and we can switch to some kind of 'disorder average' which is pretty justified since the original model was 'too much' an ideal one.
Answer: Uniform convergence is often both too strong and too weak (it isn't sufficient for an improper integral over an infinite interval).  Better ones are dominated convergence and monotone convergence (see the Lebesgue dominated convergence theorem and the Lebesgue monotone convergence theorem).
Comment: @Joriki: the functions $f_n(x)=\tfrac1n$ converge uniformly to the zero function on $\mathbb R$, yet $\int_{\mathbb R}f_n\not\to0$! This is a silly example, but shows you where the problem lies.
Comment: Could you say more specifically for which case uniform convergence isn't sufficient? The proof I linked to shows that in a certain sense it's always sufficient (but that sense might not apply to the situation you have in mind).
Comment: @Fabian the functions are constant so the convergence is independent of $x$ and thus uniform.
Comment: the wikipedia page with Lebesque's theorem doesn't exist as such, did you [mean](http://en.wikipedia.org/wiki/Dominated_convergence_theorem)?
Comment: @rcollyer: I've fixed the links; they contained an excess slash in the end.
Answer: In some cases, a class of theorems called Tauberian theorems can help you to justify interchanging the order of two limiting operators. For example, if the improper integral $\int_{0}^{\infty} f(x) \, dx$ exists, then
$$\int_{0}^{\infty} \int_{0}^{\infty} x^{n} s^{n-1} f(x) \; e^{-xs} \, ds dx = \int_{0}^{\infty} \int_{0}^{\infty} x^{n} s^{n-1} f(x) \; e^{-xs} \, dx ds$$
holds for all $n$. (Of course, existence of both iterated integrals are also guaranteed.) Originally, Tauberian theorems are answers to the following question: For what condition (Tauberian condition) ensures that a stronger summability method implies a weaker summability? Since a stronger summability method often exploits a good approximation to the identity, these theorems may be regarded as a special kind of interchanging the order of limiting operators. For example, a function $f(x)$ is Abel-summable to $I$ if
$$\lim_{\delta \to 0+} \int_{0}^{\infty} f(x) e^{-\delta x} \, dx$$
exists with the value $I$. Then this reduces to the ordinary summability if we have
$$\lim_{\delta \to 0+} \int_{0}^{\infty} f(x) e^{-\delta x} \, dx =
\int_{0}^{\infty} f(x) \, dx = \int_{0}^{\infty} \lim_{\delta \to 0+} f(x) e^{-\delta x} \, dx.$$
For the integral in question, we may understand it as the Cauchy principal value. That is, we identify this integral with
$$ \lim_{\epsilon \to 0+} \sum_{n=1}^{\infty} \int_{\pi(n-1) + \epsilon}^{ \pi n - \epsilon} \frac{e^{-x}}{\sin x} \, dx.$$
By circumventing poles, this integral can be managed by several techniques.
Comment: I don't see how to get the principal value of the integral from 0 to any number less than $\pi$... on the other hand, the principal value integrals with respect to the other poles are expressible in terms of digamma functions.
Comment: Oh, you're right. It also seems to me that there is no way to cancel out the pole at the origin, causing the value to explode to $+\infty$. I shoud have checked its existence first...
Comment: We determined that the pole at the origin was the cause of the problem. But, I also found that if the integration limits each corresponded to a pole, i.e. $x \in [\pi(n-1), \pi n]$, you are unable to compensate for the pole. But, if you shifted the integral to $x \in [\pi(n - 1/2), \pi (n + 1/2)]$ the poles can be compensated for, and the series of integrals is an alternating series, $i \sum (-1/e)^n$, which converges to $-i/(1-e)$.
Answer: Here's a nice general treatment of the interchange of limiting processes using uniform convergence. It applies to integration, differentiation and series alike.
Comment: Maybe I'm wrong, but it seems that the author assumes that the limits exist and are finite. Is it true or am I missing something?
Comment: @shamovic: I think you're right, but how is that relevant? Those conditions are fulfilled here.


Drupal ui inside module

Question: Am i doing wrong to define, jQuery Accordion inside my .module file,
just like this:
<?php
  drupal_add_library('system', 'ui.accordion');

Drupal no longer loading jquery itself.
Comment: Drupal loads Jquery by default... Jquery UI Plugins needs to be loaded separately based on requirement as you did above...
Comment: Where you load the library from depends on what you are trying to do. To get the best possible answer you need to provide more information on what you are trying to do.
Comment: Are you doing that at the top level and not inside a function / hook?
Comment: @MPD, now i am doing it as suggested below and it is running fine.
Answer: Yes that's wrong, you need to put it inside a hook function.
Which one depends on where you're trying to use it. To add it to a render array, for example a form, you might use
$form['#attached']['library'][] = array('system', 'ui.accordion');

Comment: API page says, This hook_init is not run on cached pages.

To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.
Comment: Fair enough @AnilSagar, though I've never had a problem using that method with caching enabled (and the docs have been wrong before). I've updated the answer with the globally accepted solution
Comment: Flush the cache is enough...
Comment: liked the first answer, now .. i still don't know what excatly to put in my module file. :(
Comment: Sorry @Roland, Anil was right to bring that up as the docs do explicitly say not to do that. `hook_page_alter()` might be appropriate: `function MYMODULE_page_alter(&$page) { $page['#attached']['library'][] = array('system', 'ui.accordion'); }`. It'll need a cache clear to work
Comment: a question in direct correlation with this topic.
do i have to uninstall / install the module with every try, or is it enought to flush the cache ?
Comment: @Roland Any time you add a new hook or change the module .info file (and maybe in a couple of other situations) you need to flush the caches for the changes to get picked up. You only need to uninstall and reinstall if you change your module's db schema (but in that case you can use an update hook instead). So flushing caches will do the trick for most things
Comment: maybe there is a typo inside but the page_alter is not working? preprocess_page is working.
Comment: I didn't try it but it "should" work since the `$page` array gets run through `drupal_render()`, and that invokes the `#attached` functionality. In theory at least. If the preprocess method works, go with that one - it'll have the same effect and shouldn't break caching. Interesting that it doesn't work with the page alter hook though
Comment: ok thx to both of you :)
Answer: You can add below code in your theme template.php
function NAME_OF_THEME_preprocess_page(&$variables) {
  drupal_add_library('system', 'ui.accordion');
}

Comment: This is also not preferred; `#attached` in a render array should be used if we're being strict about it :)
Comment: I'm not 100% (I've only seen this mentioned in issues on d.o and perhaps a question or two here), but I think mostly because of render array caching. Theoretically the preprocess method should have the same effect, but I think they're trying to standardise how css/js/libraries are added to pages by using render arrays. This is certainly more true for Drupal 8, so maybe the ethos is being backported if not the full code
Comment: Looks like this method is working better for the OP, maybe this is the better approach for adding libraries globally
Comment: @Clive : Interested to know why it's not preferred way to do...

Drupal ui inside module


Qual é a necessidade de uma interface possuir métodos abstratos?

Question: Sabemos que em uma interface os métodos não possuem implementação, apenas assinatura, ou seja, apenas a definição dos seus métodos sem o corpo, concluímos então que todos são já métodos abstract, certo? Mas então porque existem declarações como:
interface Exemplo {
    void umMetodo();

    abstract void outroMetodo();
}

class ImplementaExemplo implements Exemplo {

    @Override
    public void umMetodo() {
        // TODO Auto-generated method stub

    }

    @Override
    public void outroMetodo() {
        // TODO Auto-generated method stub

    }

}

Qual a necessidade de existir um método abstrato em uma interface? Teria relação exclusivamente para criar a possibilidade de interface funcional?
Answer:
Sabemos que em uma interface os métodos não possuem implementação

Não é verdade.

Qual a necessidade de existir um método abstrato em uma interface?

Nenhuma. Totalmente redundante. Métodos em interfaces são abstratos, a não ser que sejam explicitamente declarados como default.

Teria relação exclusivamente para criar a possibilidade de interface funcional?

A convenção adotada por algumas pessoas é que a uma interface funcional deve ser explicitamente declarado como abstrato, diferenciando de uma interface normal. Mas a única restrição de verdade é que deve ter apenas um método para ser usado em lambdas. Tenho a impressão que a convenção começou ser usada por desconhecimento de como o mecanismo funciona já que falam em métodos abstratos.
Comment: @JeffersonQuesado dei uma melhorada, tinha misturado as coisas.
Comment: Só tem um método abstrato.
Comment: Interfaces funcionais deveriam ter o `abstract` na assinatura? Omitir isso então seria uma fuga de convenção tal como nomear classe com letra minúscula?
Comment: Na primeira colocação acabei esquecendo do Java 8, falha minha, obrigado pelo alerta.
Comment: @Maniero mas ainda estou um pouco confuso em relação a interface funcional, na sua frase da a entender que a interface deve possuir somente um método para ser declaração com uma interface funcional, correto? Então independente se o método é declarado explicitamente como abstrato ou não, uma interface com um único método é uma interface funcional? Obrigado
Comment: Sim, é considerado, apesar não garantir. Veja: https://pt.stackoverflow.com/q/11162/101
Comment: Pois é, muito estranho, no próprio Java tem a classe Consumer ( você pode verificar aqui: https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html )  até com a anotação @FunctionalInterface que possui mais de um método.
Comment: @Emanoel apenas ratificando o que o Maniero falou: `andThen` tem implementação _default_, deixando aberto apenas o `accept`, portanto apenas esse método é abstrato


Error when trying to migrate comments to a clean D8 site: What's wrong with my .yml file?

Question: I'm trying to migrate content from my current D7 site to a Drupal 8 installation.
I've managed to import some of the nodes, and now I want to import the comments for those nodes.
Every time I click on "run" (.../admin/structure/migrate/manage/importarComentarios/migrations/importar-comentarios/process/run) I get an error:

What am I doing wrong?
This is my migrate_plus.migration.importarComentarios.yml file:
id: importar-comentarios
label: Comments
migration_tags:
  - CSV
migration_group: importarComentarios
<code>source:
  plugin: csv
  path: 'public://csv/exportar-comentarios-genericos.csv'
  header_row_count: 1
  delimiter: ','
  enclosure: '"'
  keys:
    - id
  column_names:
    0:
      nid: 'nid'
    1:
      created: 'created'
    2:
      body: 'body'
    3:
      autor: 'autor'
    4:
      cid: 'cid'
    5:
      titulo: 'titulo'
    6:
      mail: 'mail'

destination:
  plugin: entity:comment

process:
  entity_id: nid
  subject: title
  'comment_body/value': body
  'comment_body/format':
    plugin: default_value
    default_value: "html"
  # Migrate our custom field
  field_mail: mail
  field_nombre: autor
  status:
    plugin: default_value
    default_value: '1'
  created: created
  nombre: autor
  email: mail
  # The comment type (aka the comment's bundle).
  comment_type:
    plugin: default_value
    default_value: 'comentario'
  # The type of entity we're attaching this comment to.
  entity_type:
    plugin: default_value
    default_value: 'node'
  # The field we should attach this comment to. This is a field on your node.
  field_name:
    plugin: default_value
    default_value: 'comentarios'

migration_dependencies: {}
</code>
And this is the migration overview:
This is the overview

This is the destination

This is the process

And when clicking the source, I get:

The website encountered an unexpected error. Please try again later.

My configuration is:
My content type is called contenido

And these are the fields of my comments

And my contenido content type has a comentarios field for comments
Comment: The unexpected error thing is the equivalent of a windows blue screen. Check your server error logs and recent errors in Drupal logs and post them to see what is happening exactly.
Comment: Alternatively enable verbose error logging with backtrace in the settings and try the things that cause the unexpected error page again.
Answer: <code>  keys:
    - id
</code>
The yml is using a key 'id' that is not defined in the column_names. Since you have a 'nid' column, I suggest changing 'id' to 'nid'.


Android AdWhirl with AdMob and InMobi

Question: Previously I used for Ads just AdMob.
Now I want to use AdWhirl with AdMob and InMobi integration.
AdWhirl with AdMob work fine. But there are no instructions how to integrate AdWhirl and InMobi. Also on AdWhirlAndroidSDK there is list of "supported" mobile ad network and among them there is no InMobi. My question is does AdWhirl support InMobi or not? If yes, where can I found working example of AdWhirl + InMobi integration. If no, why is in AdWhirl interface support for InMobi?
Oh, I'm using AdWhirl 3.0.
Comment: at Google IO 2011, AdMob announced that they would be integrating something similar to AdWirl into their core service very soon, I'd wait a little :-)
Comment: Hehe... I don't like that word soon. Still there will be some sort of integration (with other ad networks) which I as a developer need to do.
Comment: Check out: http://goo.gl/kBTog & http://goo.gl/MShlG
Comment: But still I need to implement InMobi with AdWhirl and still don't know how or is it supported at all?
Comment: Yeah hence why I'm writing in a comment. I don't know an answer to your question :-)
Comment: hehe... thx anyway... I really can not wait for google to announce something different and I will still have to do a lot of things
Answer: I represent InMobi's Global Ops team and would like to work with you in integrating with InMobi. Can you shoot an e-mail to email@example.com and I'll work with you to getting this fixed.
Thanks :)
Edit:
For your Android Integration, please use the following methods:
If you are using the SDK source, please replace the InMobi adapter in your source with the file located at the following dropbox linke:
Adwhirl – InMobi Adapter for Android - http://dl.dropbox.com/u/30899852/InMobiAdapter.java
If you are using the compiled SDK Jar from Adwhirl, please use the following jar (exclusively)
Adwhirl Compiled Jar with updated InMobi Adapters - http://dl.dropbox.com/u/30899852/adWhirl/AdWhirlSDK_Android_3.0.0.jar
Please note that this jar is compiled with default adapters which are a part of the SDK source bundle from Adwhirl. The only change is that the InMobi adapter has been updated to work with the new SDK from InMobi. Also note, this is not an official release from Adwhirl but provided by InMobi. I do not represent Adwhirl and only represent InMobi
Hope this helps. As before, please feel free to reach out to us at firstname.lastname@example.com
AJ

Android AdWhirl with AdMob and InMobi


Proxying email to different mailservers on different domains on one public IP address

Question: I have a Proxmox machine with 2 virtual machines running on it, and also two domains, let's say domainA.com and domainB.com. Both domains are pointing to the Proxmox public address and also I have set up nginx to reverse http traffic based on incoming domain name to each of the VMs.
network looks like this :
proxmox with nginx = #public IP# and 192.168.1.1, domainA.com = 192.168.1.2, domainB.com=192.168.1.3)

I also want to set up mail server on each of the VM and route incoming mail communication based on the domain name. For example when I receive mail with recipient firstname.lastname@example.com I want to forward the communication to 192.168.1.2, when I receive mail with recipient email@example.com I want to forward the communication to 192.168.1.3.
How can I achieve this? I was having trouble doing this with nginx and I am not sure this is going to work
Answer: Mail protocols don't have any equivalent of HTTP's Host header on which the virtual hosting and reverse proxying is based.
Any "virtual mail hosting" is based on the simple fact you can integrate domain name into username of mail user. It is not possible to differentiate users by mail server hostname to which they connect, say, via SMTP or IMAP or anything; there is no place in the protocol other than username where domain name may be put into. A reverse proxy is therefore needs to know username, i.e. to perform authentication; but then this is not just a reverse proxy anymore.
Also I don't know any solutions which do analogous to SNI for mail protocols, so all mail "virtual hosts" could only use the same single SSL certificate of hosting server. This means, there is no way at all to use different mail server hostnames for different hosted domains, other that exist in the certificate (in the CN or SAN field).

For SMTP, a limited mimicking of reverse proxy is possible. With Postfix that might be done like this:

Set up a "reverse proxy" system which will consider itself as a relay for both domains. For that, you need to add them into relay_domains setting in the main.cf. Of course, internet senders for both domains must be directed to that system (i.e. MX of all domains must be set to this relay host name).

You'd better give your relay a way to filter out undeliverable destinations. In other words, relay must always know the actual list of mailboxes on target servers. This is to reduce spam load and a probability of the backscatter (this is much more important than you might think!). For example, synchronize mailbox databases of end servers with it periodically and configure relay_recipient_maps on relay host. Remember what I said about "not just a reverse proxy"?

Set up transport maps on this "reverse proxy", which will direct mail for each domain to appropriate settings. This includes adding lines to the /etc/postfix/transport file:

domainA.com smtp:[192.168.1.2]
domainB.com smtp:[192.168.1.3]

Square brackets direct Postfix to not to do MX lookup and use the specified address directly; it'll just connect there to port 25 to deliver mail.
Then specify this file as transport_maps in main.cf (see Postfix docs how to do that correctly)

Setup an MTA on the target hosts. They are configured as usual, except that you should specify the relay host as trusted, for antispam systems of those MTAs to trust its Received: header (you must not trust any Received: headers which were added by systems not under your control).
Comment: Thank you very much for detailed answer, this might exactly be what I was looking for.


General form of a Lie Algebra

Question: Given $G=\left\{A\in M_2(\mathbb{R})\mid A^\top XA = X\right\}$.
Need to find the basis. Error in question
Comment: Treat $Y^TX+XY=0$ as a system of homogeneous equations in the unknown four entries $y_{ij}$ of the matrix $Y$. Use linear algebra techniques to find a basis for the solution space. I got a different basis (but a 1-dimensional space anyway).
Answer: Let
$$
Y=\pmatrix{a&b\cr c&d\cr}.
$$
Recall that (from the earlier questions?)
$$
X=\pmatrix{3&1\cr 1&1\cr}.
$$
The matrix equation defining the Lie algebra looks like
$$
Y^TX+XY=\pmatrix{6a+2c&a+3b+c+d\cr a+3b+c+d&2b+2d\cr}=0.
$$
This is a system of 4 linear homogeneous equations (two of them are the same, though). The bottom right corner tells you that $b=-d$. The top left tells you that $c=-3a$. Making these substitution in the remaining equation gives $0=a-3d-3a+d=-2a-2d,$ so $a=-d$, and hence $c=-3a=3d$. Putting it all together you get
$$Y=d\left(\begin{array}{rr}-1&-1\\ 3&1\end{array}\right).$$
The Lie algebra is thus 1-dimensional. It is spanned by the above matrix.

General form of a Lie Algebra


How to change the values in dataframe in pandas when indices are not unique

Question: I have a dataframe like this:

Now I want to update the value in RUNS column for KOHLI in IPL with 8000. Is it possible? I understand that indices are not unique and that is why I want to know the answer
Comment: Do not link to code and especially code screenshots. Make code a part of your question.
Answer: Try this:
<code>df.loc[df.eval("index == 'IPL' and Name == 'kohli'"), 'Runs'] = 8000
</code>
Comment: or `df.loc[(df.index == 'IPL') & (df.Name == 'kohli'), 'Runs'] = 8000`
Comment: BTW, I wasn't aware of how `eval` worked.  My crazy answer universe just got bigger.
Comment: @piRSquared, thank you! I really like `df.eval()` because [it gives us a  very easy way to lookup/update rows in Multi-Index DF](http://stackoverflow.com/a/41329585/5741205)


What are the implications of the fundamental theorem of calculus?

Question: Can someone explain to me the implications of FTC in word? I was incorrectly taught that integration is DEFINED as the reverse of differentiation, which is stuck in my head instead of the limit of the sum. Consequently, I just naturally Think of finding the "integral" as computing what I now know as an "anti-derivative" ( never introduced to that term in my education) and cannot really grasp FTC properly.
I would really like if someone could boil it down into words, in addition to the theorem in mathematical notation. I just see fancy notation in all the answers, which i understand perfectly, but cannot put into words in my mind without writing everything down
And what are F(x), f(x) and f(t) representing in the 2 different parts of FTC?
Comment: See [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus)
Comment: The antiderivate is not unique, only upto addition of a constant. But if you differentiate any antiderivate, you will return to your original function.
Comment: @OVERWOOTCH Part of your confusion might just be the terminology. 'Antiderivative' is just another term for indefinite integral. Indefinite integration is *defined* to be the opposite of differentiation. Definite integration, on the other hand, is *defined* to be the area under the curve. The FTC tells us that we can work out the area under the curve using the indefinite integral. This is actually a very interesting result that isn't trivial. It's not trivial because we define definite integrals in terms of areas—not in terms of indefinite integrals.
Comment: Take a look at this [previous answer](https://math.stackexchange.com/a/3273123/568204) of mine where I try to clearly stress the difference between differentiation, anti-differentiation (more commonly called indefinite integrals), and integration (definite), and how the Fundamental theorem of calculus comes into the whole picture.
Comment: @OVERWOOTCH This important and interesting result—that the area under the curve is somehow linked to the indefinite integral—is the crux of the Fundamental Theorem of Calculus.
Comment: @peek-a-boo i read your answer and it has really cleared up a lot. Can you tell me if  have understood this correctly?
The first part of the FTC says that if A(x) is the DEFINITE integral or net area function( i know definite integrals arent just about area but this helps me remember) of f up till some point "x", then the derivative of that function, A'(x), is f itself. What this means that, since every continuous function has an area under it, every function must have an derivative. No other use for this part.
Comment: And the second part says that to compute the definite integral/ net area under f, instead of Doing it from first principles by finding the limit Of the reimann sum, we can just find find the antiderivative. Is this correct? Also, the usual notation of FTC part 1, where derivative Os w.r.t x but f is a function of t, is really confusing me
Comment: most of what you said is correct, but "every function must have an derivative" is very wrong. Perhaps you meant to say something like "the 'area' integral function $x \mapsto A(x)$ of a continuous function $f$ is differentiable"?
Comment: Im sorry, i missed the "anti-" part. Thats why i used "an' and not "a". Would that he correct?
Answer: In plain English, the fundamental theorem of calculus states that the rate of change of the area under the curve of a function at any point is the value of the function at that point.
Indeed, informally speaking, if you consider the area under the curve of a function from $a$ to $x$ where $a$ is fixed and $x$ is gradually "moving" to the right, you can see that the increase in the area under this curve as you go from $x$ to $x+dx$ is the area of the very thin rectangle with base $dx$ and height, approximately, $f(x)$. This area is $f(x)dx$ and so the rate of change of the area under the curve at $x$ is $$f(x)dx/dx = f(x)$$.
Comment: 1/x is continuous in (0,infinity). In my answer, I assumed that the height of the thin rectangle is f(x). I need f(x) to be continuous to make this assumption.
Comment: 1/x is continuous in (0,infinity). In my answer, I assumed that the height of the thin rectangle is f(x). I need f(x) to be continuous to make this assumption. The point is that if f(x) is continuous then it can't vary too much if the change in the independent variable is very small. In the thin rectangle the variation in the independent variable is infinitesimal. So I can assume that the height of the rectangle is more or less f(x).
Comment: Im sorry for this stupid question but why does f have to be a function of t? Why cant both A( the definite integral/area function) be both functions of x?
Comment: t is the independent variable, and you are integrating from a, a fixed point, to t=x, a variable point. This area will be a function of x - as x increases the area will increase. You are interested in the rate of change of the area under the curve of f(t) from t=a to t=x. This rate at any point t=x is given by f(x).
Comment: Oh ok. Thanks a lot. One last thing,  could you elaborate on the condition of continuity? Why does the function have to be continuous? 1/x isnt continuous and its anti derivative does exist ( lnx )
Comment: @OVERWOOTCH As strange as it may sound, $1/x$ is continuous. Please look it up.
Comment: Oh ok. Thanks a lot


Ending a called Sub procedure and continuing to the next called Sub procedure

Question: I am currently working on a project in which I use a Validate sub procedure to validate a set of values within a group of text boxes and then use a second sub procedure Sum to add the values of the text boxes together.
Currently when I call in the subs like so:
Private Sub SumButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SumButton.Click

    Call ValidateProcedure()
    Call Sum()

End Sub

The ValidateProcedure doesn't stop if an error is found, the validate procedure works like so:
'Purpose: To make sure all values entered into text boxes 1-4 & the category textbox are valid
    Dim Score1Message As String
    Dim Score2Message As String
    Dim Score3Message As String
    Dim Score4Message As String
    Dim CategoryMessage As String

    'TextBox1 Validation
    If Score1TextBox.Text = "" Then
        Score1Message = "Score 1 is blank"
    ElseIf Score1TextBox.Text > 10 Or Score1TextBox.Text < 0 Then
        Score1Message = "Score 1 is not in range: 0-10"
    Else
        Score1Message = "Score 1 is valid"
    End If

    'Textbox 2 Validation
    If Score2TextBox.Text = "" Then
        Score2Message = "Score 2 is blank"
    ElseIf Score2TextBox.Text > 10 Or Score2TextBox.Text < 0 Then
        Score2Message = "Score 2 is not in range: 0-10"
    Else
        Score2Message = "Score 2 is valid"
    End If

    'Score 3 Validation
    If Score3TextBox.Text = "" Then
        Score3Message = "Score 3 is blank"
    ElseIf Score3TextBox.Text > 10 Or Score3TextBox.Text < 0 Then
        Score3Message = "Score 3 is not in range 0-10"
    Else
        Score3Message = "Score 3 is Valid"
    End If

    'Score 4 validation
    If Score4TextBox.Text = "" Then
        Score4Message = "Score 4 is blank"
    ElseIf Score4TextBox.Text > 10 Or Score4TextBox.Text < 0 Then
        Score4Message = "Score 4 is not in range: 0-10"

    Else
        Score4Message = "Score 4 is valid"
    End If

    'Category Validation
    If CategoryTextBox.Text = "" Then
        CategoryMessage = "Category is blank"

    ElseIf CategoryTextBox.Text <> "a".ToUpper Or CategoryTextBox.Text <> "b".ToUpper Or CategoryTextBox.Text <> "c".ToUpper Then
        CategoryMessage = "Category is not value A,B or C"
    Else
        CategoryMessage = "Category is valid"
    End If

    'Display validation strings in statusLabel
    StatusLabel.Text = Score1Message & Environment.NewLine &
        Score2Message & Environment.NewLine &
        Score3Message & Environment.NewLine &
        Score4Message & Environment.NewLine &
        CategoryMessage

End Sub

So what I'm trying to do is make it validate the values of the text boxes and if there are no errors then proceed with the Sum sub procedure. Any advice appreciated!
Answer: You need to use a Function which return a Boolean value of validating result:
If Validate() = True Then
    Sum()
End If

Change your procedure(Sub) ValidateProcedure to a Function
Private Function Validate() As Boolean
    'Because you concatenate all your messages together in the end,
    'then may be better to use StringBuilder
    Dim errormsg as New StringBuilder()

    'TextBox1 Validation
    If Score1TextBox.Text = "" Then
        errormsg.AppendLine("Score 1 is blank")
    ElseIf Score1TextBox.Text > 10 Or Score1TextBox.Text < 0 Then
        errormsg.AppendLine("Score 1 is not in range: 0-10")
    Else
        errormsg.AppendLine("Score 1 is valid")
    End If

    'Textbox 2 Validation
    If Score2TextBox.Text = "" Then
        errormsg.AppendLine("Score 2 is blank")
    ElseIf Score2TextBox.Text > 10 Or Score2TextBox.Text < 0 Then
        errormsg.AppendLine("Score 2 is not in range: 0-10")
    Else
        errormsg.AppendLine("Score 2 is valid")
    End If

    'Score 3 Validation
    If Score3TextBox.Text = "" Then
        errormsg.AppendLine("Score 3 is blank")
    ElseIf Score3TextBox.Text > 10 Or Score3TextBox.Text < 0 Then
        errormsg.AppendLine("Score 3 is not in range 0-10")
    Else
        errormsg.AppendLine("Score 3 is Valid")
    End If

    'Score 4 validation
    If Score4TextBox.Text = "" Then
        errormsg.AppendLine("Score 4 is blank")
    ElseIf Score4TextBox.Text > 10 Or Score4TextBox.Text < 0 Then
        errormsg.AppendLine("Score 4 is not in range: 0-10")
    Else
        errormsg.AppendLine("Score 4 is valid")
    End If

    'Category Validation
    If CategoryTextBox.Text = "" Then
        error.msg.AppendLine("Category is blank")

    ElseIf CategoryTextBox.Text <> "a".ToUpper Or CategoryTextBox.Text <> "b".ToUpper Or CategoryTextBox.Text <> "c".ToUpper Then
        errormsg.AppendLine("Category is not value A,B or C")
    Else
        errormsg.AppendLine("Category is valid")
    End If

    StatusLabel.Text = errormsg.ToString()
    'Then based on the error messages return a Boolean value:
    If errormsg.Length = 0 Then
        Return True
    Else
        Return False
    End If
End Function

Comment: Hey Fabio,
Sorry I don't quite follow I'm an extremely amateur programmer.
So I convert the Validate Sub Procedure to a Function?

I am not too familiar with functions. Such as knowing where to put the return or what variables to include in the parenthesis in this case
Comment: `Function` can be created like a `Sub` without a parameters
Comment: Thanks Fabio, I will work through the code you put up (There are a few things I haven't ran into yet such as Errormsg.appendline and StringBuilder) I don't want to use anything I don't completely understand but once I completely understand these concepts I'll definitely use it thank you! Would there be a way to validate weather it is true or false without using the errormsg.length?
Comment: then just put `return False` on all `if else`, and `return True` in the end of code
Comment: Sorry to be annoying Fabio, but if I put I put return False at the end of all the ElseIf statements then it terminates without delivering the statuslabel.text!
Comment: :) Thats why was created `errormsg` object of `StringBuilder` type. And after all `if else` print error messages (`StatusLabel.Text = errormsg.ToString()`), after that check if error messages object are empty (`if errormsg.Length = 0`). If so then return true
Comment: Haha thanks Fabio, Well I better get very familiar with Stringbuilder and those other functions. Thanks alot for adding to my knowledge ^^  You've been a great help!


Analytic function SQL

Question: For each matter the order of the table CUSTOMERS display the name of the customer (companyname), and the following three columns - the minimum, maximum and average
value of orders this customer with the discount (data from tables ORDERS and ORDERDETAILS).
Note: It is assumed that the request will contain only one word SELECT.
The scheme of databases:

select distinct c.companyname,
sum(od.unitprice*od.quantity*(1-od.discount)) over (partition by o.orderid) as "SUM"
from customers c, orders o, orderdetails od where c.customerid=o.customerid
and o.orderid=od.orderid

This query displays the total value of orders. As additionally find the minimum, maximum and average value of orders?
select c.companyname,
min(od.unitprice*od.quantity*(1-od.discount)) over (partition by o.customerid) as "MIN",
max(od.unitprice*od.quantity*(1-od.discount)) over (partition by o.customerid) as "MAX",
avg(od.unitprice*od.quantity*(1-od.discount)) over (partition by o.customerid) as "AVG"
from customers c, orders o, orderdetails od
where c.customerid=o.customerid and o.orderid=od.orderid

This query finds the minimum, maximum and average cost is not the whole order, but only sub-orders (as in one order may be several lots).
Answer: I think you just want group by, but twice.  Once at the orders level and once at the customer level:
select companyname, min(mino), max(maxo), sum(sumo)
from (select c.companyname, o.orderid,
             min(od.unitprice*od.quantity*(1-od.discount)) as mino
             max(od.unitprice*od.quantity*(1-od.discount)) as maxo
             sum(od.unitprice*od.quantity*(1-od.discount)) as sumo
      from customers c join
           orders o
           on c.customerid = o.customerid join
           orderdetails od
           on o.orderid = od.orderid
      group by c.companyname, o.orderid
     ) co
group by companyname;

Note that I also introduced explicit join syntax.  If you are learning SQL, you should learn the right way to express joins, using the join keyword and the on clause.
EDIT:
One select is a ridiculous limitation.  Presuming this is for a course, it is even worse to impose such a restriction where modern join syntax is not a requirement.
But, I think it is possible.  Stupid query, but still possible.
      select distinct c.companyname,
             min(min(od.unitprice*od.quantity*(1-od.discount))) over (partition by companyname) as mino,
             max(max(od.unitprice*od.quantity*(1-od.discount))) over (partition by companyname) as maxo
             sum(sum(od.unitprice*od.quantity*(1-od.discount))) over (partition by companyname) as sumo
      from customers c join
           orders o
           on c.customerid = o.customerid join
           orderdetails od
           on o.orderid = od.orderid
      group by c.companyname, o.orderid

I would never write a query like this.  The double nested aggregation is both clearer and probably has better performance.  But it is interesting (in a perverse way) that this could be done.
Comment: Note: It is assumed that the request will contain only one word SELECT.

Analytic function SQL


Election forensics using statistical methods in practice?

Question: Are you aware of any examples of election forensics in practice? Or at least any applied research on real large-scale datasets (e.g. govermental elections)? Thanks.
Comment: http://sekhon.berkeley.edu/elections/election2000/butterfly.review.pdf - Wouldn't consider it "applied" research, but may be of interest.
Answer: Walter Mebane (University of Michigan) has written a lot on using Benford's Law distributions of digits as tests for electoral fraud, both as a methods problem and in a series of applications.  There are several working papers listed here: http://www-personal.umich.edu/~wmebane/
Answer: A quick Google led to a paper by Cantu and Saiegh on Argentinian elections, which appears to have some good references as well. The website FiveThirtyEight does a lot of election prediction and perhaps has some good links. And I seem to remember Andrew Gelman doing some forensics work, but couldn't find a link.


How to get the number of items / rows / length / count of gtk.ListStore

Question: Consider this example:
import pygtk
pygtk.require('2.0')
import gtk

initarr = [ "aa", "bb", "xx" ]

liststore1 = gtk.ListStore(str)
for item in initarr:
  liststore1.append([item])

# one more:
liststore1.append(["whatever"])

# how to get length/size of liststore1 at this point?

As the comment says - how do I get the length / size of liststore1 at end of this code?
Comment: `print len(liststore1)`?
Answer: Just simply print len(liststore1)
To count particular items in a list:
l = ["foo","foo","bar"]
print l.count("foo")
2


Did Bach use a pendulum clock as a metronome?

Question: The reason I ask is because I have heard say that tempo ordinario is something like 60 bpm. Is it much of a stretch to assume Bach and his contemporaries could have used pendulum clocks as metronomes (on occasion)?
Answer: From what I have read (various books and articles) would (should my memory be accurate) indicate that clocks or watches were used in some case. Other cases would us terms like "heartbeat" or "moderate walking" (probably used to define "moderato") or "quick counting" or "slow counting."
It's not so easy to know what the actual timing was. Human heartbeat seems to be the most common measure.


If $F(t,x)$ decreases in $x$ for every $t$, show that if $f,g$ satisfy the equation $x' = F(t,x)$, then $|f(t)-g(t)|$ monotonically decreases.

Question: Given a decreasing function $F(t,x)$ by $x$ for every $t$, show that if $f,g$ satisfy the equation $x' = F(t,x)$, $|f(t)-g(t)|$ monotonically decreases.
I've tried deriving, I've tried plugging in some things to no avail. I'd appreciate it if anyone could point me in the right direction. Thanks.
Answer: Let $h(t)=(f(t)-g(t))^2$. Then
$$
h'(t)=2\,(f(t)-g(t))(f'(t)-g'(t))=2\,(f(t)-g(t))\,(F(t,f(t))-F(t,g(t))\le0.
$$


How to ensure a notification peeks (not heads-up)

Question: I have a notification that is popped up during a I/O task that I'd like to peek so the user knows the details are elsewhere (the status bar).  On older devices, my code works, but on newer devices the notification does not dismiss to the status bar, it becomes a permanent heads-up.  I expect that on newer devices the notification update (current file) causes the peek to reset.  Anyone know of a way to ensure the notification is a peek, not a heads-up?
My app is full-screen, which is why a default priority peeks.
    Util.createNotificationChannel(
        applicationContext,
        "copy",
        "Copying...",
        "Notifications for copy tasks.")

    val builder = Util.createNotification(
        applicationContext,
        "copy",
        applicationContext.getString(R.string.copyingImages),
        applicationContext.getString(R.string.preparing))

    val notifications = NotificationManagerCompat.from(applicationContext)
    notifications.notify(builder.build())

    ...
    (loop)

    builder
        .setProgress(images.size, index, false)
        .setContentText(value.name)
        .priority = NotificationCompat.PRIORITY_DEFAULT
    notifications.notify(builder.build())

Answer: I believe Notification.Builder.setOnlyAlertOnce() will have the result you expect.
Comment: I did look into this, but it stopped showing permanently for that notification.  The issue was that `setAlertOnce` will control whether a particular `id` is ever shown again.  So you need to ensure that every series of related notifications share a roughly UUID.
Answer: @paulajcm had the core of it:

I believe Notification.Builder.setOnlyAlertOnce() will have the result you expect.

The other aspect to take into consideration is that the notification id must be unique or you'll never peek for that type of notification again since you've effectively set that id to not peek again.
builder.notify(JOB_TAG, id, notification) // id must be 'unique'
The other thing I did was toggle setOnlyAlertOnce(false) for the final message, so there's a peek to notify the operation is complete as well:
        builder
            .setContentText("Complete")
            .setProgress(0,0,false)
            .setOnlyAlertOnce(false)
        notifications.notify(builder.build(), notificationId)

So now it's clear to a user when a long-running background task has started and ended, without bugging them in between.


bypass proxy setting in windows service

Question: In windows I have a system variable http_proxy=a.b.c.d:8080
I need to bypass these proxy when I boot a service but I check and always has these variable.
How could I bypass?
Comment: Does this answer your question? [Setting environment variable for service](https://serverfault.com/questions/813506/setting-environment-variable-for-service)
Comment: don't works. If I put HTTP_PROXY="AAAA" in the environment in the registry. Then when I execute with a scheduling job a set command I see again HTTP_PROXY=A.B.C.D:8080. Don't modify these value. However if I put a new variable like TRY=1, I can see these variable with set.
Answer: Change the windows service to a service account that doesn't have the environment variable set,and then restart the service
Edit:
You can try to set the no_proxy environment variable for a specific domain
set no_proxy=mycompany.com
Hopefully you are able to figure to which domain your service connects.
Comment: Problem is that is a system variable so I understand it's impossible that  any user don't have the variable
Comment: Yes correct, it's also a bit odd to set a proxy using an system environment variable. Usually it's been done in the internet options in the control panel. Or using a group policy also setting the internet options. If the service communicates over a certain port you might be able create a bypass or exception in the proxy itself, or if it communicates with a certain known endpoint.
Comment: Thanks! And is there no option to put http_proxy="" or something like that in user environment variables to override the sytem variable?
Comment: There might be, but if you keep that system environment variable it will take priority over the user environment variable and might even cause conflicts. Maybe you are able to host that service in a docker container or something like that?
Comment: Impossible. I need to install in machine local witho docker and nothing like that
Comment: I found something i will update my post with a edit
Comment: Thanks again, another problem is host dont have domain. It says me in the log, cannot connect to e URI "http://OPCT:511/twsz/JobScheduler/job". So I need to bypass OPCT host (without domain)
Comment: If you know the ip you can make something in the local host file like serviceopct.domain and then use that in the no proxy. Very nasty by way. `C:\Windows\System32\drivers\etc\hosts`. Or run network monitor or Wireshark and start the service and see where it tries to connect to by making a network capture
Comment: Thanks! It solved with no_proxy in environment system variable.

bypass proxy setting in windows service


View nodes in a listing only, not on their own?

Question: I have created two node-types: 'match' and 'set'. When a 'match' node is viewed it displays a listing of several 'set' nodes. I've acheived this by calling node_load_multiple in hook_node_view. That's all 'set' nodes do: they are listed by a match node. 'Set' nodes can be created, edited and deleted, but I only want the user to be able to view them in listings.
So, I want to deny access to viewing 'set' nodes on their own page at node/1 or whatever. I've denied access to 'set' nodes using the node access mechanism, but then they don't appear in my listing either.
How can I set these nodes so that they can only be viewed in my listing?
The only thing I can think of is not to call node_load_multiple but to write by own db_select query to retrieve all the necessary 'set' nodes to list in a match 'node': a bit messy.
Hope this makes sense. I open to any suggestions. Thanks.
Comment: I'm 100% certain this question has been asked before, though I can't find it ATM. Page manager can hide content types for you. So can Rabbit Hole, but I strongly dislike that type of "single use" modules, so I don't recommend it.
Comment: I agree about using modules to do one task, if, with a bit of effort, you can write a few lines of code to do the same. However, Rabbit Hole sounds perfect. The other options seem to involve bypassing the node module. I like the 'unpublish the node' idea. I could do this and the then write my own db query. Thanks for the ideas!
Answer: I believe you could use the node_view hook.  In that hook you can check for the node type (set) and view mode (full) and add your logic.  If you're using a reference field to relate the set to the match then you could probably redirect the user back to the match.
When you're listing sets on the match page you could also not render them as links a user doesn't try to view the set directly.


Convert $r^2\cos(2\theta)=9$ to Cartesian

Question: I need to convert $r^2\cos(2\theta)=9$ to Cartesian coordinates.
How should I do it?
What I did:
$$r^{2}\cos2\theta=r^{2}2\cos^{2}\theta-1=9\Rightarrow r^{2}\cos^{2}\theta=5\Rightarrow x^{2}=5$$
Did I'm right?
Thank you!!
Comment: Look closely at the equality $r^{2}\cos2\theta=r^{2}2\cos^{2}\theta-1$.  You have the right idea but have made a very careless error.
Comment: @David, can you tell me please what is the error? Thank you!!
Comment: @David, Ohh... I forgot the $()$. So it's: $r^2((2\cos^2\theta)-1)$...
Comment: That's it.  If you proceed carefully you should end up with $x^2-y^2=9$.
Comment: How did you get an $x^4$?
Comment: @David, my mistake.. Sorry!
Answer: $$r^2 \cos (2\theta ) =r^2 \cos^2 \theta  -r^2 \sin^2 \theta $$
but
$$x=r\cos \theta , y=r\sin\theta $$
so we obtain $$x^2 -y^2 =9.$$