How do many examples end up in a normal distribution/nice symmetric bell curve?

Question: I understand what standard deviation means and what a normal distribution looks like but I don't understand what normal distribution is used for...
Many typical examples explaining normal distributions goes "X of individuals in a large group follows a normal distribution pattern…" where X can be height/test scores/ etc.
What I don't understand is HOW can the height or test score end up as a nice symmetric bell curve?
Answer: First it is worth noting that while we often model a certain data type as being normally distributed, this does not necessarily mean that we believe it exactly follows a normal distribution. Take your height example. Many researchers (myself included) believe that modeling height by a normal distribution does a fairly good job of describing the distribution of heights. But clearly it's not exactly normal: you can't have negative height, but all normals with positive variance have a positive probability of being negative. Despite this, the distribution of heights is fairly normal.
So why is it that many data types will follow an approximately normal distribution? To me, this can be motivated by central limit theorems (in an undergraduate course, you probably heard of *the* central limit theorem, but there's more than one...). Under a variety of conditions, averages approach a normal distribution.
Why does this explain why various phenomena are approximately normal? Well, suppose the outcome you are measuring is actually the combination of a whole lot of different small effects. In the case of height, there are a lot of genes that each contribute to your height, along with your diet as a youth, etc. So you could think of the final measure of height as a combination of a large number of factors. Even as an average, if you will. As long as a small number of these factors do not completely dictate height (or similarly, these factors aren't too correlated), then there's a central limit theorem that will suggest that this measurement should be approximately normal.
Keep in mind, this is merely heuristic reasoning and I wouldn't use such logic to decide that a given outcome must be approximately normal. But in my own musings, it's the been my personal explanation why an approximately normal distribution might naturally occur.
Comment: If it's not exactly normal, why don't scientists just use the exact model? Also, how do we know distribution of heights is fairly normal? If I plot out the graph of students in different classes at my school, all classes' height graphs should look different, no?
Comment: "All models are wrong, but some are useful" -George Box. So heights might not be *exactly* normal, but they can be close enough for useful approximations. And since there's no distribution that's known to do better...
Comment: In regards to plotting out the height of students in different classes, they would be slightly different, this is standard sampling error which is exactly as we expect. The normality assumption states that you would assume if you plotted all the heights, you would expect a bell shaped histogram, not that you expect each class to look exactly the same.
Comment: If I was being a twit, I'd guess that the reason that normal distributions are assumed so often is that everyone's favorite estimators (mean and standard deviation) are maximum likelihood estimators and sufficient, too, and all our favorite tests work on data with normal assumptions.  Somewhat kinder, the central limit theorem makes the tests and confidence intervals based on normal assumptions work reasonably well when you have large sample sizes even if your population is not too horribly non-normal.
Comment: Truth be known, almost every large dataset that I've worked with deviates from normality, but, being a large dataset, we often don't care because of the CLT.  On the other hand, if it were a small dataset, we wouldn't have the power (probably) to show that it isn't normal and ignorance is bliss sometimes...


PostreSQL- How to convert float containing a number of seconds to MM:SS.sss

Question: I have a float8 that contains a number of seconds ie 65.455. I was trying to format a column in a view so that it would read as 1:05.455.
Using postgres command like this:
TO_CHAR((user_data.totaltime || ' second')::interval, 'MI:SS')
I can format it as 1:05  but i loose the precision i need.
Anyone know of a way to achieve what i need ? It doesn't look like interval allows the formatting of milliseconds.
Answer: Try justify_interval:
SELECT justify_interval(
          CAST(65.455::text || ' seconds' AS interval)
       );

Comment: That throws an error:

SQL Error [42883]: ERROR: function justify_interval(text) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 356
  ERROR: function justify_interval(text) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 356
  ERROR: function justify_interval(text) does not exist
  Hint: No function matches the given name and argument types. You might need to add explicit type casts.
  Position: 356
Comment: It was missing a type cast; fixed.
Comment: Accept answer as it is almost the best way of doing it ;-) I did find that the following worked just as well in my view definition:

(timetest.runtime)::text::interval AS runtime_t1
Answer: Here is a rather brute force you may do this, using the base string functions:
SELECT
    FLOOR(65.455 / 60)::text || ':' || LPAD(FLOOR(65.455 % 60)::text, 2, '0') ||
        TRIM(LEADING '0' FROM (65.455 % 1)::text);

This outputs:
1:05.455

Demo
Comment: A bit brutal, but works perfectly .... and as my data will only ever have a few hundred rows will work just fine ;-)


Como fazer um RSS feed funcionar no Angular 4?

Question: O código abaixo está funcionando numa página HTML

            <title>Titulo da página</title>
            <meta charset="utf-8">

powered by Surfing Waves

Como poderia fazer ele funcionar num projeto angular 4 ?
Comment: Qual é a dificuldade? Já fez algum projecto em angular?
Comment: sim, eu já fiz.
Answer: Pode baixar o documento usando HttpClient e pode usar o:

https://developer.mozilla.org/en-US/docs/Web/API/DOMParser

Exemplo básico:
import { HttpClient } from '@angular/common/http';

...

title = '';
description = '';

constructor(private http: HttpClient) { }

...

downloadXml() {
    this.http.get("http://site.com/feed.rss").subscribe(res => {
         parseXml(res); //Baixo o XML
    }, err => {
         console.log(err);
    });
}

...

parseXml(data) {
    let parser = new DOMParser;
    let doc = parser.parseFromString(data, "application/xml");

    this.title = doc.querySelector("channel > title").text;
    this.description = doc.querySelector("channel > description").text;

    ...
}

E no HTML ficaria algo como:

{{title}}

{{description}}

Para pegar os itens terá que ir iterando com for e pegando somente os textos, por exemplo:
title = '';
description = '';
items = [];

constructor(private http: HttpClient) { }

...

parseXml(data) {
    let parser = new DOMParser;
    let doc = parser.parseFromString(data, "application/xml");

    this.title = doc.querySelector("channel > title").text;
    this.description = doc.querySelector("channel > description").text;

    let items = doc.querySelectorAll("channel > item");
    let objs = [];

    for (let el of items) {
         let obj = {
             "link": el.querySelector("link"),
             "title": el.querySelector("title"),
             "description": el.querySelector("description")
         };

         objs.push(obj);
    }

    this.items = objs;
}

E no HTML ficaria assim (usando *ngIf para verificar se existe algo e *ngFor para iterar os valores em this.items):

{{title}}

{{description}}

{{item.title}}

{{item.description}}

Comment: @BraianSilva tá respondido https://pt.stackoverflow.com/a/395784/3635, em futuros comentários de preferencia já coloque o link de suas perguntas, se já existirem ;)
Comment: eu entendi que você colocou a classe de serviços e a página HTML, mas o a classe de componente como vai ficar?
Comment: @wladyband como assim, você quer que um serviço em background fique atualizando sozinho os dados? Esse exemplo que postei é o básico de como fazer o "parse" do RSS (que até então me parecia a sua dificuldade). Exatamente aonde é a sua dificuldade agora?
Comment: me desculpe, só tinha um pouco de paciência comigo, eu consigo compreender seu código, os códigos então sem dizer onde é componente ou é serviço, eu conseguir identificar onde se encontra as páginas.
Esrou me referindo a isso:
class MidiaExibirComponent
class MidiaService
Comment: @wladyband você já desenvolvel algo em Angular? É pra web ou pra mobile (ionic)? Porque é assim, Angular você usa de "maneira" livre, cria a classe, cria o template, no caso o HTML ali pode ir dentro de um documento foo.html e carregar assim no seu `.ts` `templateUrl: "foo.html"`, se quiser injetar o HTML dentro do .ts usaria assim https://pastebin.com/4NASVzvS
Comment: entendi, vou pegar seu código e realizar os testes, muito obrigado
Comment: @wladyband mas é um projeto WEB ou é um aplicativo hibrido (ionic por exemplo) para celular?
Comment: é um projeto web em angular 4
Comment: @wladyband e como estruturou a primeira página? Chegou a criar alguma página a mais, tipo uma "página 2" ou "página de contato"? ps: só pra constar  `...` no código que postei acima é de exemplo, é pra dizer que ali iria mais códigos, mas a ideia é que se conhece o básico do Angular vai entender aonde é o construtt e aonde vão os métodos ;)
Comment: você respondeu certo minha pergunta, foi eu que fiz a pergunta mau feita, mesmo assim muito obrigado, vou ver se faço uma nova postagem e dessa vez criando uma pergunta mais completa.
Comment: @GuilhermeNascimento como pegar a "img" do **content:encoded**, que é onde tem o src da img?


Given an inequality on the $\limsup$ of the infimums of functions, construct a sequence of points matching it

Question: Let $(X,d)$ be a metric space, and let $f$ be a real valued function defined on $X$. Let $f_n$ be a sequence of real valued functions defined on $X$.
Fix $u \in X$
Assume that for every $\delta > 0, \limsup_{j\to\infty} \inf\{f_j(v): d(u,v) <\delta \} \leq f(u)$
Then, the claim is that there exists a sequence $\{u_j\}$ which converges to $u$ in $X$ such that
$$\limsup_{j\to\infty} f_j(u_j) \leq f(u) $$

To prove the claim, here is wht I tried:
Let $u_n$ such that
$$f_n(u_n) < \inf \{f_n(v): d(u,v) < \frac{1}{n} \} + \frac{1}{n} $$ Then, I took the limsup of both sides, but then my "delta" $\frac{1}{n}$ shrunk to zero, so I cannot conclude what I want.
How should I proceed?
Answer: The problem becomes more transparent if it is recast in terms of the epigraph of $f_j$, which is the set
$$E_j = \{(v,y): y\ge f_j(v) \}\subset X\times \mathbb{R}$$
The given condition says: for every $\epsilon>0$ and every $\delta>0$, for all large enough $j$ there is a point  $(v,y)\in E_j$ such that $d(u,v)<\delta$ and $y = f(u)+\epsilon$.  (Indeed, this is saying that $f_j(v)\le f(u)+\epsilon$.)
We can simplify this by using $\epsilon=\delta$, and  then reword the assumption concisely as
$$\operatorname{dist}((u,f(u)), E_j)\to 0 \tag{1}$$
(This refers to a metric on the   product $X\times \mathbb{R}$; for example the metric $\rho ((v,y),(w,z)) = d(v,w) + |y-z|$ will do.)
Now the solution is immediate: pick a point $(v_j,y_j)\in E_j$ such that
$$\rho( (u,f(u)), (v_j,y_j)) < \operatorname{dist}((u,f(u)),E_j) +\frac1j  $$
Then $\rho( (u,f(u)), (v_j,y_j))\to 0$, which implies both $v_j\to u$ and $\limsup f(v_j) \le f(u)$.
Comment: From $y_j\to f(u)$ and $f(v_j)\le y_j$.
Comment: I don't understand the part that begins with " The given condition says:..". How do I know that there is a point in $E_j$?
Comment: Expanded to clarify.
Comment: What I do not understand is that the given condition is for the limsup of inf of $f_j$ over the $\delta$ neighborhood of $u$. So, all I can deduce is that for any $\epsilon$ and any $\delta$, for all large enough j, $\inf \{f_j(u): d(u,v) < \delta \} \leq f(u) + \epsilon$. Am I missing something?
Comment: Yes, this is correct. Use $\epsilon/2$ here: $\inf \{f_j(u): d(u,v) < \delta \} \leq f(u) + \epsilon/2$, then there is $v$ such that $f_j(v)\le f(u)+\epsilon$.
Comment: I understand it now. My last question is, can you explain to me how you get $\limsup f(v_j) \leq f(u)$ in your last sentence?
Comment: thank you very much for your patience :)


How to compute this integral involving sech?

Question: Does anybody know how to so solve this integral:
$$
\int\limits_{-\infty}^{+\infty}\text{sech}(t-h)\,e^{ikt/\epsilon}\,\mathrm{d}t
$$
and where $h\in \mathbb{R}$ is a constant, $k\in\mathbb{Z}$ and $\epsilon>0$.
Comment: Is complex analysis a tool that may be used?
Comment: Is $h\in\mathbb{R}$? If not, that would complicate matters.
Comment: If $h$ is real, this is a Fourier transform. @Ambesh is this for homework?
Comment: I think you might want to consider the [stationary phase approximation](http://en.wikipedia.org/wiki/Stationary_phase_approximation)...or method of steepest descent, whichever (I always get them confused!).
Comment: @AlexNelson I'm not very good in complex analysis. I guess that must be the way. I tried with some software without results. Is there any software that can solve this by using complex variable analysis?

$\epsilon$ is small and positive.
Comment: @AlexSchiff $h$ is real. This is not really homework. My aim was to find the Melnikov function of some orbits. And by doing some computations I reached to this integral where I got stuck.
I know about Fourier series, but not Fourier transform. One of my steps was to do the fourier series of a function. That is why the exponential term is there.
Answer: To get simpler (at least typographically) expressions, first we substitute $u = t+h$:
$$\int_{-\infty}^\infty \frac{e^{ikt/\epsilon}}{\cosh (t-h)}\,dt = e^{ikh/\epsilon}\int_{-\infty}^\infty \frac{e^{iku/\epsilon}}{\cosh u}\,du.$$
Also, let's write $c = k/\epsilon$ to simplify notation further.
The integrand is an entire meromorphic function, with simple poles in $i\left(n+\frac{1}{2}\right)\pi,\; n \in \mathbb{Z}$. We evaluate the integral by considering a rectangular contour $C_R$ with vertices at $-R,R,R+\pi i, -R+\pi i$, and letting $R\to \infty$. By the residue theorem,
$$\int_{C_R} \frac{e^{icz}}{\cosh z}\,dz = 2\pi i \operatorname{Res}\left(\frac{e^{icz}}{\cosh z}; \frac{\pi i}{2}\right) = 2\pi i\frac{e^{-c\pi/2}}{\sinh \frac{\pi i}{2}} = 2\pi e^{-c\pi/2}.$$
The integrals over the vertical sides of the rectangle tend to $0$ as $R\to \infty$, since $\lvert e^{icz}\rvert = e^{-c\operatorname{Im} z} \leqslant e^{\lvert c\rvert\pi}$ is bounded independently of $R$, and $\cosh (\pm R + it)\to \infty$ uniformly for $t\in[0,\pi]$ as $R\to\infty$.
For the integral over the side on the line $\operatorname{Im} z = \pi$, since $\cosh (z+\pi i) = - \cosh z$, we obtain
$$\int_{-R+\pi i}^{R+\pi i} \frac{e^{icz}}{\cosh z}\,dz = \int_{-R}^R \frac{e^{icz}e^{-c\pi}}{-\cosh z}\,dz = -e^{-c\pi}\int_{-R}^R\frac{e^{icz}}{\cosh z}\,dz,$$
so
$$2\pi e^{-c\pi/2} = \left(1+e^{-c\pi}\right)\int_{-\infty}^\infty \frac{e^{icu}}{\cosh u}\,du,$$
and
$$\int_{-\infty}^\infty \frac{e^{icu}}{\cosh u}\,du = \frac{2\pi e^{-c\pi/2}}{1+e^{-c\pi}} = \frac{2\pi}{e^{c\pi/2}+e^{-c\pi/2}} = \frac{\pi}{\cosh \frac{c\pi}{2}}.$$
Expanding $c$ and gathering the factor from the substitution at the beginning,
$$\int_{-\infty}^\infty \frac{e^{ikt/\epsilon}}{\cosh (t-h)}\,dt = e^{\large \frac{ikh}{\epsilon}}\frac{\pi}{\cosh \frac{k\pi}{2\epsilon}}.$$
Comment: @Ambesh He first thought the contour enclosed two poles, $\pi i/2$ and $-\pi i/2$, and therefore, that I forgot one residue. But he misread the contour, hence his "Nevermind" edit.
Comment: Are you missing the residue at $-\frac{\pi i}{2}$? Or am I mistaken? EDIT: Nevermind, read the contour incorrectly.
Comment: Just ignore my comment, sorry.
Comment: I figured out Wolfram Alpha's syntax for Fourier transforms, and it  [agrees with](http://www.wolframalpha.com/input/?i=Exp%5B%28i*k*h%29%2Fepsilon%5D*Sqrt%5B2Pi%5D*FourierTransform%5BSech%5Bx%5D%2Cx%2Ck%2Fepsilon%5D) @DanielFischer's answer.
Comment: @AlexSchiff What do you mean? The residue is not right?
Comment: Thank you @DanielFischer, and to all of you. I will review all the steps to understand this method.
Answer: A related problem. Here is another approach using the Mellin transform technique. First we write the integral as

$$ I = \int\limits_{-\infty}^{+\infty}\text{sech}(t-h)\,e^{ikt/\epsilon}\,\mathrm{d}t= e^{\frac{ik}{\epsilon}} \int\limits_{-\infty}^{+\infty}\text{sech}(t)\,e^{ikt/\epsilon}\,\mathrm{d}t= 2\,e^{\frac{ik}{\epsilon}} \int\limits_{-\infty}^{+\infty}\frac{e^{ikt/\epsilon}}{e^{t}+e^{-t}}\,\mathrm{d}t.  $$

To finish the problem follow the technique.


Jquery Horizontal Accordion Webkit Bug

Question: I'm trying to build a horizontal accordion with Jquery.  It seems to be working "ok" in Firefox.  But in Webkit (Safari 3 + 4, and Chrome) the sub-level UL flashes after the Hide function.  Any help would be greatly appreciated. To see a working demo: http://ableobject.com/horaccordion1.html
Here is what I'm working on:

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

    <title>untitled</title>

                    Top-level 1

                    Top-level 2

Bottom Level A1

Bottom Level A2

Bottom Level A3

Bottom Level A4

                    Top-level 3

Bottom Level B1

Bottom Level B2

                    Top-level 4

Answer: This sounds like it is related to an issue I had a little while ago with webkit. There is a webkit bug that sometimes causes an element's parent to revert to its original size after an animation that reduces the elements' width. After the animation, the element's parent jumps back to its original size in order to accommodate its content.
Edit: Removed comments about jQueryUI. Not sure why I thought you were using it.
The bug was discussed here, which details a workaround.
I submitted a bug report to jQuery as well.
Basically, you would need to  simultaneously reduce the width of your $sub element's parent by the same amount as $sub is being reduced. So if the width of $sub is 100px, there would be a separate animate() to reduce the parent by 100px.
I haven't tested any of this with your example, but I think it is probably the key.
Edit 2:
A new version using divs
CSS:
.title {
       list-style: none;
       margin: 0;
       padding: 0;
       float: left;
       height: 32px; /* For testing */
       font-family: helvetica;
       font-size: 18px;
       clip: auto; overflow: hidden;
}
.menu {
       height: 32px; /* For testing */
       clip: auto; overflow: hidden;
       float: left;
}
a, a:link, a:hover, a:visited, a:active {
       color: black;
       text-decoration: none;
       padding: 12px;
       font-weight: 700;
       float: left;
       color: #222;
}

 .menu a, .menu a:link, .menu a:hover, .menu a:visited, .menu a:active {
   color: black;
   text-decoration: none;
   padding: 12px;
   font-weight: normal;
   float: left;

}
javascript:
    // Prevents us from having to check for null.
    var $current = $('#someFictionalElement');
    var $previous = null;
    $(document).ready(function(){
    $(".menu").css({width: 0});  // hide submenus by default on load

    $(".title").click(
        function() {
            $previous = $current;
            $current = $(this);
            var $currentMenu = $current.next();

            $previous.next().animate({ width: 0 }, {duration: 1000, queue: false} );

    // Make sure that if there's no menu text (like Top Level 1 and 4) that it does not animate.
    // This is because of the pixels added for Firefox (see comment below)
            if( $currentMenu.width() == 0 && $currentMenu.text() != ''  ) {

    // Expand the menu but keep it hidden so we can get its width
                $currentMenu.css({visibility: 'hidden', width: ''});

    // Store the width, and add a few pixels for Firefox
                var currentWidth = $currentMenu.width() + 3;

    // Make menu visible and set with to 0 in preparation for the animation
                $currentMenu.css({visibility: 'visible', width: 0})
                            .animate({ width: currentWidth }, 1000);
            }
    });

    $(".title a").hover(
        function(){$(this).animate ({ opacity: 0.7 }, 200);},
        function(){$(this).animate ({ opacity: 1 }, 600);}
    );
});

HTML:

            Top-level 1

            Top-level 2

            Bottom Level A1
            Bottom Level A2
            Bottom Level A3
            Bottom Level A4

            Top-level 3

            Bottom Level B1
            Bottom Level B2

            Top-level 4

Comment: I've tried it out http://ableobject.com/horaccordion2.html but when I'm going from Toplevel 4 from an expanded Toplevel 3 it still flashes.  I'll try to figure it out and repost... but at the moment the solution escapes me.
Maybe:

  $sub.parent().css({ width: '' });
             $current = $sub;

?
Comment: How important is the use of 'list' elements to you? After finally ditching them and using div's, I came up with a fairly concise accordion that works in webkit.
Comment: Its not all that important, I just didn't want to define widths for the list items (or, divs).
Comment: No need to set widths on divs when you float left. Not sure if this is the best way, but you don't have the webkit flashing problem anyway. It's the cleanest and most concise way I could find. Only weird thing was a Firefox fix that was needed (see code comments). Hope its helpful.
Comment: great, thanks patrick. There seems to be another issue with webkit about center-aligning the menu.
It works in Firefox by using
display: table;
margin: 0 auto;
and ie IE using
text-align: center;
on #container
but webkit won't doesn't work!
Thanks for all your help!
Comment: Yes, I see. Looks like webkit is actually centering it, but the width #container is still expanded as though all the menu items are shown. If you give the #container a background color, and make your browser window wide enough, you'll see that it is actually centered. (If your screen isn't big enough, you would need to delete some menu items to see the effect.) I'll play around some more and see if I can come up with something.
Answer: I'm posting this as a separate answer just in case you still find the previous one useful.
Please note the following:

I have not tested this in ie.
This goes back to a 'nested' version, so I changed the class and variable names a little.
An empty menu is no longer needed when there is no menu to display.
The width of each menu's 'container' is now being reduced the same amount as the menu. This is what eliminates webkit's temporary flash (which was the original strategy).
You'll notice the the timing of the animation of the menu is slightly different than that of the menu's container. Basically, you want the container to be a little ahead when expanding, and the menu to be a little ahead when reducing. If the timing is set to be equal, you can get some flashing of the menu.
As explained in the comments, at the beginning, each menu 'memorizes' its width when fully expanded by setting a previously non-existent attribute called 'fullWidth'. It then retrieves the value of this attribute when needed. You could just as easily use global variables, or jQuery's data() function to store the info. The point is that things are simplified if each menu is aware of how wide it should be when it is expanded.

So here it is. Hope it helps!
CSS
#container {
    margin: 0 auto 0 auto;
    text-align: center;
    display: table;
}

.menuContainer {
       margin: 0;
       padding: 0;
       float: left;
       height: 32px; /* For testing */
       font-family: helvetica;
       font-size: 18px;
       clip: auto; overflow: hidden;
}
.menu {
       height: 32px; /* For testing */
       clip: auto; overflow: hidden;
       float: left;
}
a, a:link, a:hover, a:visited, a:active {
       color: black;
       text-decoration: none;
       padding: 12px;
       font-weight: 700;
       float: left;
       color: #222;
}

.menu a, .menu a:link, .menu a:hover, .menu a:visited, .menu a:active {
   color: black;
   text-decoration: none;
   padding: 12px;
   font-weight: normal;
   float: left;
}

javascript
var $currentMenuContainer = $('#someFictionalElement');
var $previousMenuContainer = null;

$(document).ready(function() {

// Iterate through each .menu element, setting the full width of each menu to a 'custom'
//        attribute called 'fullWidth'. Since the full width should never change, this
//        makes it easy to recall it quickly. You could use global variables instead.
// After setting 'fullWidth', it then collapses each menu and title.
$(".menu").each(function() {
    var $theMenu = $(this);
    var $theMenuContainer = $theMenu.parent();
    $theMenu.attr({fullWidth: ($theMenu.width() + 3)});   // Add a few pixels for firefox
    var menuContainerWidth = $theMenuContainer.width() - $theMenu.attr('fullWidth') + 6;  // Add DOUBLE the pixels here
    $theMenu.css({width: 0});
    $theMenuContainer.css({width: menuContainerWidth});
});

    $(".menuContainer a").click(
        function() {
// Set the current and previous elements properly
            $previousMenuContainer = $currentMenuContainer;
            $currentMenuContainer = $(this).parent();
            var $previousMenu = $previousMenuContainer.find('.menu');
            var $currentMenu = $currentMenuContainer.find('.menu');

// Collapse the previous menu
            $previousMenu.animate({ width: 0 }, {duration: 480, queue: false} );

// Subtract the width of the previous menuContainer's menu from the menuContainer (only if its menu is displayed)
            if($previousMenu.width() > 0) $previousMenuContainer.animate({width: ('-=' + $previousMenu.attr('fullWidth'))}, 500);

// Expand the current menu and its menuContainer if it's not showing
            if($currentMenu.width() == 0) {
                // Increase the menuContainer width by the full width of its menu
                $currentMenuContainer.animate({width: ('+=' + $currentMenu.attr('fullWidth'))}, 480);
                // Increase the menuContainer to its full width
                $currentMenu.animate({ width: $currentMenu.attr('fullWidth') }, 500);
            }
    });

    $(".menuContainer a").hover(
        function(){$(this).animate ({ opacity: 0.7 }, 200);},
        function(){$(this).animate ({ opacity: 1 }, 600);}
    );
});

HTML

        Top-level 1

        Top-level 2

            Bottom Level A1
            Bottom Level A2
            Bottom Level A3
            Bottom Level A4

        Top-level 3

            Bottom Level B1
            Bottom Level B2

        Top-level 4

Edit: Add the following DTD to the top of your page-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

Comment: This works great, now if i can only figure out how to center it in IE :)
Comment: I'm encountering a strange bug in Firefox... I've changed the link size to 16px, and now the Bottom Level A4 disappears?  I've tried adding more (and less) pixels... and playing with the padding... I can't seem to get it to show up
Comment: For ie to center, add the following to the very top of the page.
I think I should be able to figure out the Firefox issue. Will probably get back to you on Monday.
Comment: OK, I actually got it pretty quick. I've corrected the .each() method in the javascript. How ever many pixels are added to the menu, twice as many need to be added to the menu's container.
Comment: Everything is working well, I'm converting it to work with Ems as well.   doesn't seem to center it, neither does containing it with .  I've put a test up at http://ableobject.com/horaccordion.html

Jquery Horizontal Accordion Webkit Bug


Adding existing entity to navigation property of a different entity

Question: I'm using EF4 and I'm running into a problem when I try to do something that looks quite trivial to me.
I have two entities, let's call them A and B. These entities have a many-to-many association between them with a navigation property on A that contains a list of related B entities.
What I want to do is to add existing B entities to a new A entity. When I try to do that, I get an exception:

AcceptChanges cannot continue because
  the object's key values conflict with
  another object in the
  ObjectStateManager. Make sure that the
  key values are unique before calling
  AcceptChanges.

Has anyone run into such a problem?
More info that might be relevant:

I've created the DB from the model.
I have a base entity that both A and B entities inherit from.

Update: Found a solution - detach the linked entity and re-attach it to the context, then everything goes as planned.
Comment: Have you read this?
http://stackoverflow.com/questions/1008582/invalidoperationexception-when-calling-savechanges-in-net-entity-framework

Double checked that PK's and ID props are configured correctly?
Comment: Checked that now. Everything looks OK...
Comment: Might be related to this:- http://stackoverflow.com/questions/2777034/complex-entity-framework-linked-graphs-issue-how-to-limit-change-set-break-the
Comment: Can you post some code showing the adding and saving changes steps and the objectcontext around this?
Answer: I had a similar problem today. In my case my table was a view and I had addded a stored procedure for the InsertFunction. Trouble was that I did not confiugre result bindings from my stored procedure. The symptom was that I could add a single entity fine but got an "key values conflict" exception when adding multiple entities.
Once I made the stored procedure return the new ID (key) and then configured the EF's result biding all was fine.
To the end of the stored procedure add something like this:
select SCOPE_IDENTITY() as NewWidgetId

In the EF config set the result binding:
NewWidgetId -> WidgetId : <widget's type>

I found this site helpful: Using Stored Procedures for Insert, Update & Delete in an Entity Data Model
Hope this helps
Rob Smyth


GAM: Do shrinkage smooth splines also address for concurvity?

Question: I have a gam model with automatic predictor selection based on cubic splines (bs = cr) and SELECT == T or shrinkage cubic splines (bs = cs) and SELECT == F.
Now I'm wondering if predictors affected by concurvity are automatically dropped from my model by the shrinkage methods, or if I should remove them from the model myself after checking for concurvity.

My Model looks like this:
genericModel <- mgcv::bam(formula = TT2_ScaledTransformed ~
            s(NDVI, k = k, bs = cr) + ... +
            s(BuildingHeight_10m_10std, k = k, bs = cr),
            data = trainSet,
            family = gaussian, method = "fREML", select = TRUE,
            control = ctrl,
            cluster = cl, gamma = 1.4)

E.g. in this example, BuildingHeight and NDVI (Index for Vegetation) are partly concurved, because these two parameter are partly inverse.
And I check for concurvity like this:
print(concurvity(genericModel, full = TRUE))

And I evaluate my model based on AIC.
Answer: In short, no, using select = TRUE doesn't automatically drop concurved terms. You should still check the concurvity of the terms in the resultant model, and decide whether to drop terms or not for highly concurved ones, checking how the other estimated terms change when you drop a concurved term.
That said, fitting with method = "REML" (or "ML" or "fREML" depending on context) and select = TRUE is likely the best protection against the issues raised by concurved terms in the model that we have if you don't want to or can't drop concruved terms.


How to make vocal growl less airy?

Question: I can growl (Tim Foust/Avi Kaplan-style), but my low growl notes sound very airy.
Is there any way to get them to sound "fuller"? Or at least minimise the wind-like noise?
Comment: Can you give us an audio clip of what you're going for?  When I read "growl" I think of death metal, but you're referencing one country and one a capella singer, so I'm a bit confused.
Comment: @Sarkreth I'm pretty sure this one's a bass technique. It's in some of those vocal range videos, it's their lowest notes. https://www.youtube.com/watch?v=x3i1D22zszM
Answer: To minimise wind noise a few things come to mind.

Use a pop shield (however I imagine you are already).
Place the microphone off axis from the vocalist so that the "wind" doesn't directly fall onto the diaphragm of the microphone.

It could be down to the type of microphone you are using, the frequency response and acoustics.
Generally compression, EQ (away form the high end for the growl possibly), de-essers, noise gates and any typical type of processing would help, particularly for "fullness ".A Focusrite Voicemaster is a good bit of kit to look at which has all the vocal processing things you may consider to beef up the sound.
Hope this helps!

How to make vocal growl less airy?


How to prove $\int_{0}^{\infty}\frac{e^{-mr}}{r}e^{-i\overset{\to}{q}\cdot \overset{\to}{r}}d^3 r=\frac{4\pi}{m^2+q^2}?$

Question: I would really appreciate if someone could help me about the  following: $$\int_{0}^{\infty}\frac{e^{-mr}}{r}e^{-i\overset{\to}{q}\cdot \overset{\to}{r}}d^3 r=\frac{4\pi}{m^2+q^2}?$$
where $r=|\overset{\to}{r}|$, $q=|\overset{\to}{q}|$, $\overset{\to}{q}$ and $\overset{\to}{r}$ are three dimensional vectors, and $m$ is an scalar.
Thanks in advance.
What I've tried: using spherical coordinates, we have $d^3 r=dxdydz=r^2dr\sin \theta d\theta d\phi$, where $0\leq r<\infty$, $0\leq \theta \leq \pi$, and $0\leq \phi \leq 2\pi$. Then $$\int_{0}^{\infty}\frac{e^{-mr}}{r}e^{-i\overset{\to}{q}\cdot \overset{\to}{r}}d^3 r=\iiint \frac{e^{-mr}}{r}e^{-irq\cos\theta}r^2dr\sin \theta d\theta d\phi$$ $$=2\pi \iint \frac{e^{-mr}}{r}e^{-irq\cos\theta}r^2dr\sin \theta d\theta,$$ $$=2\pi \iint e^{-mr}e^{-irq\cos\theta}rdr\sin \theta d\theta,$$ where $r=|\overset{\to}{r}|$ and $q=|\overset{\to}{q}|$. Now how can I compute the last integral?
Comment: What is $d^{3}r$?
Comment: What is division by a vector $r$? Are you writing $\int_0^{\infty}$ for a triple integral? Please try to use standard notations from Calculus.
Comment: @geetha290krm you are right. sorry. I've just edied my question.
Comment: I suppose that the same symbol $r$ is here used for both the position vector $(x_1,x_2,x_3)$ (or $(x,y,z)$ if you prefer) and for the length of it (i.e. the distance from origin). In $e^{-imr}/r$ it is a scalar, while in $e^{-iq\cdot r}$ it is a vector (and so is $q$).
Comment: @md2perpe This question comes from the form factor in particle physics. This is an exercise that I couldn't understand. I think you are right.
Comment: If $m$ and $q$ are both scalars, then we have $e^{-imr} e^{-iqr} = e^{-i(m+q)r}$ so the result should contain $m+q,$ not $m^2+q^2.$ Likewise, if $m$ and $q$ are both vectors, we would have $|m+q|$ in the result.
Comment: Also, I think that the integral should be over 3 dimensions (and all of space). Otherwise, when we have made one $r$ into the position vector, we don't know which position vector we should take for each radius $r$.
Comment: Hint: write the integrand as $\lim_{a\rightarrow 0 } \frac{e^{-i (m+q) r}}{r+a}$
Comment: @md2perpe By your good comments, I've just edited my question. Thank you four comments.
Comment: @geetha290krm I've used standard notations from Calculus. Thanks for the comment.
Comment: I don't think there should be an imaginary unit in $e^{-imr}$ but just be $e^{-mr}.$ With the latter I get the expected result.
Comment: @md2perpe Yes, $e^{-mr}$ is right.  Could you please wirte me your answer? I couldn't finish it. Thank you very much.
Comment: You will see it in a while.
Comment: @md2perpe Appreciate it.
Comment: Hint: let $u=\cos\theta$
Answer: We want to evaluate the following integral:
$$
I := \iiint_{\mathbb{R}^3} \frac{e^{-mr}}{r}e^{-i\mathbf{q}\cdot\mathbf{r}} \, \mathrm{d}^3 r,
$$
where $m$ is a constant scalar, $\mathbf{q}$ is a constant vector, $\mathbf{r}$ is the position vector $(x,y,z)$ and $r=|\mathbf{r}|=\sqrt{x^2+y^2+z^2}$ is the distance from origin to the position.
Because of symmetry we can assume that $\mathbf{q} = q\hat{z},$ where $q$ is a scalar and $\hat{z}$ is the unit vector in the $z$ direction. We then have
$$
I
= \iiint_{\mathbb{R}^3} \frac{e^{-mr}}{r}e^{-q\hat{z}\cdot\mathbf{r}} \, \mathrm{d}^3 r
= \iiint_{\mathbb{R}^3} \frac{e^{-mr}}{r}e^{-iqz} \, \mathrm{d}^3 r
.
$$
Introducing spherical (polar) coordinates,
$$
\mathbf{r} = (x,y,z) = (r\sin\theta\cos\phi, r\sin\theta\sin\phi, r\cos\theta),
$$
we get
$$
I = \int_{r=0}^\infty \int_{\theta=0}^\pi \int_{\phi=0}^{2\pi}
\frac{e^{-mr}}{r} e^{-iqr\cos\theta}  \, r^2 \sin\theta \, \mathrm{d}\phi \, \mathrm{d}\theta \, \mathrm{d}r
\\
= 2\pi \int_{r=0}^\infty \int_{\theta=0}^\pi r e^{-mr} e^{-iqr\cos\theta} \, \sin\theta \, \mathrm{d}\theta \, \mathrm{d}r
\\
= 2\pi \int_{r=0}^\infty r e^{-mr} \left[ \frac{1}{-iqr} e^{-iqr\cos\theta} \right]_{\theta=0}^\pi \mathrm{d}r
\\
= 2\pi \int_{r=0}^\infty r e^{-mr} \frac{1}{iqr} \left( e^{iqr} - e^{-iqr} \right) \mathrm{d}r
\\
= \frac{2\pi}{iq} \int_{r=0}^\infty \left( e^{-(m-iq)r} - e^{-(m+iq)r} \right) \mathrm{d}r
\\
= \frac{2\pi}{iq} \int \left[ \frac{1}{-(m-iq)}e^{-(m-iq)r} - \frac{1}{-(m+iq)}e^{-(m+iq)r} \right]_{r=0}^\infty \mathrm{d}r
\\
= \frac{2\pi}{iq} \left( -\frac{1}{-(m-iq)} + \frac{1}{-(m+iq)} \right)
\\
= \frac{2\pi}{iq} \frac{2iq}{m^2+q^2}
= \frac{4\pi}{m^2+q^2}
.
$$
Comment: I really appreciate your nice explanation and your help. I got it properly. Thanks very much.
Answer: We can also view the integral as the Fourier transform of $f(\mathbf{r}) := \frac{e^{-m|\mathbf r|}}{|\mathbf r|\}.$
As a distribution, $f$ satisfies the differential equation
$\Delta f - m^2 f = -4\pi\delta,$
where $Delta$ is the Laplace operator.
Taking the Fourier transform of this equation gives
$$-|\mathbf{q}|^2 \hat f(\mathbf{q}) - m^2 \hat f(\mathbf{q}) = -4\pi$$
i.e.
$$
\hat{f}(\mathbf{q}) = \frac{4\pi}{m^2+|\mathbf{q}|^2}.
$$
The "hard" part here is to show that $f$ satisfies that differential equation. For $r>0$ a direct calculation gives $\Delta f = m^2 f.$ At origin we essentially have a $\frac{1}{r}$ behavior, contributing with $\Delta(\frac{1}{r}) = -4\pi\delta.$
Comment: @Jakob. Yes, it is the most general solution, since $m^2+q^2$ has no zeros (unless $m=0$).
Comment: @Jakob. If $m=0$ then we have $q^2$ as a factor and we could add both a $A \delta(\mathbf q)$ term and a $\mathbf B\cdot\nabla\delta(\mathbf q)$ term, where $A$ and $\mathbf B$ are constants.
Comment: But $\hat f(q)=4\pi/m^2+q^2$ is not the most general solution to your second equation, no? So you need some boundary condition or similar to single out this solution, no?!
Comment: Ah, you're right, I was missing this. Thank you for the respond. Because if we have $=0$, then $+\mathrm{const.}\delta()$ could be added to $$, correct? But, as you point out, since $m^2+q^2\neq 0$, here this would amount to trivially add a zero.


How can I prove $\det(\overline M)=\overline{\det(M)}$?

Question: Of course $\overline M$ is the complex conjugate of an $n\times n$ matrix $M$.
Someone gave me advice to use the definition of determinant, then it means I have to use cofactor expasion here?
Comment: It is easier with the closed expression of $\det(A)$ as a sum over all permutation in $n$ : $\det(A)=\sum_{\sigma \in S_n}sgn(\sigma)\cdots$
Comment: Antoine's answer is great and transparent. As an alternative, you can triangularize $M=PUP^{-1}$ and observe that this reduces to the upper triangular case where the determinant is just the product of the diagonal terms. The only trick is to observe that $\overline{P^{-1}}=\overline{P}^{-1}$. But I would still go with Antoine's answer.
Answer: You have the following definition of the determinant:
$$\det(M) = \sum_{\sigma\in\mathfrak{S}_n}\varepsilon(\sigma)\prod_{i=1}^{n}m_{i,\sigma(i)}.$$
Then one has $$\det(\bar M) = \sum_{\sigma\in\mathfrak{S}_n}\varepsilon(\sigma)\prod_{i=1}^{n}\bar m_{i,\sigma(i)} = \sum_{\sigma\in\mathfrak{S}_n}\varepsilon(\sigma)\overline{\prod_{i=1}^{n}m_{i,\sigma(i)}} = \overline{\sum_{\sigma\in\mathfrak{S}_n}\varepsilon(\sigma)\prod_{i=1}^{n}m_{i,\sigma(i)}} = \overline{\det M},$$ all this equalities holding because conjugation is a $\mathbb R$-algebra homomorphism.
Comment: Sorry, I can't understand some of your notations. Can you explain it more simply just appropriate to linear algebra level?
Comment: @postman you can read wikipedia for the permutation definition of determinant.
Answer: If you want to use the Laplace development (cofactors), then you can do it by induction.
The case for $1\times1$ matrices is obvious, so let $n>1$ and assume the result for $(n-1)\times(n-1)$ matrices.
If $A=[a_{ij}]$ is an $n\times n$ matrix, denote by $A_{ij}$ the matrix obtained by removing the $i$-th row and the $j$-th column. To not complicate notations, let $B=\bar{A}=[b_{ij}]$ with $b_{ij}=\overline{a_{ij}}$.
The expansion of $\det B$ along its first line is
$$\det B=(-1)^{1+1}b_{11}\det B_{11}+(-1)^{1+2}b_{12}\det B_{12}+\dots+
(-1)^{1+n}b_{1n}\det B_{1n}$$
By induction hypothesis, $\det B_{ij}=\overline{\det A_{ij}}$, so you can write
\begin{align}
\det B&=
(-1)^{1+1}\overline{a_{11}}\,\,\overline{\det A_{11}}+
(-1)^{1+2}\overline{a_{12}}\,\,\overline{\det A_{12}}+\dots+
(-1)^{1+n}\overline{a_{1n}}\,\,\overline{\det A_{1n}}
\\[4pt]
&=
(-1)^{1+1}\overline{a_{11}\det A_{11}}+
(-1)^{1+2}\overline{a_{12}\det A_{12}}+\dots+
(-1)^{1+n}\overline{a_{1n}\det A_{1n}}
\\[4pt]
&=\overline{
  (-1)^{1+1}a_{11}\det A_{12}+
(-1)^{1+2}a_{12}\det A_{12}+\dots+
(-1)^{1+n}a_{11}\det A_{1n}
}
\\[4pt]
&=\overline{\det A}
\end{align}


lazyload.js requiring action to display images on initial load

Question: I am using the lazyload.js library to lazy load images that are dynamically loaded into an infinitely-scrolling view. After I start scrolling and loading the next pages of results, the lazyloading works just fine.
Upon initial load, the images do not lazyload in until some action occurs in the window, be it a slight scroll, clicking on a clickable element in the container, etc. If I put a timer on the call to $('.lazy').lazyload(), it works fine but I do not want to do that (it's very hacky).
After the initial load if I run $(window).resize() from the javascript console, the images load in just fine, but even if I do this in code after the initial load, it does not work.
Is there a way I can force the images to lazyload upon initial loading?
Note that the images are placed onto the page after the initial page load via an AJAX call.
Answer: I am personally not a fan of lazyload.js (the performance is terrible) but that should actually work out of the box. The loading should be triggered on document ready.
Given that resize doesn't seem to work either, can you verify that these events actually fire? Perhaps something is off with your HTML (doctype, or god-knows-what).
Comment: Do you have anything you'd recommend as opposed to lazyload.js?
Comment: I'm biased, I implement lazy loading with jQuery.isInView because I have written the thing. Another contender would be jquery.visible, it is the (cough) second-best in terms of speed. I have tested a bunch of components here: http://output.jsbin.com/lisudi/3 . Maybe that can help you to pick one which works for you, depending on the number of lazy-loading items on your page. For smooth scrolling, you have to finish the job in less than 16ms (on the slowest platform you plan to support).
Comment: so I just implemented isInView and still the same issue! I have to do a SLIGHT scroll in order for anything to show up. I'm starting to think it's something I'm doing wrong, hah. I don't get it.
Comment: Actually @hashchange this seems to only be an issue some of the time...I am dynamically loading my images into a container via an AJAX call on a single page app when this module loads, do you have any recommended methods of calling my `lazyLoadImages` method (which contains the isInView code) until the images are loaded, or something to that effect?
Comment: Can't really give you advice without seeing the code. But if you can come up with a bare-bones, minimal demo and post it on JS Bin or the like, I'll give it a shot (briefly, I'm afraid, no extensive debugging).


Calculating a Point's X position on Catenary Curve, given pos Y

Question: How can I calculate for the X coordinate given the Y value of the position? In this example the Y position is -3 units, as seen in the image below.
https://en.wikipedia.org/wiki/Catenary
We know the Span = 100 (width) and the Sag = -10 (height). I'm not sure where to begin in solving for the two points X position marked yellow in the image below.
If for any reason it's easier to solve for the X position on a Parabola rather than a Catenary I'm fine with that, they are similar enough it would be ok.
Comment: Have you tired using the values you know and the general form of the catenary curve? i.e. when $x$ is $0$, $y$ is $-10$, or when $x$ is $50$, $y$ is $0$?
Answer: For a parabola, this isn't hard at all. The parabola equation is then
$$
y = -10 + 10 \left (\frac{x}{50}\right)^2
$$
To solve for $y= -3$, you write
\begin{align}
-3 &= -10 + 10 \left (\frac{x}{50}\right)^2\\
7 &=  10 \left (\frac{x}{50}\right)^2\\
\frac{7}{10} &=  \left (\frac{x}{50}\right)^2\\
\sqrt{\frac{7}{10}} &=  \pm \frac{x}{50}\\
50 \sqrt{\frac{7}{10}} &=  \pm x\\
\pm 50 \sqrt{\frac{7}{10}} &=  x
\end{align}
giving $x \approx \pm 41.83.$


Standard deviation vs standard error of the mean for intervals

Question: I couldn't find a question like this anywhere on Cross Validated. Also I struggled to write the title for this question.
Imagine I have a satellite picture of a straight road, and I expect that the number of cars per unit length is roughly constant. I choose a section of the road, and split it into $N=10$ equal intervals. I then find the number of cars per unit length for each interval, $x_i$ for $i$ in range 1 to 10.
I then calculate the mean number of cars per unit length
$\hat{\mu} = \bar{x} = \sum\limits_{i=1}^N \frac{x_i}{N}$,
and the sample standard deviation
$\hat{\sigma} = s = \sqrt{\frac{N}{N-1} (\sum\limits_{i=1}^N \frac{x_i^2}{N}-\hat{\mu}^2)}$
I want a value for the error in the mean number of cars per unit length. So, I think, I must find the estimated standard error of the mean, $\frac{s}{\sqrt{N}}$.
However, does this not mean that if I shrink the length of my intervals whilst increasing the number of intervals $N$ so that it still covers the same section of the road, I will get a lower standard error of the mean? Isn't this reduction of the error value cheating? It leads me to believe that I should use the standard deviation as my error value.
But what if I increase the range of my section, so that I genuinely have a higher $N$? I do expect to have a lower error in that case.
Which should I use, and have I made a mistake in my thinking somewhere?
Comment: You used $\mu$ and $\sigma$ for sample mean and standard deviation, when conventionally those symbols represent population quantities. This can lead to errors and misunderstandings, so I've put hats on them to make it clear we're discussing estimates of $\mu$ and $\sigma$.
Answer: Note that you defined your quantities to be the mean and standard deviation of cars per unit length.
So let's imagine your section is $k$ units long, and you take $n=k$ intervals.
Then your $s$ really does estimate standard deviation of counts-per-unit-length.
Now take $n=2k$ intervals. Is the standard deviation you get from counts in intervals of length $\frac{1}{2}$ the standard deviation per unit length? No, it's the standard deviation of counts per half-unit length.
Those will on average be smaller. They'll be multiplied in effect by a factor of $\sqrt{\frac{1}{2}}$.
So when you now divide $s$ by $\sqrt{n}=\sqrt{2k}$, you're computing the standard error of the mean-per-half-unit-length, which is not what you wanted at all. Of course it gets smaller when you do that. You'll have a number that's on average half as big as the thing you were trying to work out.
So when you scale back to the equivalent per unit length, you have to double the mean to get a mean per unit length, and correspondingly, you will have to similarly scale the standard error for the rescaling of the mean (doubling it). There's actually no gain at all (the only difference comes from the small effect of Bessel's correction - the population quantities being estimated scale exactly).
Comment: Your calculation of the mean is defined in your question. With the definition given in your question you are *not computing the mean per unit length*. To make it mean *per unit length*, you must divide by the number of units of length in a segment. If your segments are half a unit long, you divide by 1/2 ... i.e. you must double the average in that half-unit segment to get the *mean per unit length*.
Comment: Then your post no longer makes sense to me. Are you saying that - in spite of saying "I count the number of cars", that $x_i$ is not in fact a count? Please edit your question to either show how many units of length the section of road is, or show how you calculate $x_i$ (and then also change the phrasing so you don't say you count something that's not a count). Do you mean something like "I count the number of cars in an interval and then *scale* that count by dividing by the length of the interval to obtain the number of cars per unit length"?
Comment: Yes, I'm about to do this. Sorry for the hiatus
Comment: Surely you don't have to double the mean, because each (twice as small) interval will contain about half the number of cars?
Comment: Perhaps I didn't make it clear, but $x_i$ is the no. of cars per unit length in the interval
Comment: Your last sentence is what I intended to mean. But, ok, let's imagine $x_i$ is just the count. I find that the mean of the 2nd count (which has twice as many, half as long intervals) is half the mean of the 1st count, i.e., $\hat{\mu_2}=\frac{1}{2}\hat{\mu_1}$, and also $s_2=\frac{1}{2}s_1$ (ignoring Bessel's correction). So when you divide each by the respective lengths of their intervals, you get the same $\hat{\mu}$ per unit length and $s$ per unit length for both. But then, per unit length, $SEM_2=\frac{1}{\sqrt{2}}SEM_1$
Comment: I reached that by plugging $2N$s in place of $N$s, and $\frac{1}{2}x_i$s in place of $x_i$s, in the formulae
Comment: Actually, if the answer to http://stats.stackexchange.com/questions/142343/the-fallacy-of-splitting-data-collection-time-into-shorter-intervals-to-reduce-e/142354#142354 is to be believed, the $s_2$ should be higher for the smaller-and-more-intervals case
Comment: Please edit to clarify your question further.
Comment: That is, please place any clarification in your question, because your question needs to stand on its own, even if all comments were deleted. In particular you need to explicitly describe in your question how $x_i$ is defined/ calculated.
Answer: What you're describing here sounds like a version of the "bias variance tradeoff"
Your concern is that you are getting a free lunch by shrinking the size of your road segments by increasing the total number of segments.  But remember, when you shrink the road segments you increase the variance across segments.  So sure, you are increasing $N$ that, in turn, decreases the standard error in the mean but you are also increasing standard deviation since the number of cars per unit length is now quite different from segment to segment.  For example, many of your segments will likely have zero cars in then as you increase $N$.
There is a related situation in online experimentation where bootstrapping a sample to compute confidence intervals is hard if the sample has tens of millions of measurements.  Kleiner et al proposed a bootstrap that essentially subdivides the large sample array into $N$ non-overlapping segments, computes a metric across each segment, and takes those as bootstrap samples.  So the whole operation is $O(N)$
This is equivalent to your scenario.  In the Kleiner case, it's easier to see the tradeoff.  The smaller $N$ is the less variance from sample to sample I will have since each segment is big enough to include open road stretches, traffic jams, etc... But I will accept a bias sample that those segment car counts will be dominated by traffic jams and I won't ever really "see" a segment of bare road.
The larger $N$ the greater variance I will experience across my bootstrap (segments with just traffic jams, some with just bare road, etc...) but I will reduce bias in that road scenarios with low car counts will surface in the samples.
The solution is to balance the two against each other to achieve your desired outcome.  Do I want an accurate picture of the diversity of road scenarios or a stable measure of the general road congestion for example?
Answer: Your problem description sounds like a Poisson-type scenario. I don't see any issue with how you estimate the number of cars per unit length. Let's take an example.
Suppose your data for 4 units of length are 13, 12, 10, and 13. Taking the entire length, we would estimate the mean number of cars per unit length $\lambda$ as $$\hat \lambda={{13+12+10+13} \over {4}}=12$$ The variance of this estimator is ${\lambda \over n},$ which we would estimate with ${\hat \lambda \over n},$ where $n$ is the number of intervals. So our estimate is $$s^2 ={ {12} \over {4}} = 3.$$
Now suppose you use intervals that are twice as long. Now your data are $25$ $(13 + 12)$  and $23$ $(10 + 13).$ The estimators are now $$\hat \lambda_1 = {{25} \over {2}}$$ and $$ \hat \lambda_2 = {{23} \over {2}} $$ If we average these we find, as before, $$\hat \lambda=12$$
Given that we have summed two estimators and divided by $2,$ the variance estimate will be ${{1} \over {4}}$ times the sum of the estimated variances. So we have $$ s^2 = {{1} \over {4}} \left({{25} \over {4}} +{{23} \over {4}}\right) =3$$
Answer: Ok, this is what I think is a quick and dirty answer, based on other answers and after playing around with some data.
If you have twice as many samples by making them half as long, then the mean of your count - the number of cars in each interval (not per unit length) - is halved, the SD ($s$) and SEM ($\frac{s}{\sqrt{N}}$) both decrease. But you don't want to be taking the mean count without regard of the interval size - it's a meaningless number.
If you take the mean rate - in this case, the number of cars in each interval per unit length - you get the same mean, a higher SD, but approximately the same SEM. So it works out this way.


TypeScript Factory Subclass is not Assignable to Type Superclass

Question: I want to use the Factory Pattern using TypeScript to convert raw data into a User.  I have two different types of Users: Employee and Customer.  Both extend the base class and compile without problems.  Below is an extremely simplified version of these three classes.
abstract class User {
  constructor(data: any) { }

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Employee extends User {
  static '@type' = 'Employee';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

class Customer extends User {
  static '@type' = 'Customer';

  static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
    return new this(data);
  }
}

Simple enough.  Now for the Factory.  I want to create a Factory that will take raw data returned from the server and convert that data into something the rest of the system can use (i.e. an instance of User).  What I want to do is something like
class UserFactory {
  /**
   * Vends a User constructed from the raw data from the server.
   *
   * @param userData (Object) - the User definition, as obtained from the server
   *
   * @return (User) the User initialized from `userData`
   */
  static vend<T extends User>(userData: any): T {
    switch (userData['@type']) {
      case Employee['@type']:
        return Employee.createFromServer(userData);

      case Customer['@type']:
        return Customer.createFromServer(userData);

      default:
        throw new Error('Unknown User type.');
    }
  }
}

As you can probably guess (since I'm here and not relaxing over the weekend), that doesn't work.  I get the following error:

Type 'Employee' is not assignable to type 'T'.

Since T extends User and Employee extends User without adding or removing anything (in this simplified version), it seems like the above should work.  What's more annoying is it seems the above will work in other languages (e.g. Java (tested), C++), I'm just not sure why it won't work in this situation.
Somebody on GitHub suggested that the problem might be with overloading the constructor, but clearly that's not occurring here.
So, why isn't Employee assignable to type T?  (How) can I get the above to work?  Is there a better way to handle this in TypeScript?  A correct answer will answer at least the first 2 questions.
Addendum
createFromServer() is redefined in subclasses for a reason.  This is a minimally reproducible example.  The constructors don't actually take the raw data from the server.  Instead the createFromServer() converts the raw data into arguments the constructors can understand.
Answer: I can't speak to the specific reason why TypeScript won't correctly infer the type, however, casting to any does allow the code to compile and for type inference to work correctly. eg.
class UserFactory {
    /**
     * Vends a User constructed from the raw data from the server.
     *
     * @param userData (Object) - the User definition, as obtained from the server
     *
     * @return (User) the User initialized from `userData`
     */
    static vend<T extends User>(userData: any) : T {
      switch (userData['@type']) {
        case Employee['@type']:
          return <any>Employee.createFromServer(userData); // Cast

        case Customer['@type']:
          return <any>Customer.createFromServer(userData); // Cast

        default:
          throw new Error('Unknown User type.');
      }
    }
  }

// Tests
const employee = UserFactory.vend<Employee>("");
employee.customerId = 7; // Error
employee.employeeId = 7;

const customer = UserFactory.vend<Customer>("");
customer.customerId = 7;
customer.employeeId = 7; // Error

// Added id properties to Employee and Customer
  abstract class User {
    constructor(data: any) { }

    static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
      return new this(data);
    }
  }

  class Employee extends User {
    static '@type' = 'Employee';
    public employeeId : number;

    static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
      return new this(data);
    }
  }

  class Customer extends User {
    static '@type' = 'Customer';
    public customerId : number;
    static createFromServer<T extends User>(this: new (...args: any[]) => T, data: any): T {
      return new this(data);
    }
  }

Answer: It's not working because you've written too much code. You should be leveraging polymorphism. What this means is simply removing the static factory methods from the two base classes.
That way will work as you expect and you will have less code to maintain. In fact, it's the very reason why the static method in the User class has a this type and news the containing class using the this reference. It enables derived classes to inherit a factory that intrinsically has their more derived type
Also this isn't Java. In fact I couldn't think of a language less like Java than TypeScript
Comment: Remember, this is an extremely simplified version of the real code.  I don't show the real reason I'm doing a lot of things.  The `createFromRequest()` methods naturally look very different in the subclasses as the raw data from the server looks very different and the constructors don't actually take the raw data as its argument (why even use factories in that case?).
Comment: @c1moore plenty of reasons, for example the constructors themselves could be doing the actual work. At any rate, if that is the case you could make this work simply by removing the type constraints and the return type annotations.
Comment: Yet in the extremely simple case of `class MySet extends Set { add(myElement: MyElement): MySet;` I still get the message about "type MySet is not assignable to type 'this'".
Comment: @torazaburo I don't know what the `Set` class in your code is (it's not an ES2015 Set since it's not generic) but it sounds like you should be specifying the return type as `this`.
Comment: Yes, it needed to be have a return type of `this` as you say. As an aside, apparently TypeScript, at least the version of TS and typings that I am using, accepts non-generic `Set` and interprets it as `Set`.
Comment: Interesting. That's weird. Unless there is a default generic, that should trigger a syntax error. Regarding the return type. The reason you have to specify `this` is because that is what the base `Set`, in `lib.es2015.d.ts`, specifies it and using a less specific type breaks that contract
Comment: yep. don't set those factories as static properties on the class... you'll run into chicken egg  problems.


How many factors of $N$ are a multiple of $K$?

Question: How many factors of $N = 12^{12} \times 14^{14} \times 15^{15}$ are a multiple of $K = 12^{10} \times 14^{10} \times 15^{10}$ ?

Any approach to attempt such questions ?
Comment: Start by fully factorizing each...
Comment: $N = 3^{27}2^{26}7^{14}5^{15}$ and $K = 3^{20}2^{20}7^{10}5^{10}$
Answer: This the same as asking how many divisors for the number
$$\frac NK=2^8\cdot3^7\cdot 5^5\cdot 7^4.$$
Answer: Look at it this way:
$$N=2^{38}3^{27} 5^{15} 7^{14}$$
Now ask yourself how many factors are a multiple of:
$$K=2^{30}3^{20} 5^{10} 7^{10}$$$$
Comment: ... i.e. how many divisors $R=\frac{N}{K}=2^8 3^7 5^5 7^4$ has. We would dare to say $9\cdot 8\cdot 6\cdot 5$.
Answer: Hint:
Since $\;N=2^{38}\cdot3^{27}\cdot5^{15}\cdot7^{14}\;,\;\;K=2^{30}\cdot3^{20}\cdot5^{10}\cdot7^{10}\;$
You need that each multiple has at least the same ammount of prime factors as $\;K\;$ has...


How to justify interchange of summation and integral with $f_n(x)=x^2 \cos(2nx)/n$ on $[0, \pi/2]\times \mathbb{N}$?

Question: I am trying to compute
$$\int_0^{\pi/2}\sum_{n=1}^\infty  \frac{x^2\cos(2nx)}{n}\,dx.$$
To do so, I would like to interchange integral and sum, but I am having trouble justifying the validity of this exchange. By Fubini-Tonelli, we just need to check that
$$\int_0^{\pi/2}\sum_{n=1}^\infty  \frac{x^2|\cos(2nx)|}{n}\,dx$$
is well-defined classically (the order is irrelevant to existence). However, I am not sure how to control or estimate this expression. I thought of re-writing the magnitude of $\cos(2nx)$ as $\frac{1}{\sqrt{2}}(1+\cos(4nx)^{1/2}$ but wasn't able to make much progress.
Comment: The map $g:\theta\mapsto\sum^\infty_{n=1}\frac{\cos 2n x}{n}$ is in $L_2([0,\pi])$ by Bessel's inequality.  Hence $g\mathbb{1}_{[0,\pi/2]}$ is also in $L^2[0,\pi]$. As $S_N=\sum^N_{k=1}\frac{\cos 2nx}{n}$ converges to $g$ in $L_2$ (Parseval's theorem) $S_N\mathbb{1}_{[0,\pi/2]}$ converges to $g\mathbb{1}_{[0,\pi/2]}$ in $L_2[0,\pi]$. The conclusion follows from continuity of the dot product.
Answer: As you pointed out, we can try to apply Fubini's theorems. The requirement is
$$\sum_{n=1}^\infty\int_0^{\pi/2}\frac{x^2\,\lvert{\cos(2nx)}\rvert}{n}\,\mathrm dx<\infty.\tag{$\star$}$$
If this is the case, then Fubini's theorems give us that:

the sequence $n\mapsto\int_0^{\pi/2}\frac{x^2\cos(2nx)}n\,\mathrm dx$ is summable;
the function $x\mapsto\sum_{n=1}^\infty\frac{x^2\cos(2nx)}n$ is defined for almost every $x\in(0,\frac\pi2)$ and is integrable;
further, $$\sum_{n=1}^\infty\left(\int_0^{\pi/2}\frac{x^2\cos(2nx)}n\,\mathrm dx\right)
=\int_0^{\pi/2}\left(\sum_{n=1}^\infty\frac{x^2\cos(2nx)}n\right)\mathrm dx.\tag{$\heartsuit$}$$

By introducing the change of variables $y\gets2nx$, we compute
\begin{align*}\int_0^{\pi/2}\frac{x^2\,\lvert{\cos(2nx)}\rvert}n\,\mathrm dx&=\frac1{8n^4}\int_0^{n\pi}y^2\,\lvert{\cos y}\rvert\,\mathrm dy\\[.4em]&\ge\frac1{8n^4}\sum_{k=0}^{n-1}\int_{k\pi}^{k\pi+\frac\pi4}y^2\,\lvert{\cos y}\rvert\,\mathrm dy\\[.4em]&\ge\frac1{8n^4}\sum_{k=0}^{n-1}\frac\pi4(k\pi)^2\cos\left(\frac\pi4\right)\end{align*}
which is unfortunately of order $n^{-1}$. Therefore $(\star)$ cannot hold as the integral there is not summable.

Nonetheless, we can still establish $(\heartsuit)$ as the series $\Sigma f_n(x)$ is uniformly convergent on the compact interval $[0,\frac\pi2]$.
From a classical trigonometric sum (see, e.g., Dirichlet's kernel),  we have $$d_n(x):=\sum_{k=1}^n\cos(2kx)=\frac{\sin(nx)\cos((n+1)x)}{\sin(x)}$$ (where the fraction equals $n$ for $x=0$). Besides, Abel's summation formula gives that $$s_n(x):=\sum_{k=1}^nf_k(x)=x^2\sum_{k=1}^n\frac{d_k(x)-d_{k-1}(x)}k=x^2\sum_{k=1}^{n-1}\frac{d_k(x)}{k(k+1)}+\frac{x^2d_n(x)}n.$$
Now for all $n>m$, $$\lvert s_n(x)-s_m(x)\rvert\le\sum_{k=m}^{n-1}\frac{x^2\lvert d_k(x)\rvert}{k(k+1)}+\frac{x^2\lvert d_n(x)\rvert}n+\frac{x^2\lvert d_m(x)\rvert}m.$$
We observe that the sequence $(x^2d_k(x))_{k\ge1}$ is uniformly bounded on $[0,\frac\pi2]$ because $\lvert{\cos}\rvert,\lvert{\sin}\rvert\le1$ and the function $x\mapsto x^2/{\sin(x)}$ is bounded there. It easily follows by Cauchy's criterion that $(s_n)_{n\ge1}$ is uniformly convergent on $[0,\frac\pi2]$. This implies $(\heartsuit)$ as $$\left\lvert\int_0^{\pi/2}s_n(x)\,\mathrm dx-\int_0^{\pi/2}s_\infty(x)\,\mathrm dx\right\rvert\le\int_0^{\pi/2}\lvert s_n(x)-s_\infty(x)\rvert\,\mathrm dx\le\frac\pi2\|s_n-s_\infty\|_\infty\xrightarrow[n\to\infty]{}0.$$
(I found that the value of $\int_0^{\pi/2}s_\infty(x)\,\mathrm dx$ is $-3\pi\zeta(3)/16$.)
Answer: Let $f_n(x)=\cos(2nx)$. Then $f_n$ satisfies
$$
            -\frac{d^2}{dx^2}f_n=\lambda_n f_n, \;\; \lambda_n=4n^2,\\
              f_n'(0)=0,\;\; f_n'(\pi/2)=0.
$$
Because of this, the functions $\{ f_n \}_{n=1}^{\infty}$ are mutually orthogonal in $L^2[0,\pi/2]$. And
$$
     \int_0^{\pi/2} \cos^2(2nx)dx = \frac{1}{2}\int_0^{\pi/2} \cos^2(2nx)+\sin^2(2nx)dx \\
         = \frac{1}{2}\int_0^{\pi/2} dx = \frac{\pi}{4}.
$$
So the following sum converges in the norm of $L^2[0,\pi/2]$:
$$
           \sum_{n=1}^{\infty}\frac{\cos(2nx)}{n}.
$$
Because $x^2\in L^2[0,\pi/2]$, it follows that
$$
        \int_0^{\pi/2} x^2 \sum_{n=1}^{\infty}\frac{\cos(2nx)}{n}dx = \sum_{n=1}^{\infty}\int_0^{\pi/2}x^2\frac{\cos(2nx)}{n}dx.
$$
This is because of continuity of the inner product in $L^2[0,\pi/2]$.


List all fields with the feature they are defined in

Question: I'm interested in generating a list of all fields with a column highlighting the feature that contains the field base setting and another column highlighting the field instance feature, (if the field is defined in a feature).
Something like this...

Field Name     |   Field Base Defined In  | Field Instance Defined In
field_subtitle |   mysite_shared_fields   | blog_story_feature
field_other    |   mysite_shared_fields   | blog_story_feature

Has anyone attempted this? Or can anyone suggest a solution.
Comment: Have you looked at `{field_config}` table? And [`hook_field_schema`](https://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook_field_schema/7)? It should give you idea where you don't have this data, and where you can have some of it. Not all, mind you.
Comment: Thanks Molot, this is useful for getting the initial list.
Answer: Some useful functions /snippets below
<code>field_info_instances();

$features_map = features_get_component_map();

$features_map['field_base'];
$features_map['field_instance'];
return;
foreach (field_info_fields() as $key => $field) {
  $base = isset($features_map['field_base'][$key]) ? join(',',$features_map['field_base'][$key]) : 'NOT IN A FEATURE!';
  $instance = 'todo';
  $rows[] = array($key, $base, $instance);
}
print theme('table', array('header' => array('machine_name', 'base', 'instance'), 'rows' => $rows));
return;

$components = features_get_components();
$field_base_component = $components['field_base'];
features_include_defaults($field_base_component);
$field_instance_components = $components['field_instance'];
</code>
Answer: For older sites where field instances and sites are not stored separately in features
<code>$features_map = features_get_component_map(NULL, TRUE);

// loop through field instances, this gives a deep array of
// content types...
foreach (field_info_instances() as $type => $bundles) {
  // ...containing bundles...
  foreach ($bundles as $bundle => $field) {
    // ...containing fields
    foreach($field as $field_name => $field_info) {
       // the key for the feature is...
       $features_instance_key = $type . '-' . $bundle . '-' . $field_name;
       if ( isset($features_map['field'][$features_instance_key]) ) {
         $in_feature = join(',', $features_map['field'][$features_instance_key]);
       }
       else {
         $in_feature = 'NOT IN A FEATURE';
       }
       $instance_map[$field_name] = $in_feature;
    }
  }
}

foreach (field_info_fields() as $key => $field) {
  $rows[] = array($key, $instance_map[$key]);
}
print theme('table', array('header' => array('machine_name', 'feature'), 'rows' => $rows));
return;
</code>


Non-biased User Interface for building training set

Question: I want to use machine learning to detect objects of type A among objects of types B-Z.  I require human expertise to initially classify these objects as A, B, C... Z.  The individuals who can provide the initial classification are not familiar at all with machine learning and need a simple interface.
Unfortunately, type A objects are naturally rare (< 1%) in the population.  In most datasets type A objects do not occur at all, in a few datasets they will be present at ~5%.  Generating a balanced training set will require somehow informing the user as they go along if they are lacking objects of a particular type relative to another.  However, depending on the random order of presentation of the datasets, type A objects may not occur until well after the beginning of classification.
The challenge I am facing is to create a user interface that will encourage users to classify approximately the same number of objects of each type, without orienting the user.  I have to find a way to push the user to classify all the type A objects they find, but not invent type A objects where there are none.
Do you know of any publications that address these challenges?  Or examples of similar interfaces to gain inspiration?
Thanks in advance!
Answer: This is more a UX question I suppose where what you are trying to avoid is an enforced hierarchy. Visual hierarchies encourage action in some direction (colour, positioning etc) and are hard to avoid.
Examples: http://www.creativebloq.com/ux/ways-guide-website-visitors-111413511
If there is a full alphabets worth of object types, creating a non-list based UI will be key. Rule out thing like dropdowns because people are more oriented towards the top and bottom of those lists. A horizontal, always visible button layout would be safer (though people would tend toward the edges and centre naturally, just be aware).
Avoid scroll at all costs, it slows everything down and people just want to do what is easiest, which in this case means select the same thing over and over.
If you want an even distribution of answers then actively guide people. Give feedback (a simple counter for each class would work) and tell people they should be roughly even. This may be difficult to do well without seriously increasing the user's congnitive load. Keeping track of 20+ numbers is difficult.
Also be mindful of how complex the object being classified is and give it the prominent positioning in the UI.
White space is your friend to allow people to quickly classify (don't spend as much time hunting for the button their trying to hit) and minimise the human time spent. If it work very quickly, give it 2 human passes and cross validate their classifications, though this may only be relevant if the classification process is highly subjective.
Also consider linespace for speed of use.
http://uxmovement.com/content/how-margins-and-line-lengths-affect-user-reading/


Multilingual Themes

Question: I am trying to switch themes when the site language is switched. Is it possible to have separate themes for each language in a Drupal 7 multilingual site?
Answer: Yes - you can create different themes for just about any condition you like as long as you have a way of switching between them. There are several theme switcher modules available but one of the better ones is 'ThemeKey' which does what you are looking for:

ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.

Multilingual Themes


how to use Images without path in handlebars

Question: I want to deliver image list into Handlebars view.
ArrayList<ImageIcon> images = new ArrayList<>();
for(Photos p : photos){
    ByteArrayInputStream bis = new ByteArrayInputStream(p.getImage());
    BufferedImage bim = ImageIO.read(bis);
    images.add(new ImageIcon(bim));
}

model.addAttribute("photos", images);

I'm sure that there are ImageIcon objects in this arrayList by debugging.
Then, how can I use this array in handlebars like this.
{{#each photos as |photo|}}

{{/each}}

I want to use this images without file path.
Comment: The type of p.getImage() is byte[] which is from postgresql
Answer: @GetMapping("/displayImage")
public void displayImage(@RequestParam("email")String email, HttpServletResponse response) throws IOException {
    List<Photos> list = photoService.showImages(email);

    byte[] binaryImage = list.get(0).getImage();
    response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
    response.getOutputStream().write(binaryImage);
    response.getOutputStream().close();
}


Rational Solution to $\frac{x-x^3}{(x^2+1)^2} + \frac{y-y^3}{(y^2+1)^2} = \frac{z-z^3}{(z^2+1)^2}$

Question: Find a (all) rational solutions, 0<(x,y,z)<1 to the equation:
$$\frac{x-x^3}{(x^2+1)^2} + \frac{y-y^3}{(y^2+1)^2} = \frac{z-z^3}{(z^2+1)^2}$$
or else show there are no rational solutions.
This equation arises in the following context:
A Magic square is an 3x3 positive integer matrix where all the rows, columns and diagonals have the same sum.  An open question is whether a Magic Square of Squares exists (all the entries are themselves squares).  A hourglass configuration examines the top row, middle entry and bottom row of the Magic Square.  A valid hourglass configuration has the top row, bottom row, center column and both diagonals having the same sum.
Showing the above equation has no solutions implies there is no valid hourglass configuration of Squares and thus no Magic Square of Squares exists.

With $m_i,n_i$ positive integers, $m_i>n_i$ and one of $m_i,n_i$ even.
For i = 1,2,3, let

$$a_i=(m_i^2+n_i^2)^2$$
$$b_i=4m_i n_i (m_i^2-n_i^2)$$
$$c_i=(m_i^2+n_i^2)^2$$
So that $a_i$ and $a_i±b_i$ are squares as $b_i$ are congruum.
With
$a=a_1 a_2 a_3$
$a±b_1 a_2  a_3= a_2  a_3(a_1±b_1) $
$a±a_1  b_2 a_3=a_1  a_3 (a_2±b_2) $
$a±a_1  a_2 b_3=a_1  a_2 (a_3±b_3) $
We have 3 arithmetic sequences of 3 squares, all with center a.

If  $a_2 a_3 b_1+a_1 a_3 b_2-a_1 a_2 b_3=0$
, we can form a valid hourglass configuration as:

$$[ a_1 a_2 a_3+b_1 a_2  a_3   ,   a_1 a_2 a_3+a_1  b_2 a_3   ,       a_1 a_2 a_3-a_1  a_2 b_3$ ]$$
$$   [ -  ,a_1 a_2 a_3,  - ] $$
$$[  a_1 a_2 a_3+a_1  a_2 b_3   ,   a_1 a_2 a_3-a_1  b_2 a_3  ,     a_1 a_2 a_3 - b_1 a_2  a_3  ]$$

Rearranging

$a_2 a_3 b_1+a_1 a_3 b_2-a_1 a_2 b_3=0$
$\frac{b_1}{a_1} +\frac{b_2}{a_2}-\frac{b_3}{a_3}=0$
$\frac{4m_1 n_1 (m_1^2-n_1^2 )}{(m_1^2+n_1^2)^2} +\frac{4m_2 n_2 (m_2^2-n_2^2 )}{(m_2^2+n_2^2)^2}-\frac{4m_3 n_3 (m_3^2-n_3^2 )}{(m_3^2+n_3^2)^2}=0$
Divding by 4 and multiplying each term by $\frac{1}{m_i^4}$  and let $x=\frac{n_1}{m_1},y=\frac{n_2}{m_2},z=\frac{n_3}{m_3}$
You obtain the original equation:
$$\frac{x-x^3}{(x^2+1)^2} + \frac{y-y^3}{(y^2+1)^2} = \frac{z-z^3}{(z^2+1)^2}$$
So showing this equation has no rational solutions -> there is no valid Magic Square Square hour glass configuration -> there is no valid Magic Square of Squares
Note:
You can obtain a closely related equation that has rational solutions, but I don't know how to use a solution from the related equation to find a rational solution main equation.  The related equation is obtained by noting that in
$$\frac{x-x^3}{(x^2+1)^2}$$
Multiplying top and bottom by $$\frac{1}{x^2}$$
Yields
$$\frac {\frac{1}{x}-x} {(\frac{1}{x}+x)^2}$$
Which equals
$$\frac {\frac{1}{x}-x} {(\frac{1}{x}-x)^2+4}$$
substituting in the main equation
$$a=\frac{1}{x}-x , b=\frac{1}{y}-y, c=\frac{1}{z}-z$$
Gives
$$\frac{a}{a^2+4} + \frac{b}{b^2+4} = \frac{c}{c^2+4}$$
With further substituting $$a =2a, b=2b, c=2c$$
has rational solutions.  See:
rational number solutions to $\frac{a}{a^2+1} + \frac{b}{b^2+1} = \frac{c}{c^2+1}$ with $abc\ne 0$
In this equation, setting c to a fixed value yields a series of elliptic curves.  You can generate a parameterized solution via the following MAGMA code:
<code>R<c>:=PolynomialRing(RationalField());
K<c>:=FieldOfFractions(R);
A<a,b>:=AffineSpace(K,2);
C := Curve(A,a*(b^2+4)*(c^2+4)+b*(a^2+4)*(c^2+4) -c*(a^2+4)*(b^2+4));

Genus(C);

Cp := ProjectiveClosure(C);
E, f:=EllipticCurve(Cp,Cp![c,0]);
boo,g:=IsInvertible(f);
T,h:=TorsionSubgroup(E);
P:=Cp![0,c,1];

Q:=f(P);
g(2*Q);
</code>
((-c^7 - 4c^5 - 48c^3 + 64c)/(c^6 - 12c^4 - 16c^2 - 64) : (8c^5 +
128c)/(c^6 - 4c^4 - 16*c^2 + 64) : 1)
so for any c:
$$a=\frac{((-c^7 - 4c^5 - 48*c^3 + 64c)}{(c^6 - 12c^4 - 16c^2 - 64)}$$
$$b=\frac{(8c^5 +  128c)}{(c^6 - 4c^4 - 16c^2 + 64)}$$
is a solution to:
$$\frac{a}{a^2+4} + \frac{b}{b^2+4} = \frac{c}{c^2+4}$$
as $a=\frac{1}{x}-x , b=\frac{1}{y}-y, c=\frac{1}{z}-z$
$$a=\frac{-(z^{14} - 3 z^{12} + 49 z^{10} - 203 z^8 + 203 z^6 - 49 z^4 + 3 z^2 - 1)}{(z^{13} - 18 z^{11} + 47 z^9 - 124 z^7 + 47 z^5 - 18 z^3 + z)}$$
$$b=\frac{(8 z (-1 + 5 z^2 - 26 z^4 + 26 z^6 - 5 z^8 + z^{10}))}{(1 - 5 z^2 - 5 z^4 + z^6)^2}$$
and:
$$x=\frac{-a\pm\sqrt{a^2+4}}{2}$$
$$y=\frac{-b\pm\sqrt{b^2+4}}{2}$$
so if the discriminants:
$$a^2+4$$
$$b^2+4$$
are squares, we have a solution to the original equation.
Comment: There are infinitely many positive integer solutions with $x=1$ and $y=z.$
Furthermore, there are infinitely many positive integer solutions with $z=1$ and $xy=1.$
Comment: Thanks for the reply.  Reworked a bit, hope, it's clearer.
Comment: I think you  probably want an algebraic solution but Wolfram Alpha offers a few integer solutions [here](https://www.wolframalpha.com/input/?i=solve+%5Cfrac%7Bx-x%5E3%7D%7B%28x%5E2%2B1%29%5E2%7D+%2B+%5Cfrac%7By-y%5E3%7D%7B%28y%5E2%2B1%29%5E2%7D+%3D+%5Cfrac%7Bz-z%5E3%7D%7B%28z%5E2%2B1%29%5E2%7D+over+integers). Perhaps they may help check your algebra.
Comment: Thanks, Wolfram is giving 0 or negative solutions.
Comment: Added context.  Showing the equation has no solutions solves a related problem.
Answer: $$\frac{x-x^3}{(x^2+1)^2} + \frac{y-y^3}{(y^2+1)^2} = \frac{z-z^3}{(z^2+1)^2}\tag{1}$$
$\bullet\ x=1$
Clearly, if $y=z$ then equation $(1)$ has infinitely many positive solutions as follows.
$(x,y,z)=(1,y,y).$
$\bullet\ y=1$
Similarly, equation $(1)$ has infinitely many positive solutions as follows.
$(x,y,z)=(x,1,x).$
$\bullet\ z=1$
Substitute $z=1$ to equation $(1)$ then,  we get
$(x-x^3)(y^2+1)^2+(y-y^3)(x^2+1)^2=-(xy-x+1+y)(xy-1)(xy+x+1-y)(x+y).$
Hence if $xy-x+1+y=0$ or $xy=1$ then equation $(1)$ has infinitely many positive rational solutions as follows.
$(x,y,z)=(x,\frac{1}{x},1),(x, \frac{x-1}{x+1}, 1).$
Assuming all $(x,y,z) \ne  1$, no positive rational solution was found with height$\lt100.$
Comment: @AlWicks, If you really want the solution with $(x,y,z) \ne 1$, you should have made the condition $0<(x,y,z)<1$ not $(x,y,z)>0$ from the beginning.
Comment: Yes, want x,y,x <> 1.
Comment: Yes, I see, my bad, sloppy, thanks for your reply!


My question is if 0 ≤ a, b < n and a congruent to b mod n, then how is a = b?

Question: I was trying to understand how this works in order to write a proof and I am unable to.
Comment: Welcome to Mathematics Stack Exchange.  $a\equiv b\pmod n$ means $n|a-b$; i.e., $a-b=kn$.  But if $0\le a,b\lt n$ then $-n<a-b<n$ so $k=0$
Comment: @manooooh:  I elaborated a bit on that detail in my answer below
Comment: @J.W.Tanner how do go from $0\leq a,b<n$ to $-n<a-b<n$? Thank you.
Answer: $a\equiv b \pmod n$ means $n|a-b$; i.e., $a-b=kn$.
If $0\le a<n$ and $0\le b < n$ (i.e., $-n<-b\le0$) then $-n\lt a-b <n$, so $k=0$, so $a-b=0$.
Answer: $b-a$ is a multiple of $n$, yet $b-a\le b-0<n$ and $b-a> b-n\ge 0-n$. Therefore $b-a=0$.
Answer: By definition $n$ divides $a-b$, hence $|b-a|$. However $\;0\le |b-a|<n$ if $0\le a,b<n$. How many nonnegative multiples of $n$ which are smaller than $n$ do you know?


Correlation between two ordinal categorical variables

Question: What is the best statistical test for investigating if there is any correlation between 2 categorical variables?
Both are satisfaction scores:
1st variable is:

Overall satisfaction with the service.
1: Not at all satisfied; 10: Completely satisfied

2nd variable is:

Satisfaction with the availability of information for the service"
1: Not at all satisfied; 10: Completely satisfied.
Comment: The question concerns *ordinal* variables, rather than nominal categorical ones - I think that ought to be made clear in the question.
Comment: Other relevant questions: [How does the Goodman-Kruskal gamma test and the Kendall tau or Spearman rho test compare?](http://stats.stackexchange.com/q/18112/22228) and [Kendall Tau or Spearman's rho?](http://stats.stackexchange.com/q/3943/22228)
Comment: "Ordinal" added by me to the title. (Note that nobody forces you to regard these variables as ordinal and not interval.)
Comment: @ttnphns Thanks - in that case I will tag it also.
Comment: For categorical variables, you apply polychoric correlation. LISREL program and FACTOR software could do the polychoric correlation.
Answer: I would go with Spearman rho and/or Kendall Tau for categorical (ordinal) variables.
Related to the Pearson correlation coefficient, the Spearman correlation coefficient (rho) measures the relationship between two variables. Spearman's rho can be understood as a rank-based version of Pearson's correlation coefficient.
Like Spearman's rho, Kendall's tau measures the degree of a monotone relationship between variables. Roughly speaking, Kendall's tau distinguishes itself from Spearman's rho by stronger penalization of non-sequential (in context of the ranked variables) dislocations.
Answer: Both of these have enough levels that you could just treat them as continuous variables, and use Pearson or Spearman correlation. You can then calculate a significance (p) value based on your correlation and sample size.
If you really want to treat the data as categorical, you want to run a chi-squared test on the 10x10 matrix of overall satisfaction vs. availability satisfaction. You will need a decent amount of data for this (~thousands), since the majority of the cells should contain at least 5 observations for the test to be valid. This would allow for more general types of dependence between the two measures, in which even nearby levels show different relationships (e.g. rating1=9 tends to predict rating2=4, rating1=8 tends to predict rating2=10) which are probably not likely in your data.
Comment: +1 for treating as continuous but chi-squared test misses ordinality
Answer: I went and searched for it, found this from John Ubersax:   http://www.john-uebersax.com/stat/tetra.htm
and some papers
https://link.springer.com/article/10.1007/s11135-008-9190-y
https://escholarship.org/content/qt583610fv/qt583610fv.pdf
Comment: Welcome to CV, thank you for your contribution. Please add the full references of your links in case they die in the future.


Changing from a Profile to Standard profile after the installation

Question: Its possible from moving from a custom profile or a Distro and move to a the Standards profile ?
The reason, I'm asking this is because I build a website with the Recruiter distro. At first everybody likes the workflow of the recruiter, then after a while my client ask me to change the entire workflow of the website. I have change some many things from the distro that is not longer useful to have the recruiter profile. I'm running issues with some incompatibility with some modules that the distro is not running the latest version. And I do not think that I need the distro any more.
I have try to move some modules from the profile/recruiter/module to sites/all/modules and the module does not seem to be working.
So my goal would be to remove the /profile/recruiter and move everything to /sites/all/modules & /sites/all/themes
Answer: I figure out how to do it. You will need to use the Profile Switcher module in order to achieve moving from one profile to another one.


ACF and PACF interpretation

Question:  Click for ACF image 2
These are my ACF and PACF of my data set . Can any one help me determine whether the data is stationary ? if so What order of AR , MA ?
Answer: The periodicity in your (P)ACF plots strongly suggests seasonality of length slightly less than 0.02 of the cycle you defined. Since $7/365\approx 0.019$, I suspect that you have daily data, which you specified as frequency=365. We can't say much more.
Note that it is not very good practice to examine (P)ACF plots any more (the box-jenkins approach). Nowadays, it's better to choose models based on AIC, after determining any necessary differencing using appropriate methods. I suggest you look at ?forecast::auto.arima and FPP2.
If you do have daily data with possible intra-yearly seasonality, you may want to look at our multiple-seasonalities tag.
Comment: Yes its a daily data I used the auto.arima function and it resulted in following  Series: myts
ARIMA(1,0,0) with non-zero mean

Coefficients:
         ar1      mean
      0.2103  236.0485
s.e.  0.0284   65.4923

sigma^2 estimated as 3181549:  log likelihood=-10569.71
AIC=21145.41   AICc=21145.43   BIC=21160.65
Comment: Try clarifying that the more relevant seasonal cycle is of length 7, rather than 365: `ts(..., frequency=7)`. I suspect that `auto.arima()` will then give you a seasonal model based on this frequency.

ACF and PACF interpretation


Babel does not appear to be transforming my React-Native code

Question: I'm fairly new to RN and want to get flow types and decorators working in this project.
I am on version 0.41.2 of RN. It comes with a .babelrc in the project root, which I have added the plugins to:
{
"presets": ["react-native"],
"plugins": ["transform-decorators-legacy", "transform-flow-strip-types"]
}

I understand in older versions of RN I needed to extend the .babelrc from my node_modules folder, but that this shouldn't be the case on my current version.
So what gives, why can I not run my project without getting syntax errors?
Comment: What are the errors?
Comment: @loganfsmyth There are no errors, it fails silently. The syntax errors are to do with the flow types not being stripped out and the decorator `@` symbol not being transpiled
Answer: Your config should work. Have you tried running watchman watch-del-all and npm run start -- --reset-cache/yarn start -- --reset-cache? If you update your .babelrc and meet errors this may help in some cases.


Unknown directories /pipermail /poll accessible in Drupal 7

Question: My Drupal 7 install, has the Simplenews and Polls modules enabled, but Simplenews is set to subscribe registered members only, and Polls are only open to authenticated users. Yet, the mysite.com/pipermail and mysite.com/poll directories are accessible to anonymous view.
The mysite.com/poll directory returns a page with the Drupal theme only, and the word "Polls" in the page title, and no other data. The mysite.com/pipermail directory returns a blank page, absolutely no data.
These directories are not seen anywhere in the directory tree when I checked using File Manager in cPanel. This is a CentOS 5.10, php 5.4 install. How does one check Drupal's internal directory tree, especially to verify whether the permissions are correctly set on these unknown directories?
How do I remove these problematic directories? Also, is it possible that this flaw can be maliciously attacked, say by ftp upload means, etc.?
Comment: Did you check permissions in "admin/people/permissions" ?
Comment: Yes, I checked the permissions and anonymous user doesn't have access to anything in Polls.  In simplenews, I've checked the subscribe option for anonymous users, because I need the 'silent' option of subscription for simplifying sending of service messages.
Answer: Drupal is a Dynamic Content Management system unlike old style files and directories where you find path specific directory.. Various features are available from modules in Drupal... Modules implements menu paths using hook_menu...
For your case, module exposes permissions settings which you can set in "admin/people/permissions" for different roles... Login as admin and access above page to set access permissions..


How to prevent ssh user to login if same user is still logged in?

Question: For security reasons, I want to restrict users to have more than one ssh connection.
In terminal, if I check $ last user , I'll find the user is still logged in.
Is any solution to check if user is still logged in don't allow to login again?
Comment: https://unix.stackexchange.com/questions/127077/number-of-ssh-connections-on-a-single-linux-machine
Comment: Does this answer your question? [sftp concurrent connection](https://serverfault.com/questions/392749/sftp-concurrent-connection)
Comment: @GeraldSchneider, IMHO the fist is better match :)
Comment: IMO as well, but we can't close as a duplicate on a different site. The second answers it as well and it's not necessary to replicate the answer.
Answer: You can't directly limit the ssh connections. But you can limit the logins of this user. Edit /etc/security/limits.conf and add line:
specificuser  hard    maxlogins   1

This will limit the logins to 1 for specificuser (independently if we talk about ssh, telnet or console logins)
Answer: Configure the option "MaxStartups " in the "/etc/ssh/sshd_config file":
MaxStartups 1

Then restart the ssh service.
This setting allows a maximum of one connection for each user
https://man7.org/linux/man-pages/man5/sshd_config.5.html
Answer: If you are using the same user for all users on your company (aka root), you can add the next code on the begging of the /etc/profile file to filter one user by IP address:
# Limit logins to one user by IP
NEW_LOGIN=$(last -n 1 | head -n 1 | awk '{print $3}')
CURRENT_LOGINS=$(w -hs | awk '{print $3}' | grep "$NEW_LOGIN" | wc -l)
if [ "$CURRENT_LOGINS" -ge "2" ]; then
  echo "Only one login per user/IP is allowed, closing this connection to $NEW_LOGIN"
  exit 1
fi


Find the sum of n terms of a series

Question: Find the sum of n terms of series whose $n$th term is $\frac{n^2(n^2-1)}{4n^2-1}$.
Answer: Hint
If you use partial fraction decomposition, you find something which is very interesting since $$\frac{n^2(n^2-1)}{4n^2-1}=\frac{n^2}{4}-\frac{3}{16}-\frac{3}{32 (2 n-1)}+\frac{3}{32 (2 n+1)}$$ Have a look at the third and fourth term and notice that $\cdots ???$
Comment: Yeap, I got it!
Comment: Simple, isn't ? Glad to have helped. Try to remember the trick ! Cheers.

Find the sum of n terms of a series


Targeting a  and converting it into an array

Question: I would like to target all the
 and convert it into an array. I have tried spread operator, Array.from or by using methods like .split() or .splice(). But it seems that the problem is to find the right target and understand how to operate with Element object-text which I have not yet...

const targetDates = document.querySelector('.data');
console.log(targetDates.childNodes.entries)

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>

            1429
    1368
    1661
    1687
    1593
    1495
    1565
    1500
    1635

Answer: That element has a single child node, which is a text node.

const p = document.querySelector('#dates');
console.log(p.childNodes.length);

            1429
    1368
    1661
    1687
    1593
    1495
    1565
    1500
    1635

In such a case, it's usually easiest to use .textContent to retrieve only the text inside the element, and then you can manipulate the text to process the numbers as you like - such as splitting by newlines, or by matching numbers in the string with a regular expression:

const p = document.querySelector('#dates');
const nums = p.textContent.match(/\d+/g);
for (const num of nums)  {
  console.log(num);
}

            1429
    1368
    1661
    1687
    1593
    1495
    1565
    1500
    1635

Answer:   const targetDates = document.querySelector('.data');
  const textData=targetDates.childNodes[0].textContent;
  const finalTextData=textData.trim().split('\n');//using trim() because the of the first blank space

  const newValue=finalTextData.map(item=>item.trim())

So with the .textcontent you can access to the content of
 then you have to remove the blank space at first via trim() and split them base of '\n' which is Enter.Although you can find some RegExp to solve the problem ,you can also solve this issue with this steps


K-Means Clustering on Distributed System

Question: Can anyone explain how the k-means clustering algorithm converges on distributed systems? It seems that each node in our hadoop cluster would simply find a local optimum. How do we update across multiple nodes?
Answer: At each iteration, local results are merged on a central node. You do not independently run k-means on each node!
The data volume is constant in the data set size, and the CPU cost is neglible,  so this is very favorable. k-means is embarassingly parallel,  and all the advanced methos aim at achieving sublinear processing time.


Correct solution to these ODEs

Question: I have three linear ODEs that I would like to solve:
$$
-\frac{\mathrm{d}y_1}{\mathrm{d}x} = \delta(x-a) \text{ with } y_1(x_{max})=0 \\
\frac{\mathrm{d}^2y_2}{\mathrm{d}x^2} = \delta(x-a) \text{ with } y_2(x_{max})=0, \frac{\mathrm{d}y_2}{\mathrm{d}x}(x_{max}) = 0 \\
-\frac{\mathrm{d}^3y_3}{\mathrm{d}x^3} = \delta(x-a) \text{ with } y_3(x_{max})=0, \frac{\mathrm{d}y_3}{\mathrm{d}x}(x_{max}) = 0, \frac{\mathrm{d}^2y_3}{\mathrm{d}x^2}(x_{max}) = 0
$$
where $ x \in D = [0, x_{max}], a\in D$ and $\delta$ is the Dirac-delta function.
I tried applying Laplace transforms however they require knowledge of the $y_i$ functions at the point $0$ which I do not have. So, I've solved the first equation in the following way
$$
-\int\limits_{x}^{x_{max}} \frac{\mathrm{d}y_1}{\mathrm{d}x'} \mathrm{d}x' = \int\limits_{x}^{x_{max}} \delta(x'-a) \mathrm{d}x' =
\begin{cases}
1 \text{ when } 0 \leq x<a,\\
0 \text{ when } a<x \leq x_{max}.
\end{cases} \iff \\
y_1(x) = \begin{cases}
1 \text{ when } 0 \leq x<a,\\
0 \text{ when } a<x \leq x_{max}.
\end{cases}
$$
For the second ODE I obtained
$$
- \frac{\mathrm{d}y_2}{\mathrm{d}x} = \begin{cases}
1 \text{ when } 0 \leq x<a,\\
0 \text{ when } a<x \leq x_{max}.
\end{cases} \iff \\
y_2 = \begin{cases}
x+c \text{ when } 0 \leq x<a,\\
0 \text{ when } a<x \leq x_{max}.
\end{cases}
$$
I am unsure how to determine that constant since the only knowledge that I have is at
$x_{max}$, knowledge that I've already used.
For the third ODE I obtained
$$
y_3 = \begin{cases}
\frac{x^2}{2} + c_1 x + c_2 \text{ when } 0 \leq x<a,\\
0 \text{ when } a<x \leq x_{max}.
\end{cases}
$$
where again I do not know how to determine the constants.
So, the question is how to correctly solve these three ODEs with their adjacent boundary conditions for the $y_i(x)$ functions.
Comment: You can always shift the Laplace transform to insert input data where you need it: $\int_b^\infty e^{-s(t-b)} f(t) dt = \int_0^\infty e^{-st} f(t+b) dt$.
Comment: This is probably how I would hand-solve this problem, either that or just change variables to be more convenient (change the direction of time and shift things so the domain is $[0,x_{max}]$ and the initial data is at $0$).
Answer: In order to obtain the condition for the second ODE, we use the Fundamental Theorem of Calculus:
$$
y_2(a+\epsilon)-y_2(a-\epsilon)=\int_{a-\epsilon}^{a+\epsilon}y_2'(x)\,dx
=-\epsilon,
$$
which implies continuity of $y_2$ at $x=a$:$^{(a)}$
$$
y_2(a^-)=y_2(a^+) \Rightarrow -a+c=0 \Rightarrow c=a.
$$
Applying the same argument to the third ODE, we conclude that $y_3'$ and $y_3$ must also be continuous at $x=a$, so that
$$
y_3'(a^-)=y_3'(a^+) \Rightarrow a+c_1=0 \Rightarrow c_1=-a; \\
y_3(a^-)=y_3(a^+) \Rightarrow \frac{a^2}{2}-a^2+c_2=0 \Rightarrow
c_2=\frac{a^2}{2}.
$$

$^{(a)}$Note that $y_2(x)=-x+c$ if $0\leq x<a$, as $-y_2(x)=1$ in this region.

ADDENDUM: Solution by Laplace transform
Let me show how the problem may also be solved using the Laplace transform. The key is to consider $y(0)$, $y'(0)$, etc. as coefficients to be determined a posteriori. I will show how this procedure works by solving the second ODE,
$$
y''(x)=\delta(x-a). \tag{A.1}
$$
Applying the Laplace transform to both sides of (A.$1$) yields
$$
-y'(0)-sy(0)+s^2\mathcal{L}[y]=e^{-as}. \tag{A.2}
$$
Solving for $\mathcal{L}[y]$ and taking the inverse transform we obtain
\begin{align*}
y(x)&=\mathcal{L}^{-1}\left[\frac{y'(0)}{s^2}+\frac{y(0)}{s}
+\frac{e^{-as}}{s^2}\right] \\
&=[y'(0)x+y(0)]H(x)+(x-a)H(x-a), \tag{A.3}
\end{align*}
where $H$ is the Heaviside step function. (Note that $y(x)$ is continuous at $x=a$, as argued in the first part of the answer.)
Now, let us apply the conditions $y(x_{max})=0, y'(x_{max})=0$ to (A.$3$). The latter implies
$$
y'(0)+1=0 \Rightarrow y'(0)=-1; \tag{A.4}
$$
the former then implies
$$
[y'(0)+1]x_{max}+[y(0)-a]=0 \Rightarrow y(0)=a. \tag{A.5}
$$
Combining the last three equations we finally obtain
$$
y(x)=(-x+a)[H(x)-H(x-a)]=
\begin{cases}-x+a,&\mathrm{if}\, 0\leq x<a, \\
0,&\mathrm{if}\, a\leq x\leq x_{max},
\end{cases} \tag{A.6}
$$
which agrees with the result obtained in the first part of the answer.

Correct solution to these ODEs