Composite Simpson's rule vs Trapezoidal on integrating $\int_0^{2\pi}\sin^2x dx$

Question: A simple question comparing both methods for numerical integration for a very specific case. We expect the Simpsons rule to have a smaller error than the trapezoidal method, but if we want to calculate
$
\int_0^{2\pi}\sin^2x dx
$
with $n=5$ equidistant points, we have for the trapezoidal rule (not an efficient code, didactic purposes only):
% MATLAB code
x = linspace(0,2*pi,5); % domain discretization
y = sin(x).^2; % function values
h = x(2)-x(1); % step
w_trapz = [1 2 2 2 1]; % weights for composite trapezoidal rule
w_simps = [1 4 2 4 1]; % weights for composite simpson rule
I_trapz = sum(y.*w_trapz)*h/2; % numerical integration trapezoidal
I_simps = sum(y.*w_simps)*h/3; % numerical integration simpsons

The exact answer for this integral is $\pi$ and we check that:
I_trapz =

    3.1416

I_simp =

    4.1888

So, for this particular case, the trapezoidal rule was better. What is reason for that?
Note that the error term in the Composite Simpson's rule is
$
\varepsilon=-\frac{b-a}{180}h^4f^{(4)}(\mu)
$
for some $\mu\in(a,b)$
while the error term for the Composite Trapezoidal rule is
$
\varepsilon=-\frac{b-a}{12}h^2f^{(2)}(\mu)
$
Evaluating the second and forth derivatives of $f(x)=\sin^2(x)$, and noticing $b-a=2\pi$ and $h=\pi/2$, the error term for each of the numerical techniques is:
$
\varepsilon_{Simpson}=-\frac{2\pi}{180}\left(\frac{\pi}{2}\right)^4\left(-8\cos2\mu\right)\\
\varepsilon_{Trapz}=-\frac{2\pi}{12}\left(\frac{\pi}{2}\right)^2\left(2\cos2\mu\right)
$
We estimate the maximum error in each approximation by finding the maximum absolute value the error term can obtain. Since in both approximations we have $\cos(2\mu)$ and $\mu\in(0,2\pi)$, then $\max{|\cos(2\mu)|}=1$, and we have
$
\max{\left|\varepsilon_{Simpson}\right|}=\frac{2\pi}{180}\left(\frac{\pi}{2}\right)^4\left(8\right)=\frac{\pi^5}{180}\approx1.70\\
\max{\left|\varepsilon_{Trapz}\right|}=\frac{2\pi}{12}\left(\frac{\pi}{2}\right)^2\left(2\right)=\frac{\pi^3}{12}\approx2.58
$
We see the error term is smaller for the Simpson method than that for the Trapezoidal method.
However, in this case, the trapezoidal rule gave the exact result of the integral, while the Simpson rule was off by $\approx1.047$ (about 33% wrong).
Why is that? Does it have to do with the number of points in the discretization, with the function being integrated or is it just a coincidence for this particular case?
We observe that increasing the number of points utilized, both methods perform nearly equal. Can we say that for a small number of points, the trapezoidal method will perform better than the Simpson method?
Comment: already fixed the typo. thanks
Answer: Old question, but since the right answer hasn't yet been posted...
The real reason for the trapezoidal rule having smaller error than Simpson's rule is that it performs spectacularly when integrating regular periodic functions over a full period. There are $2$ ways to explain this phenomenon: First we can start with
$$\begin{align}\int_0^1f(x)dx&=\left.\left(x-\frac12\right)f(x)\right|_0^1-\int_0^1\left(x-\frac12\right)f^{\prime}(x)dx\\
&=\left.B_1(x)f(x)\right|_0^1-\int_0^1B_1(x)f^{\prime}(x)dx\\
&=\frac12\left(f(0)+f(1)\right)-\left.\frac12B_2(x)f^{\prime}(x)\right|_0^1+\frac12\int_0^1B_2(x)f^{\prime\prime}(x)dx\\
&=\frac12\left(f(0)+f(1)\right)-\frac12B_2\left(f^{\prime}(1)-f^{\prime}(0)\right)+\frac12\int_0^1B_2(x)f^{\prime\prime}(x)dx\\
&=\frac12\left(f(0)+f(1)\right)-\sum_{n=2}^{2N}\frac{B_n}{n!}\left(f^{(n-1)}(1)-f^{(n-1)}(0)\right)+\int_0^1\frac{B_{2N}(x)}{(2n)!}f^{(2N)}(x)dx\end{align}$$
Where $B_n(x)$ is the $n^{\text{th}}$ Bernoulli polynomial and $B_n=B_n(1)$ is the $n^{\text{th}}$ Bernoulli number. Since $B_{2n+1}=0$ for $n>0$, we also have
$$\begin{align}\int_0^1f(x)dx=\frac12\left(f(0)+f(1)\right)-\sum_{n=1}^{N}\frac{B_{2n}}{(2n)!}\left(f^{(2n-1)}(1)-f^{(2n-1)}(0)\right)+\int_0^1\frac{B_{2N}(x)}{(2n)!}f^{(2N)}(x)dx\end{align}$$
That leads to the trapezoidal rule with correction terms
$$\begin{align}\int_a^bf(x)dx&=\sum_{k=1}^m\int_{a+(k-1)h}^{a+kh}f(x)dx\\
&=\frac h2\left(f(a)+f(b)\right)+h\sum_{k=1}^{m-1}f(a+kh)-\sum_{n=1}^N\frac{h^{2n}B_{2n}}{(2n)!}\left(f^{2n-1}(b)-f^{2n-1}(a)\right)\\
&\quad+\int_a^b\frac{h^{2N}B_{2N}(\{x\})}{(2N)!}f^{2N}(x)dx\end{align}$$
Since we are assuming $f(x)$ has period $b-a$ and all of its derivatives are continuous, the correction terms all add up to zero and we are left with
$$\begin{align}\int_a^bf(x)dx&=\frac h2\left(f(a)+f(b)\right)+h\sum_{k=1}^{m-1}f(a+kh)+\int_a^b\frac{h^{2N}B_{2N}(\{x\})}{(2N)!}f^{2N}(x)dx\end{align}$$
So the error is $O(h^{2N})$ for some possibly big $N$, the only limitation being that the product of the Bernoulli polynomial and the derivative starts to grow faster than $h^{-2N}$.
The other way to look at it is to consider that $f(x)$, being periodic and regular, can be represented by a Fourier series
$$f(x)=\frac{a_0}2+\sum_{n=1}^{\infty}\left(a_n\cos\frac{2\pi n(x-a)}{b-a}+b_n\sin\frac{2\pi n(x-a)}{b-a}\right)$$
Since it's periodic, $f(a)=f(b)$ and the trapezoidal rule computes
$$\int_a^bf(x)dx\approx h\sum_{k=0}^{m-1}f(a+kh)$$
Since $\sin\alpha\left(k+\frac12\right)-\sin\alpha\left(k-\frac12\right)=2\cos\alpha k\sin\alpha/2$, if $m$ is not a divisor of $n$,
$$\begin{align}\sum_{k=0}^{m-1}\cos\frac{2\pi nkh}{b-a}&=\sum_{k=0}^{m-1}\cos\frac{2\pi nk}m=\sum_{k=0}^{m-1}\frac{\sin\frac{2\pi n}m(k+1/2)-\sin\frac{2\pi n}m(k-1/2)}{2\sin\frac{\pi n}m}\\
&=\frac{\sin\frac{2\pi n}m(m-1/2)-\sin\frac{2\pi n}m(-1/2)}{2\sin\frac{\pi n}m}=0\end{align}$$
If $m$ is a divisor of $n$, then
$$\sum_{k=0}^{m-1}\cos\frac{2\pi nkh}{b-a}=\sum_{k=0}^{m-1}\cos\frac{2\pi nk}m=m$$
Since $\cos\alpha\left(k+\frac12\right)-\cos\alpha\left(k-\frac12\right)=-2\sin\alpha k\sin\alpha/2$, if $m$ is not a divisor of $n$,
$$\begin{align}\sum_{k=0}^{m-1}\sin\frac{2\pi nkh}{b-a}&=\sum_{k=0}^{m-1}\sin\frac{2\pi nk}m=-\sum_{k=0}^{m-1}\frac{\cos\frac{2\pi n}m(k+1/2)-\cos\frac{2\pi n}m(k-1/2)}{2\sin\frac{\pi n}m}\\
&=-\frac{\cos\frac{2\pi n}m(m-1/2)-\cos\frac{2\pi n}m(-1/2)}{2\sin\frac{\pi n}m}=0\end{align}$$
And even if $m$ is a divisor of $n$n
$$\sum_{k=0}^{m-1}\sin\frac{2\pi nkh}{b-a}=\sum_{k=0}^{m-1}\sin\frac{2\pi nk}m=0$$
So the trapezoidal rule produces
$$\int_a^bf(x)dx\approx(b-a)\left(\frac{a_0}2+\sum_{n=1}^{\infty}a_{mn}\right)$$
Since the exact answer is $\int_a^bf(x)dx=(b-a)a_0/2$ we see that the effect of the trapezoidal rule in this case is to approximate the function $f(x)$ by its $2n-1$ 'lowest energy' eigenfunctions and integrate the approximation. This is pretty much what Gaussian integration does so it's amusing to compare the two for periodic and nonperiodic functions. The program that produces my data looks like this:
module Gmod
   use ISO_FORTRAN_ENV, only: wp=>REAL64
   implicit none
   real(wp), parameter :: pi = 4*atan(1.0_wp)
   contains
      subroutine eval_legendre(n,x,p,q)
         integer, intent(in) :: n
         real(wp), intent(in) :: x
         real(wp), intent(out) :: p, q
         integer m
         real(wp) r
         if(n == 0) then
            p = 1
            q = 0
         else
            p = x
            q = 1
            do m = 2, n-1, 2
               q = ((2*m-1)*x*p-(m-1)*q)/m
               p = ((2*m+1)*x*q-m*p)/(m+1)
            end do
            if(m == n) then
               r = ((2*m-1)*x*p-(m-1)*q)/m
               q = p
               p = r
            end if
         end if
      end subroutine eval_legendre
      subroutine formula(n,x,w)
         integer, intent(in) :: n
         real(wp), intent(out) :: x(n), w(n)
         integer m
         real(wp) omega, err
         real(wp) p, q
         real(wp), parameter :: tol = epsilon(1.0_wp)**(2.0_wp/3)
         omega = sqrt(real((n+2)*(n+1),wp))
         do m = n/2+1,n
            if(2*m < n+7) then
               x(m) = (2*m-1-n)*pi/(2*omega)
            else
               x(m) = 3*x(m-1)-3*x(m-2)+x(m-3)
            end if
            do
               call eval_legendre(n,x(m),p,q)
               q = n*(x(m)*p-q)/(x(m)**2-1)
               err = p/q
               x(m) = x(m)-err
               if(abs(err) < tol) exit
            end do
            call eval_legendre(n,x(m),p,q)
            p = n*(x(m)*p-q)/(x(m)**2-1)
            w(m) = 2/(n*p*q)
            x(n+1-m) = 0-x(m)
            w(n+1-m) = w(m)
         end do
      end subroutine formula
end module Gmod

module Fmod
   use Gmod
   implicit none
   real(wp) e
   type T
      real(wp) a
      real(wp) b
      procedure(f), nopass, pointer :: fun
   end type T
   contains
      function f(x)
         real(wp) f
         real(wp), intent(in) :: x
         f = 1/(1+e*cos(x))
      end function f
      function g(x)
         real(wp) g
         real(wp), intent(in) :: x
         g = 1/(1+x**2)
      end function g
      function h1(x)
         real(wp) h1
         real(wp), intent(in) :: x
         h1 = exp(x)
      end function h1
end module Fmod

program trapz
   use Gmod
   use Fmod
   implicit none
   integer n
   real(wp), allocatable :: x(:), w(:)
   integer, parameter :: ntest = 5
   real(wp) trap(0:ntest),simp(ntest),romb(ntest),gauss(ntest)
   real(wp) a, b, h
   integer m, i, j
   type(T) params(3)
   params = [T(0,2*pi,f),T(0,1,g),T(0,1,h1)]
   e = 0.5_wp
   write(*,*) 2*pi/sqrt(1-e**2)
   write(*,*) pi/4
   write(*,*) exp(1.0_wp)-1
   do j = 1, size(params)
      a = params(j)%a
      b = params(j)%b
      trap(0) = (b-a)/2*(params(j)%fun(a)+params(j)%fun(b))
      do m = 1, ntest
         h = (b-a)/2**m
         trap(m) = trap(m-1)/2+h*sum([(params(j)%fun(a+h*(2*i-1)),i=1,2**(m-1))])
         simp(m) = (4*trap(m)-trap(m-1))/3
         n = 2**m+1
         allocate(x(n),w(n))
         call formula(n,x,w)
         gauss(m) = (b-a)/2*sum(w*[(params(j)%fun((b+a)/2+(b-a)/2*x(i)),i=1,n)])
         deallocate(x,w)
      end do
      romb = simp
      do m = 2, ntest
         romb(m:ntest) = (2**(2*m)*romb(m:ntest)-romb(m-1:ntest-1))/(2**(2*m)-1)
      end do
      do m = 1, ntest
         write(*,*) trap(m),simp(m),romb(m),gauss(m)
      end do
   end do
end program trapz

For the periodic function
$$\int_0^{2\pi}\frac{dx}{1+e\cos x}=\frac{2\pi}{\sqrt{1-e^2}}=7.2551974569368713$$
For $e=1/2$ we get
$$\begin{array}{c|cccc}N&\text{Trapezoidal}&\text{Simpson}&\text{Romberg}&\text{Gauss}\\
\hline
3&8.3775804095727811&9.7738438111682449&9.7738438111682449&8.1148990311586466\\
5&7.3303828583761836&6.9813170079773172&6.7951485544312549&7.4176821579266701\\
9&7.2555830332907121&7.2306497582622216&7.2544485033158699&7.2613981883302499\\
17&7.2551974671820254&7.2550689451457968&7.2568558971905723&7.2552065886284041\\
33&7.2551974569368731&7.2551974535218227&7.2551741878182652&7.2551974569565632
\end{array}$$
As can be seen the trapezoidal rule is even outperforming Gaussian quadrature, producing an almost exact result with $33$ data points. Simpson's rule is not as good because it averages in a trapezoidal rule approximation that uses fewer data points. Romberg's rule, usually pretty reliable, is even worse than Simpson, and for the same reason. How about
$$\int_0^1\frac{dx}{1+x^2}=\frac{\pi}4=0.78539816339744828$$
$$\begin{array}{c|cccc}N&\text{Trapezoidal}&\text{Simpson}&\text{Romberg}&\text{Gauss}\\
\hline
3&0.77500000000000002&0.78333333333333333&0.78333333333333333&0.78526703499079187\\
5&0.78279411764705875&0.78539215686274499&0.78552941176470581&0.78539815997118823\\
9&0.78474712362277221&0.78539812561467670&0.78539644594046842&0.78539816339706148\\
17&0.78523540301034722&0.78539816280620556&0.78539816631942927&0.78539816339744861\\
33&0.78535747329374361&0.78539816338820911&0.78539816340956103&0.78539816339744795
\end{array}$$
This is a pretty hateful integral because its derivatives grow pretty fast in the interval of integration. Even here Romberg isn't really any better that Simpson and now the trapezoidal rule is lagging far behind but Gaussian quadrature is still doing well. Finally an easy one:
$$\int_0^1e^xdx=e-1=1.7182818284590451$$
$$\begin{array}{c|cccc}N&\text{Trapezoidal}&\text{Simpson}&\text{Romberg}&\text{Gauss}\\
\hline
3&1.7539310924648253&1.7188611518765928&1.7188611518765928&1.7182810043725216\\
5&1.7272219045575166&1.7183188419217472&1.7182826879247577&1.7182818284583916\\
9&1.7205185921643018&1.7182841546998968&1.7182818287945305&1.7182818284590466\\
17&1.7188411285799945&1.7182819740518920&1.7182818284590782&1.7182818284590460\\
33&1.7184216603163276&1.7182818375617721&1.7182818284590460&1.7182818284590444
\end{array}$$
This is the order we expect: Gauss is pretty much exact at $9$ data points, Romberg at $33$, with Simpson's rule and the trapezoidal rule bringing up the rear because they aren't being served the grapefruit of a periodic integrand.
Hope the longish post isn't considered off-topic. Is the plague over yet?
Comment: That was a good answer and I really liked the code, will use some of that :)
Answer: Another point of view is the sampling theorem, as the integrated function is periodic and integrated over 2 periods. The limit frequency of $\sin^2x =\frac12(1-\cos2x)$ is $2$, so with 4 sub-intervals you are at the minimal sampling frequency. If you write $S(h)=\frac{4T(h)-T(2h)}3$ as per Richardson extrapolation, then the term $T(2h)$ is under-sampled with only 2 sub-intervals, inviting substantial aliasing errors. The Simpson method just "does not see" the correct function.
A more regular error behavior should, by this logic, be visible in the next refinements with 8 or 12 sub-intervals in the subdivision of the integration interval.
Answer: In the last line of your code, you have h/2.  It should be h/3.  You also are using the trapezoid weights instead of the simpson's weights.  In fact, I can't figure out why your two results are different at all, since the calculations in the last two lines are identical.
Comment: Sorry for that. I actually typed it wrong here. The code is actually correct. Fixed the typo.
Answer: For this value of $h$, the terms $f''(\xi)$ or $f^{(4)}(\xi)$ in the error formula  can become dominant. If for the trapezoidal rule $f''(\xi)$ is small in comparison with $f^{(4)}(\xi)$ for Simpson's rule, you can have this effect. Also, if the integrand function is not regular enough this can happen (not the case here).
Regarding your error estimates, remember that they are upper bounds for the error. Just because the maximum error is larger for the trapezoidal rule, it does not mean that the same will happen with the actual error.
Comment: @Thales  When $h$ isn't small, $h^2$ or $h^4$ can be of the same magnitude (or even larger) than $\|f''\|_{\infty}$ and $\|f^{(4)}\|_{\infty}$. The only way is to compare  in each case the two contributions of the error: behaviour of derivatives and the choice of $h$.
Comment: Is there any guides to observe that "for a (given) value of h, the error can become dominant" or is it case dependent?


How to restrict string parameter to some keyof alue

Question: I'am working with the Array.some function in TypeScript. I need to restrict the possible strings I will receive as the keys of some Object.
Form example I have an array with some names of the object's properties and my object implements an interface:
    const props = ["a", "b", "c"]

    interface A {
        a: any,
        b: any,
        c: any
    }

Then I call the some function
    props.some( (prop) => {
        // ...
    })

I tried with:
    props.some( (prop: keyof A) => {
        // ...
    })

But I received "Type string is not assignable to type keyof A"
How is this usually resolved?
Answer: When defining the array, define it as const so its typed as a tuple, whose members are all keys of A, so that it doesn't get automatically widened to string[]:
const props = ["a", "b", "c"] as const;

Then
props.some( (prop) => {

will have prop be typed as 'a' | 'b' | 'c'.


ColdFusion and saving Chinese chars and changing Admin settings

Question: I need to be able to save Chinese chars in my active database with ColdFusion 9
I have already figured out how to do it set the field types to NVARCHARS and NTEXT.
I have checked off Enable High ASCII characters and Unicode for data sources configured for non-Latin characters under the Datasources section.
It works great but... here is the question.
Changing the option  Enable High ASCII characters and Unicode for data sources configured for non-Latin characters  - will this create any other downstream issue with the current application?  We will need to update the database structure - I am not sure what effect this option will have to my legacy code.
Comment: Hopefully you have a test environment since that's the only way to know for sure.
Answer: That should not have any effect on your database or your code. It's just a setting on how the application server (coldfusion) communicates to your database server.
Comment: Those two statements seem quite contradictory.
Comment: I misread. I though it said 'future' applications, as if it would make the database server or application server different and unusable.


jQuery function deixa de funcionar após busca Ajax

Question: Eu fiz um sistema em Codeigniter que faz busca em tempo real. Na minha busca, envio os parâmetros via Ajax para o controller e faço a consulta.
Mando todo o HTML para uma view. Depois eu pego todo o HTML dessa view pelo ajax e alimento a minha página substituindo o conteúdo atual pelo novo. Eu fiz um video de 1 minuto mostrando o erro:
https://www.youtube.com/watch?v=bRkY3JwBV-0
O erro é que a function que eu fiz de mostrar/esconder conteúdo (clicando na imagem) funciona antes do Ajax mas não funciona após o Ajax que some com o conteúdo atual e alimenta a div com conteúdo novo.

Function que deixa de funcionar

$('a[href^="#"]').bind("click", function(event){

    event.preventDefault();

    var the_id = $(this).attr("href");

    $(".detalhes").addClass('hide');

    $("div"+the_id+"").parent(".detalhes").removeClass('hide');

    $(".theblog ").removeClass("hide");

    $(this).parents(".theblog").addClass("hide");

    $('html, body').animate({ scrollTop:$(the_id).offset().top-25}, 'slow');
});

Eu estava estudando sobre elementos que não existem e delegate estes dias e acho que tem alguma coisa haver com esse assunto, será que alguém consegue me ajudar a resolver. Eu acho que eu tenho que mudar essa função pra ela funcionar nos elementos que existem e nos que vão existir.
Bom, é isso.
Answer: Você precisa adicionar os eventos em um elemento pai, que não seja alterado pelo ajax depois do carregamento inicial, algo como:
$("body").on("click", 'a[href^="#"]', function(event){

    event.preventDefault();

    var the_id = $(this).attr("href");

    $(".detalhes").addClass('hide');

    $("div"+the_id+"").parent(".detalhes").removeClass('hide');

    $(".theblog ").removeClass("hide");

    $(this).parents(".theblog").addClass("hide");

    $('html, body').animate({ scrollTop:$(the_id).offset().top-25}, 'slow');
});

Pense da seguinte forma, os eventos são atribuídos apenas no carregamento inicial, então todos os 'a[href^="#"]' ja existentes vão receber as atribuições e vão funcionar, mas em seguida, você limpa eles e substitui por novos sem essa atribuição de eventos, então a função deixa de funcionar. Mas fazendo a atribuição no body, ele que vai responder pelo evento e repassar para seus filhos 'a[href^="#"]' tanto os já existes como todos os novos que forem criados depois...


determining a used server's fair market value

Question: I have a customer that has a server he no longer needs. I have another customer who needs a server. This server isn't new but it will easily handle the job. Is there a way to determine what a fair price should be?
If anyone here knows based on the hardware, here's the makeup of the machine.
http://speccy.piriform.com/results/PSbBt5KqBldaPpQ31OozPKW
Answer: For most commodity hardware, straight-line depreciation over 6 years  is probably a safe bet.
<code>Price = Price * ((6-age)/6)
</code>
Comment: I'm more a fan of 18-month double declining `Price = Purchase * 0.5 ^ (Age/1.5)` as it accurately reflects Moore's Law.
Answer: I'd use eBay completed listings as a fair indicator of the value someone is willing to pay for server hardware. A similar server is available (but hasn't sold) on eBay for $900US. I'd estimate $600-$700 for this server setup.


string split '\' in jquery or javascript

Question: I tried to split the string with special character '\' but its not working.
str = 'c:\images\jhjh.jpg';

result = str.split('\');

help me to resolve the issue. Thanks in advance
Comment: String should have proper escaping `'c:\\images\\jhjh.jpg'.split('\\');`. One backslash by its own is an escape character, to denote "\" literally you have to escape it itself with one more "\".
Comment: @coolguy but will it result in an array? dun dun dun..
Comment: yeah ofcourse it will be an array
Comment: Thanks for the Reply. However, I am not populating the values, its a auto generated path from input type "file". Also, I have even tried to replace '\' with "\\" and its not working.
Answer: Your input string should escape \ and also you should escape \ in split function argument as well.
This should work
str = 'c:\\images\\jhjh.jpg';
result = str.split('\\');


Fubini theorem for infinite sum Terence Tao

Question: I just have a question below. I don't understand why we need this proof below ? By assumption we know that the we have that $\Sigma_{(n,m) \in \mathbb{N}\times\mathbb{N}} f(n,m)$ is absolutely convergent. This tells us that any rearrangements of the sequence above is also absolutely convergent. Don't we get the proof right away ?
Comment: Are you trying to apply the theorem on rearrangements of a single sum to rearrangements of a double sum?
Comment: It's not quite the same thing because this isn't in the form of a rearrangement of a single infinite sum. The idea of the proof is essentially the same though, if you aren't using any machinery from measure theory.
Comment: Rearrangements are for linearly ordered infinite series. Double infinite sums are not linearly ordered infinite series.
Answer: In the corresponding theorem for a single sum, you are somewhat limited in the "types" of rearrangements you can do.  Specifically, a rearrangement of a single sum is required to reach each term in the original sum within a finite number of steps.  For instance, it would be invalid application of the corresponding theorem for a single sum $\sum_{n=1}^\infty a_n$ to write it as $$\sum_{n=0}^\infty a_{2n+1} + \sum_{n=0}^\infty a_{4n+2} + \sum_{n=0}^\infty a_{8n+4} + \cdots$$
since such a rearrangement has infinitely many terms before it even reaches, e.g. $a_2$, and then doubly-infinitely many terms before it reaches $a_{12}$.  This, however, is exactly the type of rearrangement that Fubini's theorem allows us to use.
In this way, we can realize Fubini's theorem for sums as just a natural expansion of the types of rearrangements allowed for single sums, but we still need to prove that such an expansion of the previous theorem is valid.  It doesn't merely follow from that previous theorem.
Comment: That is nice. Thank you!


Facebook Graph API get access token

Question: I'm new to Facebook Development using PHP. I have created a nice script which gathers the facebook news feed from my fan page to a JSON array using the graph api....
eg//
  $url="https://graph.facebook.com/".$fbID."/feed?access_token=".$token."&limit=20";

(ghdn using the curl commands to collect the JSON..)
The problem is the access token expires after 2 hours, how can I make this not expire or renew?
Thanks for any help...
Comment: This question appears to be off-topic because it shows no prior research whatsoever.
Comment: try the answer on this page.... [How do you renew an expired Facebook access token?](http://stackoverflow.com/a/6711354/623952) or [another facebook/token answer](http://stackoverflow.com/a/9151853/623952)
Answer: If your fan page is public and has no restrictions like demographic restriction, then you can use your App Access Token to query and retrieve your fan page's feed.
In case your fan page is having restrictions you may use Page Access Token by giving your app manage_pages permission and retrieving Page Access Token using following Graph request
/{user-id}/accounts

Facebook Graph API get access token


Qual é o erro nesta expressão regular?

Question: Qual é o erro desta expressão regular. Já testei com outra função e a máscara funciona. Mas nesta para números com centavos, não funciona. Qual é o erro?

<form>

Só número: <input id="numero" onkeypress="mascara(this,soNumeros)"/>

</form>

<form>

Só número: <input id="numero" onkeypress="mascara(this,soNumeros)"/>

</form>

Comment: Olha resposta do @Brunno, ela atende perfeitamente ao que você quer fazer.
Comment: Não vejo problema nisso, se você checar grandes internet bankings, esses digitos funcionam desta forma, você vai digitando e precisa adicionar os zeros para "crescer" um valor. Desde que a mascara mostre ao usuário de que se ele digitar 120, vai formatar como 1,20 antes(como na solução do brunno), não tem problema. Deve-se atentar ao caso dele desligar o javascript, mas creio que uma tela de confirmação seria suficiente.
Comment: @rray já foi formatado. Ainda estou me interando com a formatação do stackoverflow.
Comment: Retira o escape \. de ambas as regex, testei sem eles e funcionou normalmente.
Comment: @Diego Felipe é para tirar os símbolos "\" e o "."? Tirei o "\" e continua aceitando letras.
Comment: @Diego Felipe  Vi, mas tem uma situação, até comentei lá. O usuário precisa digitar 00 para inserir valores apenas em reais. Se não digitar 00, o valor é alterado.
Comment: @Diego Felipe  verdade. Vou usar assim e faço uma observação no formulário para o usuário.
Answer: O objecto window está sobrescrevendo o valor informado no campo de texto, veja a linha 16.
var v = this; //Está instrução não faz muito sentido

O objecto window não tem a função indexOf().
Comment: coloquei com as alterações citadas por você. Confira, por favor no pastebin:

http://pastebin.com/JTf3PRJ5
Answer: Para adicionar a mascara só com JavaScript e Regex, eu faria da seguinte forma:
document.getElementById('numero').addEventListener("keyup", mascara); //Pego evento de keyup ()

function mascara() {
    var v = this.value; //Pego valor
    v = v.replace(/\D/g, ''); //Valida se é numero
    v = v.replace(/(\d{2})$/, ',$1'); //Seto valores antes da virgula
    v = v.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
    this.value = v != '' ? 'R$ ' + v : 'Grátis'; //Retorno seu valor com (R$) ou se estiver vazio seta para (Grátis) :D
}

Segue um jsfiddle da mascara :)
Comment: Brunno
@ preferi a regex, só fiz algumas mudanças, pois quando eu digitava 1000, o correto seria estruturar para 10,00, mas a regex colocava a vírgula assim: 100,0. Tinha parte da regex que inseria a "," após 3 números. Só fiquei com a última linha, que  é para inserir "," antes dos dois últimos números.
Comment: funcionou, mas tem um detalhe: se eu digitar 120 reais, vai me retornar 1,20. A função tem que aceitar a vírgula ou o ponto digitado pelousuário. Se o usuário digitar outro caracter que não seja a vírgula, não aceita no campo. Se digitar automaticamente, ou o usuário digita 00 no final ou vai alterar o valor.
Comment: Tem um caractere "*" que é chamado de lazy, alguma coisa assim para encontrar um caractere no campo de edição.
Comment: @AndréNascimento, então cara esse exemplo acima ele vai colocar a mascara de forma incremental, na minha aplicação ele atendeu legal, mas é sim possível algumas alterações para que aceite ponto ou virgula mais vai ter que mudar um pouco o funcionamento da regex .. Outro caso seria usar algum plugin, existem vários que fazem isso :D Mais que não quiser colocar jQuery no meio ai vale analisar a alteração na regex hehehe'

Qual é o erro nesta expressão regular?


Will a voice teacher help me improve if I'm a bad singer?

Question: I want to learn how to sing despite me being bad at it. I love to sing, it frees me and brings me joy! I recently got a voice teacher. I know this is a probably a dumb question. (Probably because I'm anxious and don't believe in myself) Will I improve my singing and eventually become a pretty decent sounding singer with a vocal teacher and persistent practice?
Comment: If a teacher **doesn't** help you improve then you're either going to the the wrong teacher or ignoring all their advice.
Comment: What makes you think you're a bad singer in the first place? I was told for years by school teachers my singing was awful, and as a gullible child, I believed I was just bad at it (and since I loved singing, it hurt as hell). Years later I found out that the pitch they made us sing at was simply too high for me. I couldn't hold the tone because my vocal chords were strained and exhausted. All I needed was to sing lower, and hey presto, all of a sudden I'm nothing exceptional, but decent enough not to shoo off an audience as a solo singer-songwriter.
Comment: So whenever I hear someone say they're bad at singing - and I tell you, it seems that at least half of all people think that - I get very skeptical. Yeah, where does this come from? Got it from a reliable source? Seems that most of the time it's not true.
Comment: You'll certainly *improve* your singing with a teacher - who really will be the one to answer this question. Whether it'll be a pretty decent sounding singer, how can we tell? We don't have the ability to look into the future of a complete stranger!
Comment: Do you actually have a vocal teacher right now (sadly, bonus points if they said you're bad at singing right now) and this is why you're asking?
Comment: No, they didn't say that I was bad. I haven't asked them, they might say average.
Comment: That's a Good point!
Comment: It seems to be the case that not _everyone_ can become a good singer, but since you recognize your limitations now, I'm sure you'll be able to tell when you improve. Not posting as an answer since this is anecdotal/speculation.
Answer: As long as you avoid damage to your voice (which is one reason why a teacher is a good idea) it is clear that you will improve with guidance and practice. And unless you have a damaged or malformed vocal apparatus there is nothing that should hinder you to develop your voice. Learning to sing is equally about developing muscles, technique, body feeling and getting rid of bad habits carried over from speaking. As such you being a "bad singer" does only mean that you are not there yet. But this can quickly change once you start to train your voice.
Finally as you said singing can be a very freeing and empowering thing, it can help you get rid of stress and bad feelings, so if you enjoy it you will have a benefit even if you do not become the greatest singer of all time. Singing in a choir can be lots of fun and socially rewarding. You do not need to be flawless to justify making singing a part of your life.
Comment: Nothing is wrong with my voice. So, I can improve. Thanks for responding! I will probably get better! My simple singing goal is to just sound pretty decent while singing a song and not sound terrible. You know, like, being good at karaoke, not be ashamed to open my mouth and sing, when I try to sing, people won't say it's terrible, and finally, I just wanna sing for myself and sound nice, because I love reading, learning and watching about singing! I'm so captivated by it! I probably will discover that I have a decent voice to sing with. With my teacher helping me!Thanks for your advice,Lazy.
Comment: "Learning to sing is equally about developing muscles, technique, body feeling and getting rid of bad habits carried over from speaking" is a great summary +1
Answer: It's certainly worth a try!  Also, you could sing alongside other, better singers - join a choir or other performing group.  And just do a lot of singing!
Don't be discouraged if you can't copy the performance of your favourite singer, in their key.   They had to pick the right key for THEM.  So do you.
Usual disclaimer about practising so hard that it hurts.
Comment: It is worth a try! Thanks for responding! I have heard that some singers transpose songs to fit their vocal range? Because it's just simply out of their range. Like a female singer transposing a song originally written from a guy. And I won't practice SO much that it hurts! I just love to sing and wanna get better at it! :) Thanks guys for replying!

Will a voice teacher help me improve if I’m a bad singer?


About the number of $K$-homomorphisms

Question:
Let $K\subseteq L\subseteq M$ be fields with $[L:K]=n$. I should prove that the number of $K$-homomorphisms from $L$ to $M$ (so field homomorphisms that fix pointwise $K$) is less or equal than $n$?

The case $L=K(u)$ is easy, because any $K$-homomorphism exchanges the roots of the minimal polynomial of $u$ over $K$. But what about the general case? I think that it is necessary an induction argument on $n$.
Answer: We wish to prove for a given homomorphism $K \to M$ that the number of ways to extend it to a homomorphism of $L \to M$ is at most $[L:K]$.
This proof is a standard argument using induction. We induct on $n$. If $n = 1$ we have $L = K$ and there is nothing to prove, for the extension of any given homomorphism $K \to M$ to one of $L \to M$ is just the original homomorphism itself!  Now suppose in the general case that $[L:K] > 1$. Choose $\alpha \in L \notin K$ and consider the tower
$$\begin{array}{c} L \\ | \\ K(\alpha) \\ | \\ K. \end{array}$$
If $K(\alpha) = L$ then the number of homomorphisms of $L$ into $M$ that extend a given homomorphism $K \to M$ is just going to be the number of roots of the minimal polynomial of $\alpha$ over $K$ which is $\leq [L:K]$. If $K(\alpha) \neq L$, then by induction the number of homomorphisms $L \to M$ that extend a given homomorphism $K(\alpha) \to M$is $\leq [L : K(\alpha)]$, and the number of homomorphisms from $K(\alpha) \to M$ that extend a given $K \to M$ is $\leq [K(\alpha) : K]$. Thus the total number of homomorphisms $L \to M$ that extend  a given homomorphism $K \to M$  is $\leq [L:K(\alpha)][K(\alpha) : K] = [L:K]$.
Comment: @awllower  I have edited my answer.
Comment: Why do the number of $K$-homomorphisms from $L$ to $K$ is less or equal than the product $[L:K(\alpha)][K(\alpha):K]$? I don't understand the last sentence of your answer.
Comment: @Galoisfan The number of homomorphisms from $L$ to $M$ that fix $K$ pointwise is the number of homomorphisms from $L$ to $M$ that fix $K(\alpha)$ pointwise ***multiplied by*** the number of homomorphisms from $K(\alpha)$ to $M$ that fix $K$ pointwise.
Comment: Ok, maybe it is a stupid question, but I don't understand precisely this point:

"The number of homomorphisms from $L$ to $M$ that fix $K$ pointwise is the number of homomorphisms from $L$ to $M$ that fix $K(\alpha)$ pointwise multiplied by the number of homomorphisms from $K(\alpha)$ to $M$ that fix $K$ pointwise."

Why do you take the product?
Comment: @Benjalim But this fact needs to be proved, and is not in the induction hypothesis. Per chance the hypothesis should be modified?
Comment: @Galoisfan, every $K$-hom from $L\rightarrow M$ extends a $K$-hom from $K\rightarrow M$ (and there is only one $K$-hom $K\rightarrow M$.) This hom extends to at most $[K(\alpha):K]$ $K$-homs $K(\alpha)\rightarrow M$. Then, by the induction hypothesis, each of those (at most) $[K(\alpha) : K]$ maps extends to at most $[L : K(\alpha)]$ maps $L \rightarrow M$. Hence, we have a total of, at most, $[L : K(\alpha)][K(\alpha) : K]$ maps $L\rightarrow M$.
Answer: I assume that you are familiar with the notion of sparability, in particular, separable extensions and separable closures and let us begin by an observation: a field homomorphism is either $0$, or an isomorphism into a subfield of the target. Hence, a $K$-field homomorphism is an isomorphism, if $K\not=0$.

If $L/K$ is separable, then by the primitive element theorem, we know that $L=K(u)$ for some $u\in K$, which case you have solved.
  Now if $L/K$ is inseparable, $K$ must be an (infinite) field of characteristic $p\not= 0$. (And $K$ cannot be algebraically closed, otherwise $L=K$.)
  By taking separable closures, and by reason of the multiplicativity of the degrees of extensions, we can assume that $L/K$ is purely inseparable. Thus every $\alpha\in L$ satisfies $\beta=\alpha^{p^t}\in K$ for some $t\in\mathbb N$. Now $\alpha$ satisfies $x^{p^t}-\beta=(x-\alpha)^{p^t}=0$ so that every $K$-homomorphism of $L$ must leave $\alpha$ invariant. Since $\alpha\in L$ was arbitrary, it follows that the only such homomorphism is the identity.

The proof is complete now.
If some inappropriate points occur, tell me, thanks.
Comment: Either 0 or an inclusion.
Comment: An injective homomorphism is an isomorphism into a subfield. Sorry if this is confusing.
Comment: All inclusions are isomorphisms between the domain and image. That doesn't imply all K-field homomorphisms are isomorphisms. The first sentence, as restated, gets the point across. You could also say field homomorphisms restrict to isomorphisms of the domain.
Comment: Certainly you are right, but, as I have seen, the use of the word *isomorphism* is another word for *monomorphism* in the book [**Basic Number Theory** by *André Weil*](http://www.amazon.com/Basic-Number-Theory-Classics-Mathematics/dp/3540586555). So that is why I say sorry, if the terminology is not standard. Hope it does not cause a serious problem. P.S. Your last sentence is not right, either; it should be *field homomorphisms restrict to inclusions of the domain.* Regards.

About the number of $K$-homomorphisms


What does a single event tell me?

Question: Let's assume we have a physical experiment which runs continuously and shows some events we are interested in.
An event could be detecting a certain type of particle.
Or, to make it more demonstrative, the event may be overheating of our contraption. (We know it will automatically recover.)
We start our experiment, knowing that it should not be able to overheat at all.
Let's consider various possible observations after running it for one day:
We started with the assumption that it does not overheat at all.

It just runs smoothly, and it never overheated.

That tells us we were probably right.

It overheats at random times about once per minute.

We now expect the next overheat event to occur in roughly a minute

It overheated once.

What do we know based on this?

We learned that it can overheat. Should we assume that it will overheat again?
The probability of overheating is not 0 as we expected. Anything else?
One may argue the method of statistics just does not apply here, because we do not have a set of samples to base on. But there seems to be some information we get.
Do we just update our estimate when an event occurs to be the number of events up to now per time passed since start? Could we say anything about how sure we are about it?
Comment: @MWaz You can actually maximize a (single parameter) likelihood from a single observation, like an exponential distribution for time-to-event. Due to the mean-variance relationship, you get a standard error as well.
Comment: There is a rich literature on this called reliability analysis. The trick is that a "single event" is comprised of many measures: such as the time series of inputs given to the system, any measures of system state (such as operating temperature prior to over heat failure), the actually timing of failure, and the extent of failure (did the system recover? Fully? how long did it take to recover? )
Comment: You cannot say how sure you are about the chance of overheating. You have a standard deviation of 0 and cannot construct a confidence interval. In this case, I believe you are limited to saying the event happened and given that you know this was a true event (the sensor was working correctly and so on), it may happen again but you do not know how often and cannot even say how confident you are it will happen again.
Answer: Granted that a single observation may not tell you everything you'd like to know, but continuing from @AdamO's Comment, information from one occurrence may be useful.
Now you know that overheating can happen. You might assume that such events happen according to a Poisson process with rate $\lambda$ so that times between events are exponential with rate $\lambda$ and mean $\mu = 1/\lambda.$
If $X \sim \mathsf{Exp}(\text{rate} =\lambda),$ then
$X/\mu \sim \mathsf{Exp}(1).$ Consequently,
$$0.95 = P(L \le X/\mu \le U) = P(X/U \le \mu \le X/L),$$
where $L$ and $U$ cut probability 0.025 from the lower and upper tails, respectively, of $\mathsf{Exp}(1).$
If $X = 2.3$ hours, a computation in R gives the 95% CI $(.62,\, 90.8)$ hours.
Not as much as you might like to know, nevertheless some information. (Without intervention, you shouldn't be astonished if there's another overheating event within the week.)
<code>2.3/qexp(c(.975,.025), 1)
[1]  0.6234956 90.8451475
</code>

What does a single event tell me?


Cardinality, $|x|=|y|$  implies $|A^x|=|A^y|$

Question: I am trying to prove, without using the Schroder-Bernstein theorem, (where a modulus defines cardinality) that
i.) $|x|=|y|$ implies $|A^x|=|A^y|$
and
ii.) $|x|=|y|$ implies $|x^A|=|y^A|$.
Thank you!
Answer: I don't think you even need Cantor-Bernstein-Schroeder:
Let $f\colon x\to y$ be a bijection.

Define $f_A\colon A^y\to A^x$ by $f_A(g) = g\circ f$. Prove that $f_A$ is a bijection.
Try a similar idea: use $f$ to construct a map $x^A$ to $y^A$ and prove it is a bijection.
Answer: If $|x|=|y|$, you have a bijection $f:x\to y$. You want to use $f$ to construct bijections $g:A^x\to A^y$ and $h:x^A\to y^A$. The first is slightly easier; I'll do the second and let you see if you can adapt the ideas to do the first yourself.
An element of $x^A$ is a function $\varphi:A\to x$, and you want $h$ to match it up with some function from $A$ to $y$. You already have a function $f$ that matches elements of $x$ with elements of $y$, so use it to 'translate' the output of $\varphi$: $f(\varphi)$ should be the function that takes $a\in A$ to $\varphi(a)$ and then takes that to $f(\varphi(a))$ over in $y$:
$$A\stackrel{\varphi}\longrightarrow x\stackrel{f}\longrightarrow y:a\mapsto \varphi(a)\mapsto f(\varphi(a))\;.$$
The function that does this is clearly the composition $f\circ\varphi$, so we should set $h(\varphi)=f\circ\varphi$:
$$h:x^A\to y^A:\varphi\mapsto f\circ\varphi\;.$$
Comment: Thank you! I wasn't sure which to vote - I appreciate your time in answering this. This is the first way that I constructed the proof.
Answer: Two sets $x$ and $y$ have the same cardinality precisely when there is a bijection $f:x\to y$.
Thus, for both parts, there is a bijection $f:x\to y$. How can you use $f$ to create a bijection between $A^x$ and $A^y$? Think about how you might turn an element of $A^x$ into an element of $A^y$ using $f$.
You can use the same idea for the second problem.
Answer: To say that $|x|=|y|$ is to say that the difference between $x$ and $y$ is just in the labels of the names. An element of $A^x$ is a function whose domain is $x$ and its co-domain is $A$.
If we agreed that simply by changing the name of every element in $x$ we can get $y$, fix a renaming method (that is, pick a particular way to rename from $x$ to $y$) and take some $f\in A^y$, define $\hat f\in A^x$ to be the function which sends $x\in X$ to $f(y)$ such that $y$ is the element we get by renaming $x$ in the renaming method.
Rigorously a renaming method is simply a bijection $\varphi\colon y\to x$, and we simply define $\hat f = \{\langle\varphi(y),f(y)\rangle\mid \langle y,f(y)\rangle\in f\}$. We can show that this is a function from $x$ into $A$ and if $f\neq g$ then $\hat f\neq\hat g$.
Therefore $\hat\bullet\colon A^y\to A^x$ is a bijection and $|A^x|=|A^y|$.
The second question is essentially the same, this time we have a function from $A$ to $x$, so we simply compose it with $\varphi$, our bijection.

The Cantor-Bernstein theorem simply tells us that if we have two injections then we have a bijection. To prove something like $|x|=|y|\implies |A^x|=|A^y|$ without the use of Cantor-Bernstein would depend on how many laws you have already proved using bijections and injections.
For example, if you prove that $|x|\leq |y|\implies |A^x|\leq|A^y|$ then you can simply write:

Since $|x|=|y|$ we have that $|x|\leq |y|$ and therefore $|A^x|\leq|A^y|$; similarly $|y|\leq|x|$ and therefore $|A^y|\leq|A^x|$.
By Cantor-Bernstein we have that $|A^x|=|A^y|$.

However, after quite some time you realize that proving that aforementioned property is not easier than constructing explicit bijections.
Comment: @JoshuaBunce: That is the definition of cardinality. Cantor-Bernstein says that if $|a|\leq|b|$ and $|b|\leq|a|$ then $|a|=|b|$. That is to say if there is an injection from $a$ into $b$ and another injection from $b$ into $a$ then there is a bijection from $a$ onto $b$.
Comment: @JoshuaBunce: I don't know about that, but I do plan on taking a mind reading course during my Ph.D. studies... so maybe in a few years I could answer your second question too! :-)
Comment: The theorem I am mentioning is one that states that two sets have the same cardinality if there exists a bijection between them.
Comment: Right. What was I thinking...


Diferences between: migrate_d2d and migrate

Question: I need to migrate a d7 site to a d7 distribution. This is to migrate from d7 to d7.
I found this modules which I undertand will help me with this task.I've read the documentation but I don't fully understand the diferences between them.
Which one is the right module for my situation?
Answer: From Drupal-toDrupal data migration (migrate_d2d) module page:

migrate_d2d provides a framework based on the Migrate API

So the diference is - migrate is an API module for migrations, and migrate_d2d uses it to perform task like yours. Either way you will use migrate, only difference is - do you feel you need to write what authors of migrate_d2d already wrote? Or maybe you want to use or modify their work to save some time?
Comment: so, using migrate_d2d will save me to write code that is already written? am I right?
Comment: @chefnelone yes. It will still use migrate in the background. And it will force you to do things the way authors of migrate_d2d decided to go. But migrating from Drupal to Drupal does not leave too wide field for interpretation ;) so it does not hurt.
Comment: @chefnelone and you cannot use migrate directly, as it is an API with no user interface and no "external" interface. It does nothing on it's own (out-of-the-box it only can create, but not read) and always require external code to use it.


Usar jquery.validate para validar dimensões da imagem

Question: Gostaria de saber como usar o jquery validate para validar as dimensões da imagem que está sendo enviada. No meu caso, a imagem tem que ter 400px de altura e largura.
Answer: Para fazer isso é necessário criar uma validação customizada, segue um exemplo:

function readImage(file, element) {
var reader = new FileReader();
var image  = new Image();

reader.readAsDataURL(file);
reader.onload = function (_file) {
    image.src = _file.target.result;
    image.onload = function() {
        $(element).data('height', this.height);
        $(element).data('width', this.width);
        $(element).data('size', ~~((file.size / 1024) / 1024));
    }
}
};

jQuery.validator.addMethod('height', function (value, element, param) {
if ($(element).data('height')) {
    return $(element).data('height') == param;
}    return this.optional(element) || true;
}, 'A altura deve ser exatamente {0}px');

jQuery.validator.addMethod('width', function (value, element, param) {
if ($(element).data('width')) {
    return $(element).data('width') == param;
}    return this.optional(element) || true;
}, 'A largura deve ser exatamente {0}px');

jQuery(function ($) {
"use strict";
$('#image').change(function () {
   var files = this.files;
    if (files && files[0]) {
        readImage(files[0], '#image');
    }
});

   $('#update_profile').validate({
    rules: {
        image: {
            required: true,
            width: 400,
            height: 400,
        }
    },
});
});

<form id="update_profile" method="post" action="">
<input type="file" name="image" id="image" />
<input type="submit" value="Save" />
</form>

Fonte 1
Fonte 2
Comment: Muito bom. Obrigado!


Selecting a Record With MAX Value

Question: In SQL Server 2008 I have a table CUSTOMERS that has two columns as:
ID,
BALANCE
How can I write the query that selects the ID of the customer who has maximum balance, "in the most effective way"?
Option 1: ORDER BY BALANCE and SELECT TOP(1) --> costs too much.
Option 2: Firstly Get MAX amount, then make another query that uses the amount in where clause --> costs too much and not seem reliable.
Comment: If you add a non clustered index to Balance you should find that Option 1 is much quicker.
Comment: Do you want to know all the IDs in the event of a tie? It seems you are looking for a random one in the event of a tie as is.
Answer: Note: An incorrect revision of this answer was edited out. Please review all answers.
A subselect in the WHERE clause to retrieve the greatest BALANCE aggregated over all rows. If multiple ID values share that balance value, all would be returned.
SELECT
  ID,
  BALANCE
FROM CUSTOMERS
WHERE BALANCE = (SELECT MAX(BALANCE) FROM CUSTOMERS)

Comment: @SergeProfafilecebook Strange - I wonder why this answer was accepted so many years ago. There should be a subquery in the `HAVING` or `WHERE`.
Comment: Column BALANCE is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.
Comment: Im no SQL expert but doesnt Group By have its own cost??
Comment: @Baz1nga - You cannot work on aggregate functions with additional columns without having a group by clause.  Everything has a cost but at what is the real question?
Comment: What version of SQL Server is that original answer valid for? It doesn't even make any sense, much less actually run. (If you're aggregating by id, what is the balance being shown?)
Comment: @MgSam No idea. I vaguely remember this answer reappearing 3 years ago. I can't delete it because it's accepted, though shouldn't have been. I'm going to edit out the top section entirely. Downvote freely.
Answer: Here's an option if you have multiple records for each Customer and are looking for the latest balance for each (say they are dated records):
SELECT ID, BALANCE FROM (
    SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DateModified DESC) as RowNum, ID, BALANCE
    FROM CUSTOMERS
) C
WHERE RowNum = 1

Comment: This is nice syntax, but I noticed the performance of `SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DateModified DESC)` is really impact full when selecting a larger set of data
Answer: What do you mean costs too much?  Too much what?
SELECT MAX(Balance) AS MaxBalance, CustomerID FROM CUSTOMERS GROUP BY CustomerID

If your table is properly indexed (Balance) and there has got to be an index on the PK than I am not sure what you mean about costs too much or seems unreliable?  There is nothing unreliable about an aggregate that you are using and telling it to do.  In this case, MAX() does exactly what you tell it to do - there's nothing magical about it.
Take a look at MAX() and if you want to filter it use the HAVING clause.
Answer: Say, for an user, there is revision for each date. The following will pick up record for the max revision of each date for each employee.
select job, adate, rev, usr, typ
from tbl
where exists (  select 1 from ( select usr, adate, max(rev) as max_rev
                                from tbl
                                group by usr, adate
                              ) as cond
                where tbl.usr=cond.usr
                and tbl.adate =cond.adate
                and tbl.rev =cond.max_rev
             )
order by adate, job, usr

Answer: The query answered by sandip giri was the correct answer, here a similar example getting the maximum id (PresupuestoEtapaActividadHistoricoId), after calculate the maximum value(Base)
select *
from (
    select PEAA.PresupuestoEtapaActividadId,
        PEAH.PresupuestoEtapaActividadHistoricoId,
        sum(PEAA.ValorTotalDesperdicioBase) as Base,
        sum(PEAA.ValorTotalDesperdicioEjecucion) as Ejecucion
    from hgc.PresupuestoActividadAnalisis as PEAA
    inner join hgc.PresupuestoEtapaActividad as PEA
        on PEAA.PresupuestoEtapaActividadId = PEA.PresupuestoEtapaActividadId
    inner join hgc.PresupuestoEtapaActividadHistorico as PEAH
        on PEA.PresupuestoEtapaActividadId = PEAH.PresupuestoEtapaActividadId
    group by PEAH.PresupuestoEtapaActividadHistoricoId, PEAA.PresupuestoEtapaActividadId
) as t
where exists (
    select 1
    from (
        select MAX(PEAH.PresupuestoEtapaActividadHistoricoId) as PresupuestoEtapaActividadHistoricoId
        from hgc.PresupuestoEtapaActividadHistorico as PEAH
        group by PEAH.PresupuestoEtapaActividadId
    ) as ti
    where t.PresupuestoEtapaActividadHistoricoId = ti.PresupuestoEtapaActividadHistoricoId
)

Selecting a Record With MAX Value


The Galois group of a specific polynomial $ f(x) = x^6-2x^3+2 \in Q[x] $

Question: Hello all I was given this question in Algebra asking me to show a polynomial's Galois group has both a subgroup and quotient group isomorphic to $S_3$ the three symmetric group.
The polynomial in question over Q is $ f(x) = x^6-2x^3+2 \in Q[x] $
I know this polynomial is irreducible over Q via Eisenstein with p=2
This I know so the polynomial is irreducible over a field Q with char zero therefore it is separable, so it has a Galois group for its splitting field.
I also know this is the minimal polynomial of $ \sqrt[3]{1+i} $ over Q. I cannot seem to proceed and actually prove that the Galois group has both a subgroup and quotient groups isomorphic to $ S_3 $, I also know the Galois group is a subgroup of the six symmetric group $S_6$ but cannot use any of this information to prove the claim. Help appreciated thanks all
Answer: Getting late here, so a quick sketch (or extended hint) with steps only.

Show that the zeros of $f(x)$ are the three cube roots of $1+i$ and the cube roots of $1-i$.
Let $L$ be the splitting field of $f(x)$ over $\Bbb{Q}$. Given that the ratio $(1+i)/(1-i)$ is a primitive fourth root of unity show that $L$ contains a twelfth root of unity $\zeta$.
If $w$ is one of the cube roots of $1+i$, show that $L=\Bbb{Q}(w,\zeta)$, and conclude that $[L:\Bbb{Q}]=12$.
Because $L$ contains a cube root of $(1+i)$ and a cube root of $(1-i)$ it also contains a cube root of $(1+i)(1-i)=2$. Why does this imply that $L$ contains the splitting field $M$ of $x^3-2$?
It is well known that $Gal(M/\Bbb{Q})\cong S_3$. Why does this imply that $Gal(L/\Bbb{Q})$ has a quotient group $\cong S_3$?
Show that $L$ is the splitting field of $x^3-(1+i)$ over $K=\Bbb{Q}(i)$. Why does this imply that $Gal(L/\Bbb{Q})$ has a subgroup $\cong S_3$?

If you want to play with a realization of $Gal(L/\Bbb{Q})$ as a subgroup of $S_6$ you can use the numbering of zeros of $f(x)$:
$$
\begin{aligned}&x_1=w, &&x_2=w\zeta^4, &&x_3=w\zeta^8,\\
 &x_4=\overline{w}=w\zeta^{11},&&x_5=x_4\zeta^4=w\zeta^3,&&x_6=x_4\zeta^8=w\zeta^7.
\end{aligned}$$
The conjugates of $\zeta$ are $\zeta^k,\gcd(k,12)=1$. But there is the relation $w^3=1+i=1+\zeta^3$ that the automorphisms must respect. So if you specify the image $\sigma(w)$ under an automorphism $\sigma$ to one of the roots, then this leaves only two options for $\sigma(\zeta)$ (instead of all four).
Comment: Thank you very much very helpful answer
Answer: Hint: What is the dimension of the extension field of f(x) over $\mathbb{Q}$?
Comment: First find of the extension field of f(x) over $\mathbb{Q}$. To do this, find all the roots of the polynomial, then find a way of adjoining the roots not in $Q$.
Comment: You didn't adjoin it well. However, $6$ seems to be the degree. Why do you think that it will not tell you that the degree of the splitting field over $\mathbb{Q}$???
Comment: Let $w$ be a primitve cube root of 1. The splitting field is $Q(i, w, (1+i)^{1/3})$ which has degree 12.
Comment: Thank you kindly but that is what I cannot figure out
Comment: I know the dimension of the extension $ [Q[\sqrt[3]{1+i}]:Q]$ is of degree 6 but this does not tell me what is the degree of extension of the splitting field over Q
Comment: I know that I adjoined only one root and got degree 6 but the splitting field is Q adjoined with all roots of the polynomial so it could have slightly larger degree but determining the splitting field is hard for me
Comment: If $K$ is the splitting field of f(x) over $\mathbb{Q}$ then $[K,\mathbb{Q}]\leq n!$, where $n$ is the degree of f(x).
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/25875/discussion-between-zbigniew2015-and-chuks).


I'm facing a performance issue in SharePoint online app parts

Question: The custom app parts in SharePoint add-ins (SharePoint hosted) gives bad performance when adding them into a custom page in the hosted site.
Is there a solution for this problem?
Comment: What do you mean by bad performance? You mean they load slowly?
Comment: Yes, I mean they load slowly.
Answer: The slow performance is most likely caused by the way the app parts are placed on the SharePoint page - each app part is contained within it's own iFrame which points to the app web. When the page loads, another full HTTP call has to be performed for the content from each app part placed on the page. Unfortunately - this behaviour is a part of the Add-in model and cannot be changed. Source: How to add SharePoint-hosted add-in as an app part
It has it's positives, as it allows to display content from provider-hosted apps in a web-part like manner. The biggest downside is - it treats SharePoint-hosted apps the same way.
To boost the performance I would suggest (if possible) switching to the SharePoint Framework, which is client-side only, doesn't use internal app webs and renders directly inside the page's DOM without being wrapped with any iFrames. Take a look here: Build your first SharePoint client-side web part

I’m facing a performance issue in SharePoint online app parts


Find the element representing evaluation at a point in the Hilbert space of $L^2$ holomorphic functions on the disk

Question: The space $S$ of holomorphic functions on the disk $\mathbb{D}$ which are also in $L^2(\mathbb{D})$ is a Hilbert space, with the inner product being $\langle f, g\rangle = \int f(z) \overline{g(z)} dA(z)$, where $dA$ denotes Lebesgue measure. The linear functional $L_{z_0}$, given by $f\mapsto f(z_0)$, is a bounded linear functional on $S$, and thus there must exist some $g_{z_0}\in S$ so that $L_{z_0}(f) = \langle f, g_{z_0}\rangle$ for all $f$. It turns out, this function is given by
$$g_{z_0}(w) = \frac{1}{(1-\overline{z_0}z)^2}$$
I have seen this proven by representing $f$ and $g$ as power series, performing the multiplication, and working out the coefficients of the $g$ power series by brute force, which is fine. But I want to think that there is an easier way to do it, or at least a more conceptually satisfying way. For example, I would think to do it by first noting that for $z_0 = 0$, $g_{z_0}$ can be a constant function (I believe $1/\pi$), and then getting the general case by composing with a Mobius transformation; indeed, the function $g_{z_0}$ is closely related to the derivative of such a Mobius transformation, but I have not been able to get such an approach to work. I realized that I don't really know any machinery for working with non-holomorphic functions (like $\overline{g_{z_0}}$), and area integrals of complex functions are also somewhat new to me.
In sum, Can anyone give me a conceptually satisfying way of approaching this problem, hopefully one that uses some classical complex analysis tricks like Cauchy's integral formula, Mobius transformations, and the like?
Or, Can you direct me to a resource which has the basic tools for solving this problem?
Answer: Your Möbius transformation idea is good, but it needs one extra thing  to work. We know that
$$
f(0) = \frac{1}{\pi}\iint_{|z|<1} f(z)\,dA(z)
\tag1$$
Given $z_0$, apply (1)  to $g = (f\circ \phi^{-1})(\phi^{-1})'$ where $\phi(z)=  (z-z_0)/(1-\bar z_0z) $ is a Möbius transformation sending $z_0$ to $ 0$. (Here, $(\phi^{-1})'$ is that extra thing.) Since
$$\phi'(z) = \frac{1-\bar z_0 z + \bar z_0(z-z_0) }{(1-\bar z_0 z)^2} = \frac{1- |z_0|^2 }{(1-\bar z_0 z)^2} \tag2$$
the change of variables $z=\phi(w)$ yields
$$
 f(z_0) (\phi^{-1})'(0) = g(0) =  \frac{1}{\pi}\iint_{|z|<1} g(z)\,dA(z)
=  \frac{1}{\pi}\iint_{|w|<1} \frac{f(w)}{\phi'(w)} |\phi'(w)|^2\,dA(w)
\tag3$$
This simplifies to
$$
 \frac{f(z_0)}{\phi'(z_0)} = \frac{1}{\pi}\iint_{|w|<1}  f(w) \overline{\phi'(w)}  \,dA(w)
\tag4$$
and, using (2), further simplifies to
$$
 f(z_0) (1-|z_0|^2)  = \frac{1}{\pi}\iint_{|w|<1}  f(w) \frac{1-|z_0|^2}{(1-z_0 \bar w)^2}  \,dA(w)
\tag6$$
which is the desired result
$$
 f(z_0)   = \frac{1}{\pi}\iint_{|w|<1}  f(w) \frac{1}{(1-z_0 \bar w)^2}  \,dA(w)
\tag7$$
What's the idea of putting the derivative factor $(\phi^{-1})'$ in the formula for $g$? Without it we'd end up with the Jacobian $|\phi'|^2 = \phi'\overline{\phi'}$ as the factor of $f$ on the right hand side of (3). And we want an antiholomorphic weight there, so $\phi'$ has to be canceled off.
Comment: This is beautiful, thank you. That's exactly what I needed.


How to select only the cells I need from a XLS file with Pandas

Question: So, i'm trying to select a few lines and columns of an Excel file and turn them into a Pandas dataframe. The problem is: I must select only columns C:G and lines 19 to 245. I tried using df = pd.read_excel("Energy Indicators.xls", skiprows=18, usecols="C:G") without success.
Unfortunately I cannot change the XLS file, so I have to leave it as it is.
I always get the following error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-ff45621b0e89> in <module>()
      4 file_loc = "Energy Indicators.xls"
      5
----> 6 df = pd.read_excel(file_loc, skiprows=18, usecols="A:D")

/opt/conda/lib/python3.6/site-packages/pandas/io/excel.py in read_excel(io, sheetname, header, skiprows, skip_footer, index_col, names, parse_cols, parse_dates, date_parser, na_values, thousands, convert_float, has_index_names, converters, true_values, false_values, engine, squeeze, **kwds)
    198         skip_footer=skip_footer, converters=converters,
    199         true_values=true_values, false_values=false_values, squeeze=squeeze,
--> 200         **kwds)
    201
    202

/opt/conda/lib/python3.6/site-packages/pandas/io/excel.py in _parse_excel(self, sheetname, header, skiprows, names, skip_footer, index_col, has_index_names, parse_cols, parse_dates, date_parser, na_values, thousands, convert_float, true_values, false_values, verbose, squeeze, **kwds)
    502                                     skipfooter=skip_footer,
    503                                     squeeze=squeeze,
--> 504                                     **kwds)
    505
    506                 output[asheetname] = parser.read()

/opt/conda/lib/python3.6/site-packages/pandas/io/parsers.py in TextParser(*args, **kwds)
   1669     """
   1670     kwds['engine'] = 'python'
-> 1671     return TextFileReader(*args, **kwds)
   1672
   1673

/opt/conda/lib/python3.6/site-packages/pandas/io/parsers.py in __init__(self, f, engine, **kwds)
    728             self.options['has_index_names'] = kwds['has_index_names']
    729
--> 730         self._make_engine(self.engine)
    731
    732     def close(self):

/opt/conda/lib/python3.6/site-packages/pandas/io/parsers.py in _make_engine(self, engine)
    927             elif engine == 'python-fwf':
    928                 klass = FixedWidthFieldParser
--> 929             self._engine = klass(self.f, **self.options)
    930
    931     def _failover_to_python(self):

/opt/conda/lib/python3.6/site-packages/pandas/io/parsers.py in __init__(self, f, **kwds)
   1818         # infer column indices from self.usecols if is is specified.
   1819         self._col_indices = None
-> 1820         self.columns, self.num_original_columns = self._infer_columns()
   1821
   1822         # Now self.columns has the set of columns that we will process.

/opt/conda/lib/python3.6/site-packages/pandas/io/parsers.py in _infer_columns(self)
   2181                 columns = [names]
   2182             else:
-> 2183                 columns = self._handle_usecols(columns, columns[0])
   2184         else:
   2185             try:

/opt/conda/lib/python3.6/site-packages/pandas/io/parsers.py in _handle_usecols(self, columns, usecols_key)
   2234                 for u in self.usecols:
   2235                     if isinstance(u, string_types):
-> 2236                         col_indices.append(usecols_key.index(u))
   2237                     else:
   2238                         col_indices.append(u)

ValueError: 'A' is not in list

Could someone please help me fix this? Thank you very much
Comment: Does this answer your question? [how to read certain columns from Excel using Pandas - Python](https://stackoverflow.com/questions/33655127/how-to-read-certain-columns-from-excel-using-pandas-python)
Comment: Unfortunately not...
Answer: #Would this work?
df = pd.read_excel("Energy Indicators.xls")
df=df[list('CDEFG')]
df=df[19:245]

It may make a difference if your loading a very big file. Else this should be just fine
Comment: It's an interesting approach, but it didn't work. The error was: KeyError: "['C' 'D' 'E' 'F' 'G'] not in index"
Answer: By default read_excel use the first line of the Excel sheet to set the column names. Maybe by adding header=None ?
df = pd.read_excel("Energy Indicators.xls", header=None, skiprows=18, usecols="C:G")

Comment: Unfortunately it didn't work. The error was: ValueError: ':' is not in list
Comment: And by using column numbers: usecols=range(2,6)?


Why multiplying the standard form by an integrating factor

Question: I use the algorithm to solve a First Order Linear Differential equation for the following problem
$$2(y-4x^2)dx + xdy=0$$
It is a trivial case and we can easily transform it into the standard form:
$$\frac{dy}{dx} + \frac{2}{x}y=8x \rightarrow standard$$
From here we obtain the integrating factor $x^2$ by aplying the general procedure. We know that if we multiply the standard form by the integrating factor, we will obtain an exact equation. And it is really the case:
$$x^2 dy+(2xy-8x^3)dx = 0$$
is exact. But if we try to multiply the initial equation by $x^2$, we won't get an exact one:
$$(2x^2y-8x^4)dx + x^3dy=0$$
Obviously yields different second order partial derivatives of a possible solution. My question is: Why does it happen?
Answer: $2(y-4x^2)dx + xdy=0$ has as integrating factor $x$
Consider $2(xy-4x^3)dx + x^2dy=0$, put it in standard form and you get $\dfrac{dy}{dx} + \dfrac{2}{x}y=8x$, that you know it has as integrating factor $x^2$, that is exactly the factor you have simplified.
As the equation is equaled to zero, you can always multiply or divide by almost everything you can desire, even by the previously calculated integrating factor! The technique is based exactly in this fact.
Anyway, get the solution for $\dfrac{dy}{dx} + \dfrac{2}{x}y=8x$ and check it in $2(y-4x^2)dx + xdy=0$ and even in $(2x^2y-8x^4)dx + x^3dy=0$ , you'll see that satisfies both.


How to find out ip address of new virtual machine using libvirt 0.10.0+ (routed network)

Question: My goal is to find out ip address of new virtual machine by using libvirt api only (>=0.10). Currently I am using libvirt's net-update command: before start a new machine I set static dhcp entry for it and vm booting with known address.
It works almost fine even with old libvirt versions, but has a one bug. When I "force off" machine, it doesn't send "release" query to dhcp server (libvirt/dnsmasq) and this ip remains in leases file. If I create a new machine with same ip address before dhcp lease timed out, it won't get ip address from static entry, because dhcp server considers this ip is already used (based on information in lease file).
Are there any more robust solutions to get machine ip address or set it before start without shell access to target server or static network configuration inside virtual machine?
Comment: Seems I found a solution for cleanup stale leases -- use dhcp_release utility from dnsmasq-utils package in libvirt's machine shutdown hook.It doesn't require ssh access to server from script, but can be installed during initial hypervisor configuration. https://libvirt.org/hooks.html#qemu
Answer: In the libvirt >= 1.2.14, it is possible to query libvirt to ask for the IP addresses that have been assigned to a guest NIC, avoiding the need to setup static IP addresses. e.g.
<code># virsh domifaddr f25kubdev
 Name       MAC address          Protocol     Address
-------------------------------------------------------------------------------
 vnet1      52:54:00:b4:fc:f2    ipv4         192.168.122.13/24
</code>
I'm not sure if that's any use to you though, since you mention libvirt 0.10.0
If you have >= 1.2.10 there's a less direct way to get the info by querying the DHCP lease database
<code># virsh net-dhcp-leases default
 Expiry Time          MAC address        Protocol  IP address                Hostname        Client ID or DUID
-------------------------------------------------------------------------------------------------------------------
 2017-01-19 12:01:01  52:54:00:b4:fc:f2  ipv4      192.168.122.13/24         f25kubdev       ff:00:b4:fc:f2:00:04:52:fb:4b:29:01:5e:44:c8:b6:57:85:dd:f2:7a:98:73
</code>
you then have to manually map the MAC address to the domain you're interested in - the 'domifaddr' command just does that mapping for you.
Prior to 1.2.10, there's no way to get this info via the libvirt API at all - you'd have to poke around in the dnsmasq leases file directly.
Comment: Yeah thanks! But libvirt shipped with ubuntu 14.04 and centos 6 doesn't support it :(


Pegar nome da coluna com chave estrangeira

Question: Tenho uma tabela produtos que faz referência ao id da tabela categorias, mas não quero pegar o número id da tabela estrangeira, e sim o nome dessa referência.
Meu controlador está assim:
public function index()
{
    $prod = Produto::all();
    return view('produtos', compact('prod'));
}

Dai na minha view eu chamo o nome da categoria_id mas só recebo o número do ID.
@foreach ($prod as $p)

    {{$p->id}}
    {{$p->nome}}
    {{$p->estoque}}
    {{$p->preco}}
    {{$p->categoria_id}}

@endforeach

Como faço para retornar o nome da categoria que faz referência ao id da tabela produtos?
Comment: Poderia [edit] a pergunta colocando a classe `Produto`, principalmente mostrando como implementou a relação entre os modelos?
Answer: O que falta realmente colocar na sua pergunta são as relações de suas duas tabelas, e também os Models que são configuradas para essas tabelas, onde um Produto tem Categoria e uma Categoria está em vários Produto, ou seja, um relacionamento 1:N. Um exemplo fictio sobre uma tabela de produtos e uma tabela de categorias onde as duas se relacionam, exemplo:

Classes:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Produto extends Model
{
    protected $table = 'produtos';
    protected $fillable = ['categoria_id','descricao'];

    public function categoria()
    {
        return $this->belongsTo(App\Categoria::class,'categoria_id','id');
    }
}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Categoria extends Model
{
    protected $table = 'categorias';
    protected $fillable = ['nome'];

    public function produtos()
    {
        return $this->hasMany(App\Produto::class,'categoria_id','id');
    }
}

Como utilizar:
public function index()
{
    $prod = Produto::with('categoria')->get();
    return view('produtos', compact('prod'));
}

@foreach ($prod as $p)

    {{$p->id}}
    {{$p->descricao}}
    {{$p->categoria->nome}}

@endforeach

Nesse exemplo tem vários pontos importantes:

Criar relação das entidades sendo explicito as chaves (se seguir a nomenclaturas de nomes não precisa colocar, mas, é um boa conduta colocar principalmente para manutenção)
Carregar a relação adianta (comando with('categoria')), porque, existe a otimização de somente 2 consultas SQL diferente da outra que a cada interação e feita uma nova consulta SQL causando lentidão e um erro muito comum no desenvolvimento com Laravel.

Ref.

Como usar o relacionamento hasmany no laravel 5.2?
Salvar relacionamento 1:1 no Laravel 5.3
Como usar o relacionamento hasmany no laravel 5.2?
Laravel / Eloquent - Consulta em mais de uma tabela


Let $N(t)$ is a poisson process with rate $\lambda$, $T^* \sim \operatorname{Exp}(\lambda^*)$, find the expectation of $N(\min(t, T^*))$

Question: Currently, my approach is to split $N(\min(t, T^*))$ like the following by the law of total expectation.
\begin{align*}
&E(N(\min(t,T^*))) = E(N(t \wedge T^*)) \\
    = {}&E(N(t\wedge T^*) \mid t \le T^*) \cdot P(t \le T^*) + E(N(t\wedge T^*) \mid t > T^*) \cdot P(t > T^*).
\end{align*}
To make it less confusing and more concrete, one could think of the target expectation as $E(N(\min(3, T^*)))$ when $t=3$. Later, generalize the solution to suit any given $t$.
The first and second parts become
\begin{align*}
&E(N(t\wedge T^*)\mid t \le T^* )\\
={}& \sum_{x = 0}^\infty x P(N(t\wedge T^*) = x\mid t \le T^*)\\
={}& \sum_{x = 0}^\infty x \frac{P(N(t\wedge T^*) = x, t \le T^*)}{P(t \le T^*)}\\
={}& \sum_{x = 0}^\infty x \frac{P(N(t) = x, t \le T^*)}{P(t \le T^*)}\\
={}& \sum_{x = 0}^\infty x \frac{P(N(t) = x) P(t \le T^*)}{P(t \le T^*)}\\
={}& \sum_{x = 0}^\infty x P(N(t) = x)\\
={}& E(N(t)) = \lambda t;
\end{align*}
\begin{align*}
&E(N(t\wedge T^*) \mid t > T^*)\\
={}& \sum_{x = 0}^\infty x P(N(t\wedge T^*) = x\mid t > T^*) \hspace{1cm}\color{red}{T^* < t}\\
={}& \sum_{x = 0}^\infty x \frac{P(N(t\wedge T^*) = x \mid t > T^*)}{P(t > T^*)} \\
={}& \sum_{x = 0}^\infty x \frac{P(N(t\wedge T^*) = x ,t > T^*)}{P(t > T^*)}\\
={}& \sum_{x = 0}^\infty x \frac{P(N(T^*) = x ,T^* < t)}{P(T^* < t)}
\end{align*}
by the conditional expectation.
So, the problem is $N(T^*)$ and $T^*$  are less likely to be independent; how to find the probability $P(N(T^*) = x ,T^* < t)$?
Comment: I think you're doing a little more work than you need to; you can work directly with the expectations, instead of having to go back to the summations.  For example, if $T^*>t$, then $\mathbb{E}N(\cdot) =\mathbb{E}N(t)= \lambda t$, and we don't need to write stuff out.  Similarly, $\mathbb{E}N(T^*)$ is *linear* in $T^*$, which makes calculations for the $T^* < t$ case straightforward.
Comment: Yes; it's an application of the law of total expectation again.
Comment: Please consider adding the [tag:self-study] tag.
Comment: @jbowman. Thanks for your comments. And yes, the first term essentially ends up with $\lambda t$. I did a simulation, which is consistent with $\lambda t$. Do you mean the second term would look like $\lambda T^*$, since $T^*$ is a variable ($0 < T^* < t$), then do the integration over it? That is an interesting approach; I will try that and let you know.
Comment: @jbowman, I just tried the simulation as suggested. Unfortunately, the second term still has some underestimation at the beginning of $t$, then converges at the end. I believe the problem is still $E(N(T^*))$ is *linear* relying on $N(T^*)$ and $T^*$ are independent, which is less likely.
Comment: I am unable to decipher the notation.  Evidently $N(T)$ is a Poisson variable, so presumably it is the count of events during any interval of measure $T.$ However, it also looks like you are *conditioning* on $T,$ implying $T$ is a random variable -- but what kind of object is it really?  And if it's a random variable, what is its distribution?
Comment: @whuber, thanks for your comments. $N(t)$ is a Poisson variable, it is also equivalent to $N(T=t)$, $t$ is a realization of $T$. For any $t > 0$, $N(t)$ is a Poisson variable. Conventionally, it is denoted as {N(t), t>0}, aka, Poisson point process. In my particular problem setting, $Y = \min(T, T^*)$, I put it as $T$ is to indicate the fact $T$ could be any time point. To make it less confusing, I just edited the question accordingly.
Comment: That helps, thank you.
Answer: We can use the law of total expectations to simplify the problem as follows:
$$\mathbb{E} N(\min(t,T^*)) = \lambda \mathbb{E}\min(t,T^*)$$
Finding $\mathbb{E} \min(t,T^*)$ is straightforward:
$$\mathbb{E} \min(t,T^*) = \mathbb{E} (T^*|T^*\leq t)P(T^*\leq t) + tP(T^*> t) \tag 1$$
Using the memoryless property of the exponential distribution allows us to simplify further, as:
$$\mathbb{E} T^* = \mathbb{E}(T^*|T^*\leq t)P(T^*\leq t) + \mathbb{E}(T^*|T^*> t)P(T^*> t)$$
and $\mathbb{E} (T^*|T^*> t) = \lambda^*+t$ while $\mathbb{E} T^* = \lambda^*$.  Therefore, rearranging terms,
$$\mathbb{E}(T^*|T^*\leq t)P(T^*\leq t) = \lambda^* - (\lambda^*+t)P(T^*>t)$$
Substituting into the right hand side of eq. (1) gives us:
$$\mathbb{E}\min(t,T^*) = \lambda^* - (\lambda^*+t)P(T^*>t) + tP(T^*> t) = \lambda^*(1-e^{-t/\lambda^* })$$
One more substitution gets us to:
$$\mathbb{E} N (\min(t,T^*)) = \lambda \lambda^*(1-e^{-t/\lambda^* })$$
Now for a check via simulation.  We will set $\lambda = 1.138$, $\lambda^* = 0.842$, and $t = 1.234$:
<code>lambda <- 1.138
lambdastar <- 0.842
tc <- 1.234

tstar <- rexp(100000, 1/lambdastar)
x <- rpois(100000, lambda*pmin(tstar, tc))

lambda*lambdastar*(1-exp(-tc/lambdastar))
[1] 0.7369016

mean(x)
[1] 0.73378
sd(x)/sqrt(length(x))
[1] 0.003133204
</code>
which seems to match as well as we would hope.
Comment: Thanks for the detailed explaination, I am running an simulation on a continuous scale of $X$ and let you know how it goes.
Comment: I mean the continuous scale of $tc$ in your simulation. The result is consistent for any $tc$. Thanks so much for your generous help.


Run-loops and threads in Apple's CocoaXMLParser example

Question: In the CocoaXMLParser class of Apple's CocoaXMLParser example, the following code appears:
<code> rssConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[self performSelectorOnMainThread:@selector(downloadStarted) withObject:nil waitUntilDone:NO];
if (rssConnection != nil) {
    do {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    } while (!done);
}
</code>
According to the NSRunLoop documentation "In general, your application does not need to either create or explicitly manage NSRunLoop objects. Each NSThread object, including the application's main thread, has an NSRunLoop object automatically created for it as needed." In the context of this, why is the run-loop explicitly managed in this example? Would it not be created and destroyed automatically by the thread generated by the NSURLConnection request?
Answer: In that code, the run loop is basically just being told to run forever, so that that thread can continue to process incoming background data from the NSURLConnection.  Even though a run-loop is created for you, by default the thread would terminate when that method ended.
In general when doing something like that it's easier to put everything in an NSOperation which then goes in an NSOperationQueue (although if you are implementing NSUrlConnection callbacks you have to provide a few extra methods in the NSOperation class).
Comment: Thanks, so are you saying that the thread (in this case for a NSURLConnection) could terminate before the connectionDidFinishLoading method is called?
Comment: Exactly, in fact I have run into this exact problem before in real life -you open a valid connection, and then connectionDidFinishLoading is never called... nor are any of the other methods like didReceiveData.  In that case the background thread you were trying to load on terminated before the URL connection could even do anything.


PDF manipulation - images are distorted after few consecutive operations on PDF file

Question: I've run into this weird issue with PDF file handling. Not sure if SO is the right place to ask this, but I couldn't find any specific sites for this. I hope that someone can shed some light on the issue.
This happens with the following specific process, if some of steps are omitted - the issue is not observed.
I have a PHP application that serves PDF files to users. These files are created by authors in MS Word 2007, then printed to protected PDF (using pdf995, most likely, I can confirm if needed).
I'll call this initial PDF file as 'source' hereinafter.
Upon request, the source file is processed in PHP the following way:
we decrypt it using qpdf:
<code>qpdf --decrypt "source.pdf" "tmp_output.pdf"
</code>
Then we add security label / wartermark to it, encrypt and output to browser using mPDF 6.0:
<code>$mpdf = new mPDF();
$mpdf->SetImportUse();

$pagecount = $mpdf->SetSourceFile($fpath);
if ($pagecount) {
    for ($i=1;$i<=$pagecount;$i++){
    $tplId = $mpdf->ImportPage($i);
    $mpdf->UseTemplate($tplId);

    $html = '[security label / watermark contents...]';

    $mpdf->WriteHTML($html);
   }
}

$mpdf->SetProtection(array('copy','print'), '', 'password',128);

$mpdf->Output('final_output.pdf','I');
</code>
With the exact steps described above, images in the output that were pasted in the Word doc appear as follows:

In the source PDF, tmp_output (qpdf decrypted file) the pasted images look correct:

The distortion doesn't take place if any of the following occurs:

Word doc printed to PDF without protection
mPDF output is not protected.

As you can see there too many factors, so I don't know where to look for a bug.
Each component works correctly on it's own and I cannot find any info on the issue. Any insights are greatly appreciated.
EDIT 1
After some more testing, it appears that this only happens to screenshots taken from web browser, Windows explorer, MS Word. Cannot reproduce this with screenshots from Gimp.
It appears that something along the way attempts to convert white to alpha and fails.
Comment: Can you please share all PDFs which are used/produced in the described workflow?
Comment: @JanSlabon I don't have access to any file sharing services here, and it is not possible to attach files to questions. What to do?
Comment: @JanSlabon OK, here it is [download](http://s000.tinyupload.com/?file_id=07245342052483679163) password:pdf
Comment: It looks like mPDF has a problem with octal notation in PDF strings. They will not get interpreted but in a string value of "\000" the string \000 will be encrypted as a whole instead of a single byte with the value 0x00. Feel free to report this issue [here](https://github.com/mpdf/mpdf). They are simply missing to unescape the string as e.g. done [here](https://github.com/Setasign/FPDI/blob/master/fpdi_bridge.php#L85).
Comment: I just made a [pull request](https://github.com/mpdf/mpdf/pull/441) to Mpdf which should solve this issue.
Comment: @JanSlabon Wow, some deep knowledge there. Thanks a ton! Is my understanding correct - string encoding varies among different PDF producers and mPDF fails to handle all cases properly? hence the issue is only observed in particular scenario.
Comment: @JanSlabon kindly convert your comment to an answer so I can accept it.
Answer: The current version (6.1) of Mpdf has a bug which does not handle escaped PDF strings (imported via FPDI) correct if they should be encrypted.
A pull request, which fixes this issue is available here.


Let $x_1,x_2,\cdots$ be a sequence of real numbers such that $|x_n| \leq 1/2^n$, and set $y_n = x_1 + \cdots + x_n$.

Question: Show that the sequence $y_1,y_2,\cdots$ converges. My question is regarding the end of my proof: essentially, am I allowed to say "keep subtracting $1/2^i$ starting from i = 1 until we subtract at least $(n-1)/n$ from the infinite geometric series"? Or do I literally need to work with the formula that involves a finite number of partial sums in a geometric series. That seems very tedious. If this doesn't make sense, please read my proof below.
Proof: We want to show that $\{ y_i \}$ converges to a real number, and that's done iff it is a Cauchy sequence. Grab an arbitrary $1/n$ and suppose we have $y_b, y_a$ such that $b > a$. Then $|y_b-y_a| = |\sum_{i=1}^{b}x_i - \sum_{i=1}^{a}x_i| = |\sum_{i=a+1}^{b}x_i| \leq \sum_{i=a+1}^{b}|x_i| \leq \sum_{i=a+1}^{b}1/2^i$. To show $|y_b-y_a| \leq 1/n$, we need to pick an $m$ such that for $a,b \geq m, \sum_{i=a+1}^{b}1/2^i \leq 1/n$. Well, we can see that $\sum_{i=a+1}^{b}1/2^i \leq \sum_{i=a+1}^{\infty}1/2^i$, and so if we prove $\sum_{i=a+1}^{\infty}1/2^i \leq 1/n$, we are good. And so we basically need to find an $a$ that satisfies this, and let $m = a$. Well, we know that $1 = \sum_{i=1}^{\infty}1/2^i$, and so we subtract from $i = 1$ onwards until we subtract at least $(n-1)/n$. We know we can do this because $(n-1)/n$ is a finite number. Then, we let $a$ be the number of terms we subtracted plus 1, and then let $m=a$.
Comment: Instead of "grab an arbitrary $1/n$", it would be more appropriate to "grab an arbitrary $\epsilon > 0$". Otherwise, the proof looks fine.
Comment: Comparison test.
Answer: Yes, it's valid to say that since
$$1 = \sum_{i=1}^\infty \frac{1}{2^i},$$
and $0 < \frac{n-1}{n} < 1$, there is a natural number $m$ such that
$$ \sum_{i=1}^m \frac{1}{2^i} > \frac{n-1}{n} $$
and therefore
$$ \sum_{i=m+1}^\infty \frac{1}{2^i} < \frac{1}{n} $$
But an easier way to do this is with a change of summation variable, $j=i-a$ and $i=j+a$:
$$ \sum_{i=a+1}^\infty \frac{1}{2^i} = \sum_{j=1}^\infty \frac{1}{2^{a+j}} = \frac{1}{2^a} \sum_{j=1}^\infty \frac{1}{2^j} = \frac{1}{2^a} $$
Then just choose $a$ big enough that $\frac{1}{2^a} < \frac{1}{n}$.
Comment: Perfect. Especially the second way, since my phrasing sounded not "mathematical enough."


Understanding time complexity of fixed size k-clique

Question: Determine the time complexity of the problem (e.g. lower
or upper bound)
Input: Graph
Output: "yes" if the graph contains a Clique of size 100.
Output "no" otherwise.
Determine a lower time complexity bound on this problem
I think the time complexity is O(1) constant because the clique has fixed size
Also if anyone could help direct me to a good resource on determining time complexity for decision problems it would be much appreciated
Comment: But the graph might be big.
Comment: would it then be proportional to the size of the graph? would i denote this O(n) (if the input of graph changes constantly?) or if the graph is always say of size 10000000 would it still be constant size O(1)?
Comment: I'm no expert. Personally I felt that to discuss the running time of an algorithm one usually parameterize the problem's input.  In this case, the problem could be to test if there is a clique of size larger than K in a graph with N nodes and M edges.
Comment: @Als the naive algorithm's---check all 100-subsets of vertices---time would be proportional to {n choose 100} * {100 choose 2}, which is about O(n^100). Not exactly constant. :-) I have no idea about nontrivial lowers bounds for the problem.
Answer: There are a few issues in your question that need to be addressed. My answer here is necessarily brief and informal. To really understand and appreciate computational complexity, you'll have to study the material. Papadimitriou 's book on Computational Complexity is the standard book: Computational Complexity: A Modern Approach by Sanjeev Arora might be a lighter read for getting started.
Computitional complexity is usually measured with respect to the size of the input. For the K-Clique problem ("Does the input graph contain a clique of size K?") in the worst case you'll have to look at the whole graph (or at least most of the graph) to determine that there is no such clique. This means that the runtime of your algorithm will probably depend on the size of the graph (usually measured as the number of nodes n in your graph). Informally, this implies that the computational complexity cannot be constant, since it dependes on the size of the input.
A lower complexity bound is an asymptotic lower bound, i.e., any algorithm solving the problem has to have at least that computational complexity. So O(1) is actually a formally correct answer, though it doesn't provide much value. A tight lower bound is the highest asymptotic bound that is still a lower bound.
The K-clique desicion problem is NP-hard and thus it is very unlikely that a polynomial-time algorithm for the problem exists. You can find more about good upper-bounds in this post on cs.stackexchange.
Answer: For a constant k the complexity is actually polynomial with O(n^k).
Source: https://people.csail.mit.edu/virgi/combclique-ipl-g.pdf
Comment: this one should be in the comment section


Enable allow_url_fopen on cpanel

Question: I have cPanel and I want enable allow_url_fopen on my host.
When I use this code
if (ini_get("allow_url_fopen") ==1) {
 echo "allow_url_fopen is ON";
 } else {
  echo "allow_url_fopen is OFF";
}

Show me

allow_url_fopen is OFF
Answer: If your PHP version is under 5.4 you can use the following line of code to set allow_url_fopen to true.
ini_set('allow_url_fopen', '1');

Answer: You should not enable fopen manually but instead use these commands on the terminal to install a package
Find the path of composer by running this command first:
$ which composer
/usr/local/bin/composer

Install Package after that by using this path:
$ php -d allow_url_fopen=on /usr/local/bin/composer install package_name

OR
php -d allow_url_fopen=on `which composer` install package_name

Comment: ``php -d allow_url_fopen=on `which composer` install package_name`` also will work
Answer: How to enable or disable allow_url_fopen in cPanel
There are certain scenarios when you may be asked to make changes to your PHP configuration. Specifically, you may be directed to edit a file on your server called php.ini, and to enable or disable allow_url_fopen.
While do not allow direct changes to PHP.ini on our servers. However, PHP configuration changes can be made from cPanel by following these steps:

Log into cPanel.

Look for the SOFTWARE section and click on Select PHP version: cPanel > Software > Select PHP Version

In the new window click on the Switch To PHP Options link : Select PHP Version > Switch to PHP Options.

Here you can locate the allow_url_fopen and tick on the box next to it to enable it or un-tick the box to disable it.

Once you'll do any change, please do a left-hand side click anywhere outside the dropdown or text input box. If the change was successful, you will see a green box with a message which will confirm that the change has been applied.

That's all! Now you know how to enable or disable allow_url_fopen in cPanel.

Enable allow_url_fopen on cpanel


Display average from a column?

Question: EDITED: This has been altered to include the code suggested by Dooshta.
I need to fill a computed field with the average value of all entries in a certain field, and only from nodes that have a specific node reference field.
What I have right now in my Computed Field is:
$nids = db_query('
  SELECT entity_id FROM {field_revision_field_venue_reference_review}
  WHERE field_venue_reference_review_target_id = :nid',
  array(':nid' => $entity->nid)
)->fetchCol();

$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
   WHERE entity_id IN (:nids)',
   array(':nids' => $nids)
)->fetchField();

This is working, and displays the correct average from the correct nodes. However, I get a PODexception error on some pages that do not include the above code. This is confusing to me, because it seems that if there is bad syntax, then I should get the error on the page using the code as well as pages not using the code, right? Either that or it just shouldn't work.

As requested by Booshta, here are screenshots of the tables I'm querying.
The first is the table containing the entity reference field in the $nids part of the query

The second is the table containg the values being averaged in the $entity_field part of the query
Comment: It looks like you might be using Drupal 6 code on a Drupal 7 site...can you confirm which version you're using?
Comment: Yes, I am using D7. I believe that the code on the page I linked to is for D6, but I thought that I had changed the required portions. If the displayed code is for D6, then that would explain my issues.
Answer: I'm not familiar with the computed field module and not sure I completely understand the relationships between your nodes and fields, but here's about how you should be able to get things working.
The first query seems like it would be alright if you'd remove that extra closing bracket and used fetchField() to retrieve the value:
$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
')->fetchField();

The second one needs some more work. I'm assuming that you have review nodes with the ratings and every review node is linked to a business node with a reference field of some sort.
First I would get the nid-s of those review nodes that are linked to the current business node as an array (using fetchCol()) with something like this:
$nids = db_query('
  SELECT entity_id FROM {field_data_field_business_reference}
  WHERE field_business_reference = :nid AND entity_type = :type AND bundle = :bundle',
  array(':nid' => $entity->nid, ':type' => 'node', ':bundle' => 'review')
)->fetchCol();

Then get the average:
$entity_field[0]['value'] = db_query('
   SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review}
   WHERE entity_id IN (:nids) AND entity_type = :type AND bundle = :bundle',
   array(':nids' => $nids, ':type' => 'node', ':bundle' => 'review')
)->fetchField();

UPDATE:
To avoid the error you're getting you can try wrapping the code inside some if statements to make sure it won't be executed when necessary criteria is not met:
$node = menu_get_object();
if (isset($node->type) && $node->type == 'venue') {
  // put the query that retrieves the nids here.
  if (is_array($nids) && !empty($nids)) {
    // put the query that calculates the average here.
  }
}

If that's too restrictive you might get away with just this much:
  // put the query that retrieves the nids here.
  if (is_array($nids) && !empty($nids)) {
    // put the query that calculates the average here.
  }

Comment: My node/field relationships:
Node type - review: used as a form for users to rate the venues, linked to venues with entity reference field.
Node type - venue : displays venue information and average of ratings results using computed fields.

Thanks for the suggestions. Looks like not having the fetchField is what was giving me problems. Without it, I was getting PODexception error. I'll take a look at the second half later when I get a chance. If it works, which I'm sure it will, this is going to be selected as the answer.
Comment: I got your code to work when removing references to entity_type, type, and bundle. But I then get this error other pages:  "PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1: SELECT AVG(field_payment_review_value) FROM {field_data_field_payment_review} WHERE entity_id IN (); Array ( ) in eval() (line 11 of /Applications/MAMP/htdocs/drupal-7.12/sites/all/modules/computed_field/computed_field.module(466) : eval()'d code).
Comment: It looks like you may have broken the query syntax. Make sure all the commas, quotes, brackets are still there and in correct locations. Also check that the table and field names used in the queries match with what you got in the database. If you don't get them working you could maybe update your question with images of the relevant database tables where necessary field names are shown and the queries you've put together to retrieve the data to make it easier to track down the problem(s).
Comment: I've edited/added my queries and screenshots of the PODexception and the relevant database tables.
Comment: I misunderstood the problem (sorry about that), but your update helped to clear things up. See if the added bits in my answer help you to resolve the issue.
Comment: No problem about the misunderstanding. I thought it might be confusing posting like that, but I didn't even think of just including screenshots. The first bit you included displayed a blank page, but the second one worked perfectly. The average displays just as it should, and I don't see any errors yet. Thank you so much! My site would have been destined for failure without some help.
Comment: Glad it worked out and hopefully no other issues pop up :)

Display average from a column?


Jenkins archiveArtifacts generates 'not found' error

Question: I have very simple pipeline, like this:
pipeline {
    agent any
    stages {
        stage('Build Automation') {
            steps {
                sh '''
                echo "BUILD NUMBER: ${BUILD_NUMBER}"
                cd myproject
                mvn clean package
                '''
            }
        }
        stage('Prepare artifacts') {
            steps {
                sh '''
                cd myproject/target
                ls
                archiveArtifacts 'myproject/target/*'
                '''
            }
        }
    }
}

The Build Automation step finishes successfully but I'm always getting error form the `archiveArtifacts':
[myproject-automation_master-FALMJHZX7ZH5GMLQBBOYFJQRFPX4WIHQXBH2YXEQDL4TDAMTRYTQ] Running shell script
+ cd myproject/target
+ ls
classes
generated-sources
generated-test-sources
myapp
myapp.war
maven-archiver
maven-status
test-classes
+ archiveArtifacts myproject/target/*
/var/jenkins_home/workspace/myproject-automation_master-FALMJHZX7ZH5GMLQBBOYFJQRFPX4WIHQXBH2YXEQDL4TDAMTRYTQ@tmp/durable-6a43d2f0/script.sh: 5: /var/jenkins_home/workspacemyproject-automation_master-FALMJHZX7ZH5GMLQBBOYFJQRFPX4WIHQXBH2YXEQDL4TDAMTRYTQ@tmp/durable-6a43d2f0/script.sh: archiveArtifacts: not found

I've added ls to see if there are any files in the target folder, so they are there, but the archiveArtifacts always returns not found. I've tried various patterns like *.war, **/target/*.war , but no luck.
What might be wrong?
Comment: Instead of using `cd "myproject/target"`, you can consider  `dir('myproject/target')` if you want archiveArtifacts to run in that directory.

For eg., dir('new_directory') {steps}
Answer: You need to remove the archiveArtifacts step from the sh step. The way it is right now it is being run as part of the shell script and interpreted as a command.
        steps {
            sh '''
                cd myproject/target
                ls
            '''
            archiveArtifacts 'myproject/target/*'
        }

The above should work.
Comment: Thanks a lot! It worked. My bad, this happens when you're doing something for the 1st time, not understanding yet all the details.