Simple JQuery AutoComplete w/ Javascript Callback to format reponse

Question: I am new to JSON and trying to figure out how to get this real simple autocomplete working with some formatted response.  (all jquery autocompletes I see use the huge ui library's that I would rather stay far away from).
This is what I have so far:
$(function() {
     // u check
     $('#search-input').keyup(function() {
     $.ajax({
            dataType: 'jsonp',
            type: "POST",
            url: "/includes/myautocomplete/tags.php",
            data: "callback=autocomplete&q="+$('#search-input').val(),
            jsonp: 'autocomplete',
            success: function(json){
                $('#search-resp').html(json);
            }
        });
    });

});
I am trying to format the response with:
function autocomplete(json) {
  var html ='
';
  for(i=0;i<json.length;i++) {
    var n = json[i];
    html = '
'+n['tagname']+'
';
  }
  html = '
';
  return html;
}

My PHP looks like:
# JSON-encode the response
$json_response = json_encode($array);

# Optionally: Wrap the response in a callback function for JSONP cross-domain support
if($_POST["callback"]) {
   $json_response = $_POST["callback"] . "(" . $json_response . ")";
}

# Return the response
echo $json_response;

What am I doing wrong?  Thank you in advance.
Comment: also help to see sample of data sent from php unless you are certain your `autocomplet(json)` formatter is working properly
Answer: I believe you need to parse the json first:
success: function(data){
  var json = $.parseJSON(data);
  //then display it...
}

Comment: k.  thanks.  I added that, but then what?  How does this ajax code grab the autocomplete function to format the response?  Sorry such a noob to all this.
Comment: `$.ajax` will do the parsing automatically for json or xml when `dataType` is set accordingly
Comment: do what charlieftl has said, that should get you the desired results. In my case, whenever I use ajax, regardless of the set dataType, I still have to parse it before using it.
Comment: @domo270897  try `console.log( $.type(data))` next time... doubtful it returns `string` when response is json(p) and dataType is set
Comment: @charlietfl just did that and it does seem to return `string`, probably some issue on my end, thanks for the advice though!
Comment: @charlietfl thanks for the fiddle, I understand that I should be seeing object rather than string as a response, but I cant seem to find an issue in my code.
Comment: still not having any luck.
    `success: function(data){
     var json = $.parseJSON(data);
     var html = autocomplete(json);
     $('#search-resp1').html(html);
    }`
Comment: have you tried with just the solution posted by @charlietfl ? cause that might work. Also, I was going to suggest that you style it on the PHP side of things, like this: `$json_response = {response: ' foreach($array as $word) {echo "$word"}'}` - something like that.
Comment: get rid of the callback... you are getting ahead of yourself trying to use `jsonp` on local domain when can't get it working as regular json first. Also data has no `tagname` property as in your formatter
Answer: For starters you never call your format function
You have:
success: function(json){
      $('#search-resp').html(json);
}

which is trying to insert the full response object into the element as html.
Assuming your autocomplete function properly parses the returned array or object your code should look more like:
success: function(json){
      var jsonFormattedToHtml=autocomplete(json)
      $('#search-resp').html(jsonFormattedToHtml);
}

EDIT
Your html fomatting code has several flaws.
The biggest one is you need to concatenate html by using html += instead of html= after you first define it. Using = only wipes out any value previously set, so output of your function will simply be the closing
 only.
Also object properties in formatter don't match data shown.
Here's a working demo
http://jsfiddle.net/vgbK8/2/
Comment: thank you. still not getting a formatted out put. Just the json array
Comment: start simple and don't send the `callback`, use `json` only ,will need to set crossDomain option if trying to force jsonp on same domain, and provide sample of response  data. There is no way you should see array in html output if you pass it through your formatter function first
Comment: response data looks like:
`autocomplete([{"name":"Test","tagslug":"test"}])`
Comment: see my answer edit about other problems in code and a working demo
Comment: still nothing works. If i view the console my out put is a json array with the callback prefix....but thats it.
Comment: GET RID OF `callback` in the url, or disable it in php..and set `dataType:'json` You aren't following concepts of `jsonp` on local domain yet
Comment: Thank you for the JS Fiddle.   Could you include a text field with keyup for autocomplete?
Comment: you can easily modify a fiddle yourself and save new version using either `fork` or `update`. Try it and if have proble post link after save
Comment: thanx again.  i dont really know what i am doing here... but....http://jsfiddle.net/vgbK8/4/
Comment: updated to work  http://jsfiddle.net/vgbK8/7/ Of course this demo will always send same results since don't have server to create resonse. You will need to change to `data:{q:$('#search-input').val()}`. Also fiddle only allows `POST`
Comment: THANK YOU.  This helped and I was able to get it to work.  Thank you for your time on this.
Answer: Simple autocomplete textbox
Just include JS library in :

In  tag:
<input type="text" name="testne" id="testneer" onkeypress="IP_autoComplete('http://services.iperfect.net/ajax/countries.php?name=',this.id,'testDiv',event,'')">


Unit testing Controller.Initialize

Question: I am setting the thread culture to the culture sent via a cookie on the HttpRequest in the initialize method of a base controller I have created. I now want to create a unit test for this functionality.
In the test I have created a mock HttpContext and added the Cookie. Using this and a routeData helper, I create a RequestContext. Then I create a new controller and call Execute on it passing in the RequestContext.
I first hit a problem regarding TempData and SessionState, which I have fixed by setting the TempData and creating an EmptyTempDataProvider on the controller.
Then I had a problem with the VirtualPathProviderViewengine, which I fixed by creating a VoidActionInvoker.
Is this the best way to test the initialize method? Any doing anything similar and willing to share some code?
Thanks,
Jon
<code>namespace MyApp.UnitTests {
[TestClass]
public class ControllerTests {
    [TestInitialize]
    public void Setup() {
        RouteTable.Routes.Clear();
        MyApp.MvcApplication.RegisterRoutes(RouteTable.Routes);
    }

    [TestMethod]
    public void Thread_culture_should_be_set_to_cookie_culture() {
        // Arrange
        var context = HttpMockHelper.FakeHttpContext();
        context.Request.Cookies.Add(new HttpCookie(CultureService.CookieName, "nl-NL"));
        var reqContext = new RequestContext(context, "~/Home/Landing".Route());
        var controller = new HomeController {
            TempData = new TempDataDictionary(),
            TempDataProvider = new EmptyTempDataProvider(),
            ActionInvoker = new VoidActionInvoker()
        };

        // Act
        (controller as IController).Execute(reqContext);

        // Assert
        Assert.AreEqual("nl-NL", Thread.CurrentThread.CurrentCulture.Name);
    }
}

internal class VoidActionInvoker : ControllerActionInvoker {
    protected override ActionExecutedContext InvokeActionMethodWithFilters(System.Reflection.MethodInfo methodInfo, IDictionary<string, object> parameters, IList<IActionFilter> filters) {
        return new ActionExecutedContext(this.ControllerContext, false, null);
    }

    protected override void InvokeActionResult(ActionResult actionResult) {
    }
}

internal class EmptyTempDataProvider : ITempDataProvider {
    public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values) {
    }

    public IDictionary<string, object> LoadTempData(ControllerContext controllerContext) {
        return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
    }
}
}
</code>
Comment: What's Route()?
Answer: Sounds right to me, the initialize method takes a parameter for the requestcontext that requires an HttpContext, if I've got your post right you're mocking these objects and adding the values you want to test with and then ensuring that your method works correctly.  Sounds exactly like what I would do.  I wouldn't mind seeing some of the code though.
Edit: Your tests look good to me.

Unit testing Controller.Initialize


How to demangle names in Visual Studio assembler output?

Question: Using Visual Studio 2010/2012, one can compile a c++ source file with the /FAs switch to generate the assembly output of the resulting code. But the generated asm file contains all symbols in their mangled form.
Is there a switch or other smart way to make Visual Studio generate unmangled symbols instead? I know that one could manually feed the asm file through undname.exe but a switch would be much more convenient than a custom post-build event.
Answer: It is not possible to do so, because of the nature of /FA's output.  FA outputs valid assembly code.  The symbols one needs to express a C++ function unmangled are simply not valid label names in microsoft's x86 assembly.  There is also no good notation for anonymous namespaces.
Any output which handled those cases would not be compilable using an assembler.  If you made an assembler which did handle such names, it would need to know whose name mangling rules to apply to assemble it.  This defeats the main purpose of outputting assembly (to see EXACTLY what is going on).
Answer: If all of your symbols are compatible with extern "C" than you could wrap all of your code in the C++ source file in an extern "C" block to force all symbols to be emitted in unmangled C style rather than having C++ name mangling applied.
The Microsoft Research project http://en.wikipedia.org/wiki/Phoenix_%28compiler_framework%29 provides hooks into the toolchain and it might allow direct manipulation of how symbol names are formed, but unfortunately its last public release was for VS 2008 and it doesn't appear to have been productized for inclusion in either VS 2010 or VS 2012.
Comment: Unfortunately, a lot of my symbols are not compatible with `extern "C"`.


Unity3D and Vector Maths - Slepr, Lerp, Quaternions

Question: i have been studying unity3d for a few months and i have done some research of this mathematical concepts that we can use when moving / rotating a object.
I have read some mathematical explanations, but i cant see how it would apply/fit my needs on unity3d.
Can anyone point me out a good material about these two concepts or try to explain me when im gonna need to use quaternions and slerp? Why do i have to use it? When?
I will appreciate any help that i can get.
Answer: You need them because rotation using Euler space (3 dimensions) does not result in smooth rotation, and since arbitrary rotations must be done in multiple steps (about each axis), it is actually possible to collapse one of the dimensions during a rotation and break an animation.
Quarternions and slerp (spherical linear interpolation) uses 4 dimensions (includes imaginary number space) to perform rotations smoothly and in one single step. Almost all games and computer animations use this math to perform rotations, and some of the best tutorials for its use are thus taught in computer animation courses.
So by googling "Quarternion Computer Animation", you get some of the better articles and slide-shows. I'd start there.
Here's a fairly good one that doesn't seem to skip any steps. A brief overview on using matrix notation to perform transformations is important, and this has that covered: http://www.keremcaliskan.com/a-tutorial-on-computer-animation-ii-2/


T/F: $v_1,\dots,v_k\in\mathbb{R}^n$ linearly independent, $u\in\mathbb{R}^n,u\neq0$, then the matrices $uv_1^T,\dots,uv_k^T$ are linearly independent.

Question: If $v_{1},v_{2},\dots,v_{k}$ are linearly independent vectors in $\mathbb{R}^{n}$ and if $u$ is any nonzero vector in $\mathbb{R}^{n}$, then the matrices $uv_{1}^{T}, uv_{2}^{T}, \dots, uv_{k}^{T}$ are linearly independent.
Is this true or false? Please help me.
Comment: But if by vector product you mean dot-product, then each of the $uv_j^T$ is a number, not a vector, so I assume you'd mean the cross-product, but the cross-product is only defined for $\mathbb R^3$ .Are you referring to something else?
Comment: If $u$ and $v$ are row vectors $uv_j^T$ is a real number, but if $u$ and $v$ are column vectors, it is a matrix.
Answer: Hint: Note that $a_1uv_1^T + \dots a_kuv_k^T = u(a_1v_1^T+\dots a_kv_k^T)$. Also, if $u, v \in \mathbb{R}^n\setminus\{0\}$, $uv^T \neq 0$.
Comment: What does this part $u, v \in \mathbb{R}^n\setminus\{0\}$ mean?
Comment: It means that $u$ and $v$ are non-zero vectors in $\mathbb{R}^n$.
Comment: and $u(a_1v_1^T+\dots a_kv_k^T)$ is linear combination
Comment: The expression $a_1v_1^T+\dots + a_kv_k^T$ is a linear combination of the vectors $v_1^T, \dots, v_k^T$, while $u(a_1v_1^T+\dots + a_kv_k^T)$ is the product of the $n\times 1$ matrix $u$ with the $1\times n$ matrix $a_1v_1^T+\dots + a_kv_k^T$.
Comment: Vector space is called linearly dependent if $a_1v_1^T+\dots a_kv_k^T=0$ where nonzero vectors $v$ and not all zero scalar $a$ exist. Here, $a_1uv_1^T + \dots a_kuv_k^T = 0$ $u(a_1v_1^T+\dots a_kv_k^T) = 0$. Therefore, the statement is false.
Comment: Am I missing anything?
Comment: It doesn't make sense to talk about the linear (in)dependence of a vector space. Linear (in)dependence applies to a finite set of vectors: a collection of vectors $\{v_1, \dots, v_k\}$ is said to be *linearly independent* if the only solution to the vector equation $a_1v_1 + \dots + a_kv_k = 0$ is the trivial solution (i.e. $a_1 = \dots = a_k = 0$). Why is the statement false?
Comment: well, is there any way to figure out a solution for here?
Comment: Yes. Suppose $\{uv_1^T, \dots, uv_k^T\}$ were linearly independent. What would that imply about $\{v_1^T, \dots, v_k^T\}$?
Comment: they are linearly independent. $uv_{1}^{T}+uv_{2}^{T}+ \cdots +uv_{k}^{T} \neq 0$ right?
Comment: that was stupid sorry. kernel of {$v_{1}^{T}, \cdots , v_{k}^{T}$} is {0}
Comment: $uv_1^T+uv_2^T+\dots uv_k^T\neq 0$ is true, but that does not imply that $\{v_1^T, \dots, v_k^T\}$ is linearly independent.

$\{v_1^T, \dots, v_k^T\}$ is a collection of vectors, it does not have a kernel, a linear transformation has a kernel.
Comment: sorry I'm completely confused right now. Could you be more explicit please?
Comment: If we want to determine whether $\{uv_1^T, \dots, uv_k^T\}$ is linearly independent or not, we need to consider the solutions to the vector equation $a_1uv_1^T + \dots + a_kuv_k^T = 0$. Are there any other solutions apart from $a_1 = \dots = a_k = 0$?
Comment: so here, we want to find $a_{i}$ for $u(a_{1}v_{1}^{T}+ \cdots + a_{k}v_{k}^{T} = 0$ and we divide both side by $u$ and we have $a_{1}v_{1}^{T}+ \cdots + a_{k}v_{k}^{T} = 0$
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10899/discussion-between-michael-albanese-and-mark)
Comment: I've just finished typing, thank you so much for your help
Answer: If we want to determine whether {$uv_{1}^{T}, \dots, uv_{k}^{T}$} is linearly independent or not, we need to consider the solutions to the vector equation $a_{1}uv_{1}^{T} + \cdots + a_{k}uv_{k}^{T} = 0$. $\rightarrow$ $u(a_{1}v_{1}^{T} + \cdots + a_{k}v_{k}^{T}) = 0$. If $uv^{T}=0$, then either $u$ or $v$ is zero. We were given that $u$ is not zero and $v_1, v_2, \dots, v_k$ are linearly independent. Since $u$ is non-zero, this part $(a_{1}v_{1}^{T} + \cdots + a_{k}v_{k}^{T})$ from $u(a_{1}v_{1}^{T} + \cdots + a_{k}v_{k}^{T}) = 0$ has to be zero. Therefore we conclude that solution for $a_{1}uv_{1}^{T} + \dots + a_{k}uv_{k}^{T} = 0$ is $a_{1}=a_{2}=\cdots=a_{k}=0$, and $uv_{1}^{T}, uv_{2}^{T}, \cdots, uv_{k}^{T}$ are linearly independent if $v$ is linearly independent and $u$ is nonzero vector.
Thanks to Michael Albanese
Comment: Careful. You say $v$ is linearly independent and non-zero but you don't say what $v$ is. If $uv^T = 0$ then either $u = 0$ or $v = 0$. As $u(a_1v_1^T + \dots + a_kv_k^T) = 0$ and $u = 0$, $a_1v_1^T + \dots a_kv_k^T = 0$.


Expected Value Review Question Help; Discrete Mathematics

Question: I'm studying for my discrete exam and I can't figure out this problem in the review, any help is appreciated.
When Jane and Bob have a child, this child is a boy with probability
1/2 and a girl with probability 1/2, independent of the gender of previous children. Jane
and Bob stop having children as soon as they have a girl.
What are the random variables:
B = the number of boys that Jane and Bob have
G = the number of girls that Jane and Bob have.
What are the expected values E(B) and E(G)
Comment: Do you know the mean of a geometrically distributed random variable  or do you need to derive it?
Comment: no, i think i need to derive it
Answer: The mean number of girls is obviously $1$.
For the mean number of boys, call having a boy a failure. We want to find the expected number of failures until the first success. We could do it by summing an infinite series, or by conditioning, or by thinking.
Let $a$ be the expected number of failures. If there is a success on the first trial  (probability $1/2$), then the number of failures is $0$. If there is a failure on the first trial, the conditional expectation of the number of additional failures, given there was a failure on the first trial, is $a$. Thus in that case the expected total number of failures is $1+a$. Thus
$$a=(1/2)(0)+(1/2)(1+a).$$
Solve for $a$. We get $a=1$.  The expected number of boys is also $1$.
If we think about it, the result is obvious. On any birth, the expected number of boys is the same as the expected number of girls.
Remarks: $1.$ With the series approach, we end up summing the infinite series
$$\frac{1}{4}+\frac{2}{8}+\frac{3}{16}+\frac{4}{32}+\cdots.$$
There are arious methods for summing this sort of series. The problem has been solved repeatedly on MSE.
$2.$ If you already know that the geometric with parameter $p$ has expectation $\frac{1}{p}$, then you can see that the expected total number of children is $2$, and hence the expected number of boys is $1$.
Comment: How did u solve for a. that u get a = 1. I got a = -1?
Comment: Steps: $a=\frac{1}{2}+\frac{1}{2}a$. So $\frac{1}{2}a=\frac{1}{2}$. So $a=1$.  Or else multiply through by $2$. We get $2a=1+a$ so $a=1$.


Finding the coefficients $p_0,p_1,p_2,q_1,q_2,q_3$ of Padé approximation

Question: Determine the Padé approximation of degree $5$ with $ n =2 $ and $ m= 3$ for $f(x) = e^{-x}$.

Suppose $r$ is a rational function of degree $N$.$$
r(x) = \frac{p(x)}{q(x)} = \frac{p_0 +p_1x + \cdots + p_nx^n}{q_0 +q_1x+ \cdots + q_mx^m}.
$$
The Padé approximation technique is$$
f(x)-r(x) = f(x)-\frac{p(x)}{q(x)} = \frac{f(x)q(x)-p(x)}{q(x)} = \frac{\left(\sum\limits_{i=0}^{\infty} a_ix^i \right)\left(\sum\limits^m_{i=0}q_{i}x^i \right)-\sum\limits^n_{i=0} p_ix^i}{q(x)}.
$$
To find the Padé approximation we need to choose $p_0,p_1,p_2,q_1$ and $q_2,q_3$. The Maclaurin expansion of $e^{-x}$ is $\sum\limits_{i = 0}^{\infty} \dfrac{(-1)^i}{i!} x^i$. Since $q_0 \neq 0$, thus $q_0= 1$ if $x= 0$, and $p_0 =1$. How does one find $p_1,p_2,q_1,q_2,q_3$ ao that$$
r_{2,3}(x) = \frac{p_0+p_1x+p_2x^2}{q_0+q_1x+q_2x^2+q_{3}x^3}?
$$
Does one have to transform this into a linear equation to solve?$$
\begin{bmatrix}
a_0 &  &  & &\\
a_1 & a_0 & & &\\
a_2 & a_1 & a_0&& \\
a_3 & a_2 & a_1& a_0&\\
a_4 & a_3 & a_2 & a_1&a_0\\
\end{bmatrix} \begin{bmatrix}
q_1\\
q_2\\
q_3\\
0\\
0
\end{bmatrix} - \begin{bmatrix}
p_1\\
p_2\\
0\\
0\\
0
\end{bmatrix} = -\begin{bmatrix}
a_1\\
a_2\\
a_3\\
a_4\\
a_5
\end{bmatrix}
$$
How do I solve this linear system so I may obtain the solution? Can someone demonstrate a concise method of Gaussian elimination to find $r_{2,3}$ and that can also work for $r_{1,4}$ or any $r_{n,m}$ for Padé approximation?
Comment: @keith I found a website that shows a method using Gaussian Elimination with backward substitution to approximate the answer. Unfortunately it does not state how to use this method to find other r(x) such as $n= 2$ and $m=3$.

 [Website](https://jmahaffy.sdsu.edu/courses/s10/math541/lectures/pdf/week13/lecture.pdf)
Comment: They do $n=3$ and $m=2$. I think the method is similar in your case.
Answer: $\newenvironment{gmatrix}{\left\lgroup\begin{matrix}}{\end{matrix}\right\rgroup}$In general, to find the Padé approximation $r(x) = \dfrac{\sum\limits_{k = 0}^n p_k x^k}{\sum\limits_{k = 0}^m q_k x^k}$ for $f(x) = \sum\limits_{k = 1}^\infty a_k x^k$, it reduces to find the solution to$$
\begin{gmatrix}
a_0 &&&\\
a_1 & a_0 &&\\
\vdots & \ddots & \ddots &\\
a_{m + n} & \cdots & a_1 & a_0
\end{gmatrix} \begin{gmatrix}
q_0 \\ q_1 \\ \vdots \\ q_{m + n}
\end{gmatrix} = \begin{gmatrix}
p_0 \\ p_1 \\ \vdots \\ p_{m + n}
\end{gmatrix}, \tag{1}
$$
where $p_{n + 1} = \cdots = p_{m + n} = 0$, $q_{m + 1} = \cdots = q_{m + n} = 0$. In order to solve this system of equations, usually it is assumed that $q_0 = 1$ and (1) becomes$$
\begin{gmatrix}
a_0 &&\\
\vdots & \ddots &\\
a_{m + n - 1} & \cdots & a_0
\end{gmatrix} \begin{gmatrix}
q_1 \\ \vdots \\ q_{m + n}
\end{gmatrix} - \begin{gmatrix}
p_1 \\ \vdots \\ p_{m + n}
\end{gmatrix} = \begin{gmatrix}
a_1 \\ \vdots \\ a_{m + n}
\end{gmatrix},\ p_0 = a_0.
$$
Since\begin{align*}
&\mathrel{\phantom{=}}{} \begin{gmatrix}
a_0 &&\\
\vdots & \ddots &\\
a_{m + n - 1} & \cdots & a_0
\end{gmatrix} \begin{gmatrix}
q_1 \\ \vdots \\ q_{m + n}
\end{gmatrix} = \begin{gmatrix}
a_0 &&\\
\vdots & \ddots &\\
a_{m + n - 1} & \cdots & a_0
\end{gmatrix} \begin{gmatrix}
q_1 \\ \vdots \\ q_m \\ 0 \\ \vdots \\ 0
\end{gmatrix}\\
&= \begin{gmatrix}
a_0\\
\vdots & \ddots\\
a_{m - 1} & \cdots & a_0\\
a_m & \cdots & a_1 & 0\\
\vdots & \ddots & \vdots & \vdots & \ddots\\
a_{m + n - 1} & \cdots & a_n & 0 & \cdots & 0
\end{gmatrix} \begin{gmatrix}
q_1 \\ \vdots \\ q_m \\ 0 \\ \vdots \\ 0
\end{gmatrix} = \begin{gmatrix}
A & B\\
C & O
\end{gmatrix} \begin{gmatrix}
q_1 \\ \vdots \\ q_m \\ 0 \\ \vdots \\ 0
\end{gmatrix},
\end{align*}
where$$
A = \begin{gmatrix}
a_0\\
\vdots & \ddots\\
a_{m - 1} & \cdots & a_0
\end{gmatrix},\ B = -I_n,\ C = \begin{gmatrix}
a_m & \cdots & a_1\\
\vdots & \ddots & \vdots\\
a_{m + n - 1} & \cdots & a_n
\end{gmatrix},
$$
and $O$ is an $m × n$ zero matrix, and$$
-\begin{gmatrix}
p_1 \\ \vdots \\ p_{m + n}
\end{gmatrix} = -\begin{gmatrix}
p_1 \\ \vdots \\ p_n \\ 0 \\ \vdots \\ 0
\end{gmatrix} = \begin{gmatrix}
A & B\\
C & O
\end{gmatrix} \begin{gmatrix}
0 \\ \vdots \\ 0 \\ p_1 \\ \vdots \\ p_n
\end{gmatrix},
$$
then (1) is equivalent to$$
\begin{gmatrix}
A & B\\
C & O
\end{gmatrix} \begin{gmatrix}
q_1 \\ \vdots \\ q_m \\ p_1 \\ \vdots \\ p_n
\end{gmatrix} = \begin{gmatrix}
a_1 \\ \vdots \\ a_{m + n}
\end{gmatrix},\ p_0 = a_0. \tag{2}
$$
Now, to find the Padé approximation $r(x) = \dfrac{\sum\limits_{k = 0}^2 p_k x^k}{\sum\limits_{k = 0}^3 q_k x^k}$ for $f(x) = \mathrm{e}^{-x} = \sum\limits_{k = 1}^\infty \dfrac{(-1)^k}{k!} x^k$, from (2) there is $q_0 = 1$, $p_0 = 1$, and$$
\begin{gmatrix}
1 &&& -1\\
-1 & 1 &&& -1\\
\dfrac{1}{2} & -1 & 1\\
-\dfrac{1}{6} & \dfrac{1}{2} & -1\\
\dfrac{1}{24} & -\dfrac{1}{6} & \dfrac{1}{2}
\end{gmatrix} \begin{gmatrix}
q_1 \\ q_2 \\q_3 \\ p_1 \\ p_2
\end{gmatrix} = \begin{gmatrix}
-1 \\ \dfrac{1}{2} \\ -\dfrac{1}{6} \\ \dfrac{1}{24} \\ -\dfrac{1}{120}
\end{gmatrix},
$$
thus $q_1 = -\dfrac{3}{5}$, $q_2 = -\dfrac{3}{20}$, $q_3 = -\dfrac{1}{60}$, $p_1 = \dfrac{2}{5}$, $p_2 = -\dfrac{1}{20}$. Therefore,$$
r_{2, 3}(x) = \frac{1 + \dfrac{2}{5}x - \dfrac{1}{20} x^2}{1 - \dfrac{3}{5} x - \dfrac{3}{20} x^2 - \dfrac{1}{60} x^3}.
$$
Comment: Are the blank spaces in your matrix zeros?
Comment: One last question I know you might have answered it in the answer but why does the -1 columns go at the 2nd to last column and the last column of A?
Comment: One last thing if you add the negative on the matrix $b$ that should give you $\frac{1-2/5x+1/20x^2}{1+3/5x+3/20x^2+1/60x^3}$ which gives you the final answer.
Comment: @Jon Why reversing the signs? They're not the solution to (2) if signs are reversed.
Comment: I just do that to match the answer given in the solution that's all.


Local fundamental theorem of affine geometry

Question: The fundamental theorem of affine geometry implies that a bijection $f \colon \mathbb R^n \to \mathbb R^n$ is affine if $n \geq 2$ and $f$ maps lines to lines. I was wondering, does this hold locally? Suppose $\Delta$ is a (non-degenerate) simplex of dimension $n$, $f \colon \Delta \to \Delta$ a bijection mapping each vertex to itself, and mapping segments to segments, can we readily say that $f = \textrm{id}_\Delta$? (I chose a simplex as there exists a unique affine map mapping vertices to themselves, namely $\textrm{id}_\Delta$.)
Comment: It seems it suffices to prove it for $n=2$, as you can easily proceed by induction from there.
Comment: Correct, if it's true for some $n$, then each "face" is mapped identically, any inside point is at the intersection of the image of the segments whose edges are on the boundary, passing through the considered point, hence the proposition holds for $n+1$.
Answer: No, this is not true.  Let us say $\Delta=\{(x_0,\dots,x_n)\in[0,1]^{n+1}:\sum_i x_i=1\}$.  Let $a_0,\dots,a_n>0$ be any sequence of positive constants and define $g(x_0,\dots,x_n)=(a_0x_0,\dots,a_nx_n)$.  Then there is a bijection $f:\Delta\to\Delta$ given by $f(x)=g(x)/s(g(x))$ where $s(g(x))$ denotes the sum of the entries of $g(x)$.  This bijection fixes the vertices of $\Delta$ and is not the identity unless all the $a_i$ are the same.  However, I claim that it sends segments to segments.
To prove this, let $x,y\in\Delta$ and let $t\in[0,1]$.  We wish to show that $f(tx+(1-t)y)$ is on the line segment between $f(x)$ and $f(y)$.  But now observe that since $g$ is linear,
\begin{align*}f(tx+(1-t)y)&=\frac{tg(x)+(1-t)g(y)}{ts(g(x))+(1-t)s(g(y))} \\
&=\frac{ts(g(x))}{ts(g(x))+(1-t)s(g(y))}f(x)+\frac{(1-t)s(g(y))}{ts(g(x))+(1-t)s(g(y))}f(y)
\end{align*}
which is evidently a convex combination of $f(x)$ and $f(y)$.
However, these are the only examples of such maps if $n\geq 2$.  To sketch the proof, observe that by starting with the barycenter and the vertices and repeatedly taking intersection points of segments between the points you have, you can generate a dense subset of each boundary edge of $\Delta$.  It follows that a segment-preserving bijection $\Delta\to\Delta$ which fixes the vertices is uniquely determined by where it sends the barycenter.  But now note that $a_0,\dots,a_n$ may be chosen so that $f$ as constructed above maps the barycenter of $\Delta$ to any other point in its interior.

Here is a more geometric perspective on what's going on.  Note that if we think of $\Delta$ as sitting inside an affine space $\mathbb{A}^n$ which in turn sits inside a projective space $\mathbb{P}^n$, then these bijections do extend to automorphisms of the projective space (but not the affine space).  So a "local collineation" on an open subset of projective space still must be "linear" in the sense of projective geometry (i.e., in homogeneous coordinates).  It's just that if your open subset happens to be contained in an affine space, it may not look linear in those particular affine coordinates.
Moreover, note that while an automorphism of $\mathbb{A}^n$ is determined uniquely by where it sends $n+1$ points, an automorphism of $\mathbb{P}^n$ is only determined uniquely by where it sends $n+2$ points.  So considering automorphisms of projective space exactly gives you one more "degree of freedom" beyond just fixing the $n+1$ vertices of a simplex (as seen above where the barycenter can be mapped anywhere in the interior of the simplex).
Comment: An affine space $\mathbb{A}^n$ embeds in $\mathbb{P}^n$ by mapping $(x_0,\dots,x_{n-1})$ to the point with homogeneous coordinates $[x_0,\dots,x_{n-1},1]$.  The image of this embedding is all points of $\mathbb{P}^n$ whose final coordinate is nonzero (since you can then always scale to make the final coordinate $1$).  The complement is thus the points with last coordinate $0$, which form a hyperplane in $\mathbb{P}^n$.  This is thought of as a "hyperplane at infinity" which is added to $\mathbb{A}^n$ to form $\mathbb{P}^n$.
Comment: I see, I am just not familiar at all with the relation between affine and projective spaces. Concretely I can see the simplex $\Delta$ sitting inside $\mathbb R^{n+1}$, then any linear map of $\mathbb R^{n+1}$ transforms $\Delta$ into some (possibly degenerate simplex), which can be radially projected on the affine space in which $\Delta$ sits. But what do you mean by "the affine space sits inside a projective space"? One is a set of points, the other one a set of lines.
Comment: This makes a lot of sense, especially visualizing with plain old $\mathbb R^3$. Thank you for your time.


What is the largest area from this following triangle?

Question: Given coordinates A(2,0), B(0,2), and C is in line x+y= 5. We want to form the triangle ABC from these coordinates.
What is the largest possible area for this triangle?
My thinking about this problem is firstly we need to find a couple of coordinates such that the coordinates is formed the special triangle such that equilateral, isosceles or right isosceles triangle.
By using a distance concept, I've discovered that we cannot form the equilateral triangle from this problem. Instead of that, I can only get the form of isosceles triangle with area $$3*sqrt{17}$$, based on condition the coordinate of C is (2,5;2,5).
My question: Is my thinking true? Or there is another method to find the coordinate C such that maximizes the area of triangle?
Comment: Is $AB$ parallel to the line $x+y=5$?
Comment: Based on my picture, I think AB is parallel to the line x+y=5. But, is it matter to this problem? Thanks
Comment: The area of a triangle is half base times height. You have a base $AB$ given. What can you say about the height from that base? (Draw a diagram)
Comment: We can draw a line perpendicular to the line x+y=5 from the base. It means we need to find the height from the trapezium here. Is it true? Thanks
Comment: I am sorry, you have not defined a triangle.
Answer: I don't think you will ever get an equilateral triangle in this case.
The area will be symmetric about the point (2.5,2.5) and as we approach infinity, the area of the triangle approaches zero (could be seen easily by drawing a figure). This implies the area will be maximum at the point of symmetry.
Answer: So here is how the things sketch out

The base of your triangle will be the line between (2,0) and (0,2). And the height of the triangle will be the (perpendicular) distance be the red and blue lines. SO no matter what triangle you draw between the lines with the base between (2,0) and (0,2) you always get the same area.


Prediction of a continuous variable

Question: I'm trying to create a model to predict a continuous variable, that is the revenue of a movie, given many predictors, such as its budget, the length of the film, the genre... I'm planning to use MLP, but I'm not sure on how to deal with the dependent variable: should I bin it in different ranges of revenues? If so, how many classes could work with MLP? If not, what should I do with it?
Comment: Please correct me if I'm wrong, but it sounds like you have a regression task and you are under the impression that MLPs can only be used for classification. That isn't true. MLPs can be used for regression without turning the dependent variable into a categorical variable: simply use an activation in the last layer that is suitable for regression (like a linear activation)
Comment: For example, see [scikit-learn's MLPRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPRegressor.html)
Answer: You can use an MLP for a regression task. A typical loss function would be mean square error, but there are many others with different statistical properties. Likewise, while a classification task usually has a softmax or sigmoid activation on the output, a regression task typically uses the identity function, but you have other options as well.

Prediction of a continuous variable


Amazon EC2 Windows 2008 Instance Unresponsive After Reboot

Question: After doing some fairly inconsequential set up of a new Windows 2008 server instance it will cease responding to any connection attempts after a reboot. RDP, HTTP, HTTPS, you name it. I am unsure if this is because the installation has become corrupt or if something in Windows 2008 is triggering security measures and simply blocking all inbound connections.
Answer: A user on the Amazon forum's led me to a solution. The problem will occur after binding an SSL cert to a website in IIS that was not issued from a recognized CA. I'm not sure if this would be classified as a bug or by design but it's confusing either way. To resolve the issue you must verify the existence of the issuing CA's certificate in the Trusted Root Certificate Authorities store. You can do this with the following steps:

Click Start
Type 'mmc' in the search and hit
enter
Click file->add remove snap in
Locate the Certificates snap in and click Add
Select the Computer Account
Click Ok
Expand the Certificates snap in
Locate the Trusted Root Certificate Authorities store

If the issuing CA of your SSL cert does not exist you must import it into the store. You can do this by retrieving a cer file for the issuing CA, and importing it by right clicking and selecting All Tasks->Import... and following the steps in the wizard.


An interesting wire-tying problem to match wire ends in as few trips as possible

Question: You have $N$ wires that all extend from one location to a second distant location. The wire ends at both locations are unlabeled, and the goal is to label them all (on both ends) with distinct labels $1,2,\ldots, N$ so that the two ends of the same wire have the same label for every wire. I.e., the goal is to match every pair of wire ends.
The operations you can perform (on either end) are as follows: You can tie or untie any subset of wires together, and you can use a connectivity detector to tell if two wires are tied together on the other end. While on one of the two locations of wire ends, you can tie, untie, and test connectivity as much as you want. However, the goal is to minimize the number of trips between the two locations so that you can guarantee that you can label all the wire ends.
It seems like perhaps considering the case of even $N$ and odd $N$ separately may be a good idea, but still, is there an easy-to-describe strategy to minimize the number of trips? And prove the solution is optimal? If it helps, especially to prove optimality, we might assume that you only tie/untie wires at the starting location, and only test connectivity at the second location.
Answer: I have found a provably optimal solution for odd $N$ if we assume that you can only test connectivity at the second location, and only tie/untie at the first location. First label the wires $1$ to $N$ at the first location.
Then tie together wires in pairs in consecutive order, i.e. $(1,2)$,$(3,4)$, and so on, and leave wire $N$ untied. Then travel to the second location and determine all pairs of wires that are connected, by testing all pairs, and also likewise determine the wire $N$ that isn't tied to anything.
Then travel back, untie everything, and now tie together in consecutive pairs $(2,3)$,$(4,5)$, etc., up to $(N-1,N)$, leaving wire 1 untied. Travel to the second location and determine all pairs that are connected along with the wire 1 that isn't tied to anything.
Now, we know which wire is wire 1, but then by the first round of tying we know which wire is wire 2, and then by the second round of tying we know which wire is wire 3, and then by the first round of tying we know which wire is wire 4, etc. And clearly you have to tie wires and test connectivity at least twice, so this solution is optimal, at least when you can only tie at the first location and test at the second location.
However in terms of one-way trips, this takes 3 trips and if we are allowed to tie wires at the 2nd location and test connectivity at the first location I can't prove that we can't do it all in 2 one-way trips.
Also, I don't have a similar solution for even $N$ unless we use 5 one-way trips, and I think it's probably possible to get it down to 3 one-way trips for even $N$ too.
Comment: This problem, with this solution, resurfaced at [The Riddler, 2016-12-16](http://fivethirtyeight.com/features/build-your-own-death-star-and-defeat-the-stormtroopers/)
Answer: For $N=1$ You need no trips. For $N=2$ the operations are not enough to solve the problem in any way. For $N\geq3$, at least two one-way trips are necessary, because in the first trip, you can't distinguish a wire from the one(s) connected to it without separating them later. It can be shown that two one-way trips are sufficient to identify all the wire ends (but if you really need to "label" the wire ends, it's sufficient to travel once more, similar to $N=1$. It's easy to see that this "extra" trip is necessary too).
Let's first assume that $N$ is odd. Label the wires $1$ to $N$ at the first location. tie together wires in pairs: $(2,3),(4,5),\dots$. Travel to the other side. Determine all the pairs (call them twins) and identify wire $1$. Tie wire $1$ and another wire (call it $a$) together, Tie $a$'s twin and another wire (call it $b$) together, Tie $b$'s twin and another wire together, and so on. Travel back and separate the tied pairs. Check which wire is connected to wire $1$, that would be $a$; Then $a$'s twin is identified and $b$ will be the one connected to it, and so on.
Now assume that $N$ is even. Tie together wires in pairs: $(2,3),(4,5),\dots$, so wires $1$ and $N$ are not connected to any other wire. Travel to the other side. Determine all pairs and the two lonely ones. Let one of the lonely ones alone again and use the other one in the same way as the odd case. Travel back and identify the wire that was alone in both trips, and then identify the other wires similar to the odd case.
Comment: I think I understand, basically you are saying that rather than maintain the ordering in the pairings of wires when wires are ordered, we can just tie a sequence of different pairs together at the 2nd location (such that all wires except one are used) after we make the first 1-way trip to test, and then we can still identify everything because we are tying the wires in a new chain at the 2nd location, where no two originally paired wires are tied together at the 2nd location. I believe I also see the case of an even number of wires. Thanks.
Answer: This can be done in $\log_2n$ trips.
When you start out you label one of the wires $1$ and tie the other $n-1$ wires together. Go to the other side and label the unconnected wire $1$ and choose another wire and label it $2$. Tie this wire to wire $1$. Go back to the first side and untie all wires and test for connectivity. You'll now have wires $1$ and $2$.
Since you have two wires, you can tie one remaining wire to $1$ and label it $3$ and tie another wire to $2$ and label it $4$. Proceed to the other side and untie all wires. Testing for connectivity will give you $3$ and $4$.
Having labeled wires $1 .. k$, tie an unlabeled wire to $1$ and label it $k+1$, a wire to $2$ labeled $k+2$ up to a wire tied to $k$ labeled $2k$. Go to the other side, untie all wires and test for connectivity. You now have $2k$ wires labeled.
Since you double the number of wires you label on each trip, you label all wires in $\log_2n$ trips.
Answer: Tie cables in bunches of 1, 2, 3, 4,.....n i.e. greatest n such that (Z =) N - n(n+1)/2 >n and in the first trip itself Z is known
Now treating Z as the new N, repeat the above steps...
After a few recursions, the no. of steps would dramatically come very little i.e.
For N = 3,4,5,6,7,8,9,10 its respectively 2,3,3,3,4,4,4,5
For N = 100, its 6 only
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: In this way 26796 (or 1+2+3+...231) cables can be labelled in just 6 trips (i.e. 3 to & fro moves as 231 = 1+2+...21 & 21 = 1+2+3+4+5+6 & 6=1+2+3 & 3=1+2)


All nginx access logs from 127.0.0.1 (so can't use fail2ban)

Question: Problem
I'm trying to configure fail2ban to block ddos attacks using the chunk shown here.
Basically it looks at all requests and if any single IP makes more than 240 requests over 60 seconds it blocks them for two days.
However all the logs in my nginx access are from 127.0.0.1 which makes the whole thing pointless.
What could cause nginx to log all traffic as coming from the server?
(I'm running Drupal on a LEMP stack with perusio's nginx config.)
Comment: What are you running in front of nginx?
Comment: Hmm. Varnish. I'd not thought of that. Shoot that would explain it. I'm going to need to somehow get the logs from varnish
Answer: Since you have varnish in front of nginx, it thinks all the requests are coming from 127.0.0.1, since technically they are.
To resolve this, use the nginx real ip module to pick the client's IP address out of the X-Forwarded-For header, which Varnish automatically adds to requests (unless you told it not to).
An example nginx configuration would be:
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;

Comment: Thanks Michael you've just rescued my Sunday afternoon. As it turns out the chunk is actually in Perusio's config but I just hadn't understood the purpose and so I hadn't set it up.
Answer: The example piece of configuration Micheal is talking about is in the top level nginx config at /etc/nginx/nginx.conf if you're using Perusio's config.
http {
    ## MIME types.
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ## FastCGI.
    include /etc/nginx/fastcgi.conf;

    ## Default log and error files.
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ## Use sendfile() syscall to speed up I/O operations and speed up
    ## static file serving.
    sendfile on;
    ## Handling of IPs in proxied and load balancing situations.
    set_real_ip_from 0.0.0.0/32; # all addresses get a real IP.
    real_ip_header X-Forwarded-For; # the ip is forwarded from the load balancer/proxy

You need to change 0.0.0.0/32 to 127.0.0.1.


Browser opens then closes prior to Ruby Script failing

Question: All ruby test scripts have this same issue.
Once the Browser opens, it closes after 22 seconds and prior to the rest of the test script running. Below is the function that fails after b = Watir::Browser.new :chrome. All the scripts were running without issues 3 weeks ago. Now none will advance pass b = Watir::Browser.new :chrome.
def startBrowser

time0 = Time.new
  b = Watir::Browser.new :chrome

  b.goto "https://test.mtc.byu.edu/assessmenttools/"

  if browser.title == "Assessment Tools"
    puts "Assessment Tools".yellow
    return browser
  else
    browser.close()
    return nil
  end
end

Answer: My guess is that the version of chromedriver and/or selenium-webdriver are not compatible with the new version of Chrome.
Try:

Update your chromedriver to the latest version, which is currently 2.9.
Update your selenium-webdriver to the latest version, which is currently 2.39.0 - gem install selenium-webdriver
Answer: It seems it the same bug as Chromedriver crashes when lauched from watir-webdriver
It is due to a childprocess issue ( https://github.com/jarib/childprocess/issues/71#issuecomment-35094547 )


A few questions about cyclic groups

Question: I cannot understand how is $\langle 1 \rangle$ the creator of $(\mathbb{Z},+)$. I know that this element can create all-natural numbers, simply by adding-1 a certain amount of times, but the negative numbers cannot be created. So what I thought is that each element has a negative number, but still, I can't see how $\langle 1 \rangle$ can create by itself all elements of $\mathbb{Z}$, only both -1 and 1 can create together all elements.
In addition, I have seen a couple of times that for example - the group $Z^{*}_8$ if defined as $Z^{*}_8=\{[1],[3],[5],[7]\}$. In order to check the elements that a certain element create, which means the order, we check the power of the element until we start returning on the elements created, let say $\langle 5 \rangle=\{[5]^{1},[5]^{2},[5]^{3}\}=\{[5],[1],[5]\}$ so the order is 2. Now, I know that power represents the amount of time we run the method $*$ of the group, but if so, why is here with $Z^{*}_8$ we see (*) as ($\cdot $), and in the group - $(\mathbb{Z},+)$ we check as $\langle 2 \rangle=\{2,2+2,2+2+2,...\}$ and so on?
I hope you can help me understand this. Thanks!
Comment: Review the definition of *generator*.  Negative exponents (or coefficients) are allowed. This creates all the negative naturals.
Comment: Use `\langle x \rangle` for $\langle x \rangle$ instead of `< x >`
Comment: @VIVID I wanted, but I thought it is better. Anyway I am gonna change it.
Answer: Notice that $\langle 1\rangle$ contains $-1$, since without it it isn't a group ($-1$ is the inverse element of $1$, because $1+(-1)=0$ in $(\mathbb{Z},+)$). Hence, you should understand that $\langle 1\rangle$ being a group implies $-1\in \langle 1\rangle$ so then you can easily see how it generates all integers.
In the second question, in $\mathbb{Z}_8^\times$ you're referring to the multiplicative group of $\mathbb{Z}_8$, to be said, the $\mathbb{Z}_8$ elements that have inverse for multiplication (Notice this is NOT the same as inverse for addition, the operation you use in integer groups). So in $\mathbb{Z}_8^\times$ the operation you're using is multiplication, while in $\mathbb{Z}$ or $\mathbb{Z}_8$ you're using addition, and powers in addition and multiplication are different though both can share the same $a^n$ notation:

In multiplication, $a^n=a\cdot a\cdots a$
In addition, $a^n=a+a+\cdots+a$
Comment: Got it. Thank you so much!!!
Comment: Thanks! what about my second question?
Comment: @Anon142 you're welcome! I'm still reading it, I'll edit if I know how to help you with that question.
Comment: No problem. Thank you! :)
Comment: @Anon142 I'm a bit confused about the notation you used in second question. Do you mean $\mathbb{Z}_8^\times$ when you say $\mathbb{Z}_8^*$?
Comment: @AlejandroBergasaAlonso those are both common notations for the same thing.
Comment: @Randall Thanks! I had never used that notation before, now I know.
Comment: So they referred to the multiplicative group?
Comment: @Anon142 exactly.
Answer: A group $G$, written multiplicatively, is called cyclic if there is an elemet $a \in G$ with $G = \langle a \rangle =\{a^n \mid n \in \mathbb{Z}\}$.  Note that $n$ spans all the integers.  If the group is written additively, this becomes
$$
G = \langle a \rangle =\{na \mid n \in \mathbb{Z}\}.
$$
So in exponential notation we get terms like
$$
\ldots, a^{-2}, a^{-1}, a^0=e, a, a^2, \ldots
$$
In additive notation this would read
$$
\ldots, -2a, -a, 0, a, 2a, \ldots
$$
With $a=1$ this explains why $1$ generates all of $\mathbb{Z}$ (as does $-1$).

A few questions about cyclic groups


Webforms: pages 1,2 of 4 not being displayed

Question: I'm developing my first Drupal 8 Webforms application. It had three pages to start with and I had managed to get it to do what I wanted it to. I have also developed a WebformHandler to go with it.
I needed to add an extra page between the old 1st and 2nd page. I created this using the "build" tab and it was created in 4th position in the list of pages, so I dragged it up to 2nd position and did "Save Elements".
But then, when I used the "View" tab to try out the form, the dialogue started at the 3rd page (the old 2nd page). I have now deleted the new 2nd page and appear to have the same old configuration that worked, but using the "View" tab still ignores the first page.
I have flushed all the caches; I have looked in the database for anything obvious (but not found anything); I have looked at the YAML files in the module I created for the Webform; I have even rebooted the server.
I have tried to scan the entire Drupal file tree looking for files that have been modified in the last couple of hours (since the webform last started correctly), but I haven't managed to find anything, except the WebformHandler, but that isn't called before the initial page is shown.
Using a different browser (Safari instead of Chrome) produces the same result, so I guess the problem is on the server and not the client.
Somewhere, something is holding information about my webform: could anyone help me to locate it?
Comment: If you can't figure this out, please export the webform config and create a GIST (https://gist.github.com/) so that we can look at the source code.
Comment: most likely a indentation in the source yml enable webform devel and view the source see if any thing is miss aligned ?
Comment: Thanks for your comments. I have found the problem. The element editor in Webforms includes an "Access" tab. For the pages in question, I had removed all permissions for all roles under this tab, which included the "administer" role I work under, so – obviously :-) – I had no access to those pages.
Comment: @StephenWinnall Could you post this as an answer for the benefit of future visitors?
Answer: I was looking in the wrong places...
The element editor in Webforms includes an Access tab. For the pages that were not being shown I had removed all the permissions, which included the permissions of 'Administrator', the user I was logged in as. So – obviously – those pages were not shown.
Duuhh.


Probability that seems to exceed 1

Question: Suppose we have the following information based on independent events:

The probability of contracting Alpha variant is .4
The Delta variant is 50% more contagious than Alpha
The Omicron BA1 variant is 50% more contagious than Delta
The Omicron BA2 variant is 50% more contagious than Omicron BA1

Calculating this as-is would give the following probabilities:

Probability of Alpha = .4
Probability of Delta = .6
Probability of Omicron BA1 = .9
Probability of Omicron BA2 = 1.35

Since we know that the probability of an event cannot exceed 1, it is clear I am not thinking about this correctly.  Can you nudge me in the right direction?
Comment: You appear to be interpreting "more contagious" directly in terms of probabilities.  That doesn't make sense either statistically or epidemiologically.  Your calculations help demonstrate that fact.  Whatever "contagious" means and however it is measured, you need an epidemiological model to translate that into probabilities.
Answer: Think about rolling multiple 6 sided dice. (And rolling a particular number on a dice would be a model for getting infected)
The probability to roll 3 or less with one single dice is 50%.
When you have $1.5 \cdot 1.5 \cdot 1.5 = 3.375 \approx 3 $  more dice then this probability to roll a 3 or less is now, 87.5% and not 150% percent.

The number of dice is a very simple toy-model for the probability to get sick. In reality you have many factors, the number of people you encounter, the probability that they are infectious, how long they are infectious, how much viral parts they carry around, how well the transmission is, etc.
In terms of the contagiousness it is often related to the $R_0$ value which is a combined value of all above and relates to the number of other people that get infected by another infected person. (And this value is estimated by observing and comparing the growth rate of different viruses and using measurements in test animals, laboratory and interviews that investigate contacts of positively tested people and how many of those contacts get infected)
Then the probability to get sick/infected might be much more subtle. For a highly contagious disease like COVID most people will eventually get infected one or more times. The contagiousness only influences how fast it happens and how steep the peak will rise. It is not so much about if you get infected, but more about when you get infected.
Comment: @Dave It is slightly different. You are relating 50% more contagious somehow with 2 times less probability to not get sick. The mechanism behind it is not so clear. How would you interpret 100% more contagious?
Comment: I like the dice example. At its essence, this is the same as what I posted, yes?

Probability that seems to exceed 1


Basic standard error issue with short event

Question: I'd like to measure the duration of a function call. The function call has one parameter, n. If I were to graph an average of the function call's duration, with n on the x axis, I would also provide the standard error for each n.
The function call duration is, however, extremely short. It seems more appropriate to time, say, 100 calls. Is this approach completely orthogonal to the earlier use of the standard error? Does an average of the 100 calls now count as 1 measurement? Does it have a standard error?
Answer: Does an average of the 100 calls now count as 1 measurement?
Basically you can measure anything and define the measurements to be the values of an (unknown) variable. In your case this variable X:="average duration across 100 functions calls given parameter n", so 100 calls count as one measurement.
Does it have a standard error?
Yes, given you have enough data (2 points), you can measure the standarddeviation/error of every variable. The question is whether the value is meaningful, which is only the case when the distribution is symmetric. If you are not sure about that you are better of considering the percentiles of the data or a robust scale measurement (see On univariate outlier tests (or: Dixon Q versus Grubbs))
Is this approach completely orthogonal to the earlier use of the standard error?
No. Let's assume a normal distribution $N(\mu,\sigma^2)$. When one repeatly draws a sample of 100 values from this distribution and calculates the average across this values, is this the same as estimating the mean from $N(\mu,\sigma^2)$ based on samples of size 100. The distribution of this estimation is t-distributed (approximately normal) with mean=$\mu$ and variance=$(\frac{\sigma}{\sqrt{n}})^2$
In summary: I'd check that the average duration of function calls is approximately normal (or symmetrically) distributed and just report the error. If this is not true, I'd report the percentiles instead. In the latter case (or in general) a boxplot provides a good visualization.
Comment: Thankyou. I do though want to express the time in terms of one function call. I'm afraid I find your answer difficult to follow.
Comment: @user643722 I do not understand. Then treat the duration of one function call as single measurement instead of the average duration across 100 calls ? Without stating what exactly yo do not understand, I cannot adjust my answer. But maybe I am on the wrong track and only someone else can help us out.
Comment: Thanks again. I'll think your answers over. The small time I measure for one function call varies considerably. It seems sensible to measure the duration for 100, and average. But would I improve things by doing this n times, to obtain a standard error? Or would it be equally good to measure the duration of n*100 functions, and average?
Comment: @user643722 The latter is more precise and hence recommended.
Comment: Ok. But then I have no standard error, just the time for n*100 function calls.
Comment: @user643722 I am in chat "ten fold" now. Please join if you want to continue the discussion.
Comment: @user643722 since you did not show up: If you use n*100 functions calls, you have n*100 measurements and hence both an average and a standard-error. This is more precise than having n measurements (with each measurement=average across 100 calls) and calculating average and standard error across this n values.  Frankly, I cannot follow your line of thought.


When is the ring of functions of a quotient variety a smooth algebra?

Question: Let $V$ be a finite-dimensional complex vector space over an algebraically closed field $k$ of characteristic $0$. Let $k[V]$ be the ring of functions on V. Since $V$ is a smooth (non-singular) variety, we know that $\mathbb C[V]$ is a smooth $k$-algebra.
Assume that $G$ is a finite subgroup of $GL(V)$. In general, the quotient variety $V/G$ is not smooth. However, what can we say about the ring of functions $k[V]^G$ of $V/G$? Is it smooth or non-smooth?
If it is non-smooth under what conditions it is smooth? Thank you.
Comment: What's your definition of a smooth algebra? The first definition that comes to mind is that a ring of functions ought to be smooth iff the associated variety is, but since you're asking this question that's clearly not your definition.
Comment: I use the definition from Loday's book "Cyclic Homology". Let $k$ be a field. A commutative and unital $k$-algebra $A$ is smooth over $k$ if it is flat over $k$ and if for any maximal ideal $\mathfrak{m}$ of $A$, the kernel $J$ of the localized map $\mu_{\mathfrak{m}}:(A\otimes_kA)_{\mu^{-1}(\mathfrak{m})}\to A_{\mathfrak{m}}$ is generated by a regular sequence in $(A\otimes_kA)_{\mu^{-1}(\mathfrak{m})}$.
Comment: If you have the book at your disposal, the definition is on page 102.
Comment: As per the result Loday states immediately following the definition (proposition 3.4.2), Loday's definition of smooth is equivalent to the standard definition of smoothness in the presence of a noetherian assumption. So $k[V]^G$ is smooth iff $V/G$ is smooth.
Comment: Thank you. Good to know.
Answer: The definition of smooth you state in the comments can be phrased geometrically as saying the diagonal $\Delta : X \hookrightarrow X \times_k X$ is a regular embedding. Note the flatness is automatic since $k$ is a field. Using the fact that $\Delta^*(I/I^2) \cong \Omega_{X/k}$ where $I$ is the ideal of $\Delta(X)$ and some standard results on formal smoothness, its not hard to see that this definition is equivalent to saying that $X/k$ is formally smooth.
If $X$ is a variety (or more generally for any morphism of finite presentation) formal smoothness is the same as smoothness so the question is really to characterize when is $V/G = \mathrm{Spec} k[V]^G$ smooth when $V$ is a finite dimensional vector space over an algebraically closed field of characteristic $0$ and $G$ a finite group acting linearly. This is answered by the following well known theorem. First we need some background.
Definition: Let $G \subset GL(V)$. An non-identity element $g \in G$ is called a pseudoreflection if it fixes a codimension $1$ subspace of $V$.
Theorem: (Chevalley-Shephard-Todd) With $G$ and $V$ as above, the following are equivalent:

$G$ is generated by pseudoreflections.
$V/G$ is smooth.
$k[V]^G$ is isomorphic to a polynomial algebra.
$k[V]$ is flat as a $k[V]^G$ algebra.
Comment: Thank you for the comprehensive answer.


Window onload function if else statements

Question: I would like to run different functions depending if a field is checked or not during page load.
So I use window.onload. The first if condition works great but I would like to add more if conditions as defined below. But it doesn't seem to be the proper way.
I thought I could work with if and if else. Does someone know how to make multiple if conditions work for window.onload function?

Comment: On which evidence is your conclusion _'it doesn't seem to be the proper way'_ based?
Comment: *I would like to run different JS functions depending if a field is checked or not during page load* - unless you have dynamic page generation on the server-side, there's not much to check in an `onload` event, the controls will be in the state what you've written in the HTML code, so you could also make them red and not-red the same way. In fact even if you have dynamic page generation, this initial "coloring" could be done by the generator too.
Comment: Thank you all for you great ideas, I clarified everything more in my main text. And comments. Really appreciate all of your ideas!
Answer: You can eleminate repeating tasks by taking the dynamic parts of your code, in this case your ID selectors, and put them in an array (or object) which you can loop over.
const fieldMap = [
  ['field1', 'field2'],
  ['field3', 'field4']
];

window.onload = function() {
  for (const [fieldA, fieldB] of fieldMap) {
    if (document.getElementById(fieldA).checked) {
      document.getElementById(fieldB).style.color = 'red';
    }
  }
}

The principle of writing your code like this is called DRY (Don't Repeat Yourself)
Comment: Thank you very much, thats new to me and sounds good. So is it right that it's possible that every girls get checked individual and if condition is fulfilled all fitting  functions are working?
Like field1 and also field3 are  checked then field 2 and 4 will turn Text red. But if only field 1 is checked only field 3 is turning text into red colour?
Comment: Yes, that is the case. For every set of fields it checks if `fieldA` is checked, and if so, sets the red text on `fieldB`. If any of the fields isn't checked then the text won't be set and vice versa.
Comment: Your idea is awesome! Please check my update in the main post. I can't make it fully work. Thanks very much in advance.
Comment: You're welcome, but please refrain from modifiying the question with provided answers. Any new issues should be posted as a new question. Though it's hard to say why it doesn't work without the HTML related to the question. Please post a new question with the HTML, the updated JavaScript and any error messages your console provides.
Answer: winow.onload executes your function() when the page is fully loaded, but it happens just once. If the code you provided is correct then I think you might be missing } at the end. However, there's still one thing that bothers me. If you check if a specified checkbox is checked it checks the checked property only when the page is fully loaded, not when the user clicks on the #field checkbox. If you want the check whether the user checked the checkbox then you can use eventlistener 'check'.
Comment: Thank you. For events happening based on user clicks after page load I already have a function


A proof using Menelaus' theorem and Ceva's theorem.

Question:
Need to show (d)
I have followed the problem and came up with the expression of the expression of the individual line segments:
from (b): $AB = \frac{CX}{RX} \cdot RB \cdot \frac{CQ}{QA}
$
$CQ = QA \cdot \frac{RB}{AB} \cdot \frac{XC}{RX}$
$RB = \frac{CQ}{QA} \cdot AB \cdot \frac{RX}{XC}$
$QA = CQ \cdot \frac{AR}{RB} \cdot \frac{RX}{XC}$
and from (c): after applying Ceva's theorem
$\frac{AR}{RB} \cdot \frac{BP}{PC} \cdot \frac{CQ}{QA} = 1$
which leads to the explicit expression for PC and BP.
When I attempted (d), the workload is quite a lot when I tried to combine the explicit expressions of each line segments, and it wasn't clear to me how it would yield the result.
Comment: Please do [not use pictures for critical portions](//math.meta.stackexchange.com/a/20529/290189) of your post. Pictures may not be legible, cannot be searched and are not viewable to some, such as those who use screen readers. [Scanned pages from books are discouraged on SE network](//meta.stackexchange.com/q/155600/259305). Questions should contain sufficient context so that it is [answerable with the text alone](//math.meta.stackexchange.com/a/1807/290189).
Answer: It is the Angle Bisector Theorem.
$\displaystyle \frac{BP}{PC}=\frac{\textrm{area of }\triangle BAP}{\textrm{area of }\triangle CAP}=\frac{\frac{1}{2}(AB)(AP)\sin\angle BAP}{\frac{1}{2}(AC)(AP)\sin\angle CAP}=\frac{AB}{AC}$


O evento addEventListener não é escutado

Question: Não sei se isso pode interferir ou não, mas eu tenho 3 formulários iguais na mesma página e outros 2 scripts sendo chamados da mesma forma (com window.addEventListener)
HTML

<form method="POST">

  Nome
  <input type="text" class="form-control" name="name" id="name" placeholder="Nome">

  E-mail
  <input type="email" class="form-control" name="email" id="email" placeholder="E-mail">

  Telefone/Celular
  <input type="tel" class="form-control" name="phone" id="phone" placeholder="Telefone/Celular">

  <input type="hidden" value="Colorimetria" name="course" id="course">

  <input type="hidden" value="" name="module" id="module">

  <button type="submit" class="waves-effect waves-light cta btn-large btn-solicitar-modal pulse-hover" id="buttonPress">
   Solicitar curso
  </button>

</form>

JavaScript
window.addEventListener('DOMContentLoaded', () => {

    var regexCharactere = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
    var regexEmail = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
    var regexTel = /(?:^\([0]?[1-9]{2}\)|^[0]?[1-9]{2}[\.-\s]?)[9]?[1-9]\d{3}[\.-\s]?\d{4}$/;
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var phone = document.getElementById('phone');
    var buttonPress = document.getElementById('buttonPress');

    /*A próxima linha não escuta o evento a ser chamado, ignorando todo o resto do código*/

    buttonPress.addEventListener('click', (e) => {
        if(!regexCharactere.test(name.value) || name.value == "" || name.value == undefined || name.value == null) {
            alert("Nome não reconhecido");
            name.focus();
            e.preventDefault();
        }

        if(!regexEmail.test(email.value) || email.value == "" || email.value == undefined || name.value == null) {
            alert("E-mail inválido");
            email.focus();
            e.preventDefault();
        }

        if(!regexTel.test(phone.value) || phone.value == "" || phone.value == undefined || phone.value == null) {
            alert("Insira um telefone correto\n(DDD) + num do telefone");
            phone.focus();
            e.preventDefault();
        }

    });

});

Comment: Testei o seu código e o evento é chamado, aparecem 3 alerts quando se clica no botão sem preencher nada, pode esclarecer qual a sua dúvida? Se preencher os campos de forma válida os alerts aparecem na mesma, penso que seja o seu regex que não funcione bem.
Comment: Como? Eu acabei de testa-lo e não deu nenhuma chamada de evento amigo... Você alterou algo?
Comment: Você disse que tem 3 forms iguais na mesma página, mas está usando `document.getElementByid()` para pegar os inputs... ID significa identificador e deve ser único. Se você tem vários elementos com o mesmo ID você deveria considerar usar classes.
Comment: @fernandosavio entendi, obrigado pela dica. Vou segui-lá.
Answer: Execute e veja que o evento está sendo chamado corretamente.
A diferença do meu código para o seu é que eu não inseri as tags de script iniciais.

window.addEventListener('DOMContentLoaded', () => {

    var regexCharactere = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
    var regexEmail = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
    var regexTel = /(?:^\([0]?[1-9]{2}\)|^[0]?[1-9]{2}[\.-\s]?)[9]?[1-9]\d{3}[\.-\s]?\d{4}$/;
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var phone = document.getElementById('phone');
    var buttonPress = document.getElementById('buttonPress');

    /*A próxima linha não escuta o evento a ser chamado, ignorando todo o resto do código*/

    buttonPress.addEventListener('click', (e) => {
        if(!regexCharactere.test(name.value) || name.value == "" || name.value == undefined || name.value == null) {
            alert("Nome não reconhecido");
            name.focus();
            e.preventDefault();
        }

        if(!regexEmail.test(email.value) || email.value == "" || email.value == undefined || name.value == null) {
            alert("E-mail inválido");
            email.focus();
            e.preventDefault();
        }

        if(!regexTel.test(phone.value) || phone.value == "" || phone.value == undefined || phone.value == null) {
            alert("Insira um telefone correto\n(DDD) + num do telefone");
            phone.focus();
            e.preventDefault();
        }

    });

});
<form method="POST">

  Nome
  <input type="text" class="form-control" name="name" id="name" placeholder="Nome">

  E-mail
  <input type="email" class="form-control" name="email" id="email" placeholder="E-mail">

  Telefone/Celular
  <input type="tel" class="form-control" name="phone" id="phone" placeholder="Telefone/Celular">

  <input type="hidden" value="Colorimetria" name="course" id="course">

  <input type="hidden" value="" name="module" id="module">

  <button type="submit" class="waves-effect waves-light cta btn-large btn-solicitar-modal pulse-hover" id="buttonPress">
   Solicitar curso
  </button>

</form>
Comment: Obrigado @MauroAlmeida, por mais que o código esteja errado na forma lógica, estava mais preocupado pq ele não estava chamando... Uma coisa que percebi nas minhas páginas é que tenho versões diferentes de jquerys entre outros arquivos. Talvez seja isso, de acordo com você não alterou uma linha do meu código (só não adicionou a chamada do script).
Answer: Insira e.preventDefault(); logo após abrir o escopo da função. Esse comando evita que a página seja redirecionada pelo método POST do seu form.
buttonPress.addEventListener('click', (e) => {
  e.preventDefault();

  // restante do código
})

Comment: Obrigado pela dica @Elihofni, mas mesmo assim não está indo. E o intuito da pergunta é o evento que não esta sendo executado...


Putting less weight on certain data points in a series for forecasting

Question: I have a data set that contains outliers (big orders) i need to forecast this series taking the outliers into consideration. I already know what the top 11 big orders are so i dont need to detect them first. I have tried a few ways to deal with this 1) forecast the data 10 times each time replacing the biggest outlier with the next biggest until the last set is run with them all replaced and then compare results 2) forecast the data another 10 times removing the outliers in each until they are all removed in the last set. Both of these work but they dont consistently give accurate forecasts. I was wondering if anyone knew another way to approach this?
One way i was thinking was running a weighted ARIMA and work it so that less/minimal weight is put on those specific data points. Is this possible?
I just want to point out that removing the known outliers does not delete that point completely, only minimizes it as there are other deals that happened in that quarter
One of my data sets is the following:
data <- matrix(c("08Q1",    "08Q2", "08Q3", "08Q4", "09Q1", "09Q2", "09Q3", "09Q4", "10Q1", "10Q2", "10Q3", "10Q4", "11Q1", "11Q2", "11Q3", "11Q4", "12Q1", "12Q2", "12Q3", "12Q4", "13Q1", "13Q2", "13Q3", "13Q4", "14Q1", "14Q2", "14Q3", "14Q4",155782698,   159463653.4,    172741125.6,    204547180,  126049319.8,    138648461.5,    135678842.1,    242568446.1,    177019289.3,    200397120.6,    182516217.1,    306143365.6,    222890269.2,    239062450.2,    229124263.2,    370575382.9,    257757410.5,    256125841.6,    231879306.6,    419580274,  268211059,  276378232.1,    261739468.7,    429127062.8,    254776725.6,    329429882.8,    264012891.6,    496745973.9),ncol=2,byrow=FALSE)

the known outliers in this series are:
outliers <- matrix(c("14Q4","14Q2","12Q1","13Q1","14Q2","11Q1","11Q4","14Q2","13Q4","14Q4","13Q1",20193525.68,18319234.7,12896323.62,12718744.01,12353002.09,11936190.13,11356476.28,11351192.31,10101527.85,9723641.25,9643214.018),ncol=2,byrow=FALSE)

please do not say about seasonality as this is only one type of data set, i have many ones without seaonality and i need the code to work for both types.
Edit by javlacalle: This is a plot of the observed data and the time points defined in the first column of outliers.
Comment: Plotting your data on logarithmic scale makes the supposed  outliers even less convincing. For whatever reason, you have peaks every 4th quarter. So you have trend, seasonality, some irregularity. That's par for the course, and nothing pathological. Even @IrishStat's analysis, which often produces models more complicated than would suit many other researchers, comes close to saying that.
Comment: Further, your request not to mention seasonality misses the point that the "outliers" in this example are interpretable largely as a reflection of seasonality. That is, seasonality really is germane.
Comment: A simple solution, why don't you simply subtract those big orders from your data and run the forecast model?
Comment: I respect your practical constraints, but it is no longer clear what the question is. Your question as posted above concerns a specific dataset, but your comments downplay that dataset entirely and ask for a much more general strategy, roughly: I may have outliers; I may have seasonality; I want a general robust method for forecasting. The thread seems in permanent tension between your posing a very specific question and your seemingly wanting a much more general answer.
Comment: What are the values in the second column of the matrix `outliers`? Why are the points "13Q1", "14Q2" and "14Q4" duplicated in the first column of this matrix? The series does not seem to have as many outliers as you detected. Maybe you are interested in forecasting a smooth pattern of the series?
Comment: they are repeated because these are the top 11 bookings in the series. they are considered outliers because they may not happen again in this pattern. they may not all be outliers but i would like to find a way to tell and then deal with the series. I have already triend running the series 10 times each time replacing the biggest order with the next biggest order and then comparing the results to find a point the forecasts level out. but this isnt as accurate as i would like
Comment: In the question you say that `outliers` are _known outliers_ but in the comment above you say _they may not all be outliers_. Do you or don't you know the outliers? If you know them (they may be some exceptional events that you observed in the history of the data), then you could fit an ARIMA model with dummies for those points.
If you don't know them, then you could do an analysis in the lines of the answer given by Irishstat. If any of these situations fits your purposes, I could give you some guidance about how to do it in R.
Comment: im saying that they arent exactly 'outliers' but just big orders that arent definitly going to happen again. but whether all the 11 i gave are affecting the series or not isnt clear either. I know that these are the only ones that can be outliers. Where commands in R that detect outliers dont select these ones
Comment: I have edited you question with the plot of the data and the outliers that you mention. Is that a correct interpretation of your data? If so, what about fitting an ARIMA model with dummies for the points in red? Or are you interested in selecting an ARIMA model and detecting  outliers as done in the answer given by Irishstat?
Comment: @javlacalle it is correct, however keep in mind that the whole data point isnt an outlier itself, only some bookings within that quarter are
Comment: @NickCox i know that here it shows seasonality as it is the total business but in other, smaller, data sets there is no seasonality at all
Comment: Indeed: other datasets you don't show us may not behave similarly, but if they pose problems you should ask separate threads. Your point to @Javlacalle doesn't really mention a problem. It's on all fours with saying that my food consumption during a day is dominated by three outliers, namely meals. If I have daily data, that's correct but immaterial. If you aggregate over any time scale, then fine structure within those intervals does not enter into an analysis.
Comment: I have edited the question with some R code that applies one of the ideas that I mentioned. I wouldn't treat this data set this way. I think it is more appropriate an analysis in the lines given by Irishstat. But as you insist in somehow dealing with those particular observations, maybe trying this code helps you clarifying your question.
Comment: @NickCox I just tried to give some ideas to the original poster to clarify the question. I still don't understand the question, why the OP insists in treating those observations as outliers and ignoring seasonality, so I am not in a position to give an answer.
Comment: As suggested by @NickCox, I have removed some content from my previous edit and have included it as part of my answer below.
Comment: if you're sure these are outliers, then remove them. It seems that you're not so sure after all.
Comment: @NickCox there may be seasonlity with these big order, but in other data sets there isnt. i need something that i can use for all sorts of data as it needs to be automatic and frequent, there isnt time to adapt the code for each type of data
Comment: @forecaster i have tried that already but the forecast isnt close to the actual amount. i need other methods
Comment: @Aksakal i am not positive that ALL of those are outliers, they may or may not affect the outcome but as it isnt a transactional data set then the income in each quarter isnt constant as its all down to sales. they might not be a large sale for a few quarters and then there is a huge one or there may be 3 large in a row. so i need something that can work around these large deals and give an amount that will be aimed towards if no large deals happen...does that make sense?
Answer: The OP insists in dealing with the points that are reported in the question as outliers without considering them as part of a possible seasonal pattern.
Below I first give an idea to treat these points separately. In the second part of the answer I propose an alternative approach in the lines of the answer given by @Irishstat, which is a more appropriate analysis of the data.
The effect of these observations can be weighted by means of regression on
seasonal dummies (variables that take the value 1 at the time points related
to the outliers and 0 otherwise). Then, an ARIMA model for the residuals
of the regression could be fitted and used to obtain forecasts.
It may be more efficient to estimate jointly the coefficients for the dummies
and those of the ARIMA model, but I did not get a satisfactory result so I decided to split it in two steps as show below.
require(forecast)
x <- ts(as.numeric(data[,2]), frequency = 4, start = c(2008, 1))
outliers <- c(2011.00, 2011.75, 2012.00, 2013.00, 2013.75, 2014.25, 2014.75)
# create dummies
dummies <- matrix(0, nrow = length(x), ncol = length(outliers))
for (i in seq_along(outliers))
  dummies[which(time(x) == outliers[i]),i] <- 1
# estimate the weights for these dummies and store the residuals
fitaux <- lm(x ~ dummies)
resid <- residuals(fitaux)
# fit an ARIMA model to the residuals and display forecasts
fit <- auto.arima(resid, ic = "bic")
fcast <- forecast(fit, 8)
# full code of the plot shown below is not posted to save space
plot(fcast)

There is high uncertainty in the forecasts (wide lower and upper bounds).
Although not shown, the residuals do not show autocorrelation but there is some
sign of overdifferencing. The choice of the ARIMA model should be explored further, but I think this gives you the idea.

As mentioned in the comments above, I don't think the above approach is
appropriate. I would do and analysis in the lines of the answer given by Irishstat. The R package tsoutliers follows the approach proposed in Chen and Liu (1993) to detect outliers in time series (e.g. additive outlies, level shifts).
This is what I get:
require(tsoutliers)
fit2 <- tso(x, args.tsmethod=list(ic="bic"))
fit2
# ARIMA(0,0,0)(0,1,0)[4] with drift
# Coefficients:
#         drift        LS4
#       8810020  -64443697
# s.e.  1289215   14293608
# sigma^2 estimated as 5.529e+14:  log likelihood=-366.02
# AIC=738.04   AICc=739.24   BIC=741.57
# Outliers:
#   type ind    time   coefhat  tstat
# 1   LS   4 2008:04 -64443697 -4.509
#
# type plot(fit2) to see the shape of the detected outlier(s)
#
# refit the model with the series adjusted for outliers
# (this will save arrangements to display forecasts
# the same model as in fit2$fit is chosen
fit2 <- auto.arima(fit2$yadj, ic="bic")
plot(forecast(fit2, 8))

The series is relatively clean from outliers. None of the outliers initially proposed in the question were detected. Similarly to the results shown by Irishstat, the forecasts look now more reliable, since they reflect the overall
dynamics of the data.
Comment: +1 for great visualization and analysis. This puts everything is perspective on outliers.
Answer: If you start with a bad/insufficient model then one can incorrectly find many outliers. A good model will capture systematic patterns in the data and good diagnostic analysis can suggest periods in time where the model was inadequate suggesting required enhancements. Your 28 quarterly values graphed here  suggest the following model including two outlier adjustments  The two outliers (low values) can be seen here in the actual/cleansed plot  . The model generated the following residuals   which are free of any apparent auto-correlative structure  . The forecasts reflect the adjustment for the two anomalies
Comment: The downvote here seems unfair and I've reversed it. Not using R is not good grounds for a downvote and that is the only negative comment made.
Comment: Thankyou for your response. I am unsure of how to do this in R though.
Comment: @Summer-JadeGleek'away I suggest you look at IrishStat's user page and visit the website mentioned therein.  He is probably using software called Autobox.  That would be a place to start.  Reproducing results in R might take a lot of study.
Comment: @Summer-JadeGleek'away See also here: http://stats.stackexchange.com/questions/32742/auto-arima-vs-autobox-do-they-differ
Comment: @NickCox I did not downvote, but I would prefer to know the name of the procedure used and/or a citation for the procedure.
Comment: @http://stats.stackexchange.com/users/9355/mark-miller The best reference for the procedure is Tsay http://www.unc.edu/~jbhill/tsay.pdf which lays out how to identify anomalies ( time trends are not included here ) based upon a tentative ARIMA model.
Comment: +1 and I don't know why anyone would down vote this post. @IrishStat has taken time and effort to produce these results, I agree with Nick Cox that R is not prerequisite for answering these type of questions.
Comment: @forecaster I think you forgot upvoting this answer.
Answer: To me it's essentially the choice between pushing the uncertainty of "big" shocks to the forecasts or to remove them from the forecast. For instance, you could identify the outliers and put dummies in those dates. Then your dummies will catch the uncertainty, and since you don't forecast dummies, these uncertainties will be trapped in the dummies. You seem to expect that big sales may happen in the future, but in the approach with outliers your forecast will not reflect this possibility.
The second option is to leave the outliers in. In this case your error variance will increase, to the extent the big shocks are not correlated with your explanatory variables. Hence, when you forecast your confidence bands will widen reflecting the uncertainty you couldn't capture in your explanatory variables. After all you're not sure if the big shock would pop up at any time in future. the issue with this approach is that outliers often introduce bias in estimates, so it's not a clean packaging of uncertainty into the error term.
Whether you go with one option or another is a matter of preference and circumstances.


can I use logrotate to rotate /core files?

Question: On remote linux-based devices, I thought I'd use logrotate to manage any core files our appliance may create.  But it seems logrotate considers every core file a unique file since the filename includes the PID.  This breaks the way logrotate normally rotates files.  E.g.:
core_123
core_222
core_555

Instead of seeing these as 3 variations of the same file, it sees this as 3 unique files.  So if I had rotate 50 in /etc/logrotate.d/core, it would be willing to rotate through 50 different core_123 files, and 50 different core_222 files, etc., resulting in potentially hundreds or thousands of files.  Instead, I want to ensure that logrotate manages a maximum of 50 core_* files.
This is the exact logrotate file I was trying to make work:
/mycores/core_* {
    compress
    daily
    maxage 28
    missingok
    nocreate
    nodelaycompress
    olddir /mycores/old
    rotate 50
}

I suspect this isn't possible with logrotate, but I figured I'd post on serverfault just in case I missed something in the documentation.
Comment: It might be easier to use something like find with a -mtime option to just delete things older then some time period.
Comment: That's a question for Stackoverflow.  Since we have lots of software running on these devices and cannot control when something wrong is going to happen, we at least need to manage the cores (should they happen) so they don't eat up all the disk space.  We do want to keep some recent cores to help us in debugging issues as they come up.
Comment: Why are you generating core files in the first place?
Answer: I combined logrotate with some shell magic to get the desired effect.  Basically logrotate is still in charge of moving and compressing the files, and then kicking off the script needed to delete the old files as well as ensuring the directory doesn't have more than 50 or so files.  Here is what I did:
/mycores/core_* {
    compress
    daily
    missingok
    nocreate
    nodelaycompress
    olddir /mycores/old
    sharedscripts
    postrotate
        # delete all core_*.gz files older than 28 days
        find /mycores/old -name "core_*.gz" -mtime +28 -delete
        # make sure we have a max of 50 files; delete the oldest files if we have too many
        for filename in $(find /mycores/old/ -name "core_*.gz" -printf "%T+ %p\n" | sort --reverse | tail --lines=+51 | cut -d' ' -f2); do rm $filename; sleep 0.5; done
    endscript
}

I'm not the best bash scripter out there, so that postrotate script section might be heavier than necessary...  :)
Answer: We use a script like this. I don't see the point of involving logrotate as

these are not log files
you are not rotating them

script:
#!/bin/bash
EMAIL_TO="<%= mail %>"
EMAIL_SUBJ="Found core files on `hostname -s`"
DATETIME=`date +"%F-%H%M%S"`
EMPTY_CORE_FILES=`find /var/log/core/ -mmin +60 -type f -empty -not -name "*.gz" -not -name "*.zip" -print -exec rm {} \;`
CORE_FILES=`find /var/log/core/ -mmin +60 -type f -not -empty -not -name "*.gz" -not -name "*.zip"`
NUM_CORE_FILES=`echo $CORE_FILES | wc -w`

lockfile="/tmp/`basename $0`.lock"
lockfile -1 -r 5 -l 84600 ${lockfile} || exit 1
trap "/bin/rm -f $lockfile" EXIT INT TERM

for f in $CORE_FILES;
do
  gzip -9 $f
done

if [ $NUM_CORE_FILES != 0 ]
then

  mail "$EMAIL_TO" -s "$EMAIL_SUBJ" <<EOF
I found and gzipped $NUM_CORE_FILES on $HOSTNAME in /var/log/core, please investigate.

Files Found:
$CORE_FILES

Empty Files:
$EMPTY_CORE_FILES

EOF

fi


How do you check if string is equal to unicode character?

Question: I'm working on an add-on for Firefox that will convert user selected temperatures. Basically it loops through each character of the user's selection and determines whether it is a number, negative or decimal using if statements. Once it locates the degree symbol, I want the program to stop looping through the characters and save the number that it has pulled from the user selection.
However, since the degree symbol is a unicode character, the if statement doesn't detect the degree symbol and evaluates the statement to false. Because I have other fail-safes in place, it doesn't infinite loop.
My statement is if (str.charAt(#) == "°") but it won't evaluate to true. My test HTML file uses both the ° unicode just pasted in and also the ° code. Neither will trigger the statement to be true.
How can I fix this?
Comment: Would http://stackoverflow.com/q/31325410/6309 help?
Comment: You could use a regex for pattern matching in strings. Search for "RegExp"
Answer: Seems to work fine for me:

var str = document.getElementById('thing').innerText;
console.log(str.charAt(0) === "°");
°
Comment: It isn't working on my end, but I did try applying the code directly to my test page and it worked there, but for some reason the code inside of the Firefox extension file will not evaluate true. Strange. I'll have to get in touch with the other AMO guys and see if we can figure it out.


Insert two columns from different tables into one table

Question: I have two tables, one with user-ids and another with item-ids. There are repeated entries in both tables but that is required. There are 42,000 entries in both tables.
I need to merge these tables such that there are 42,000 entries in the third table "user-item" such that first column contains the user-ids and second column contains item-ids as is from the two previous tables.

Userinfo table: (column is userid)

18974
41092
4287
41092 and so on

Iteminfo table: (column is itemid)

13
182
13
76 and so on

Required table:

Userid  | Itemid
18974   | 13
41092   | 182
4287    |  13
41092   | 76
and so on.
Comment: As always.. please, show your structure, sample sets and desired result. Please, show your approach, why it's not working and what you've expected.
Comment: _"They are both in order..."_ In SQL tables do not have an order.  You provide ordering in your query.  _"...such that user-id i selected item-id i"_ What does this mean?  If there are repeated entries in each table and no key with which to impose an unambiguous ordering, then whether or not users and items match up correctly will be entirely random at the whim of the database.
Answer: Hope you need this::
INSERT INTO thirdTable
Select ft.userId, st.itemId
from firtTable ft
INNER JOIN secondTable st on (ft.userId = st.userId)

Comment: As I mentioned, I have repeated entries in the tables. Thus, if there are 'm' items that are repeated and 'n' that are unique entries, I get 'm^2+n' values in the resulting table, with spurious data. I solved this problem using _distinct_
Answer: INSERT
   INTO thirdTable
Select
   f.userId, s.itemId
from
   firtTable f,
   secondTable s
where
   f.userId = s.userId


How to stop the iPython notebook to run the command line, run only python code

Question: I am using iPython notebook build a online interactive teaching website, but I don't want users to run command line, any idea how to remove iPython notebook command line function? Is there any configuration or something? I have been stuck here for 3 days!
Answer: You can't make os.system or subprocess unavailable, and users could use these to build themselves terminals even if you disable the built in terminals. However, if you run the ipython instance in a sandbox then it won't matter that they have command line access.
Comment: I have seen others successfully disabling `os.system` and `command line function`, also I have tried using docker as a sandbox, but I am considering a better solution, sandbox may used up too much machine resources.
Comment: I would like to see the same feature - it is not because of security - it is because of extremely easy access to everything.  Doing it in python 1/ you need to know a bit;  2/ you dont do a random mistake so easily...