A question on Compression spectrum

Question: How to show that if $\lambda$ is in compression (or residual) spectrum of an operator $A$, then $\bar{\lambda}$ is an eigenvalue of $A^*$? Thanks.
Answer: If $A-\lambda I$ is injective, $\lambda \in \rho(A)$ iff $A$ is surjective. There are two ways for $A$ to not be surjective in this case: either the range is dense but not closed (continuous spectrum) or the range is not dense. The range is not dense iff
$$
                \{ 0 \} \ne \mathcal{R}(A-\lambda I)^{\perp}=\mathcal{N}(A^{\star}-\overline{\lambda}I).
$$

A question on Compression spectrum


Creating nested bullet list in PowerPoint 2007

Question: We're trying to create a PowerPoint slide programmaticaly. We can obtain bullets on a single level, but playing with tabs and line returns doesn't work for nested enumerations.
For now we get:

text 1
    subtext1
    subtext2
text 2

And what we want is :

text 1

subtext1
subtext2

text 2

Is there a way to control these using C# or VBA?
Answer: First, get a reference to the Paragraphs of the TextRange2, as each bulleted item is a paragraph (really a TextRange2).
Dim pres As Presentation
Set pres = Application.ActivePresentation

Dim slide As slide
Set slide = pres.Slides(2)

Dim shapes As shapes
Set shapes = slide.shapes

Dim textShape As Shape
Set textShape = shapes(2)

Dim textFrame As TextFrame2
Set textFrame = textShape.TextFrame2

Dim textRng As TextRange2
Set textRng = textFrame.textRange

Dim p As TextRange2
Set p = textRng.Paragraphs

SetIndent 1, p.Item(1)
SetIndent 2, p.Item(2)
SetIndent 2, p.Item(3)
SetIndent 1, p.Item(4)

The last four lines call a function that encapsulates the logic of setting the indent "level," which affects the style of bullets and text, and the actual indent of the bullets and text:
Private Function SetIndent(ByVal level As Integer, ByRef p As TextRange2)

p.ParagraphFormat.IndentLevel = level
p.ParagraphFormat.FirstLineIndent = 40
p.ParagraphFormat.LeftIndent = level * 40

End Function

You could certainly refactor this to meet your needs -- like passing the indent factor (I hardcoded it as 40, but your mileage may vary).


C# MVC 4 - Action dá Error 404

Question: Sou iniciante em C# MVC 4 e montei um site para fins de aprendizado.
Na página de contato do site há um formulário que envia emails automaticamente. Quando rodo ele localmente direto do Visual Studio 2013 (IIS Express) ele envia os emails tranquilamente e carrega a view de "sucesso".
Tudo certo até eu subir para o servidor da Locaweb. Agora ele dá um erro 404:

Server Error in '/usuario/site' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its
  dependencies) could have been removed, had its name changed, or is
  temporarily unavailable.  Please review the following URL and make
  sure that it is spelled correctly.
Requested URL: /usuario/site/pt-br/Contact/Sent/
Version Information: Microsoft .NET Framework Version:4.0.30319;
  ASP.NET Version:4.0.30319.34280

O grande problema é que as views estão todas lá. Revirei a internet e me falaram que eu poderia chamar a view com o caminho direto, mas também não funcionou :(
Neste caso eu não entendi se o que ele não está achando é a Action ou a View do return View().
Segue a action que está no meu controller da página de contato:
[HttpPost]
        public ActionResult Sent(Formulario formulario)
        {
            if (formulario.Validar())
            {
                try
                {
                    var mensagem = formulario.Mensagem.Replace(Environment.NewLine, "
");
                    var smtpUri = ConfigurationManager.AppSettings["smtpUri"];
                    var smtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["smtpPort"]);
                    var emailTo = ConfigurationManager.AppSettings["emailTo"];

                    var client = new SmtpClient(smtpUri, smtpPort)
                    {
                        EnableSsl = false,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials = new NetworkCredential("meuEmail", "minhaSenha")
                    };
                    var mail = new MailMessage("meuEmail, emailTo);
                    mail.IsBodyHtml = true;
                    mail.Subject = String.Format("Contato via site - Página: {0}", formulario.Pagina);
                    mail.Body = mensagem;
                    client.Send(mail);

                    return View("~/Views/Contact/Sent.cshtml");
                }
                catch (Exception e)
                {
                    return View("~/Views/Contact/Error.cshtml");
                }
            }

            return Json(new {success = false});
        }

Meu RouteConfig.cs:
 public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("i18n", "{language}/{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional, language = "pt-br" },
                new { language = "en|pt|es|pt-br|en-us" }
                );

            routes.MapRoute("Default", "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
        }
    }

Na verdade o "/usuario/site" é porque o site está no ar dentro de uma subpasta pois não quero que fique no ar com erros ainda. Ele está funcionando tranquilamente em todas páginas, menos quando tento enviar um email pela página de contato.
Alguém tem alguma ideia do que pode ser?! Obrigado!!
Comment: Atualizei a pergunta com as configurações de rota, Paulo. Obrigado!
Comment: Poderia colocar as rotas que está usando aqui?
Comment: Resolvi meu problema adicionando uma barra ("/") ao final da URL de chamada!
Answer: Pelo que vi, esta view será renderizada apenas se o verbo utilizado for o POST. tente adicionar o atributo [HttpGet] e publique novamente para ver se funciona.
Uma outra coisa me chamou a atenção na sua url: /usuario/site/pt-br/Contact/Sent/
Este /pt-br está correto?
Geralmente utilizamos algo mais simplificado como "http://www.site.com.br/NomeDoController/NomeDaAction"
no seu caso, acho que seria /Contact (Controller)
e a Action /Sent
Comment: Obrigado pela resposta Thiago! Na verdade eu quero usar POST mesmo... E como localmente está funcinonando não vejo porque trocar para GET só por esse motivo. De qualquer jeito, atualizei a pergunta com explicações sobre a URL, se puder conferir ficarei muito grato! abs
Comment: Faça o seguinte, crie uma nova Action neste mesmo controller que retorne um Content: public ActionResult Teste()
        { return Content("TESTE");}
Comment: e tente acessar a url: www.seusite.com.br/usuario/site/pt-br/Contact/Teste
Comment: www.seusite.com.br/usuario/site/pt-br/Contact/Teste ou www.seusite.com.br/site/pt-br/Contact/Teste ou www.seusite.com.br/site/pt-br/Contact/Teste uma destas deve retornar o conteúdo www.seusite.com.br/pt-br/Contact/Teste
Comment: Consegui acessar via http://meusite.com.br/usuario/site/Contact/Teste/
coloquei um método de  GET também que só renderiza a view, e no metodo de POST coloquei um RedirectToAction chamando o método de GET. Agora a view está sendo mostrada, mas o email não é enviado :(
Comment: já tentou trocar de smtp? Tenta com sendgrid....deve funcionar

C# MVC 4 - Action dá Error 404


Prove: For all integers $a$, $b$, and $c$, if $a \mid b$ and $b \mid c$ then $a \mid (3b-2c)$

Question: I keep getting this answer and I am not sure if it is correct using these steps.
By definition of divides, $b = ar$ and $c=bs$ for some integers $r$ and $s$.

By definition of divides, $b = ar$ and $c=bs$ for some integers $r$ and $s$.
Then, $(3b-2c) = 3(ar) - 2(bs)$
$= 3ar-2bs$
Let $x = 3ar-2bs$
Thus, $3b-2c= ax$ where $x$ is an integer.
By definition of divides, then, $a \mid (3b-2c)$ as was shown.

My question is: is this logic sound and if not, where did I go wrong?
Comment: Your 5 is wrong: you aree writing that $3b-2c=a(3b-2c).$
Comment: You may wish to check your definition of $x$ on line 4. Because the current $x$ doesn't satisfy $3b-2c=ax$ on line 5.
Answer: If $\ a \mid b\ $ then $\ a \mid 3b.$ Let $ ka = 3b,\ k\in\mathbb{Z}.$
Also,  $\ a \mid c\ $ and so $\ a \mid 2c.\ $ Let $ma = 2c,\ m\in\mathbb{Z}.$
$3b-2c = ka-ma=(k-m)a,\ $ and since $\ k,m\in\mathbb{Z},\ k-m\in\mathbb{Z}.\ $
So $3b-2c$ is a multiple of $a.$
Answer: Let me modify your writing as little as possible.

By definition of divides, $b=ar$ and $c=bs$ for some integers $r$ and $s.$
Then, $3b−2c=3b-2bs=b(3-2s)$
$=ar(3-2s).$
Let $x=r(3-2s).$
Thus, $3b-2c= ax$ where $x$ is an integer.
By definition of divides, then, $a \mid (3b-2c)$ as was to show.


Intersection / Union of two regular expressions

Question: Is there a way to directly form a new regular expression when given two regular expressions and the desired operation (Union or Intersection).
$$
(a+b)^*aa(a+b)^*\cup
(a+b)^*aa(a+b)^*
$$
$$
(a+b)^*aa(a+b)^*\cap
(a+b)^*aa(a+b)^*
$$
Without building NFAs and doing the operation through them?
Thank you.
Answer: You may be interested in this article: http://fox7.eu/wp-content/uploads/a4-gelade.pdf
It is shown there that:  "when constructing a regular expression defining the intersection of a fixed and an arbitrary number of regular expressions, an exponential and double exponential size increase, respectively, cannot be avoided".
Comment: The link is broken, but I found the paper here: http://dl.acm.org/citation.cfm?id=2071372
Comment: Wayback Machine: https://web.archive.org/web/20141031084156/http://fox7.eu/wp-content/uploads/a4-gelade.pdf


DNS: domain2 points to domain1

Question: I have one domain ("domain1") that is set up with hosting and mail (hosted by Gmail Apps). This domain works perfectly.
I want a second domain ("domain2") to forward to domain1, but I don't want to use "DNS Forwarding." I would like to have it act EXACTLY like domain1, so that domain2/whatever points to the same resource as domain1/whatever WITHOUT AN HTTP REDIRECT NOR BROWSER TRICKS LIKE FRAMES. I would also love to be able to send mail to "blah@domain2" and have it go to "blah@domain1".
Can this be set up, and how? I am using GoDaddy as registrar and DNS host for both domains. GoDaddy is also the web host for domain1, and mail hosting is with Google Apps.
Comment: Point domain 2 to the same server as domain 1?
Comment: I hope your site is not important for google ;) then when you do this you have dublicate content. And its possible that your site goes down in the google ranking.
Answer: For the web host, check to see if GoDaddy allow you to support multiple domains in your package. If they do that should solve the web site. If not you'll have to set up another package and clone the pages.
For email you'll need to visit your Google Apps control panel. Then under your domain settings add the new domain. I suspect you'll want to tick the box to make it an alias of your primary domain.

DNS: domain2 points to domain1


Erro ao gerar projeto jar

Question: Eu queria gerar um JAR do projeto que fiz no maven(simples). Mas gera esse erro. Por que gerou esse erro?
<code>[INFO] --- maven-war-plugin:2.2:war (default-war) @ teste-MODEL ---
[INFO] Packaging webapp
[INFO] Assembling webapp [teste-MODEL] in [C:\Users\ooo\Documents\workspace-ggts-3.6.4.RELEASE\teste-   MODEL\target\teste-MODEL-0.0.1-SNAPSHOT]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\Users\ooo\Documents\workspace-ggts-  3.6.4.RELEASE\teste-MODEL\src\main\webapp]
[INFO] Webapp assembled in [50 msecs]
[INFO] Building war: C:\Users\ooo\Documents\workspace-ggts-3.6.4.RELEASE\teste-MODEL\target\teste-MODEL-0.0.1-SNAPSHOT.war

[INFO] BUILD FAILURE

[INFO] Total time: 3.480 s
[INFO] Finished at: 2016-02-10T01:06:15-03:00
[INFO] Final Memory: 8M/21M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project teste-MODEL: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1]   http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>
Comment: Inclua seu `pom.xml`. Pelo log, o *packaging* do seu projeto é `war`, pode tentar apenas removendo o elemento ``
Comment: jar. :D Vou dormir, detalho mais tarde.
Comment: Juntamente com o `pom.xml`, inclua também o `web.xml` do projeto.
Answer: Se a sua aplicação não usa web.xml por algum motivo (servlet 3.0 por exemplo), você pode ignorar a validação desse arquivo.
Adicione o código abaixo na seção plugins do seu pom.xml
<code><plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
    <failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</code>
Retirado desse link do stackoverflow

Erro ao gerar projeto jar


Computing the integral $ \int_{1}^{\infty} \frac{x \,\mathrm{d} x}{\sqrt{2x^6+2x^3+1}}$

Question: Compute the following integral
$$ \int_{1}^{\infty} \frac{x \,\mathrm{d} x}{\sqrt{2x^6+2x^3+1}}.$$
This integral obviously converges. However, is it computable?
Comment: begin with $u =  x^3 +\frac{1}{2} $  followed by $\sinh t = 2u$ Still a long slog with uncertain outcome
Comment: Computable in what sense?  Closed form formula, maybe not.  Arbitrarily good rational approximations, certainly.
Comment: Numerically: sure, no problem. Analytically: no, I don't think so.
Comment: yes, I mean analytically computable.
Answer: The integral may be expressed in terms of elliptic integrals. Substitute $x=2^{-1/6}u$:
$$I=2^{-1/3}\int_{2^{1/6}}^\infty\frac u{\sqrt{u^6+\sqrt2u^3+1}}\,du$$
Then substitute $u+\frac1u=x$ (Byrd and Friedman 581.01) to get
$$I=2^{-4/3}\left(\int_y^\infty\frac1{\sqrt{(x-2)(x-a)(x-b)(x-c)}}\,dx+\int_y^\infty\frac1{\sqrt{(x-a)(x-b)(x-c)(x+2)}}\,dx\right)$$
where $y=2^{1/6}+2^{-1/6}$, $a=\sqrt2$, $b=\frac{-\sqrt2+\sqrt6}2$ and $c=\frac{-\sqrt2-\sqrt6}2$. Finally use B&F 258.00… or rather this small modification of B&F 258.00: if $y>a>b>c>d$,
$$\int_y^\infty\frac1{\sqrt{(x-a)(x-b)(x-c)(x-d)}}\,dx=J(a,b,c,d,y)=gF(\varphi,m)$$
where $m=\frac{(b-c)(a-d)}{(a-c)(b-d)}$ is the parameter, $g=\frac2{\sqrt{(a-c)(b-d)}}$ and
$$\varphi=\sin^{-1}\frac{\sqrt{(a-c)(b-d)}}{\sqrt{(y-a)(y-b)}+\sqrt{(y-c)(y-d)}}$$
Then
$$I=2^{-4/3}(J(2,a,b,c,y)+J(a,b,c,-2,y))$$

<code>#!/usr/bin/env python3
from mpmath import *
mp.dps = 100

print(quad(lambda x: x/sqrt(2*x**6 + 2*x**3 + 1), [1, inf]))

def bf258_00(a, b, c, d):
    y = root(2,6) + root(2,-6)
    g = 2 / sqrt((a-c)*(b-d))
    m = (b-c)*(a-d)/(a-c)/(b-d)
    s1 = sqrt((a-c)*(b-d))
    s2 = sqrt((y-a)*(y-b))
    s3 = sqrt((y-c)*(y-d))
    vphi = asin(s1 / (s2 + s3))
    return g * ellipf(vphi, m)

ra = sqrt(2)
rb = (-sqrt(2)+sqrt(6))/2
rc = (-sqrt(2)-sqrt(6))/2
I1 = bf258_00(2, ra, rb, rc)
I2 = bf258_00(ra, rb, rc, -2)
print(root(16, -3) * (I1 + I2))

0.632421879503014798952234566937018710345295154697941062278011824742339961706287315740337102826246671...
</code>

$I$ with bounds $[2^{-1/6},\infty]$ (note that $2^{-1/6}<1$) evaluates to $2^{-4/3}(J(2,a,b,c,2)+J(a,b,c,-2,2))$. $I$ with bounds $[0,2^{-1/6}]$ evaluates to $2^{-4/3}(J(2,a,b,c,2)-J(a,b,c,-2,2))$. Therefore $I$ with bounds $[0,\infty]$ requires only one elliptic integral:
$$\int_0^\infty\frac x{\sqrt{2x^6+2x^3+1}}\,dx=2^{-1/3}J(2,a,b,c,2)$$
Comment: *Of course*, elliptic integrals are "closed form"! Without so-called "special functions", we couldn't do very many integrals. They were invented exactly for that. :-)
Comment: For that matter the Appell hypergeometric functions are closed-forms as well. Whether you find them more obscure than elliptic integrals is a matter of taste (though I tend to agree with it).
Comment: Does this approach lead to a simple representation if the initial integral's lower limit is $x=0$ rather than $x=1$? Per my answer, this has a compact representation in terms of ${_2}F_1$ and I'm curious if the elliptic integral form is similarly elegant.
Comment: @Semiclassical Yes. In fact the $[0,\infty]$ integral only requires one $F$ rather than two in the given case. See edit.
Answer: I have to share @RobertIsrael and @ProfessorVector's doubts.
Call it $I$. Following @WillJagy, take $2x^3+1=\sinh t$ so$$I=\frac{1}{3\sqrt[6]{2}}\int_{\operatorname{arsinh}3}^\infty(\sinh t-1)^{-1/3}\mathrm dt.$$Using this,$$I=2^{-5/3}[(\sinh t-1)^{2/3}\cosh t\cdot f(t)]_{\operatorname{arsinh}3}^\infty$$where$$f(t):=F_1(\tfrac23;\,\tfrac12,\,\tfrac12;\,\tfrac53;\,\tfrac12(1+i)(1-\sinh t),\,\tfrac12(1-i)(1-\sinh t)),$$with $F_1$ the Appell hypergeometric function. Assuming the bracketed expression vanishes in the $t\to\infty$ limit (hopefully an expert on $F_1$ can weigh in on that),$$I=-\sqrt{\tfrac52}F_1(\tfrac23;\,\tfrac12,\,\tfrac12;\,\tfrac53;\,-1-i,\,-1+i).$$If that has a nicer closed form, I'd love to see it.
Comment: There's a nicer closed form. See my answer.
Comment: What I get from Mathematica (after integrating and simplifying under the assumption $t\geq 0$) is $$I=2^{-5/3}[(\sinh t-1)^{2/3}\cdot f(t)]_{\operatorname{arsinh}3}^\infty.$$
Comment: @Semiclassical I've fixed that for now; I'll privately review these coefficients.
Comment: Here's Mathematica code which verifies it: `FullSimplify[D[(-1 + Sinh[t])^(2/3)/(2 2^(2/3)) AppellF1[2/3, 1/2, 1/2, 5/3, (1 + I)/2 (1 - Sinh[t]), (1 - I)/2 (1 - Sinh[t])], t], t >= 0]`. Also, it looks like $f$ does vanish at infinity per your original hope.
Comment: ...but, having considered further: $f(t)$ does vanish at infinity, but $(\sinh t-1)^{2/3}$ doesn't, and it looks as if their product doesn't vanish at infinity. So the $t=\infty$ term can't be set aside so nicely...
Comment: @Semiclassical (Let alone the $\cosh t$.) That's probably why, if we multiply what I wrote before by $\sqrt[4]{2}$, you don't get what the other answer reports (ironically, it was closer before).
Comment: One other issue in this is that Mathematica doesn't seem very knowledgeable about Appell F1 identities. For instance, if I write the integration domain over $t$ analogously to in my answer, Mathematica does obtain results but doesn't recognize that they're equivalent to what I obtain by integrating over $v$.
Answer: A bit more Mathematica legerdemain: If we substitute $v=2x^3+1$, we obtain the form
$$I=\frac{1}{3 \sqrt[6]{2}}\int_3^\infty \frac{1}{\sqrt[3]{v-1}}\frac{dv}{\sqrt{1+v^2}}.$$
Writing the integration range as $\int_3^\infty = \int_1^\infty -\int_1^3$, Mathematica yields
$$I= \frac{2\pi}{3\sqrt{3}}{_2}F_1\left(\frac13,\frac56,1,-1\right)-  \frac12 F_1\left(\frac23;\frac12,\frac12;\frac53;-1+i,-1-i\right)$$
where ${_2}F_1(a,b;c;x)$ is the Gauss hypergeometric function and $F_1(a;b,c;d;x,y)$ is the Appell hyper-geometric function referenced in J.G.'s answer. Note that this means
\begin{align}
\int_0^\infty \frac{x\,dx}{\sqrt{2x^6+2x^3+1}} &= \frac{2\pi}{3\sqrt{3}}{_2}F_1\left(\frac13,\frac56,1,-1\right),\\
\int_0^1 \frac{x\,dx}{\sqrt{2x^6+2x^3+1}} &= \frac12 F_1\left(\frac23;\frac12,\frac12;\frac53;-1+i,-1-i\right)
\end{align}
Mathematica can't simplify the first term further, but there's so many identities for hypergeometric functions that further simplification seems plausible. The Appell F1 term, however, seems rather impenetrable.


Indefinite integral of trignometric function

Question: What is the trick to integrate the following
$$\int \frac{1-\cos x}{(1+\cos x)\cos x}\ dx$$
Comment: Try the Tangent Half Angle (http://en.wikibooks.org/wiki/Calculus/Integration_techniques/Tangent_Half_Angle).
Answer: We have: Integrand = $\dfrac{1}{\cos x} - \dfrac{2}{1+\cos x} = \sec x - \sec^2 (x/2)$, and
$\displaystyle \int \sec x - \sec^2 (x/2)dx = \ln (\sec x + \tan x) - 2\tan(x/2) + C$
Answer: Using $$\cos2A=\frac{1-\tan^2A}{1+\tan^2A}$$
$$\int\frac{1-\cos x}{\cos x(1+\cos x)}dx$$
$$=\int\frac{2\sin^2\dfrac x2}{\cos^2\dfrac x2-\sin^2\dfrac x2}\frac12\sec^2\dfrac x2dx$$
$$=\int\frac{2\tan^2\dfrac x2}{1-\tan^2\dfrac x2}\frac12\sec^2\dfrac x2dx$$
$$=\int\frac{2u^2-2+2}{1-u^2}du=-2u+2\int\frac{du}{1-u^2}du$$
Answer: Hint :
\begin{align}
\int\frac{1-\cos x}{\cos(1+\cos x)}\ dx&=\int\frac{\color{red}{1+\cos x}-2\cos x}{\cos(\color{red}{1+\cos x})}\ dx\\
&=\int\frac1{\cos x}\ dx-\int\frac{2}{1+\cos x}\ dx\\
&=\int\frac{\cos x}{\cos^2 x}\ dx-\int\frac{2}{1+\cos x}\cdot\frac{1-\cos x}{1-\cos x}\ dx\\
&=\int\frac{d(\sin x)}{1-\sin^2 x}-\int\frac{2-2\cos x}{1-\cos^2 x}\ dx\\
&=\int\frac{d(\sin x)}{2(1-\sin x)}-\int\frac{d(\sin x)}{2(1+\sin x)}-\int\frac{2-2\cos x}{\sin^2 x}\ dx\\
&=\int\frac{d(\sin x)}{2(1-\sin x)}-\int\frac{d(\sin x)}{2(1+\sin x)}-\int\frac{2}{\sin^2 x}\ dx+2\int\frac{\cos x}{\sin^2 x}\ dx\\
&=\int\frac{d(\sin x)}{2(1-\sin x)}-\int\frac{d(\sin x)}{2(1+\sin x)}-2\int\csc^2x\ dx+2\int\frac{d(\sin x)}{\sin^2 x}\\
&=\int\frac{d(\sin x)}{2(1-\sin x)}-\int\frac{d(\sin x)}{2(1+\sin x)}+2\int\ d(\cot x)+2\int\frac{d(\sin x)}{\sin^2 x}.
\end{align}


Breakpoint inside template function, Eclipse CDT Kepler

Question: I know this question may have been asked before, however I did not find any satisfactory answer. My problem is the following: I am developing C++ under Eclispe CDT Kepler. I use g++4.8.2 as the compiler and ggdb 7.6 as the debugger (both installed via macports), so not the clang tools that come with OS X (my OS is OS X Mavericks).
Now, in Eclipse I am able to set breakpoints and do a step-by-step debugging everywhere EXCEPT in template functions (breakpoint inside template functions are just ignored). The template functions are defined in implementation files (.cpp extension), and are standalone functions, not members of any class. I also set up qt creator with ggdb as debugging tool, and get the same behaviour, breakpoints are ignored inside template functions, and get the following warning (only when trying to add breakpoints in template functions):
&"warning: GDB: Failed to set controlling terminal: Operation not supported on socket\n"

So, it must be a ggdb problem.
Apple's default llvm works, but I must use g++ because of its OpenMP support, and can not use llvm in combination with g++.
Did you bump into such annoying behaviour? Is this a known issue with ggdb? And are you aware of any solutions to this problem, i.e. how to set up breakpoints in template functions when compiling with g++?
Thanks!
Answer: I don't recall a specific bug in this area in gdb 7.6.
Normally if this kind of problem arises it is due to missing debuginfo -- a compiler problem, not a debugger problem.  However, there isn't enough information here to really know.
When I have a problem like this I normally use objdump to view the debuginfo and search for the function I'm interested in.
Comment: It works fine in other OS-es, it's just a OS X problem I believe. Even in a terminal session, the "step" command in "gdb" does not step into a function if the function is templated... Everything works fine in Linux/Solaris though...
Comment: My `gdb` was installed through `macports`, will try to compile `gdb` from source from GNU. Thanks for the answer though!


Reusing code across React component

Question: I have a bunch of components with methods like these
class Header extends Component {

  sidebarToggle(e) {
    e.preventDefault();
    document.body.classList.toggle('sidebar-hidden');
  }

  sidebarMinimize(e) {
    e.preventDefault();
    document.body.classList.toggle('sidebar-minimized');
  }
}

I'd like to move this duplicate code to a function such as
function toggleBodyClass(className, e) {
  e.preventDefault();
  document.body.classList.toggle('sidebar-mobile-show');
}

Then refactor the functions above like so
  sidebarMinimize(e) {
    toggleBodyClass('sidebar-minimized', e);
  }

In the past, I would have used a mixin, but the React docs now discourage their use.
Should I just put this function in a regular JavaScript module and import it in the component modules, or is there a particular React construct for reusing code across components?
Comment: A small suggestion: It looks like you are using `` links as buttons (Since you're using all those `preventDefault`s). Maybe just convert them to `` elements? Then you can leave out those preventDefault calls.
Comment: @Carl Edwards is correct, the Props Proxy Higher Order Component pattern is what the react docs recommend: https://reactjs.org/docs/higher-order-components.html some more info: https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e
Answer: You could make a High Order Component with those functions as so:
import React, { Component } from 'react';

export default function(ComposedComponent) {
  return class ExampleHOC extends Component {
    sidebarToggle(e) {
      e.preventDefault();
      document.body.classList.toggle('sidebar-hidden');
    }

    sidebarMinimize(e) {
      e.preventDefault();
      document.body.classList.toggle('sidebar-minimized');
    }

    render()
      return <ComposedComponent { ...this.props } />;
    }
  }
}

Then take whatever component you wish to augment with those properties by wrapping them in the HOC:
ExampleHOC(Header);

Comment: This doesn't answer OP's question properly. You should read it again.
Comment: what you mean it doesn't answer?? that is the React Way! the only problem of the code proposed is that there is not way for the underlying component to access the functionality of the hoc, but it is easy to solve
Comment: of course it is settings asign messing about with dom in react is rarely a good idea
Comment: @DanielKhoroshko read it again. OP wants to move the logic of changing an element classname and running event.preventDefault to a method to define it once, and then use it to define methods that implement such logic in a DRY way. Your answer is not a proper implementation of this.

Also he didn't ask for a 'React way', he asked if he should do it the standard JS way or if there's a better React-specific option for this case. There isn't.
Comment: @DanielKhoroshko What am I missing for the original component to access the functionality of the HOC?
Comment: I agree this is the correct place to use the Props Proxy HOC to define the functions once and make them re-useable and DRY
Comment: @DaniGuardiola As quoted by OP: "In the past, I would have used a mixin, but the React docs now discourage their use.". HOCs are the workaround for this. Dan Abramov himself even states this: https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750
Comment: @CarlEdwards OP wants to write ONE function that toggles a class and calls preventDefault on an event. Then he wants to use that abstract functionality to create other methods without repeating that logic. I don't know why that's so difficult to understand. This answer is not for this question. The fact that HOCs exist does not mean you need to or should use it in this case. This does NOT answer OP's question.
Comment: I would quote the relevant parts of the question to sustain my argument, but here's the thing: the whole question is the relevant part. I'm not trying to be annoying or cause a discussion, but it is a bit surprising to me that you don't get why you are not answering his question. It is pretty clear to me. Can you please read it again? Have a good day.
Answer:
Should I just put this function in a regular JavaScript module and import it in the component modules

Yes. That would be a pretty standard way to share code between JavaScript files. I don't believe you need to or should do anything React-related to achieve this.
However, it is important to understand that you shouldn't directly interact with the DOM ever from a React component. Thanks @ShubhamKhatri for the heads up.
Comment: One thing to understand here is that with React you should not directly modify the DOM
Comment: @ShubhamKhatri that is true, I'm gonna add it to my answer, however it is still true.
Comment: What should I do instead of `document.body.classList.toggle` to toggle a class?
Comment: @Dónal define the classes in your render method. For example: ``. Then the method that you want to expose should toggle `this.props.classXEnabled` (true / false). This is just one example, but you should delegate the entire DOM rendering and manipulation processes to React to avoid headaches.
Answer: inherence solve your problem , create new class that extends Component and extend from your new class to share functionality and reduce the code
class SuperComponent extends Component
{
    sidebarToggle(e) {
        e.preventDefault();
        document.body.classList.toggle('sidebar-hidden');
      }

      sidebarMinimize(e) {
        e.preventDefault();
        document.body.classList.toggle('sidebar-minimized');
      }
}

---------------------------------------------------------------------

class Home extends SuperComponent
{
    someMethod()
    {
        this.sidebarMinimize();
    }
}

class Main extends SuperComponent
{
    someMethod()
    {
        this.sidebarToggle();
    }
}

Other Solution
create utils class and use it in your component
class UIUtiles
{
    static sidebarToggle(e) {
        e.preventDefault();
        document.body.classList.toggle('sidebar-hidden');
    }

    static sidebarMinimize(e) {
        e.preventDefault();
        document.body.classList.toggle('sidebar-minimized');
    }

}

class Home extends SuperComponent {
    someMethod(e) {
        UIUtiles.sidebarToggle(e);
        UIUtiles.sidebarMinimize(e);
    }
}

Comment: I appreciate the answer, but I'd prefer a composition-based solution to one that relies on inheritance.
Comment: @Dónal checkout the other solution
Answer: In my opinion, you are correct in putting the function in a regular JavaScript module and import it in the component modules.
Since a typical answer OOP answer would be to create another class extending React.Component adding that function. Then extend that class so every component you create will have that function but React doesn't want that.
One thing to verify that you are correct is in this pattern I believe.
https://reactjs.org/docs/composition-vs-inheritance.html

Reusing code across React component


Combinatorial exercise

Question: A group of 15 people go visit a city with 150 bar. At the end of the day one of those bar contains 8 people, the another one contains the other 7 people. How many ways can we get this situation? Explain why
My attempt:
$\binom{15}{8} * \binom{15}{7} * 150 * 149$
Answer: We choose can choose $8$ people from $15$ at $15 \choose 8$ ways and direct them to one of the $150$ bars.
There are 7 people left so there is ${7 \choose 7} =  1$ ways to send them to one of the $149$ bars left.
We later on use multiplication principle to obtain the answer.
The correct answer is ${15 \choose 8}{7 \choose 7}\cdot 150 \cdot 149$. (after rearragement).
Comment: Ok, but should it be multiplied by 149 instead of 140?
Comment: Sorry, that was a typo. It should be 149.
Comment: Do you fully understand the answer or would like to hear some more comment on it?
Comment: Well I did understand, but a whole explanation would be really accepted!

Combinatorial exercise


BizTalk: Service Consumer Catalog

Question: Is there a way in BizTalk, or any third party product, to know about service consumers. For Example, which channels/systems are using service X.
I have seen maintaining an excel document for this mapping but is there any product for it?
Answer: SOA Software is one company that has some sort solutions for these kind of problems. It is however quite expensive.
Try and search for SOA governance and you'll find plenty more options.

BizTalk: Service Consumer Catalog


CURL Request on form which don't have submit button

Question: Today, I'm trying to make a CURL request on a non-well coded website.
The form is composed by 2 fields and a button which trigger a JavaScript function who force the form submit.
My first question : Is a CURL request can be made with this type of form ?
If yes, is my code seems to be good ?
$postfields = array(
    'login' => 'test',
    'password' => 'test'
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $link);
curl_setopt($curl, CURLOPT_COOKIESESSION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('HeaderName: HeaderValue'));
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
$return = curl_exec($curl);
curl_close($curl);

Thanks guys
Comment: Just put it online on test server and check for yourself if it works, not exactly a good questions for SO
Answer: The JavaScript function is likely doing the following thing:
document.getElementById('form').submit();

Which has exactly the same behavior thing than pressing a submit button. So yes, your script is likely to work. Don't hesitate to try it by yourself before asking on SO, next time :-)
Comment: I'm understanding this way but Is the CURL Request will submit form even if is there is no submit form ?
Comment: "Submitting a form" is just doing a HTTP request with one or more parameters, and CURL is HTTP client. There is no notion of form submission for him.


What's wrong with using rectangles rather than triangles in Goursat's proof?

Question: I am reading the article On Goursat's Proof of Cauchy's Integral Theorem written by Harald Hanche-Olsen. In a historical remark, the author wrote that

Goursat presented a proof in 1884 for the case of a simple closed curve, by dividing up the interior into small squares...

Moore cleaned up the proof a bit, paying more careful attention to the treatment of the boundary curve. He also introduced the current idea of proof by contradiction, by subdividing and always selecting a part where the desired conclusion is maximally violated, and then applying the definition of the derivative at the resulting limit point.

Pringsheim presented a more severe criticism of Goursat's treatment of the boundary curve in 1901. He pointed out that these problems disapper if the proof technique is applied to a simple geometric figure such as a triangle.

Since some modern textbooks (such as Bak and Newman, Cartan, or Beardon) do use rectangles to present Goursat's proof, I don't understand what is the issue with rectangles. What is Pringsheim's criticism all about? Is his criticism justified? Is it OK to use rectangles?
Comment: @HansLundmark Thank you. It makes sense. I am happy to accept it if you turn it into an answer.
Answer: I think you're misreading this. As I interpret it, what he says is that the proof technique of subdividing into rectangles works fine if the boundary curve is a triangle, but that there is an additional argument needed to get from there to a more general boundary curve: "Then the theorem follows for simple polygonal paths in a simply connected domain by triangulating the interior of the path, and finally one gets it for a general path by approximating it by polygonal paths."


Moment Generating Function Questions on Technique

Question:
In this first question, I can work out that $X_i\sim \operatorname{Exp}(\lambda)$ and $N\sim \operatorname{Geom}(p)$.
Do I need the MGF of $T = \sum X_i$? How can I calculate this and how would I use this to come up with the answer?

In this example, I can work out the first 2 parts which are standard properties of MGFs, but how do I go about calculating the second 2?
Any help would be greatly appreciated! Thank you
Answer: The reason that the MGF is useful, is because it characterizes the distribution of a r.v completely, that is, if you know the MGF then you know the distribution and vice versa.
As you suggest, you have to compute the distribution of $X := \sum_{i=1}^{N} X_i$, where $N \sim \mbox{Geom}(p)$. Since the upper bound of the summation is a r.v as well, you will need conditioning here:
$$\mbox{MGF}_X(t) = \mathbb{E}[\exp(tX)] = \sum_{n \geq 1} \mathbb{E}\left[\exp\left( t \sum_{i=1}^{n} X_i\right) \ | \ N = n \right]\mathbb{P}[N=n].$$
To proceed, use that $N$ is independent of the duration times $X_i$ and the fact that $X_i$ are i.i.d.
Comment: Thank you! that makes a lot of sense. How would I go about question 2?
Answer: For the second question:
(iii) $Z := UX$ has the required mgf:
\begin{align}
M_{Z}(t) &= E(e^{tUX}) \\
&= \int_{u=0}^{1}f_U(u)E(e^{tUX}\mid U=u)\;du \\
&= \int_{u=0}^{1}E(e^{tuX})\;du \\
&= \int_{u=0}^{1}M_X(tu)\;du.
\end{align}
(iv) Let:
$$Z =
\begin{cases}
X,  & \text{if $0\leq U\leq 1/2$} \\
Y,  & \text{if $1/2\lt U\leq 1$}.
\end{cases}$$
Then,
\begin{align}
M_Z(t) &= P(U\leq 1/2)E(e^{tZ}\mid U\leq 1/2) + P(U\gt 1/2)E(e^{tZ}\mid U\gt 1/2) \\
&= \dfrac{1}{2}E(e^{tX}) + \dfrac{1}{2}E(e^{tY}) \\
&= \left[M_X(t) + M_Y(t)\right]/2.
\end{align}


nested QMap in qt

Question: I am trying to use this code in my QT app
QMap<QString,QMap>

but there is a build problem it says
C:/****/****/****/***/domparser.h:14: error: type/value mismatch at argument 2 in template parameter list for 'template<class Key, class T> class QMap'

Answer: QMap is a template class, so you need to specify the type of the inner QMap like this :
QMap<String, QMap<QString, int> > myMap;

Note the space between the '>'s otherwise the C++ lexer thinks its the >> operator.
[edited]
If you intended to try to store a generic QMap as the value type, rather than a concrete instance of QMap, within your outer map, you can't!
You cannot have something like QMap, because QMap itself is not a type, its a template - it only names a type when the template parameters are specified
Comment: "If you intended to try to store any kind of QMap as the value type ... you can't" - this could be read as meaning "no instantiation of QMap can be used as the value type of an outer QMap".  I'm sure that's not what you meant, but for the avoidance of doubt: while "QMap" is not valid, it is possible to use a *given instantiation* of QMap as a value type, e.g. "QMap >".
Comment: ... and, if the outer QMap is defined within a template, the parameters of that template could be used to instantiate the inner (value) QMap.  For example, if the outer QMap is a member of `Foo` then its complete type could be `QMap >`
Comment: Yes, my bad...
I should have said that it needed a complete instantiable(resolvable?) types as the template type parameters

nested QMap in qt


How to create html select option with data from MySql database with nodeJS

Question: How can I add values to options on select menu from MySql db with nodeJS. Instead to hard-codded below.
<select id="select_id" multiple="multiple">

              <option value="test">test</option>

              <option value="test2">test2</option>

UPDATE:
It won't update the select menu but on console.log(select) give it me the select menu that I whant, but not in the html view
fetch('/data').then(res=>res.json()).then(data=>{

        var select = document.getElementById("chkveg");
        console.log(select);
        for(var i = 0; i < data.length; i++)
        {
            var option = document.createElement("OPTION"),
                txt = document.createTextNode(data[i].username);
            option.appendChild(txt);
            option.setAttribute("value",data[i].username);
            select.insertBefore(option,select.lastChild);
        }
    })

with code below works fine. Two code blocks give it me same result on console.log(select)
var select = document.getElementById("chkveg"),
      arr = ["html","css","java"];

  for(var i = 0; i < arr.length; i++)
  {
    var option = document.createElement("OPTION"),
        txt = document.createTextNode(arr[i]);
    option.appendChild(txt);
    option.setAttribute("value",arr[i]);
    select.insertBefore(option,select.lastChild);

UPDATE 2:
I find that my jQuery function blocked adding the options in select menu.
has anyone have a idea how to solve that?
$(function() {
          $('#chkveg').multiselect({

              includeSelectAllOption: true

          });
      });

Answer: You could create an API with GET action to retrieve all of the data that you want to set as options.
For example: In your backend file, define an api like this
app.get('/data',(req.res)=>{
  // connection holds the connection to the db
  connection.query('SELECT column_name from table_name',(err,result)=>{
    if(err) throw err;
    else // result is the array of values in column_name
      res.send(result);
  })
});

Then in your client code you could do something like this:
fetch('\data').then(res=>res.json()).then(data=>{
\\ loop over the data and create markup
const markup = data.forEach(datum=>`<option>.....`)
document.querySelector("#select_id").appendChild(markup);
})

Comment: The first block is good and I have managed that, but i have problem with second block, don't give me results
Comment: Did you check if the API is giving back a response?
Comment: Yes API is giving response, I find that my jQuery function blocked adding the options in select menu.


A dodgy contour integration method giving the correct result

Question: Consider the following integral
$$I = \int_{-\infty}^\infty \frac{x}{\sinh x}dx$$
Using contour integration with some rectangular contour, it is not too hard to show that the integral evaluates to $\pi^2/2$. However, as shown in this reply, it is apparently possible to get the correct answer using a semi-circular contour in the upper half-plane, despite the fact that the integral over the contour technically doesn't vanish. As the radius of the semi-circular contour tends to infinity, there are an infinite number of poles contained within the contour with residues $i\pi n$ and $-i\pi n$ for $n$ is even and odd respectively. By assuming that the integral on the semi-circular contour vanishes, the residue theorem yields $$I = 2\pi i \sum_{n=0}^\infty (-1)^n (i\pi n) = -2\pi^2\sum_{n=0}^\infty (-1)^n n = \frac{\pi^2}{2}$$
if we consider that the last series goes to $-1/4$.
Now, despite the fact that the final answer is correct, the method used seems heretical for three reasons:

Assuming the integral on the semi-circular contour vanishes when it clearly doesn't on the imaginary axis.

Considering an infinite number of poles within the contour (although it's not too hard to accept that the residue theorem can also be used if the number of poles within a contour is countably infinite).

Assuming that the last traditionally divergent series actually converges in this context.

Why does this nevertheless yield the correct result? It's a safe assumption that it is not coincidental, since the entire family of integrals
$$I(n) = \int_{-\infty}^\infty \left(\frac{x}{\sinh x}\right)^n dx$$
can seemingly be evaluated correctly by using this method, with the only difference being the type of divergent series at the end.
Comment: So that the integral on the semicircle does vanish in the limit, you could instead integrate $z e^{iaz} \operatorname{csch}(z)$, $a>0$, around the contour.  Then use the dominated converge theorem to argue that $$\lim_{a \to 0^{+}} \int_{-\infty}^{\infty} \frac{xe^{iax}}{\sinh(x)} \, \mathrm dx = \int_{-\infty}^{\infty} \frac{x}{\sinh(x)} \, \mathrm dx. $$
Comment: @RandomVariable I believe that the integral on the semicircle does not vanish.  In fact, it seems to grow in absolute value linearly with the radius.
Comment: @MarkViola   If the radius is increased in a discrete manner so that the semicircle stays a fixed distance away from the poles of $\operatorname{csch}(z)$, then the integral will vanish since $|\operatorname{csch}(z)|$ decays exponentially to zero as $\Re(z) \to \pm \infty$, and $|e^{iaz}|$, $a>0$,  decays exponentially to zero as $\Im(z) \to + \infty$. It's more obvious if you use a rectangular contour.
Comment: @RandomVariable But can that really be the case when the sum of the residues diverges (quite badly).  See my posted solution and feel free to tear into it if I've made an error.
Comment: @MarkViola   You didn't make an error.  If $a>0$, the sum of the residues converges.  If $a=0$, then it diverges, and we get the situation that you showed.
Comment: @RandomVariable Ah, I didn't read your commnet correctly.  You never claimed that the integral of the original integrand over the "infintie" semi-circle converges.  You only claimed that the regularized integral does.  Got it now.  Apology for my confusion.
Comment: Makes sense. Didn't know about regularization!
Answer: Considering that zeta-regularization applied to $\sum_{n=1}^{\infty} (-1)^n n$ yields the correct answer, we may attempt to regularize the integral first and then appeal to the principle of analytic continuation.
In this pursuit, it doesn't really matter if we use a semicircular contour or rectangular contour. (Indeed, continuously deforming a contour while avoiding the singularities does not change the value of a contour integral.) What matters most is the fact that the sum of residues diverges as the contour encompasses larger region.  So, we will stick to rectangular contours.
First, we introduce a parameter $s$ and note that
\begin{align*}
\int_{-\infty}^{\infty} \frac{x}{\sinh x} \, \mathrm{d}x
&= 2 \int_{0}^{\infty} \frac{x}{\sinh x} \, \mathrm{d}x \\
&= 2 \lim_{s \to 1} \int_{0}^{\infty} \frac{x^s}{\sinh x} \, \mathrm{d}x
= 2 \lim_{s \to 1} J(s),
\end{align*}
where $J(s)$ is defined for all $s \in \mathbb{C} \setminus \mathbb{Z}$ by
$$ J(s) = \frac{1}{1 - e^{2\pi i s}} \int_{\mathcal{C}} \frac{z^s}{\sinh z} \, \mathrm{d}z $$
and $\mathcal{C}$ is the clockwise-oriented Hankel contour, composed of a small circle about $0$ and two half-infinite lines "just right" above and below the positive $x$-line:

Now replace each of the two half-infinite lines by a line segment of length $R$ , and denote the resulting "truncated" Hankel contour by $\mathcal{C}_R$.

Then we may write $J(s)$ as
$$ J(s) = \lim_{R\to\infty} J_R(s),
\qquad\text{where}\qquad
J_R(s) := \frac{1}{1 - e^{2\pi i s}} \int_{\mathcal{C}_R} \frac{z^s}{\sinh z} \, \mathrm{d}z. $$
From this point on, we assume $-2 < \operatorname{Re}(s) < -1$ and $R = (N+\frac{1}{2})\pi$ for $N = 0, 1, 2, \ldots$. Then, as we continuously inflate the contour $\mathcal{C}_R$ to a clockwise-oriented square $\mathcal{S}_R$ with vertices $\pm R \pm iR$, the deformation will sweep poles of the integrand at $z = \pm \pi i, \pm 2\pi i, \ldots, \pm N\pi i$. Hence,
\begin{align*}
J_R(s)
&= \frac{2\pi i}{1 - e^{2\pi i s}} \biggl[ \sum_{n = \pm 1, \ldots, \pm N} \,\underset{z=n\pi i}{\mathrm{Res}}\, \frac{z^s}{\sinh z} + \frac{1}{2\pi i} \int_{\mathcal{S}_R} \frac{z^s}{\sinh z} \, \mathrm{d}z\biggr] \\
&= \frac{2\pi i}{1 - e^{2\pi i s}} \biggl[ \pi^s (e^{i\pi s/2} + e^{3i\pi s/2}) \sum_{n = 1}^{N} (-1)^n n^s + \mathcal{O}(N^{1+\operatorname{Re}(s)}) \biggr] \\
&= \frac{\pi^{s+1}}{\sin(\pi s/2)} \sum_{n = 1}^{N} (-1)^{n-1} n^s + \mathcal{O}(N^{1+\operatorname{Re}(s)}).
\end{align*}
So, as $N \to \infty$, it follows that
\begin{align*}
J(s)
&= \frac{\pi^{s+1}}{\sin(\pi s/2)} \sum_{n = 1}^{\infty} (-1)^{n-1} n^s \\
&= \frac{\pi^{s+1}}{\sin(\pi s/2)} (1 - 2^{1+s}) \zeta(-s).
\end{align*}
However, since $\mathbb{C}\setminus\mathbb{Z}$ is connected and both sides of the above equality are holomorphic functions on $\mathbb{C}\setminus\mathbb{Z}$ that agree on a non-empty open subset, they must agree on all of $\mathbb{C}\setminus\mathbb{Z}$ by the principle of analytic continuation. This justifies OP's heuristics, and in particular,
$$ I = 2 \lim_{s \to 1} J(s)
= \frac{2\pi^2}{\sin(\pi/2)} (1 - 2^{2}) \zeta(-1)
= \frac{\pi^2}{2}. $$

Addendum. The above argument also shows that, for any $\operatorname{Re}(s) > 0$,
$$ \int_{0}^{\infty} \frac{x^s}{\sinh x} \, \mathrm{d}x
= \frac{\pi^{s+1}}{\sin(\pi s/2)} (1 - 2^{1+s}) \zeta(-s) $$
On the other hand, the left-hand side can be easily computed as:
\begin{align*}
\int_{0}^{\infty} \frac{x^s}{\sinh x} \, \mathrm{d}x
&= 2 \sum_{n=0}^{\infty} \int_{0}^{\infty} x^s e^{-(2n+1)x} \, \mathrm{d}x \\
&= 2 \sum_{n=0}^{\infty} \frac{\Gamma(s+1)}{(2n+1)^{s+1}} \\
&= 2 \Gamma(s+1) (1 - 2^{-s-1}) \zeta(s+1).
\end{align*}
Comparing both sides, we get
$$ \zeta(-s)
= - \frac{2 \Gamma(s+1)}{(2\pi)^{s+1}} \zeta(s+1) \sin(\pi s/2)
$$
and this is just the Riemann's functional equation for $\zeta(\cdot)$ in disguise.
Comment: @FShrike, You are right. To invoke analytic continuation in my argument, all we need is to find an infinite subset of $\Omega=\{z\in\mathbb{C}\setminus\mathbb{Z} : \operatorname{Re}(z)<-1\}$ that has an accumulation point in $\Omega$. The choice $-2<\operatorname{Re}(z)<-1$ was more or less for convenience.
Comment: @Zadig. Imagine the (truncated) Hankel contour is a 2D-version of a deflated balloon in a box and the poles are small round balls so that the balloon cannot reach all the way down to the pole but can only wrap around it. Then, as you blow air to the balloon, it will inflate and fill in the space inside the box that is outside of the poles. That is what I envisioned when I made that part of residue computation.
Comment: Why do you also specify $-2<\Re s$? As far as I can see, $\Re s<-1$ is necessary for the asymptotics and so long as $J(s)$ is defined - which it is - your method would work for, e.g., $s=-3$
Comment: I don't quite follow how the Hankel contour was inflated into a square contour, as well as how $J_R (s)$ equals the sum of residues and the integral over the square. Other than that, very neat answer.
Answer: We wish to evaluate the integral $\int_{-\infty}^\infty \frac{x}{\sinh(x)}\,dx$ using contour integration with a contour that is closed in the upper-half plane by a semi-circular arc.
One way to proceed is to close the upper-half plane with a semi-circular contour of radius $(N+1/2)\pi$.  Then, we can write
$$\begin{align}
\oint_{C}\frac{z}{\sinh(z)}\,dz&=\int_{-(N+1/2)\pi}^{(N+1/2)\pi}\frac{x}{\sinh(x)}\\\\
&+\int_0^\pi \frac{(N+1/2)\pi e^{i\phi}}{\sinh((N+1/2)\pi e^{i\phi})}\,i(N+1/2)\pi e^{i\phi}\,d\phi\\\\
&=-2\pi^2  \sum_{n=1}^N (-1)^n n\\\\
&=\frac{\pi^2}2 - \frac{\pi^2}{2}(-1)^N(2N+1)
\end{align}$$
Now, it shouldn't be difficult to show that
$$\lim_{N\to\infty}\left(\int_0^\pi \frac{i(N+1/2)^2\pi^2 e^{i2\phi}}{\sinh((N+1/2)\pi e^{i\phi})}\,d\phi+\pi^2(-1)^N(N+1/2)\right)=0$$
Answer: Let $N$ be a positive integer.
To make the approach rigorous, we can integrate  the modified function $$f(z) = \frac{z e^{iaz}}{\sinh z}, \quad  a >0,  $$ around the same contour, that is,  a contour consisting of the real axis from $-(N+1/2)$ to $(N+1/2)$ and the semicircle above it.
The integral will vanish along the semicircle as $N \to \infty$ through the positive integers because the magnitude of $\sinh(z)$ grows exponentially as $\Re(z) \to \pm \infty$, while the magnitude of $e^{iaz}$ decays exponentially to zero as $\Im(z) \to + \infty$.
Therefore,  we have $$\int_{-\infty}^{\infty} \frac{x e^{iax}}{\sinh x} \, \mathrm dx = 2 \pi i \sum_{n=1}^{\infty}\operatorname{Res}[f(z), i n \pi] = 2 \pi^{2}  \sum_{n=1}^{\infty}(-1)^{n-1}n e^{-a n \pi} = 2 \pi^2 \, \frac{e^{-a \pi}}{(1+e^{-a \pi})^{2}}. $$
But since  $x e^{iax} \operatorname{csch}(x)$ is dominated on $(-\infty, \infty)$ by the integrable function $x \operatorname{csch}(x)$, we have $$\begin{align} \lim_{a \to 0^{+}} \int_{-\infty}^{\infty}  \frac{x e^{iax}}{\sinh x} \, \mathrm dx &= \int_{-\infty}^{\infty}  \frac{x}{\sinh x} \, \mathrm dx \\  &=  2 \pi^{2}\lim_{a \to 0^{+} } \frac{e^{- a \pi }}{(1+e^{-a \pi})^{2}} \\   &= \frac{\pi^{2}}{2}. \end{align}$$
Comment: (+1) Nicely written as always
Comment: @MarkViola   I've gone from thinking my approach didn't answer the question, to thinking that it sort of answered the question, to now realizing that it answers the question in a fairly direct manner.
Comment: In effect, the regularization makes rigorous what the OP referenced.


Conjugate of element of the form $e = aω^2+bω+c$

Question: If $e$ is a polynomial like element of the form $aω^{n-1}+a_2ω^{n-2}+...+a_{n-1}ω+a_n$ where $ω$ is a root of a polynomial $P(x)$ of degree $n$, then what is the complex conjugate of $e$?
For instance, if $P(x)=x^2-r$, and if $ω$ is a root of $P(x)$, then $ω^2=r$. In the following field $K$ of roots of $P(x)$, each element has the form $e=aω+b$. If $ex=b^2-ra^2=s$ is an integer, then $x=-aω+b$. Therefore, $-aw+b$ is the complex conjugate of an element of the form $aw+b$.
Now suppose we are looking at $P(x)=x^3-r$, and if $ω$ is a root of $P(x)$, then $ω^3=r$. In the following field $K$ of roots of $P(x)$, each element has the form $e=aω^2+bω+c$. If $ex=s$ and $s$ is an integer, then what is $x$?
Also, for any polynomial $P(x)$ of degree $n$, with integer coefficients (does not have to be of the form $x^n-r$), and $ω$ is a root of $P(x)$, then what is $ω^n$ in terms of $ω$ or $r$?
For instance, suppose we have the polynomial $P(x)=x^4+x^3+x^2+x+1$ and $ω$ is a root of $P(x)$. In the field of roots of $P(x)$, which happens to be the field of the $5$th roots of unity, each element has the form $e=aω^3+bω^2+cω+d$.
Given the information above,
What is $ω^4$ in terms of $ω$ and $r$?
If $ex=s$ is an integer, then what is $x$? In other words what is the complex conjugate of $e=aω^3+bω^2+cω+d$?
A PARI/GP script can be used to evaluate products of elements (in the field $F$,  roots of $P(x)$) of the forms $(ay+b)(cy+d)$ where $y$ is a root of the polynomial $P(x)=x^2-s$, then $y^2=s$
<code>(20:21) gp > W(a,b,y,c,d)=(a*d + b*c)*y + (a*c*s + b*d)
%125 = (a,b,y,c,d)->(a*d+b*c)*y+(a*c*s+b*d)
(20:21) gp >
</code>
For instance, if one sets $s=-1$, then the user defined function W(a,b,y,c,d) is the same as the product of the complex numbers $(ai+b)(ci+d)$ where $i$ is the imaginary unit.
<code>(20:21) gp > W(a,b,y,-a,b)
%126 = -a^2*s + b^2
(20:25) gp >
</code>
If $(ay+b)(cy+d) = b^2 - sa^2$, then $c=-a$ and $d=b$.
<code>(20:29) gp > s=-1
%127 = -1
(20:29) gp > W(a,b,y,c,d)=(a*d + b*c)*y + (a*c*s + b*d)
%128 = (a,b,y,c,d)->(a*d+b*c)*y+(a*c*s+b*d)
(20:29) gp > W(a,b,y,-a,b)
%129 = a^2 + b^2
(20:29) gp >
</code>
When $s=-1$, $P(x)=x^2+1$, and $F$ is the field of roots of $P(x)$, or $4$th roots of unity. As in the code, W(a,b,y,a,-b) is $(ay+b)(-ay+b)=a^2+b^2$.
Two questions regarding the code,
If $(ay+b)(-ay+b)=a^2+ab+b^2$, then what does one need to set $s$ to (in the code)?
If $P(x)$ is any polynomial of degree $n$, and $y$ is a root of $P(x)$, in the field of roots of $P(x)$, with elements $e=ay^{n-1}+a_2y^{n-2}+a_3y^{n-3}+...+a_{n-2}y^2+a_{n-1}y+a_n$ and $e_2=by^{n-1}+b_2y^{n-2}+b_3y^{n-3}+...+b_{n-2}y^2+b_{n-1}y+b_n$, then what is $y^n$ defined to be? That is, using the W function (like the way it is used for W(a,b,y,c,d) explained in the code above) W(a,a_2,a_3,..a_{n-1},y,b,b_2,b_3,...b_{n-1}) in PARI/GP, which gives the product of $e$ and $e_2$, what should one set $s$ variable to?
If you have an example for this, please refer to the polynomial $P(x)=x^4+x^3+x^2+x+1$, the $5$th cyclotomic polynomial, $s$ its roots. Thank you for help, explanations, and other helpful references and guides.
Answer: I may have spotted some misunderstandings. I also want to elaborate on a few points, so an answer it is.
With the polynomial $P(x)=x^3-r$, $r$ a rational number, it often happens that the extension field $K=\Bbb{Q}(\omega)$, $P(\omega)=0$, does not contain all the zeros of $P(x)$. For example, if $\omega$ is a non-real cubic root of two, then its complex conjugate $\overline{\omega}$ is NOT an element of $K$ at all. OTOH, if we consider, instead of $K$ the splitting field $L=\Bbb{Q}(\root3\of2,e^{2\pi i/3})$ of $x^3-2$, then that field is a degree six extension of $\Bbb{Q}$. The field $L$, however, is stable under complex conjugation.
Things are markedly simpler, if $K$ is a Galois extension of $\Bbb{Q}$. In that case $K$ is automatically stable under complex conjugation. Any automorphism in the Galois group $Gal(K/Q)$ then maps a zero of $P(x)$ to some zero. The question is then to identify the usual complex conjugation among the automorphisms. You asked about $P(x)=x^4+x^3+x^2+x+1$ specifically. Because $P(x)(x-1)=x^5-1$ any zero $s$ of $P(x)$ satisfies also the equation $s^5=1$. As a complex number $s$ is on the unit circle, so $\overline{s}=1/s$. But also because $s^5=1$ we have $1/s=s^4$. So in this case $\overline{s}=s^4=-1-s-s^2-s^3$. Similarly we see that $\overline{s^2}=1/s^2=s^3$.
Consequently
$$
\begin{aligned}
\overline{a_0+a_1s+a_2s^2+a_3s^3}&=a_0+a_1s^4+a_2s^3+a_3s^2\\
&=(a_0-a_1)-a_1s+(a_3-a_1)s^2+(a_2-a_1)s^3.
\end{aligned}
$$


Cannot access Kubernetes pod

Question: I'm using Docker and Minikube on Windows for learning k8s, but I failed to deploy my first app.
I ran the following commands:

kubectl run testapp --image=saphyra/testapp:latest --port=8080
kubectl expose deployment testapp --type=NodePort
minikube service testapp

Using command  minikube dashboard I can see that the pod is created, and running, I can see the logs, and it says Tomcat started on port 8080 as expected.
So seems like everything is OK.
But how can I call the endpoint (from a browser) of the service I started?
The tutorial I followed (and many other YouTube tutorials) says now I have to be able to call the endpoints of the app.
What do I miss? How can I reach my app?
Edit:
Describe result
kubectl describe svc testapp >
Name:                     testapp
Namespace:                default
Labels:                   run=testapp
Annotations:              <none>
Selector:                 run=testapp
Type:                     NodePort
IP:                       10.110.10.61
Port:                     <unset>  8080/TCP
TargetPort:               8080/TCP
NodePort:                 <unset>  31612/TCP
Endpoints:                172.18.0.4:8080
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

kube proxy logs:
server_others.go:323] Unknown proxy mode "", assuming iptables proxy
node.go:135] Successfully retrieved node IP: 172.17.0.2
server_others.go:145] Using iptables Proxier.
server.go:571] Version: v1.17.3
conntrack.go:100] Set sysctl 'net/netfilter/nf_conntrack_max' to 524288
conntrack.go:52] Setting nf_conntrack_max to 524288
conntrack.go:127] sysfs is not writable: {Device:sysfs Path:/sys Type:sysfs Opts:[ro nosuid nodev noexec relatime] Freq:0 Pass:0} (mount options are [ro nosuid nodev noexec relatime])
conntrack.go:100] Set sysctl 'net/netfilter/nf_conntrack_tcp_timeout_established' to 86400
conntrack.go:100] Set sysctl 'net/netfilter/nf_conntrack_tcp_timeout_close_wait' to 3600
config.go:313] Starting service config controller
shared_informer.go:197] Waiting for caches to sync for service config
config.go:131] Starting endpoints config controller
shared_informer.go:197] Waiting for caches to sync for endpoints config
shared_informer.go:204] Caches are synced for service config
shared_informer.go:204] Caches are synced for endpoints config

EDIT 2
kubectl get svc testapp -o yaml >
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: "2020-03-25T17:03:57Z"
  labels:
    run: testapp
  name: testapp
  namespace: default
  resourceVersion: "3454"
  selfLink: /api/v1/namespaces/default/services/testapp
  uid: 048d05df-eaad-4d4b-845f-d98b222fe101
spec:
  clusterIP: 10.110.10.61
  externalTrafficPolicy: Cluster
  ports:
  - nodePort: 31612
    port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    run: testapp
  sessionAffinity: None
  type: NodePort
status:
  loadBalancer: {}

kubectl get pod testapp-c565bfccc-xht6j -o yaml >
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2020-03-25T17:03:52Z"
  generateName: testapp-c565bfccc-
  labels:
    pod-template-hash: c565bfccc
    run: testapp
  name: testapp-c565bfccc-xht6j
  namespace: default
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: testapp-c565bfccc
    uid: 21e2c9ab-3771-482f-8849-71754aaf5ff6
  resourceVersion: "3491"
  selfLink: /api/v1/namespaces/default/pods/testapp-c565bfccc-xht6j
  uid: c4dfdcb6-d050-4c44-99d1-6881bc39f805
spec:
  containers:
  - image: saphyra/testapp:latest
    imagePullPolicy: Always
    name: testapp
    ports:
    - containerPort: 8080
      protocol: TCP
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-689j9
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  nodeName: m01
  priority: 0
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 30
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - name: default-token-689j9
    secret:
      defaultMode: 420
      secretName: default-token-689j9
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2020-03-25T17:03:52Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2020-03-25T17:04:12Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2020-03-25T17:04:12Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2020-03-25T17:03:52Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://9a3ddc83df779bb4dc4b88718d82f7065d2dc647360fa200b4815ecc260a7ed4
    image: saphyra/testapp:latest
    imageID: docker-pullable://saphyra/testapp@sha256:b328a874297521f35c84a37cde160e23a39d6a12c7184dbe3c88ff0250b05df6
    lastState: {}
    name: testapp
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2020-03-25T17:04:11Z"
  hostIP: 172.17.0.2
  phase: Running
  podIP: 172.18.0.4
  podIPs:
  - ip: 172.18.0.4
  qosClass: BestEffort
  startTime: "2020-03-25T17:03:52Z"

Comment: minikube service testapp did not launch the browser?
Comment: It launched a tab in the browser, but ERR_CONNECTION_REFUSED
Comment: add output of kubectl describe svc testapp and logs of kube proxy pods in kube-system namespace
Comment: Requested data added @ArghyaSadhu
Answer: Okay, finally I found:
minikube start selected 'docker' as driver, so the whole kubernetes was started in a docker container, and I guess docker container was not exposed to host.
When I set driver hyperv explicit, and minikube started its own vm, everything worked fine.
However it is still a question how can I expose minikube running in docker container.
Answer: The Minikube VM is exposed to the host system via a host-only IP address, that can be obtained with the $ minikube ip command. Any services of type NodePort can be accessed over that IP address, on the NodePort.
From the information you provided, your service is listening to NodePort:31612. So, you can access your app from the browser by the following URL: minikube-ip:NodePort.
Let's say your minikube ip is 192.168.99.100 and the NodePort is 31612, then the URL will be, 192.168.99.100:31612
Comment: `minikube ip` returned 172.17.0.2. Still no connection to 172.17.0.2:31612
Comment: make sure your service and application are functional, check whether `testapp.default.svc:8080` accessible inside the cluster. To do so, use `$ minikube ssh` and use `curl`.
Comment: `curl 172.18.0.4:8080` returned the expected response
Comment: add the yamls to the question, `kubectl get pod  -o yaml` and `kubectl get svc  -o yaml`
Comment: Added to the question

Cannot access Kubernetes pod


Trouble plotting Fourier Series in MATLAB

Question: I was wondering if anybody could help me with plotting my Fourier Series in MATLAB. I've had a go at it and I don't believe I have arrived at the correct answer. I've plotted the expanded result fine but I can't seem to plot the result with the $\sum$ in it. I'm attempting to get the 3rd-order approximation for: $$e^{-t}$$
The following is my result which I believe is fine:
$$\frac{sinh(π)}{π} + \frac{2sinh(π)}{π} \sum_{n=1}^3 \frac{(-1)^n}{n^2+1} (cos(nt) + nsin(nt))$$
and the following is my MATLAB code so far:
<code>t = -pi:0.1:0;
x = exp(-t);
plot(t,x)
axis([-6 6 -5 25])
hold on
t = 0:0.1:pi;
y = exp(-t);
plot(t,y)
t = -pi:0.1:pi;
f = sinh(pi)/pi;
for n = 1:3
    sinterm = (sin(n*t)*n*(((-1)^n))/(n^2 + 1));
    if n/2 == round(n/2)
        costerm = 0;
    else
        costerm = (cos(n*t)*(((-1)^n))/(n^2 + 1));
    end
    f = f + 2*(sinh(pi)/pi)*(sinterm + costerm);
end
plot(t,f)
</code>
If someone could point out an error in my code or fix it up so that my approximation actually works, it would be greatly appreciated.
Thanks
Comment: 1) why do you have that if statement for n/2 ? 2) Take more terms in the sum to get something resounable
Comment: Yeah that piece of code is redundant and also I'm attempting to get the 3rd order approximation
Comment: if all you need is third order approximation - that is what you get. you can test it with more to convince yourself
Answer: I don't really know the background on why looking for Fourier transform for a non-periodic function, but it seems the result you got is what you can really get.
On a separate note, I always find that using anonymous functions in Matlab makes these things a lot easier. With your example:
<code>% original function
f=@(t) exp(-t)
% approximation function
f_hat=@(t) sinh(pi)/pi+2*sinh(pi)/pi*( (-1/(2)*(cos(t)+sin(t)))... % 1st order
                                     + (1/5*(cos(2*t)+2*sin(2*t)))... % 2nd order
                                     + (-1/10*(cos(3*t)+3*sin(3*t))) ) % 3rd order
% plot and compare
t=-pi:0.01:0; y=f(t); y_hat=f_hat(t);
figure,plot(t,y,'.',t,y_hat,'x')
</code>


Gauge R&R analysis - Preicision of a system

Question: I never attempted to do a GR&R analysis before so I'm sharing an overview of what I would like to attempt to do and hopefully I would get some insight/advice/reference on which approach I should use.
I have a system, containing 280 parts. One operator measures 52 points (current, voltage, power or whatever) and repeat this measurement 10 times for each part.
I would like to know how accurate/precise is my system for each part (or for all parts), could anyone give me an advice or a reference on which approach in GR&R I could use to extract the precision of the system?
Thank you
Answer: The first thing to do is write a clear step-by-step protocol for the operators. This will allow you to identify potential room for improvement in case you observe significant variance among operators and/or parts. Add to that the objective in terms of 'how much variation is acceptable and that was is not'. Variance expressed in percentages and/or in F- value gives a clear summary of how much variation there is. Together with a p-value, you could separate methods you consider acceptable and those that are not. One of the most important aspects is to decide how much variation is acceptable and not.
Perhaps this link could be of use: https://quality-one.com/grr
For actually doing the statistics I would suggest a program that is open-source. R and R-studio are great, but a simple spreadsheet could work fine for a few operators.


Android service called data from list multiple times

Question: 1.hello, I have created service for Schedule message but the problem is i have set the loop in my service method but it send the message all the message that is set on list.
2.I want to set the loop like, send message on list will be send at least ones time.
3.And the message has been sent is not send again.
//Here is my code.
//MyService class
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class SchedulerMsgService extends Service {
    private static final String TAG = "MyService";
    private DatabaseHelper mDbHelper;
    private ArrayList<schedulerDetails> myschedule = new ArrayList<schedulerDetails>();
    private String phoneNo, message, sDate, curTime;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
    }
    @Override
    public void onStart(Intent intent, int startId) {
        Log.d(TAG, "oNsTART IS rEADY ");
        mDbHelper = new DatabaseHelper(this);
        final List<schedulerDetails> ScheduleList = mDbHelper.selectAllNumbers();
        for (int j = 0; j < ScheduleList.size(); j++) {
            myschedule.add(ScheduleList.get(j));
            phoneNo = myschedule.get(j).num;
            message = myschedule.get(j).textMessage;
            sDate = myschedule.get(j).date;
            curTime = myschedule.get(j).time;

            sendSMS(phoneNo, message, sDate, curTime);
        }

        Toast.makeText(this, "condition Matched", Toast.LENGTH_LONG).show();

        // Toast.makeText(this, "condition Not Matched",
        // Toast.LENGTH_LONG).show();
    }
    public void sendSMS(String phoneNo, String message, String sDate,
            String curTime) {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
                SENT), 0);
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS Sent",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic Failure",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "Null Service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio Off",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(SENT));
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS Delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not Delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(DELIVERED));
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI);
    }
}

Answer: If the message has been sent, then remove the number from your database or add some information in the database that the message has been sent. Then mDbHelper.selectAllNumbers() can return only the numbers that need to receive the message.
Comment: sir i have try to sent message deleted but the problem is that now in list send only last set record message in list.

i want to send all message in list which have not yet time for sent

For Example if the two message set in the list which have been set time like 2 pm and the another have set the time like 2-03 pm i want to sent all message in list but in my case it send only last message set insted of both.
Comment: Sorry, I don't understand the conditions you have to send / not send messages - update your question and try to describe that with examples. -- But once `ScheduleList` contains the list and no information if that message has to be sent or not then you can't stop it from sending in the code you posted. You have to change the logic that generates this list to fit your needs.


LEFT JOIN mysql Filtrar registros não existentes NOT IN

Question: boa tarde, o que estou tentando fazer é o seguinte:
tenho duas tabelas
maquinas - armazena os dados de localização da copiadora ( endereço, cep, etc ).
leituras - armazena o código da maquina, os contadores, dataleitura, etc
eu queria exibir todos os registros da tabela MAQUINAS que não estivessem na tabela leituras no periodo determinado;
não estou acertando fazer o JOIN, se eu colocar o intervalo, normalmente ele vai filtrar somente maquinas que estejam dentro daquele intervalo, mas eu quero o contrário. quero maquinas que não estejam naquele intervalo.
não estou conseguindo usar o WHERE dataleitura NOT BETWEEN data1 AND data2
SELECT maquinas.codigo, maquinas.codnovo
FROM leituras RIGHT JOIN maquinas
ON (leituras.CodigoMaquina = maquinas.Codigo)
where inativa=0
AND dataleitura>'2015-02-11' and dataleitura<'2015-03-17'
and codigodono=5

Quem puder dá uma força ai. Valeu
Edição as 16:27:
O que eu preciso, é listar TODAS as maquinas que NÃO tenha na tabela leituras no periodo especificado
Edição as 16:48
Isso aqui quase resolve o que eu quero, tou tentando usar um HAVING aqui pra ver se vai adequar.
SELECT maquinas.codigo, maquinas.codnovo, MAX(leituras.dataleitura) as ultLcto
FROM
maquinas INNER JOIN leituras ON maquinas.codigo=leituras.codigomaquina
WHERE inativa=0 AND codigodono=5
GROUP BY maquinas.codigo
ORDER BY codigomaquina

Comment: A proposta do Lucas não resolveu o que você precisava? Pelo que você fala, acredito que o que ele propôs resolveria.
Comment: Para as duas datas que não estiverem entre o período tenta isso aqui: `WHERE dataleitura < CAST('2015-02-11' AS DATE)
OR dataleitura > CAST('2015-03-17' AS DATE)`
Comment: não entendi o uso do CAST nessa ocasião, essa função não é para conversão do tipo de dados ?
Answer: Esta imagem pode ajudar. Nosso caso é o segundo da esquerda, de cima para baixo. Tenta o seguinte:
SELECT maquinas.codigo, maquinas.codnovo
FROM maquinas
LEFT JOIN leituras ON
    maquinas.Codigo = leituras.CodigoMaquina
    AND dataleitura > '2015-02-11' AND dataleitura < '2015-03-17'
WHERE leituras.CodigoMaquina IS NULL
AND inativa = 0
AND codigodono = 5

Comment: O Registro não pode existir em dataleitura, veja a ultima edição que fiz no post. por esse motivo isso ai não funciona.  eu tenho que lista a maquina.codigo que não está dentro de leitura.
Comment: Você testou? O `WHERE leituras.CodigoMaquina IS NULL` é pra pegar os que não existem na outra tabela
Comment: vem em branco, mas existem maquinas lançadas nesse periodo
Comment: o registro não pode existir na tabela leituras. eu quero pegar maquinas.codigo que não tenha em leituras no intervalo que eu especifiquei ? tendeu ? veja minha ultima edição =)
Comment: Fiz uma alteração, veja se resolve


Trying to wait for list to be populated before iterating through it NodeJS

Question: I have some code that takes an uploaded file, executes it and gets the output. It then compares this output against expected output to check if the script did as expected.
I am now trying to improve this functionality so that an uploaded file will be run several times, each time being checked against a different expected output, or "test case". I then want to push "correct" or "incorrect" onto a results array, so that I can go through that array at the end and check whether there are any "incorrect" (whether the file failed any test case).

I have tried just callbacks within each function.
I have tried using await and async on the getArray as seen below
Using both callbacks and async together.

This is the parent function code that calls for the array to be created, and wants to iterate through it after it has been created.
var resultsArr = await getResults(file.name, files.length, markerDir);
//file.name is the name from the uploaded file object
//files.length is the number of subdirectories (number of testcases to run against)
//markerDir is the str path to where these testcases are stored

if (resultsArr){
   for(var i=0;i<resultsArr.length;i++) {

      if (resultsArr[i] == "incorrect"){
         checkForMarkerCb('incorrect'); //Calls back to frontend to
         break;                         //display result on web app
      }

      else if (i+1 == resultsArr.length) {
         checkForMarkerCb('correct');
      }
   }
}

The following is inside the getResults function that is called above
for(var i=1; i<=fileLength; i++) {
   var sampleOut = markerDir + '/test' + i + '/stdout.txt';

   //Grab expected stdout.txt
   var markerOut = fs.readFileSync(sampleOut, 'utf-8', function(err){
      if (err){
         throw err;
      };
   });

   //Run the file and grab the output
   executeFile(filename, function(fileOut){

      //Compare output with sample stdout
      if (markerOut == fileOut){
         resultsArr.push('correct');
      }

      else {
         resultsArr.push('incorrect');
      }
   });
}

//If results array has a response for each testcase
if (resultsArr.length == fileLength) {
   return resultsArr;
}

Implementation of executeFile() as requested:

function executeFile(filename, execFileCb){
   //pathToUpload is a str path to where the upload is stored

   const child = execFile('python', [pathToUpload], (err,stdout,stderr) => {
      if (err) {
         throw err;
      }

      execFileCb(stdout); //Callback with output of file
   });
}

function executeFileAsync(filename) {
    return new Promise(function(resolve,reject){
        executeFile(filename, function(err, data){
            if (err !== null) reject(err);

            else resolve(data);

        });
    });
}

which was called inside getResults() using
var fileOut = await executeFileAsync(filename)

The initial function that calls getResults().
getResults(): which gets the path to each directory and calls pushes the results of comparing outputs onto a results array.
executeFile(): uses 'child_process' to run a file and calls back with the output.

I expect the code to wait for getResults to return with the resultsArr so that the for loop can iterate through and check for any "incorrect". Instead, getResults returns before resultsArr is populated.
Using some logging, I see that the code for checking markerOut == fileOut is executed at the end after the getResults() for loop has already completed. I tried setting up the call to executeFile() to also be an async/await similar to how getResults() is called but still no change.
I may not be using async/callbacks correctly, any help is greatly appreciated.
Comment: You can only use `async`/`await` together with promises, not instead of them. `await` is syntactic sugar around a `.then()` call, but the promise is still there. You need to [make your `executeFile` function return a promise](https://stackoverflow.com/q/22519784/1048572).
Comment: Can you please show us how you tried to use `async`/`await` in `getResults`? Especially how you did convert `executeFile` so that it returns a promise?
Comment: @Bergi I declared getResults as "async function getResults(filename, fileLength, markerDir)

And when I tried to do this for executeFile, I made it return the output rather than use callbacks.

var fileOut = await executeFile(filename)

..similar to how getResults is called in the code above.
Comment: Please [edit] your question to show the code. Also show the implementation of `executeFile`, this is what seems to be important. Notice that you cannot simply `return` an asynchronous result, you need to return a promise and later fulfill it.
Comment: @Bergi made some edits, I was getting confused between promises/callbacks/async and thought using async/await was an alternative to using a promise. Is there a way to fix this with Promises?
Comment: @Bergi Thank you for that link, Ive tried converting my executeFile function with the callback to the syntax under **"3. Node Style Callback"**.. However Im unsure where I can put my if markerOut == fileOut code. Inside the Promise? Do I save the promise to a var fileOut then do it after?
Comment: You'd use `executeFile(filename).then(function(fileOut){ …` or `fileOut = await executeFile(filename);`
Comment: @Bergi Ive edited the post to show my current implementation, Ive added the function executeFileAsync and I'm calling it how you said, but am getting an *"UnhandledPromiseRejectionWarning"*
Answer: Your executeFileAsync function currently calls executeFile with a callback that is expecting two arguments, but executeFile then does call this execFileCb always with only one argument which is interpreted as an error. It also should not use throw in an asynchronous callback.
Instead, merge them into one function:
function executeFile(filename) {
  return new Promise(function(resolve,reject){
    //pathToUpload is a str path to where the upload is stored

    const child = execFile('python', [pathToUpload], (err,stdout,stderr) => {
      if (err) reject(err);
      else resolve(stdout); //Callback with output of file
    });
  });
}

Comment: Thank you so much! Finally have it properly waiting for the array to be filled and I now understand Promises. Really appreciate it!


Interpretation of logit versus independent variable plot for logistic regression

Question: I plotted the log odds of my outcome variable against my predictor variables, hwt and ist. There is a hard vertical line in my hwt plot and a hard diagonal line in my ist plot. I have two questions: (1) Why do I have hard lines in my plots (I don't understand what would cause this), and (2) does the ist plot satisfy the assumption for linearity for logistic regression? It looks "fairly" linear to me. My dataset consists of 300 observations with 269 outcomes being a "0" and 31 outcomes being a "1". The ist predictor value is a percentage, which ranges from 0-100%. The hwt variable is measured in m/ha. This is the code I used to generate the plots:

bestmodel <- glm(outcome~ hwt + ist, data = habitatdata, family = "binomial")

library(ggplot2)
probabilities <- predict(bestmodel, type = "response")
logit = log(probabilities/(1-probabilities))
ggplot(habitatdata, aes(ist, logit))+
 geom_point(size = 0.5, alpha = 0.5) +
geom_smooth(method = loess) +
 theme_bw()

ggplot(habitatdata, aes(hwt, logit))+
      geom_point(size = 0.5, alpha = 0.5) +
      geom_smooth(method = loess) +
      theme_bw()

Comment: If you're doing this to try to diagnose the adequacy of your model, it's not going to work. Notice that *the response variable is not incorporated in your plots anywhere* - not as the observed value (`outcome`), and not as some form of residual; instead all you have is the *prediction* from your model, which is a deterministic function of the input variables. What you're doing here is plotting an interestingly/weirdly transformed relationship *between your predictors*. Diagnostics for binary data are challenging: see `DHARMa` package & `arm::binnedplot()`
Answer: The diagonal and vertical lines of points are caused by the same individuals, which are those with values of the 0 for hwt.
Let's consider the second plot first. That line of points is concentrated at hwt = 0, but there is some variability in the predicted logit. That is because those individuals have different values of ist, which produces different values of the logit given the estimated regression coefficients. There is nothing strange about this.
The first plot may look strange, but it's actually a result of the same phenomenon. Consider all those units with zeroes for hwt and think about what the regression equation looks like for them. Becuase hwt = 0, all that is left is a linear relationship between iwt and the logit, and that is reflected in that diagonal line. (Note this kind of thing would happen if you had a clustering of values at the exact same value of hwt, even if that value was not zero). More specifically, if the estimated regression equation looked like $\text{logit}(p) = b_0 + b_1 (\text{iwt}) + b_2 (\text{hwt})$, see what the equation looks like for those with hwt = 0: all we have is $\text{logit}(p) = b_0 + b_1 (\text{iwt})$, which is a perfectly straight diagonal line.
To verify this, add aes(fill = hwt == 0) to your geom_point() call. You will see that those on the diagonal line in the first plot correspond exactly to those on the vertical line in the second plot, being those with hwt = 0.
Comment: Thanks, this was helpful!


How are subdomain resolved?

Question: quick question for you, when I enter adress like test.mysite.net, first I connect to my ISP DNS, than if not found there to .NET DNS, than to mysite DNS, what after that?
I mean, I know that test.mysite.net could be at different IP adress, but what if I want to run virtual server there? I get the same IP as mysite.net has, and how does server know wheather I want to reach for test.mysite or mysite directly, if they have same IP adress ?
Answer: This isn't a tricky question.
It's basic DNS operations to evaluate in the order of .net -> mysite.net -> test.mysite.net, passing the request from one domain DNS server to another.
See How Lookups Are Handled for a graphical explanation.
Comment: It's actually `.` -> `net.` -> `mysite.net.` -> `test.mysite.net.`
Comment: @harrymc, you can see the DNS root servers here - http://www.root-servers.org/.  Looks like we're up to around 200 physical servers backing up the 13 root server names.  But yes, I believe the load on the roots tends to be intense.  DNS software will often cache responses so it will know `net.`, but when the cache expires it will go back to `.` to refresh.
Comment: @grawity: I believe this is optimized, to avoid the entire world soliciting one poor DNS master server.

How are subdomain resolved?


Erro de redirecionamento de login iphone - Correlation failed

Question: Estou com problemas ao fazer login pelo google e facebook quando acesso através de um iphone, após eu autenticar minha conta, no google por exemplo, o callback não é chamado gerando uma exceção.
O login funciona assim:

O cliente clica no botão (google)
A função ExternalLogin é chamada, passando o provider(google) e a url de redirecionamento
A autenticação é feita e a url de redirecionamento é chamada.

A aplicação utiliza netCore 2.1, quando eu acesso a aplicação utilizando um navegador desktop ou pelo celular utilizando android tudo funciona perfeitamente, mas quando tento fazer o login pelo iphone utilizando o facebook ou google é gerado uma exceção "Correlation failed", como mostra a imagem abaixo:

Startup.cs
<code> public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
               options.UseSqlite("Data Source=Auth.db"));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            string clienteID = System.Diagnostics.Debugger.IsAttached ? "Meu-id" : "Meu-id";
            string clienteSECRET = System.Diagnostics.Debugger.IsAttached ? "Meu-id" : "Meu-id";
            string facebookID = "Meu-id";
            string facebookSECRET = "Meu-id";

            services
                .AddAuthentication(sharedOptions =>
                {
                    sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    options.LoginPath = "/Home/Index";
                    options.Cookie.SameSite = SameSiteMode.None;
                })
                .AddGoogle("Google", googleOptions =>
                {
                    googleOptions.ClientId = clienteID;
                    googleOptions.ClientSecret = clienteSECRET;
                    googleOptions.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo";
                    googleOptions.ClaimActions.Clear();
                    googleOptions.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
                    googleOptions.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                    googleOptions.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
                    googleOptions.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
                    googleOptions.ClaimActions.MapJsonKey("urn:google:profile", "link");
                    googleOptions.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
                    googleOptions.ClaimActions.MapJsonKey("urn:google:picture", "picture", "url");
                    googleOptions.ClaimActions.MapJsonKey("urn:google:locale", "locale", "string");
                })
                .AddFacebook(facebookOptions =>
                {
                    facebookOptions.AppId = facebookID;
                    facebookOptions.AppSecret = facebookSECRET;
                });

            services.AddTransient<IEmailSender, EmailSender>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddProgressiveWebApp();
            //services.ConfigureExternalCookie(options =>
            //{
            //    // Other options
            //    options.Cookie.SameSite = SameSiteMode.None;
            //});
            //services.ConfigureApplicationCookie(options =>
            //{
            //    // Other options
            //    options.Cookie.SameSite = SameSiteMode.None;
            //});
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy(new CookiePolicyOptions()
            {
                MinimumSameSitePolicy = SameSiteMode.None
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "LoginEmpresa",
                    template: "{Empresa}",
                    //defaults: new { controller = "Account", action = "LoginPage" });
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
    }
</code>
ExternalLogin
<code>     [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public IActionResult ExternalLogin(string provider, string returnUrl = null)
        {
            // Reque;;st a redirect to the external login provider.
            var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
            AuthenticationProperties properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
            try
            {
                //properties.AllowRefresh = true;
                return Challenge(properties, provider);
            }
            catch (Exception e)
            {
                MetodosAuxiliares.SaveExceptionError(e, "ExternalLogin/try");
            }
            return null;
        }
</code>
Answer: O erro de login estava ocorrendo por conta de um bug no Mac OSX e o IOS, o que faz com que os cookies SameSite=None sejam tratados inadvertidadamente como SameSite=Strict, e portanto não enviava solicitações entre sites, descrito aqui: https://www.chromestatus.com/feature/5088147346030592.
Corrigi o problema apenas migrando para o .NET Core 3.1, existe um bug na versão 2.1 que não atribuía o valor "None" ao SameSite cookies.
Caso o erro persista você pode criar uma classe para identificar o dispositivo e definir a melhor atribuição para o SameSite coockie:
https://www.thinktecture.com/en/identity/samesite/prepare-your-identityserver/
Outra forma de corrigir o erro é criar um middleware que intercepta o redirecionamento da página:
https://www.thinktecture.com/en/identity/samesite/prepare-your-identityserver/


How proof this property in a Hilbert space of infinite dimension

Question: I have problems with this proof,
$$u_{1},u_{2},...$$ this is an orthogonal set of vectors in an infinite-dimensional Hilbert space. Show if
$$x=\sum_{i=1}^\infty  c_{j}u_{j}$$
so...
$$\|x\|^2 =\sum_{i=1}^\infty \left\lvert c_{j} \right\rvert^2 $$
thx guys
Comment: You're right I wrote wrong, sorry my english isn`t good
Answer: $$\|x\|^2 = \langle x, x \rangle = \left\langle\sum_i c_i u_i, \sum_j c_j u_j \right \rangle
= \sum_i \sum_j c_i \overline{c_j} \langle u_i, u_j \rangle.$$
Then use the fact that $u_1,u_2,\ldots$ is orthonormal. (Orthogonality is not enough.)


how to show more information in user's profile

Question: by default user's profile in drupal show very little information about users. I can extend that by adding more fields to profiles.
but I want user's profile in such a way that it would be showing all his/her information and some more information like users last 10 posted content, top 10 rated content and most commented content etc.
how can I extend this type of profile view in drupal?
please suggest me, thanks in advance :):)
Comment: I would suggest investigating the Views module for creating blocks of content about the user, eg, your last 10, top 10, commented lists, etc.
Answer: For things like last 10 posted content, I believe you can use contextual filters in Views. With that you can create pages like /user/somebody/posts where Views will show you the last contents of user for example, also I believe you can make a block out of such a view that you can place on profile pages.
Also it may worth for you to check out the Profile2 module, you can create multiple types of profile pages with it for example.
http://drupal.org/project/profile2


Modern Filesystems and Small Files?

Question: Do modern file systems, such as ext4, ntfs, and apfs, always start files in a new sector, or may some files share the space in the same sector?
Answer: btrfs appears to be the most widely-used filesystem that uses block suballocation
https://en.m.wikipedia.org/wiki/Block_suballocation

Modern Filesystems and Small Files?