characterization of measurable simple function

Question: $\chi_{A} $ means characteristic function of set $A$. Consider a simple function
$$s = \sum_{i=1}^{n} a_i \chi_{A_i} $$
If all of $\lbrace A_i \rbrace_{i=1}^n $ are measurable sets then $s$ becomes measurable function. Does the converse also hold? I mean, if $s$ is a measurable set, then does that imply all of $\{   A_i \}_{i=1}^N $ are also measurable sets?
Answer: No. Take $s=1$, by which I mean
$$ s=\Bbb 1_N + \Bbb 1_{N^c}$$
where $N$ is a non-measurable set.
If you ask for $s$ to have a decomposition $∑_1^N a_i\Bbb 1_{A_i}$ where $A_i$ are maximally chosen sets i.e. $A_i = [s=a_i]$ then we do indeed have $A_i = s^{-1}(\{a_i\})$ are measurable sets.


Swift XCTest namespace bug?

Question: I'm wondering if I've found a namespace / XCTest bug in Swift 1.2/XCode 6.4(6E23):
I have a .swift file with a public function encode that takes a few parameters. I also have an XCTest file to test the encode function.
My XCTest file imports my code fine – I'm able to call public functions from it and even the function that is causing me trouble, encode, is autocompleting just fine when I start writing it out. However, when I try to compile it, I can see that it fails (with "Extra argument in call") because the compiler thinks I'm calling Foundation.encode rather than my own.
Changing the name of it makes it work fine, but that is beside the point which is this; Swift is supposed to prioritise your module over the system's so is this a bug or am I missing something?
Answer: One thing that could be the issue is this:
Does the swift file in which encode is declared have Target Membership set to both you're test bundle and your main bundle? If not, select the swift file and in the right menu, under Target Membership, select your test bundle as well (it should be a checkmark).
Comment: It does and, alas, it makes no difference. I have a dummy project that demonstrates the problem [here](http://gateway.ipfs.io/ipfs/QmPQanXdcNjYEbsVPvBR53qPB6sxg34zqErPnXoxKYPiX9)
Comment: I've filed a radar on this [here](http://openradar.appspot.com/radar?id=4989937497669632)

Swift XCTest namespace bug?


Go unmarshal yaml and preserve order

Question: Let's say I have the following yaml file:
key1:
    - "Value1"
    - "Value2"
key2:
    - "Value3"
    - "Value4"

And I want to unmarshal that in Go. I can let Go decide what the scheme should look like and print it out.
m := make(map[interface{}]interface{})
err := yaml.Unmarshal(yaml_file, &m)
fmt.Prinf(m)

This will print something like this:
map[key1:[Value1 Value2] key2:[Value3 Value4]]
But maps are unordered. The order is very important for me tho and I also don't want to loose the keys.
I can't just create a struct and try to unmarshal the yaml file to a slice of that struct...
type Element struct {
    Key   string
    Value interface{}
}

t := []Element{}
err := yaml.Unmarshal(yaml_file, &t)
if err != nil {
    log.Fatalf("error: %v", err)
}

Will print error: yaml: unmarshal errors: line 2: cannot unmarshal !!map into []Element
There is no field tag to tell the yaml parser to fill the Key property with the yaml key.
Is there a different way than writing my own decoder?
Answer: Just found the answer right before I wanted to post the question.
The answer is MapSlice!
You need to import yaml.v2 from gopkg. (As of writing this MapSlices don't seem to be implemented in yaml.v3 yet)
MapSlices implement exactly what I needed and are made of a number of MapItems.
type MapItem struct {
    Key, Value interface{}
}

So now just unmarshal to a MapSlice. If you want to work with your own types you can always convert it but might need to do some typecasting.
m := yaml.MapSlice{}
yaml.Unmarshal(yaml_file, &m)

t := []Element{}
for _, item := range m {
    t = append(t, Element{item.Key.(string), item.Value})
}

Comment: I'm hesitant to upvote your answer. While it may work for you, I'm unsure if it's the best advice. You should make your encoding work for you. If you care about the order of fields then whatever is generating the yaml should use an array. Even if you can read unordered data in an ordered way, you can't always be sure that the unordered data was ever actually ordered to begin with, especially if the source of the yaml is from a 3rd party service. While you may be able to accurately say that the fields in your yaml are generated in an ordered fashion, that may not be true for future googlers.
Comment: I guess your answer does answer the question-as-written correctly. That type will read in fields in order. But assuming unordered data is ordered is a big red flag.

Go unmarshal yaml and preserve order


What should I do when an answer has been added as comment?

Question: I have found a question without an answer, but there is a comment that answers it.
What should be done in such cases?
Answer: If you are able to write an exhaustive answer basing on what reported on that comment, you can write an answer. You should first comment suggesting to the user who wrote the comment to write it as answer; If that user doesn't add his own answer, then you can write the answer yourself, but:

You should give enough time for the user who wrote the comment to write an answer before to write your own answer
You should give credit to the user who wrote the comment that helped you in understanding what the answer was

Instead of an answer like it is not possible to achieve what you want, a more exhaustive answer should be given, for example explaining in detail why what the OP wants to achieve cannot be achieved.


Importance of $e^{-x^2}$ in Gaussian distribution

Question: I don't know if such question could be posed, anyway I'll try.
Let's consider the Gaussian distribution, and in particular the exponential factor (in its simplest form), $e^{-x^2}$. Its derivation, its importance via the Central limit theorem is perfectly sound to me, but conceptually I could not associate its specific form to its widespread importance: i.e. why the exponential decrease in probability density is quadratic, and not, say, $e^{-|x|}$? Why so much natural phenomena seem to obey to quadratic exponential decrease?
PS: If it could help, I've found this discussion on meta.math. I liked, in Terry Tao's answer, the link between the exponentiated version of a quadratic form and the Taylor expansion concept.
Comment: @TheGhostOfPerdition The normal distribution is something humans discovered, and its formula is something we deduced, not decided on out of whim.
Comment: Well, the central limit theorem says that if you started out with sinusoids, you'd *still* end up with the normal distribution pretty quickly. So I'd say that "we decided its importance" (without the apostrophe) is probably wrong. We decided that probability and statistics were important. Our interest in the normal distribution was a consequence of that decision.
Comment: One reason could be that $|x|$ is hard to deal with, and its not differentiable too at $x=0$
Comment: I'm not sure I 100% agree arctic. While the normal distribution we have is good, we've decided it's form, and we've decided it's importance. Another culture might not have used "e", another culture might have constructed it with sinusoids, or presented it with a series solution. They could have produced it a the derivative of it's cdf. The way we've presented it shows off our willingness to like $e^{-x^2}$, and the answer to "why do we think about stats the way we do?" could be considered a soft question.
Answer: This is an answer to a very old question, but I think it is a fairly interesting one. More precisely, this is trying to explain why the exponent of the Gaussian is $2$ and not some other number.
Consider a random walk $S_n = \sum_{i=1}^n X_i$ where the $X_i$ are of course independent and identically distributed, say with mean zero and finite variance. It is a standard fact that $\mathrm{Var}(S_n) = n \mathrm{Var}(X_1)$, and so the scale of fluctuation of $S_n$ is $n^{1/2}$. I assert that you should think of the $2$ in the Gaussian exponent as $\frac{1}{1-1/2}$ with the $1/2$ being the scale of fluctuation of $S_n$.
I'll illustrate it by using the $1/2$ fluctuation scale to give a lower bound of $\exp(-cx^2)$ on the probability that $S_n > xn^{1/2}$ for some $c>0$. By independence and the definition of $S_n$,
\begin{align}
\mathbb P\left(S_n > xn^{1/2}\right) \geq \prod_{i=1}^k \mathbb P\left(S_{n/k} > x n^{1/2}/k\right)
\end{align}
(I ignore issues like $n/k$ not being an integer just to communicate the idea more clearly.)
Set $k = a^{-2}x^2$ for some small constant $a$. Now,
\begin{align}
\mathbb P\left(S_{n/k} > x n^{1/2}/k\right) &= \mathbb P\left(S_{n/k} > xk^{-1/2} (n/k)^{1/2}\right)\\
&= \mathbb P\left(S_{n/k} > a (n/k)^{1/2}\right)\\
&\geq \delta,
\end{align}
the last inequality for some $\delta>0$ because we know $S_{n/k}$ fluctuates on scale $(n/k)^{1/2}$. So overall,
\begin{align}
\mathbb P\left(S_n > xn^{1/2}\right) \geq \delta^k = \delta^{a^{-2}x^2} = \exp(-cx^2).
\end{align}
You can get an upper bound too but you'll have to use some concentration inequalities where the feeling that the Gaussian is hiding just underneath is much stronger.
In essence, standard properties of variance say that $S_n$ fluctuates on scale $n^{1/2}$, and by using this property at smaller scales, along with additivity properties of $S_n$, you can derive the $2$ exponent, at least on the level of a lower bound. This is an indication that the same should be true for the scaling limit of $S_n$, i.e., the Gaussian.
You can check that if we had $\chi$ in place of $1/2$, you would get the exponent $1/(1-\chi)$.
I developed these ideas in an argument in the slightly different context of last passage percolation, which appears here: https://arxiv.org/abs/2007.03594
Comment: In fact I've somehow forgotten the question, but your great insight kept me back on track! Thank you!
Comment: No problem, very glad if it helps!
Answer: I'm not sure if this actually helps, but maybe it would be easier to grasp intuitively going back to the simplest case, that of a fair coin?  In particular, let's say we already know the peak probability that in $n$ flips we get exactly $\frac{n}{2}$ heads, we're only looking for its ratio to some $\frac{n}{2} \pm l$, which would be:
$$\frac{\frac{n}{2}}{\frac{n}{2}+1}\cdot\frac{\frac{n}{2}-1}{\frac{n}{2}+2}\cdot\cdots\cdot\frac{\frac{n}{2}-l+1}{\frac{n}{2}+l}$$
Now let's say that $l$ is much larger than one, and much less than $n$, in which case you can approximate the logarithm of this ratio as:
$$\int_0^l\left(\log\left(\frac{n}{2}-t\right) - \log\left(\frac{n}{2}+t\right)\right)dt = \int_0^l\left(\log\left(1-\frac{2t}{n}\right) - \log\left(1+\frac{2t}{n}\right)\right)dt$$
$$\approx-\int_0^l\frac{4t}{n}dt = -\frac{2l^2}{n}$$
All cases can ultimately be reduced to weighted iterations of this one, so it always ends up being $e^{-x^2}$.
Comment: Well, your interesting answer didn't helped directly, but surely put me on the right path to find an answer my own! As soon as I'll elaborate it rigorously, I'll write it here.


Bayesian Learning Example with a Uniform Prior

Question: I'm trying to understand an example of online Bayesian learning from Duda and Hart's textbook Pattern Classification, section 3.5, example 1.
Let $D$ be a set of data points, in this case $\{4, 7, 2, 8\}$ and consider a conditional probability $p(x|\theta) = U(0, \theta)$. Denote $D^i$ as the set of $i$ points from $D$. A uniform distribution is also assumed for the prior $p(\theta|D^0) = p(\theta)=U(0, 10)$. Then the update rule for online bayesian learning is given by equation 54:
$$ p(\theta|D^n) = \frac{p(x_n|\theta)(p(\theta|D^{n-1})}{\int p(x_n|\theta)p(\theta|D^{n-1})d\theta}$$
Next the authors state that
$$p(\theta|D^{1}) \propto p(x|\theta)p(\theta|D^0)$$
So far so good. However they state this probability as $\frac{1}{\theta}$ for $4 \leq \theta \leq 10$ and $0$ otherwise and I'm not sure how this was computed.
From what I understand initially $p(\theta) = U(0, 10)$, so for $\theta$ in the range $[0, 10]$ the probability is $1/10$. Then since $x=4$ is in the range $[0, 10]$, the probability $p(x|\theta)$, for $\theta \in [0, 10]$ is $\frac{1}{\theta}$, so then why isn't the probability $p(\theta|D^{1})$ given by $\frac{1}{\theta^2}$ for $\theta \in [0, 10]$, and $0$ otherwise?
Answer: I do not understand where your square would come from.
You have $p(\theta|D^{1}) \propto p(x_1|\theta)p(\theta|D^0)$.
On the one hand, $p(\theta|D^0)=\frac{1}{10}1_{\{0<\theta<10\}}$.
On the other hand, given $\theta\in(0,10)$, $x_1$ is uniformly distributed on $(0,\theta)$. Therefore $p(x_1\vert\theta)=\frac{1}{\theta}1_{\{0< x_1<\theta\}}$.
So $p(\theta|D^{1}) \propto \frac{1}{\theta}1_{\{0<x_1<\theta\}}1_{\{0<\theta<10\}}=\frac1\theta1_{\{0<x_1<\theta<10\}}$. In particular you have $p(\theta|D^{1}=\{4\}) \propto \frac{1}{\theta}1_{\{4<\theta<10\}}$.
Comment: Thanks I get it now, I goofed in my understanding.


Sankey bar graphs in R

Question: I'd like to make this type of plot in R.

There's more detail on the SAS macros to produce this example here: http://www.pharmasug.org/proceedings/2015/DV/PharmaSUG-2015-DV07.pdf
Does anyone have any thoughts on how I should go about doing this in R?
NOTE: I know how to make standard sankey diagrams with the D3 or google libraries. This question is specifically about the combination of bar graph and sankey diagram that the SAS macros produce.
Comment: You may need to do an overlay (using `par(new = TRUE)`) with [`SankeyR`](https://gist.github.com/aaronberdanier/1423501) and a regular barplot. Here's a reference: http://stackoverflow.com/questions/9968433/sankey-diagrams-in-r
Answer: Use the library(flipPlots), using the SankeyDiagram() function.

Sankey bar graphs in R


TheCatApi discord.py

Question: So today I was trying to add a command to my discord bot that would allow it to connect to TheCatApi, and I was unable to do it due to multiple errors. Here's my code below:
import nextcord
import os
from nextcord import Interaction, SlashOption
from nextcord.ext import commands
import asyncio
import catapi

loop = asyncio.new_event_loop()

api = catapi.CatApi(api_key=os.environ['CAT_API_KEY'])

def run_coro(coroutine):
    return loop.run_until_complete(coroutine)

class Fun(commands.Cog):

  def __init__(self, client):
    self.client = client

  testServerID = 827933970742116442

  @nextcord.slash_command(name = "cat", description = "Sends a random cat photo uwu", guild_ids=[testServerID])
  async def cat(self, interaction: Interaction):

    results = run_coro(api.search_images(limit=1))
    print(results[0].url)
    await interaction.response.send_message("heer")

print("Loaded cog: Fun.py")

def setup(client):
  client.add_cog(Fun(client))

And the monumental error below:
Ignoring exception in on_interaction
Traceback (most recent call last):
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/client.py", line 415, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/client.py", line 1741, in on_interaction
    await self.process_application_commands(interaction)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/client.py", line 1757, in process_application_commands
    await app_cmd.call_from_interaction(interaction)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/application_command.py", line 1182, in call_from_interaction
    await self.call(self._state, interaction, interaction.data.get("options", {}))
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/application_command.py", line 1186, in call
    await super().call(state, interaction, option_data)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/app
Loaded cog: Extras.py
Loaded cog: Time.py
Loaded cog: MathShit.py
Loaded cog: Admin.py
Loaded cog: Fun.py
The bot is running sir! Logged in as Meowsicle bot#4403
-------------------------------------------------------
Ignoring exception in on_interaction
Traceback (most recent call last):
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/client.py", line 415, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/client.py", line 1741, in on_interaction
    await self.process_application_commands(interaction)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/client.py", line 1757, in process_application_commands
    await app_cmd.call_from_interaction(interaction)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/application_command.py", line 1182, in call_from_interaction
    await self.call(self._state, interaction, interaction.data.get("options", {}))
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/application_command.py", line 1186, in call
    await super().call(state, interaction, option_data)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/application_command.py", line 663, in call
    await self.call_invoke_slash(state, interaction, option_data)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/application_command.py", line 704, in call_invoke_slash
    await self.invoke_slash(interaction, **kwargs)
  File "/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/application_command.py", line 719, in invoke_slash
    await self.callback(self._self_argument, interaction, **kwargs)
  File "/home/runner/Meowsicle-bot/cogs/Fun.py", line 27, in cat
    results = run_coro(api.search_images(limit=1))
  File "/home/runner/Meowsicle-bot/cogs/Fun.py", line 14, in run_coro
    return loop.run_until_complete(coroutine)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 592, in run_until_complete
    self._check_running()
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 554, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running
/home/runner/Meowsicle-bot/venv/lib/python3.8/site-packages/nextcord/client.py:422: RuntimeWarning: coroutine 'CatApi.search_images' was never awaited
  pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

I have tried putting different parts of code in and out of the class, reformatting the code, even deleting the entire thing and rewriting it and I achieved nothing. I'm using this async wrapper for the API connection. That's all of the detail I can give you but stackoverflow is asking for more.... Anyways, thanks in advance to anyone who can help! Thanks again, and good luck to anyone who decides to try and help!
Comment: Sorry for kinda weird spelling and stuff at the end but I needed "more explanation"
Comment: `asyncio.new_event_loop()`, probably not needed -- if this is a fork of D.PY, there's already an event loop created internally. Also, why are you using `runcoro` inside of an asynchronous function? You can simply use `await`, can't you?
Comment: I honestly have no idea about this, I'm kinda new to programming and especially using apis, and I'm doing what the github repository I linked shows
Answer: Well i have something that might help you
Heres the code i wrote:
import requests
import nextcord
from nextcord import Interaction
from nextcord.ext import commands

class Test(commands.Cog):
    def __init__(self, client):
        self.client = client

    guild_id = 'your_id'

    @nextcord.slash_command(name="cat", guild_ids=[guild_id])
    async def cat(self, interaction: Interaction):
        await interaction.response.defer()
        data = requests.get("https://api.thecatapi.com/v1/images/search")
        data = data.json()
        get = data[0]
        result = get["url"]
        embed = nextcord.Embed(
            title="A Cat",
            color=nextcord.Color.random()
        )
        embed.set_image(url=result)
        await interaction.edit_original_message(embed=embed)

def setup(client):
    client.add_cog(Test(client))

Comment: [Editing](https://stackoverflow.com/posts/71648275/edit) your answer to contain explanations of the code and why/how it works will add much more value to an answer than just a block of code. Remember, you're not _just_ trying to answer the OP; you're also helping developers in the future with this same problem. See [answer] for more information on writing good answers.

TheCatApi discord.py


How to argue that if we could solve the halting problem, then we could solve busy beaver?

Question: This is one of the tasks of my assignment. I have a Turing machine simulation which can simulate a busy beaver function. I have done some research about proving this problem, but still don't get it so I guess maybe you can help me here.  A good source for me to go to or example of how to argue this would be good.
Comment: If your problem is to prove that solving the halting problem allows us to solve the busy beaver problem, then asking for an "example of how to argue this" is explicitly asking for the answer to your homework. This is often called "cheating". You have just cheated. This is a very straight forward problem that applies the definitions of the halting problem and the busy beaver problem directly, and you haven't even worked hard enough to see that. Congratulations.
Comment: I'm actually asking for help.Not asking for answer if you can read it properly!My real task is different from i'm asking here.If you don't answer,please don't make such a comments.Thank you.
Comment: I read it just fine. 1) Your title: "How to argue that if we could solve the halting problem, then we could solve busy beaver?". Your request: An "example of how to argue this". An example argument is an argument and is hence an answer. 2) You say that this argument is a task on your assignment and not that it is _different_ from a task on your assignment. So you have indeed asked for a solution to your assigned task, whereas the point of the task was probably for you to think about the problem for yourself. This may not complete your entire assignment so I can see why you think it's 'help'.
Comment: I guess you don't have teaching skill that's why you don't get it.If someone asks you for a particular problem and you answered but he/she still can't get it.Haven't you tried to explain them by giving them an example.For example, how does stack works? you may say it works just as you stack a book so the top of the stack get poped off first when it's insert last.That's an example of an explanation.Anyway,even if someone is asking for an answer so what's your problem?don't answer if you don't want.A person like you if someone is asking for help, you just say keep google it!that's your lesson.
Comment: Wow, you're totally right. Thanks for teaching me this important lesson. You win!
Answer: The BB function is defined to be the maximum number of steps a Turing machine of a particular size can carry out and still halt. (Another way of putting it is that all Turing machines of size x will either halt in less than BB(x) steps, or run forever).
Assuming you have a Turing machine of complexity x, then you could determine whether it would halt or not by letting it run for BB(x) time-steps - if it hadn't halted by then, then by definition it never will.
Equally, if you could solve the halting problem, you could evaluate all possible Turing machines of size x, eliminate those that don't halt, and take BB(x) to be the maximum of the run times of the remainders.
Of course, BB(x) is non-computable - and in fact grows faster than any possible computable function you could name - hence it cannot even be approximated.
Comment: Awesome.Now I got an idea.Thanks
Answer: You can find the proof you seek here, below the proof that the Busy Beaver problem is uncomputable.


A polynomial identity and the square root of 2

Question: Inspired by Bill Dubuque and Aaron Meyerowitz' arguments in this question
https://mathoverflow.net/questions/32011/direct-proof-of-irrationality
I calculated the following polynomial identity:
$$m^2[pa^2n+2abm+b^2n]^2=p(am+bn)^4+(m^2-pn^2)(-pa^4m^2+4a^2b^2m^2+4ab^3mn+b^4n^2).$$
(Sage proof)
It follows from this identity that if $gcd(m,n)=1$ and $(m/n)^2=p$ then $p$ is a square.  Indeed, applying Bézout's identity we find $a,b$ with $am+bn=1$, and if moreover $m^2-pn^2 = 0$ then the identity becomes
$$m^2[pa^2n+2abm+b^2n]^2=p.$$
This may or may not be a "direct"/"constructive" proof of the irrationality of $\sqrt{2}$ (which is the subject of discussion in the question I linked).  But I am primarily interested in improving this proof:
Question 1: Is there any simpler such identity?  I guess by "such an identity" I mean an identity of the form
$$
P(a,b,m,n,p)^2=p(am+bn)^{k}+(m^2-pn^2)Q(a,b,m,n,p).
$$
and by "simpler" I mean of lower degree or with fewer terms.
Alternatively,
Question 2: Why does the identity work?  How would one come up with it?
(Obviously I did come up with it myself, via a tortuous path that I won't bother describing here, but I am wondering if there is an elegant way.)
Comment: See also [here](https://math.stackexchange.com/a/613723/242) for a similar use.
Answer: Oops, that was easy.  Brahmagupta's identity:
$$
(pan+bm)^2=p(am+bn)^2+(m^2-pn^2)(b^2-pa^2).
$$
Comment: Yes, in fact if memory serves correct it was Dedekind's use of this quadratic form that inspired me to find a simpler linear form.
Comment: That's interesting, I wonder if you could similarly generalize to a polynomial-identity proof of the Rational Root Test?
Comment: More generally. the Bezout-based MO proof I gave [generalizes](https://math.stackexchange.com/a/91595/242) to a proof of the Rational Root Test by induction on the polynomial degree
Answer: The proof in my MO post (better here) essentially uses composition of linear (vs. quadratic) forms when viewed as in your question, i.e. using your notation they are as below:
$\ \ \ \begin{align}\text{Quadratic form}\ \ \ \ \  (pan + bm)^2\! &-\,p(am+bn)^2\!= (m^2-pn^2)(b^2-pa^2)\\[.2em]
\text{Linear form}\ \ \ \ \  \color{#90f}{p^2} an + bm \ \ \,  &-\, p(\color{#c00}{am+bn})\, =\, (\color{#0a0}{m\,-\,pn}\,)\ (b\,-\,pa)\end{align}$
So if reduced $\,\color{#0a0}{p = m/n}\in\Bbb Q,\ \color{#90f}{p^2 = d}\in \Bbb Z\,$ then by Bezout $\,\exists\, a,b\!:\ \color{#c00}{am\!+\!bn ={\bf  1}}\, $ so above is
$\qquad\qquad\qquad\qquad\ \ \ \  \color{#90f}d\,an + bm\ \,-\ \,   p(\color{#C00}{\bf 1})\, =\, (\color{#0a0}0)(\cdots)\ \Rightarrow\ \color{#0af}{p\in\Bbb Z}$
which proves that $\, \color{#90f}{p = \sqrt d}\color{#0a0}{\in \Bbb Q}\,\Rightarrow\,\color{#0af}{\sqrt{d}\in\Bbb Z}.\, $  Said more "radically" using quadratic integers
$\qquad\qquad \color{#0a0}{0 = (m-n\sqrt d)}(b-a\sqrt d) = c - \color{#c00}{\bf 1}\sqrt d\:\Rightarrow\, \sqrt d = c = dan\!+\!bm\in\Bbb Z$
If memory serves correct, I was inspired to employ that linear form after reading a quadratic form that Dedekind employed (essentially composition of squares). In older times (before ideals, modules and algebraic number theory flourished) it was more common to see results like this expressed in the language of (binary) quadratic forms. In modern times these arguments have been simplified to linear form by using ideals and modules (see this answer for  the general correspondence between quadratic forms, ideals and numbers).
In terms of quadratic number rings, the proof shows that if an ideal $I$ contains a number $\,m - n\sqrt d\,$ that is primitive $(\gcd(m,n) = 1),\,$ and $\,n> 1,\,$ then $I$ also contains its $ $ simpler multiple $\ c- \sqrt d,\,$  simpler due to the smaller coef $\,1<n\,$ on $\sqrt d.\,$ Generally this idea reduces the coef to $\,\color{#c00}{\gcd(m,n)},\,$ which is $< n\,$ if $\,n\nmid m\,$ [when $\,n\mid m\,$ it is $\,n(m/n -\sqrt d)\,$]. Such reductions prove useful for various purposes, e.g. in   normal forms for ideals and modules, e.g. Hermite form.
As I show in this answer the above linear proof generalizes to higher degree polynomials: it yields a Bezout-based proof of the (monic) Rational Root Test by induction on degree. We can also view those proofs in the form that you seek.


gcc: Skipping incompatible libraries and returning error

Question: This question is related to my previous question. I am trying to install the "TAUCS" library
TAUCS is a C library of sparse linear solvers. It has dependency on BLAS, ATLAS, LAPACK, METIS etc.
I followed the solution of @steeldriver and it worked on one of my ubuntu computer, but not on other.
On other computer, I get the following error:
<code>$ sudo make "CC=gcc" "FC=gfortran" "LIBF77=-Wl,-Bstatic -lf2c -Wl,-Bdynamic -lgfortran"
mkdir obj
mkdir obj/linux/
echo exists > obj/linux/exists.log
gcc -c -O3 -Wall  -std=c99    -DMACHTYPE_ -I src/ -I build/linux/ -I external/src/   \
      progs/taucs_blas_underscore_test.c \
      -oobj/linux/taucs_blas_underscore_test.o
gcc   \
      -oobj/linux/taucs_blas_underscore_test \
      obj/linux/taucs_blas_underscore_test.o -L external/lib/linux -llapack -L external/lib/linux -lf77blas -lcblas -latlas -L external/lib/linux -lmetis  -Wl,-Bstatic -lf2c -Wl,-Bdynamic -lgfortran -lm
/usr/bin/ld: skipping incompatible external/lib/linux/liblapack.a when searching for -llapack
/usr/bin/ld: skipping incompatible external/lib/linux/liblapack.a when searching for -llapack
/usr/bin/ld: skipping incompatible external/lib/linux/liblapack.a when searching for -llapack
/usr/bin/ld: skipping incompatible external/lib/linux/libf77blas.a when searching for -lf77blas
/usr/bin/ld: skipping incompatible external/lib/linux/libf77blas.a when searching for -lf77blas
/usr/bin/ld: skipping incompatible external/lib/linux/libf77blas.a when searching for -lf77blas
/usr/bin/ld: cannot find -lf77blas
/usr/bin/ld: skipping incompatible external/lib/linux/libcblas.a when searching for -lcblas
/usr/bin/ld: skipping incompatible external/lib/linux/libcblas.a when searching for -lcblas
/usr/bin/ld: skipping incompatible external/lib/linux/libcblas.a when searching for -lcblas
/usr/bin/ld: cannot find -lcblas
/usr/bin/ld: skipping incompatible external/lib/linux/libatlas.a when searching for -latlas
/usr/bin/ld: skipping incompatible external/lib/linux/libatlas.a when searching for -latlas
/usr/bin/ld: skipping incompatible external/lib/linux/libatlas.a when searching for -latlas
/usr/bin/ld: cannot find -latlas
/usr/bin/ld: skipping incompatible external/lib/linux/libmetis.a when searching for -lmetis
/usr/bin/ld: skipping incompatible external/lib/linux/libmetis.a when searching for -lmetis
/usr/bin/ld: skipping incompatible external/lib/linux/libmetis.a when searching for -lmetis
/usr/bin/ld: cannot find -lmetis
collect2: error: ld returned 1 exit status
make: [build/linux/taucs_config_tests.h] Error 1 (ignored)
obj/linux/taucs_blas_underscore_test build/linux/taucs_config_tests.h
make: obj/linux/taucs_blas_underscore_test: Command not found
make: [build/linux/taucs_config_tests.h] Error 127 (ignored)
gcc -c -O3 -Wall  -std=c99    -DMACHTYPE_ -I src/ -I build/linux/ -I external/src/   \
      progs/taucs_blas_nounderscore_test.c \
      -oobj/linux/taucs_blas_nounderscore_test.o
gcc   \
      -oobj/linux/taucs_blas_nounderscore_test \
      obj/linux/taucs_blas_nounderscore_test.o -L external/lib/linux -llapack -L external/lib/linux -lf77blas -lcblas -latlas -L external/lib/linux -lmetis  -Wl,-Bstatic -lf2c -Wl,-Bdynamic -lgfortran -lm
/usr/bin/ld: skipping incompatible external/lib/linux/liblapack.a when searching for -llapack
/usr/bin/ld: skipping incompatible external/lib/linux/liblapack.a when searching for -llapack
/usr/bin/ld: skipping incompatible external/lib/linux/liblapack.a when searching for -llapack
/usr/bin/ld: skipping incompatible external/lib/linux/libf77blas.a when searching for -lf77blas
/usr/bin/ld: skipping incompatible external/lib/linux/libf77blas.a when searching for -lf77blas
/usr/bin/ld: skipping incompatible external/lib/linux/libf77blas.a when searching for -lf77blas
/usr/bin/ld: cannot find -lf77blas
/usr/bin/ld: skipping incompatible external/lib/linux/libcblas.a when searching for -lcblas
/usr/bin/ld: skipping incompatible external/lib/linux/libcblas.a when searching for -lcblas
/usr/bin/ld: skipping incompatible external/lib/linux/libcblas.a when searching for -lcblas
/usr/bin/ld: cannot find -lcblas
/usr/bin/ld: skipping incompatible external/lib/linux/libatlas.a when searching for -latlas
/usr/bin/ld: skipping incompatible external/lib/linux/libatlas.a when searching for -latlas
/usr/bin/ld: skipping incompatible external/lib/linux/libatlas.a when searching for -latlas
/usr/bin/ld: cannot find -latlas
/usr/bin/ld: skipping incompatible external/lib/linux/libmetis.a when searching for -lmetis
/usr/bin/ld: skipping incompatible external/lib/linux/libmetis.a when searching for -lmetis
/usr/bin/ld: skipping incompatible external/lib/linux/libmetis.a when searching for -lmetis
/usr/bin/ld: cannot find -lmetis
collect2: error: ld returned 1 exit status
make: [build/linux/taucs_config_tests.h] Error 1 (ignored)
obj/linux/taucs_blas_nounderscore_test build/linux/taucs_config_tests.h
make: obj/linux/taucs_blas_nounderscore_test: Command not found
make: [build/linux/taucs_config_tests.h] Error 127 (ignored)
gcc -c -O3 -Wall  -std=c99    -DMACHTYPE_ -I src/ -I build/linux/ -I external/src/   \
      progs/taucs_c99_complex_test.c \
      -oobj/linux/taucs_c99_complex_test.o
gcc   \
      -oobj/linux/taucs_c99_complex_test \
      obj/linux/taucs_c99_complex_test.o -L external/lib/linux -llapack -L external/lib/linux -lf77blas -lcblas -latlas -L external/lib/linux -lmetis  -Wl,-Bstatic -lf2c -Wl,-Bdynamic -lgfortran -lm
/usr/bin/ld: skipping incompatible external/lib/linux/liblapack.a when searching for -llapack
/usr/bin/ld: skipping incompatible external/lib/linux/liblapack.a when searching for -llapack
/usr/bin/ld: skipping incompatible external/lib/linux/liblapack.a when searching for -llapack
/usr/bin/ld: skipping incompatible external/lib/linux/libf77blas.a when searching for -lf77blas
/usr/bin/ld: skipping incompatible external/lib/linux/libf77blas.a when searching for -lf77blas
/usr/bin/ld: skipping incompatible external/lib/linux/libf77blas.a when searching for -lf77blas
/usr/bin/ld: cannot find -lf77blas
/usr/bin/ld: skipping incompatible external/lib/linux/libcblas.a when searching for -lcblas
/usr/bin/ld: skipping incompatible external/lib/linux/libcblas.a when searching for -lcblas
/usr/bin/ld: skipping incompatible external/lib/linux/libcblas.a when searching for -lcblas
/usr/bin/ld: cannot find -lcblas
/usr/bin/ld: skipping incompatible external/lib/linux/libatlas.a when searching for -latlas
/usr/bin/ld: skipping incompatible external/lib/linux/libatlas.a when searching for -latlas
/usr/bin/ld: skipping incompatible external/lib/linux/libatlas.a when searching for -latlas
/usr/bin/ld: cannot find -latlas
/usr/bin/ld: skipping incompatible external/lib/linux/libmetis.a when searching for -lmetis
/usr/bin/ld: skipping incompatible external/lib/linux/libmetis.a when searching for -lmetis
/usr/bin/ld: skipping incompatible external/lib/linux/libmetis.a when searching for -lmetis
/usr/bin/ld: cannot find -lmetis
collect2: error: ld returned 1 exit status
make: [build/linux/taucs_config_tests.h] Error 1 (ignored)
obj/linux/taucs_c99_complex_test build/linux/taucs_config_tests.h
make: obj/linux/taucs_c99_complex_test: Command not found
make: [build/linux/taucs_config_tests.h] Error 127 (ignored)
gcc -c -O3 -Wall  -std=c99    -DMACHTYPE_ -I src/ -I build/linux/ -I external/src/   \
      progs/taucs_cilk_test.c \
      -oobj/linux/taucs_cilk_test.o
progs/taucs_cilk_test.c:8:19: fatal error: cilk.h: No such file or directory
 #include <cilk.h>
                   ^
compilation terminated.
make: [build/linux/taucs_config_tests.h] Error 1 (ignored)
gcc   \
      -oobj/linux/taucs_cilk_test \
      obj/linux/taucs_cilk_test.o -L external/lib/linux -llapack -L external/lib/linux -lf77blas -lcblas -latlas -L external/lib/linux -lmetis  -Wl,-Bstatic -lf2c -Wl,-Bdynamic -lgfortran -lm
gcc: error: obj/linux/taucs_cilk_test.o: No such file or directory
make: [build/linux/taucs_config_tests.h] Error 1 (ignored)
obj/linux/taucs_cilk_test build/linux/taucs_config_tests.h
make: obj/linux/taucs_cilk_test: Command not found
make: [build/linux/taucs_config_tests.h] Error 127 (ignored)
mkdir bin
mkdir bin/linux/
echo exists > bin/linux/exists.log
mkdir lib
mkdir lib/linux/
echo exists > lib/linux/exists.log
gcc -c -O3 -Wall  -std=c99    -DMACHTYPE_ -I src/ -I build/linux/ -I external/src/   \
    -DTAUCS_CORE_GENERAL \
    src/taucs_sn_llt.c \
    -oobj/linux/taucs_sn_llt.o
In file included from src/taucs_sn_llt.c:13:0:
src/taucs.h:6:32: fatal error: taucs_config_tests.h: No such file or directory
 #include <taucs_config_tests.h>
                                ^
compilation terminated.
make: *** [obj/linux/taucs_sn_llt.o] Error 1
</code>
When I look at following location, I find those files:
<code>$cd /home/dkumar/taucs_full/external/lib/linux
$ls
blas_aux.o  CVS  libatlas.a  libcblas.a  libf77blas.a  liblapack.a  libmetis.a
</code>
How could I fix this "incompatiable libraries" issue?
Comment: Is the second machine running a 64-bit OS? the TAUCS tarball comes with a bunch of pre-built 32-bit archive libraries: there will be some extra hoops to jump through if you want to build it on a 64-bit platform (either replacing all those libs with 64-bit ones, or adding 32-bit build support to your platform and building the whole thing as a 32-bit application).
Comment: @steeldriver somehow I missed your comment, my apologies. I added 32 bit support as described: [link](http://askubuntu.com/questions/454253/how-to-run-32-bit-app-in-ubuntu-64-bit) . Could you please let me know what changes should I make in makefile?
Comment: Sorry - I tried a bunch of stuff but was unable to get it to build on 64-bit. I don't think the instructions linked in your last comment are sufficient (or, possibly, helpful at all): you'd need at least `gcc-multilib` and `gfortran-multilib`, and then add `-m32` to the flags for both `gcc` and `gfortran`. That eliminates the 'skipping incompatible libraries' errors but other errors still prevent a successful build.
Comment: your answer in my previous question did allow me to build it on 64 bit linux. But, that was my other computer. I can run it on other linux by just copying "libtaucs.a". Please let me know if you want this file.
Answer: you have to install binutils package you are missing some binaries

sudo apt-get install binutils -y
Comment: I am still getting the same error. When I tried installing binutils package, I get :the following message `$ sudo apt-get install binutils -y
[sudo] password for dkumar:
Reading package lists... Done
Building dependency tree
Reading state information... Done
binutils is already the newest version.
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 libg2c0:i386 : Depends: gcc-3.4-base:i386 (= 3.4.6-6ubuntu5) but it is not installable
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).`
Comment: ok you have already installed that package some thing is wrong with installation of that package or missing path on installed packages -- try this command "apt-get -f install"
Comment: I still get the same error. Possibly, there is something wrong about `libg2c0:i386 : Depends: gcc-3.4-base:i386 (= 3.4.6-6ubuntu5) but it is not installable`
Comment: can you reomve packages and reinstall them again ?
Comment: It seems that I will get into larger trouble as following would be removed: `The following packages would be removed: network-manager-pptp-gnome, libg2c0:i386, gcc-4.8-multilib, dkms, hardening-includes, virtualbox-guest-dkms, gcc-multilib, gfortran-4.8, pptp-linux, gcc, playonlinux, lintian, gfortran, gcc-4.8, network-manager-pptp`


What is the point of the pit stop in Daytona USA?

Question: In Daytona USA it's possible to enter the pits and change tyres. It seems to be pointless, the game doesn't model tyre degradation or anything more than cosmetic damage to the car. All it seems to do is waste time.
Why is it even in the game? Does it serve some purpose?
Answer: According to this FAQ the pits are mostly useless. The car does take some damage when it collides or gets flipped which affects the handling, but in most game modes the time lost pitting outweighs any benefit.
The exceptions are Grand Prix and Endurance mode where damage and tyre degradation make pitting worthwhile.
Answer: On the beginner level if you take "pit road, on the last lap".  You'll simply drive through and bypass the animation.  Shaves a few seconds off your time.  Especially; if you take the corner just right when getting back on the track.  5–6 seconds and if your in second place, you'll get a few extra seconds playing 2-player.


Analysis question from a past exam paper

Question: Assume that $f \in C^1 [a,b].$ Prove that $$\forall \epsilon \  \exists \delta > 0 : \\
x, y \in [a,b] , |x-y| < \delta \implies \left\vert\frac{f(x)-f(y)}{x-y} - f'(x) \right\vert < \epsilon $$
I did he following proof and I wonder if its entirely correct as the question itself would have carried 10 % of a 2hr exam.
Edit: edited the proof to make $\delta$ independent of $x$
Let $x,y \in [a,b]$
Since $f'$ is continuous on a compact set, then its uniformly continuous.
Hence
$\forall x,y \in [a,b], |x-y| < \delta \implies |f'(y)-f'(x)| < \epsilon $
By MVT, since $f \in C^1 [a,b], \ \exists c \in (x,y) : f'(c) = \frac{f(x)-f(y)}{x-y}$ .
Thus in particular, $|x-c|<|x-y| < \delta \implies |f'(c)-f'(x)| < \epsilon $ and we're done.
Comment: No!  Your construction of $\delta$ depends on $x$, but the question asks you to show there is a uniform choice of $\delta$.
Comment: Thanks, fixed it.
Answer: Your proof is not correct as $\delta$ depends on $x$ in contradiction with what is requested. You can proceed as follows.
Choose $\epsilon \gt 0$. According to Heine–Cantor theorem it exists $\delta \gt 0$ such that $\left\vert f^\prime(t) - f^\prime(x) \right\vert \lt \epsilon$ for $\vert t - x \vert \lt \delta$.
To get the conclusion, pickup $x,y$ with $\vert x - y \vert \lt \delta$. According to the mean value theorem, for $x \neq y$, it exists $t \in (x,y)$ such that
$$\frac{f(x)-f(y)}{x-y} = f^\prime(t). $$ You have $\vert t - x \vert \lt \delta$ and therefore
$$\left\vert\frac{f(x)-f(y)}{x-y} - f^\prime(x) \right\vert < \epsilon $$
Answer: I'll give a slightly different proof:
Define the function $g\colon[a,b]\times[a,b]\to\mathbb{R}$ by
$$
g(x,y)=
\begin{cases}
\frac{f(x)-f(y)}{x-y} & x\neq y\\
f'(x) & x=y.
\end{cases}
$$
Now $f\in C^1$ gives $g$ is continuous.  Since $[a,b]\times[a,b]$ is compact, we have $g$ continuous implies $g$ uniformly continuous (Heine-Cantor), i.e., for every $\epsilon>0$ there exists $\delta>0$ such that
$$
\max\{\lvert x-x'\rvert,\lvert y-y'\rvert\}<\delta\implies\lvert g(x,y) - g(x',y')\rvert<\epsilon\quad\forall x,y,x',y'\in[a,b]
$$
and our result follows from the case $x'=y'=x$.


setting toolbar height programmatically doesn't work on android 4.4

Question: I try to change the height of my toolbar programmatically:
ViewGroup.LayoutParams params =  toolbar.getLayoutParams();
params.height = (displayWidth / 1024) * 580;
toolbar.setLayoutParams(params);
toolbar.requestLayout();

the toolbar is defined like this in my xml:
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="5dp"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/bbtest"
            android:minHeight="?attr/actionBarSize"
            android:longClickable="false">
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

on android 8.0 this works like a charm. But on my android 4.4.2 tablet the height of the toolbar reduces to zero when doing this.
Does anyone know why?
Comment: @PhanVanLinh omg how did I not see this. So simple. Please write an answer, so I can accept it. Thank you!
Comment: in android 4.4, `(displayWidth / 1024) * 580` = ?. I guess your `displayWidth` is integer and it < 1024 then `(displayWidth / 1024) * 580` = 0
Comment: I face some small problem like you many time too. And the interesting is I take a lot of time for fix small problem because I never thing it is the problem :D
Answer: In your 4.4 device, the displayWidth is integer format and it < 1024 then (displayWidth / 1024) * 580 = 0.
Therefore, it make your toolbar invisible.
The solution is you can change displayWidth to float (or double) or change the operator to displayWidth * 580 / 1024


Switch between JPA and MongoDB with only configuration changes

Question: How to build a Spring Boot application which can switch between JPA and MongoDB with only configuration changes?
Answer: Well both JPA and MongoDB config are basically beans, in case of JPA it's some kind of DataSource() bean and incase of MongoDB, it's the  MongoTemplate() bean. But, if you are configuring the beans using application.yaml with built in properties like spring.data spring.data.xxx or spring.mongo.xxx
If I understood correctly what you meant by

configuration changes

then you are meaning feature toogle. In that case there are a number of ways to achieve that in Spring. @ConditionalOnPropety, @ConditionaOnMissingBean, Spring profiling - @ActiveProfile etc.
It basically depends on your particulary use case. Aditionally you can make disable any bean injection like as follows:

(@Autowired(required=false))

That way, any bean injection can be avoided.
Comment: thanks for your repense  but to understand what i mean could u please see this publication:

https://stackoverflow.com/questions/57727922/switch-between-jpa-and-mongodb-with-only-configuration-changes-with-spring-boot


Bit.ly link to Number of Facebook Likes and Twitter mentions

Question: Programatically,
How can I get the canonical link from bit.ly?
How can I get the number of facebook likes given a canonical link?
How can I get the number of twitter mentions given a canonical link?
Answer: If I understand you correctly, you want to take a http://bit.ly/s.... link and get the original, long URL, then find out the number of likes for that long link on Facebook, and tweets containing it on Twitter. Is that all about right?
For the first part, you can use the link info API to get the long URL from bitly. It may or may not be "canonical," though. It'll just be what was shortened. So it might have extra campaign parameters.
Community Wiki in case people can help with the second two parts of the questions.


Verify access token with Twitter

Question: I have a Web Api project that I have already configured to use Facebook & Google authentication.
Facebook and Google both have a way of verifying the access token given on authentication step.
Facebook:
<code>"https://graph.facebook.com/debug_token?input_token={0}&access_token={1}", accessToken, appToken
</code>
Google:
<code>"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={0}", accessToken
</code>
These return the app_id or consumer key for my applications.
What is the process for Twitter?
The documentation I have read isn't very clear and what I have tried fails and returns a 404.
Answer: You can use the Verify Credentials endpoint:
<code>https://api.twitter.com/1.1/account/verify_credentials.json
</code>
This requires OAuth1A authorization and will verify the credentials of the authorizing user.

Verify access token with Twitter


An array where every element is a divisor of a number and the divisor of the next one

Question: Before anything, I am a newbie in programming. I am actually a high school student, so therefore my question may sound stupid.
I want to create an array where every element is a divisor of a number and the divisor of the next one: e.g. for n=12
1 2 6 12

My solution:
#include <iostream>

using namespace std;

int main()
{
    int n, d, i, j, a[100];
    cin>>n;
    for(d=n; d>=1; d--)
    {
        if(n%d==0)
            j++;
    }

    for(i=1; i<=j; i++)
    {
        for(d=n; d>=1; d--)
        {
            if(n%d==0)
                a[i]=n%d;
        }
    }
    for(i=1; i<=j; i++)
    {
        cout<<a[1];
        if(a[i]%a[i+1]==0)
            cout<<a[i+1]<<" ";
    }
    return 0;
}

It gives me the following error:-1073741676 (0xC0000094)
A solution to this problem would be much appreciated. I am new to this community and I have really become passionate about programming since I entered high school. Thank you :)
Comment: Welcome to Stack Overflow! Please take the [tour] and read [ask]. Concerning your question, you will have to extract a [mcve] from your code and be more precise about what you actually observed. Without an in-depth analysis, check for buffer overflows and use of uninitialized values.
Comment: Welcome to Stack Overflow! It sounds like you may need to learn how to use a debugger to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [Debugging Guide](http://idownvotedbecau.se/nodebugging/)
Comment: Set a breakpoint at if(a[i]%a[i+1]==0) and examine the value of i. It will exceed the size of your array.
Comment: Welcome to both Stack Overflow and programming in general!  One question (and possible followup) Are you getting a compile or runtime error?
Comment: array indices are 0 based, ie valid indices into `a[100]` are 0 till 99 not 1 till 100
Comment: Yesterday I only indicated the problems in your proposal, today I edited my answer to give two ways to do, each giving a different result
Answer: j is used including to compute an index in a, but it is never initialized in your main
In
if(a[i]%a[i+1]==0)

You initialize a doing if(n%d==0) a[i]=n%d; so a[i+1] is always 0 so the modulo is always invalid.
Furthermore, because you initialize only a up to the index j you access to an uninitialized value doing a[i+1] when i is j

A possibility is :
#include <iostream>
#include <vector>
using namespace std;

int main()
{
  int n;

  if (!(cin >> n))
    return -1;

  if (n == 0) {
    cout << "there are an infinite number of solution for 0" << endl;
    return -1;
  }

  vector<int> v;

  // 1 is a first value
  v.push_back(1);

  int max = (n > 0) ? n : -n;

  for (int d = 2; d <= max; ++d) {
    if ((n % d) == 0) {
      // can be a candidate, check if compatible with last value
      if ((d % v.back()) == 0)
        v.push_back(d);
    }
  }

  for (vector<int>::const_iterator it = v.begin(); it != v.end(); ++it)
    cout << *it << ' ';
  cout << endl;

  return 0;
}

We are in C++, so I use a vector rather than a C array with a max size
I check a number was read, and I bypass the case of 0, I also manages the case where the input number is negative to stop the search, and I decide to use positive values.
Compilation and execution :
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra v.cc
pi@raspberrypi:/tmp $ ./a.out
12
1 2 4 12
pi@raspberrypi:/tmp $

Note that if I search from the number rather than from 1 that gives other values :
#include <iostream>
#include <list>
using namespace std;

int main()
{
  int n;

  if (!(cin >> n))
    return -1;

  if (n == 0) {
    cout << "there are an infinite number of solution for 0" << endl;
    return -1;
  }

  list<int> v;

  // the number itself is a first value
  v.push_back(n);

  for (int d = ((n > 0) ? n : -n) - 1; d != 0; --d) {
    if ((n % d) == 0) {
      // can be a candidate, check if compatible with first value
      if ((v.front() % d) == 0)
        v.push_front(d);
    }
  }

  for (list<int>::const_iterator it = v.begin(); it != v.end(); ++it)
    cout << *it << ' ';
  cout << endl;

  return 0;
}

That time I use a list to push_front, it was possible to still use a vector putting the value in the reverse order compared to the first version
Compilation and execution :
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra vv.cc
pi@raspberrypi:/tmp $ ./a.out
12
1 3 6 12


How do I make comments on questions & answers?

Question: Just joined the site.  This is probably a foolish question, but I see lots of comments on people's questions and answers, but no button with which I can add a comment of my own.  I see a way to answer, but not a way to comment.  What am I missing that other people are not? (I've hunted unsuccessfully for an answer on the site.)
Answer: You need a 50 reputation to write comments. As you gain more reputation, you are allowed to do more things on Stack Exchange sites. Remember that an upvote on a question increases your score by 5 and an answer, by 10. So, keep writing good questions and answers and you will be able to participate more effectively on the site!
Comment: OK, thanks for the assistance.  But meanwhile it means that stuff that should go in a comment has to be put in an answer instead (or left unwritten).  I'm not too sure that makes sense...
Comment: ...and oddly enough, *here* I seem able to make comments.
Comment: @pensator It's not odd: *"you can always comment on your questions and answers, and any answers to questions you've asked, even with 1 rep."* :)
Answer: Hello pensator and welcome to the Linguistics SE site!
I suppose this is the first SE site you sign up to, so I hope you'll have a good experience with us. Like Otavio Macedo said, you need 50 reputation for comments.
If you need further info (in the future), you can check your privileges in two ways:

Go to the FAQ on the main site and scroll down until you read "What is reputation?". There you'll see what are the "stages" you'll go through as you earn reputation.
If you hover the cursor over your name on the Main site, a drop-down window will appear. Click on "Privileges" and you'll see what you can or cannot do (yet).

You can also access this page by adding <code>/privileges</code> to any SE site address.
You should find a page with a list on the right, where you can see your progress. When a privilege reaches 100%, it'll mean you have that privilege.
Answer:
But meanwhile it means that stuff that should go in a comment has to
  be put in an answer instead (or left unwritten). I'm not too sure that
  makes sense...

Yeah, for me it's kind of weird too.. But I think they put that in order to avoid spam. In my experience, your options seem to be just not write it, write it as an answer then immediately flag it so that admins can convert to comment, or (if the issue you want to comment require admin action) flag the question and say what you want to say
Comment: I don't think that's the best way to deal with the problem. We're not supposed to do that kind of work. It can happen once, but it shouldn't be the "usual practice". :P
Comment: Ah ok. Just stating it to avoid receiving n+ flags tonight. :P :D
Comment: I know. I mean, in case you *really* want to comment it :P
Comment: yeah, good thinking, @Alenanno :P


FFmpeg concat with absolute path

Question: I try to concatenate two videos using ffmpeg I use that wrapper: wrapper.
According docs I use this commands :
ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate1.ts
ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate2.ts
ffmpeg -i concat:"intermediate1.ts|intermediate2.ts" -c copy -bsf:a aac_adtstoasc output.mp4

After two command I got two files:
/storage/emulated/0/recorder/test1_convert.ts /storage/emulated/0/recorder/test2_convert.ts
But when I execute the third command I got failure: log message: concat:"/storage/emulated/0/recorder/test1_convert.ts|/storage/emulated/0/recorder/test2_convert.ts": No such file or directory
I suppose something wrong with syntax absolute path. This is full my third command:
Comment: As with many issues involving `ffmpeg` usage on Android it is probably a quoting issue. Try it without the double quotes in the concat line.
Comment: @LordNeckbeard you were right, it was double quotes in the contact line issue, thanks.
Comment: Can you read this file by usual hava commands?
Comment: Actually the documentation has another pair of double quotes around input, see https://trac.ffmpeg.org/wiki/Concatenate. HTH.
Answer: Remove the double-quotes in the concat line.
I am not an Android user but quoting seems to be a typical problem on Android when using ffmpeg.

FFmpeg concat with absolute path


Attempted to move home folder back to original ext4 partition and now can't start session

Question: When I initially installed Ubuntu a couple years ago (12.04), I was dual-booting and made the mistake of moving my home directory to an NTFS partition. I later discovered this was why pulseaudio didn't work, so I had no sound. Everything else worked fine, though, so I never messed with it.
I've since upgraded to 14.10 and decided it was time to fix the sound.  The home folder contains way too much stuff to fit on my ext4 partition, so I figured I'd just leave it there, mount it to /media/whatever , and just have an empty home folder on the ext4 partition, that only contains things that Ubuntu and other programs put there by default.
So, I deleted the /home mounting line in my fstab and rebooted.  Now I get "can't start session" error when I try to log in.  I went in to /home in the file system, the empty one on the ext partition.  Into that folder I copied my user folder and all of the hidden files in it.
My current fstab looks like this:
proc            /proc           proc    nodev,noexec,nosuid 0       0
UUID=7a2fdc51-be6e-4b9f-bf47-eaa0a7bade6d /               ext4    errors=remount-ro,noatime,nodiratime,discard 0       1
UUID=d945e120-aae9-489d-9740-2e91654e0ec3 none            swap    sw              0       0
UUID=962A-AB5A  /boot/efi   vfat    defaults    0   1
UUID=96069BFA069BD997 /media/shared    ntfs                   defaults,umask=077,uid=1000,gid=100       0       2
tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0

(Basically what I did to break my computer was change /home to /media/shared). And a folder on the ext4 /home/[username]/ with all of the hidden files I had before.
Here is the result of ls -al on that directory:
drwxr-xr-x  9 root root 28672 Feb 15 00:04 .
drwxr-xr-x  3 root root  4096 Feb 14 23:56 ..
-rw-------  1 root root 33152 Feb 14 23:58 .bash_history
-rw-------  1 root root   220 Feb 14 23:58 .bash_logout
-rw-------  1 root root  3599 Feb 14 23:58 .bashrc
-rw-------  1 root root  3486 Feb 14 23:58 .bashrc~
drwx------ 51 root root  4096 Feb 15 00:01 .config
drwx------  3 root root  4096 Feb 15 00:01 .dbus
-rw-------  1 root root    27 Feb 14 23:58 .dmrc
-rw-------  1 root root 21954 Feb 14 23:58 .face
drwx------  4 root root  4096 Feb 15 00:01 .gconf
-rw-------  1 root root     0 Feb 14 23:58 .gksu.lock
-rw-------  1 root root   142 Feb 14 23:58 .gtk-bookmarks
-rw-------  1 root root 28628 Feb 14 23:58 .ICEauthority
-rw-------  1 root root    42 Feb 14 23:58 .lesshst
drwx------  4 root root  4096 Feb 15 00:03 .local
drwx------  3 root root  4096 Feb 15 00:03 .mission-control
drwx------  3 root root  4096 Feb 15 00:04 .pki
-rw-------  1 root root   675 Feb 14 23:58 .profile
-rw-------  1 root root   256 Feb 14 23:58 .pulse-cookie
drwx------  2 root root  4096 Feb 15 00:04 .screenlayout
-rw-------  1 root root  5676 Feb 14 23:58 .viminfo
-rw-------  1 root root    51 Feb 14 23:58 .Xauthority
-rw-------  1 root root   588 Feb 14 23:58 .xmaximarc
-rw-------  1 root root  7570 Feb 14 23:58 .xscreensaver
-rw-------  1 root root   417 Feb 14 23:58 .xsession-errors
-rw-------  1 root root   462 Feb 14 23:58 .xsession-errors.old

Plus a bunch of files I don't think matter called .fuse_hiddenXXXXX and .goutputsreamXXX.
Comment: First, nothing is listed in fstab as mounted at home. Second you should not use ntfs for /home
Comment: What are the **ownership** and **permissions** of the copied `/home/username` directory? Please edit your question to add the result of `ls -ld /home/username/{,.Xauthority}`
Comment: Thanks, I added the edit.  I know I should not use ntfs, now -- that's the mistake I'm attempting to fix.  Also I read in another thread that I can't find now that you don't need a /home line in the fstab if it's in the default place, but I could have misunderstood it.  In any case, I did try a line `UUID=7a2fdc51-be6e-4b9f-bf47-eaa0a7bade6d /home               ext4    errors=remount-ro,noatime,nodiratime,discard 0       1` which didn't seem to help.  Should I have that line in there?
Comment: I am not sure if your umask should be 077 either,
Answer: The process I used, which may have been dopey but worked, was restoring my old fstab, logging in as usual and creating a home_backup with the necessary files and permissions.
I then got rid of the /home line in fstab, booted from the Ubuntu flash disk, and cp -rp the home_backup to home.
Answer: You need to fix the ownership of the copied /home/username directory, so that the files in it are owned by (and hence writable by) the account owner i.e.
sudo chown username:username /home/username

where username is replaced by the actual username of your account.
Comment: Hi, thanks -- my only access right now is via an ubuntu usb disk, and when I'm booted up with that, my username doesn't exist - I do that and I get `chown: invalid user: [username]`.  Do I need to create a user? If I do that, is that different than creating a user on the actual install?

For what it's worth I also can't log in as guest, I get the same error.


Show the extension is not cyclic

Question: Let $D\in\mathbb{Z}$ be a squarefree integer and let $a\in\mathbb{Q}$ be a nonzero rational number. Please show that $\mathbb{Q}(\sqrt{a\sqrt{D}})$ cannot be a cyclic extension of degree 4 over $\mathbb{Q}$. Also show that if $\mathbb{Q}(\sqrt{a\sqrt{D}})$ is Galois over $\mathbb{Q}$ then $D=-1$.
I have the case $D=-1,|a|\neq2b^2$ for some $b\in\mathbb{Q}$ that the Galois group is $\mathbb{Z_2}^2$, the Klein four group (which is not cyclic). How to show in general that a group is not cyclic?
Answer: Some ideas for you to mull and complete:
$$x=\sqrt{a\sqrt D}\implies x^2=a\sqrt D\implies x^4=a^2D$$
The above almost proves the minimal polynomial (over the rationals) of $\,\sqrt{a\sqrt D}\,$ is $\,p(x)=x^4-a^2D\in\Bbb Q[x]\,$ (can you complete this?)
We get that a basis for the linear space $\,\Bbb Q(\sqrt{a\sqrt D})_{\Bbb Q}\,$ can be
$$\{1\,,\,w\,,\,w^2\,,\,w^3\}\;,\;\;w:=\sqrt{a\sqrt D}$$
But we have that
$$x^4-w^4=(x^2-w^2)(x^2+w^2)\in\Bbb Q(w^2)[x]$$
and this means that no embedding of $\,\Bbb Q(w)\,$ in some algebraic closed field containing it (take $\,\Bbb C\,$ , for example) can map a root of $\,x^2-w^2\,$ to a root of $\,x^2+w^2\,$ and neither the other way around, which already shows the extension cannot be cyclic.
That the extension is Galois means it is normal, and this in turn means $\,Q(w)\,$ contains all the roots of $\,x^4-w^4\,$  , among which there are the ones of $\,x^2+w^2\,$ :
$$\pm  w\,i=\pm\sqrt{a\sqrt D}\,i=\pm\sqrt{a\sqrt D(-1)}\;\ldots$$
Comment: Too much good work to go un-upvoted for an hour! +1
Comment: I was able to show $D<0$, but how do you show $|D|=1$? Of course assuming the degree extension is 4. Thanks.
Comment: "no embedding of ℚ() in some algebraic closed field containing it can map a root of $^2−^2$ to a root of $^2+^2$" but the Galois group of $\mathbb{Q}(\sqrt{ai})$ is the Klein 4-group, and that permutes the roots transitively, so what does this statement mean?

Show the extension is not cyclic


api endpoint returns response 404 - Angular

Question: I have method to save image. Initial this.educationalData gives back data in console.log but after that when i try to get id from endpoint. It gives me undefined.
UPDATED
it is now sending id of 1 but still respond of 404
saveImage() {
  const file = this.imageChangedEvent;
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () = >{
    this.apiService.postData('educational-award/' + this.educationalData[0].id, {
      "photo": reader.result,
      "id": this.educationalData[0].id
    }).subscribe(data = >{
      console.log('test')
    });
  };
}

UPDATE (latest)
I found out i was using the wrong endpoint. Im sorry for causing trouble to everyone.
Route::post('/upload-picture', [UserController::class, 'uploadPicture']);

Screenshot to give more clarity
UPDATED
Comment: could you please add an image after opening the arrow of `educationalData` in the console to see the data inside
Comment: oh sure man. give me a sec.
Comment: try `this.educationalData[0].id` or `this.educationalData[0]["id"]`
Comment: yep now it's sending id of 1 now but i get 404 still.
Answer: When you build your backend route like this
Route::post('/educational-award/{educational_background}',...)

you have to put the {educational_background} parameter directly inside the url string and not as a payload parameter. In your case you are passing the id as a payload parameter.

Why you are getting an undefined for id, that depends on your educationalData object and how the data is constructed in it.
Update,
After I have seen your educationalData  it seems that you have an array. So to get the id use this.educationalData [0].id .

In your saveImage function use it like this :
reader.onload = () = >{
this.apiService.postData('educational-award/'+this.educationalData[0].id, {
  "photo": reader.result,
  "id": this.educationalData.id
}).subscribe(data = >{
  console.log('test')
});

Comment: Thanks this gives me id of 1. But im still getting 404 probably my ```this.apiService.postData``` is the problem
Answer: The post-endpoint expects a path-param {educational_background}. You need to populate it on the client-side:
this.apiService.postData('educational-award/'+this.educationalData[0].id, {
  "photo": reader.result,
  "id": this.educationalData[0].id
}).subscribe(data = >{
  console.log('test')
});

Comment: yes im passing ```"id": this.educationalData.id``` but i can't get the data because its undefined. That's why post endpoint gives back 404
Comment: You need to pass it as a path-param as well, not only in the body.
Comment: yes i've updated it and copied according to your answer. the payload sends id of 1 and photo but it response to 404 still
Comment: Hm, can you add the server-side code? What does `createEducationalAward` do?
Answer: Param {educational_background} is missing
this.apiService.postData('educational-award/' + this.educationalData.id, {


matplotlib numeric values are plotted out of order

Question: I have a data file that consist of multiple y (+ve and -ve values of y) values corresponding to a single x value, if I am trying to plot it using the matplotlib I am getting a zig-zag line, I even tried with the np.sort function, but it hasn't helped. I am attaching 2 figures, the 1 one what I need and 2 one what I am getting using the matplotlib. Any comment/suggestion will be a great help.
import pandas as pd
import matplotlib.pyplot as plt

data = {0: [0.9991008043, 0.7186818868, 0.5990678817, 0.000260249999, -0.0002838699947, 0.9982619435, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.9987124801, 0.9983241558, 0.9979358315, 0.9975475073],
        1: [0.141599882, -0.0239639965, -0.8235306015, -0.5624349256, 0.9576566094, 0.1070839175, -0.7615373918, -0.7436025052, -0.7207683284, -0.7181828611, -0.7169656166, -0.7189734963, -0.7248864019, -0.7334572909, -0.7431326927, -0.7535460886, -0.7653977208, -0.7772543193, -0.7850276183, -0.7882964598, -0.788996217, -0.7894645357, -0.7800111345, -0.7680467609, -0.7651210906, -0.7626205455, 0.1662477571, 0.1776703065, 0.178896989, 0.1792297328]}
df = pd.DataFrame(data)

          0         1
0  0.999101  0.141600
1  0.718682 -0.023964
2  0.599068 -0.823531

plt.plot( df.iloc[:,0], df.iloc[:,1], marker="o", linewidth=2)

Answer:
In this case, the data is correctly cast as numeric (e.g. float), but it's usually a good idea to verify the column dtypes with df.info()
It's required to sort the x-axis values with pandas.DataFrame.sort_values()

I typically also reset the index, but it's not strictly necessary.

Using pandas v1.2.4 and matplotlib v3.4.2

# sort the values for the x-axis, which is column 0
df = df.sort_values(0).reset_index(drop=True)

# plot the sorted data
plt.plot(df.iloc[:,0], df.iloc[:,1], marker="o", linewidth=2)

It's also possible to plot the data with pandas.DataFrame.plot

df.plot(x=0, y=1, marker='o', legend=False)


Draining Dehumidifier through window

Question: We are getting a dehumidifier for our basement and attaching it to a condensate pump. We would like to drain it out the window, but we want to know how to do that without having the window needing to be cracked all the time, as we don't want little critters crawling in. What's the best method for draining through a window?
Comment: **Drill a hole in the wall.** Or drill a hole in the window, thus making the window inoperable, because there's a pipe sticking through it. Which is why the correct answer is to drill a hole through the wall, not run a pipe through a window.
Comment: An inside photo of the window and surrounding area would be helpful. You can click EDIT under your question, then use the mountain icon to add a photo. If bright light from the window makes the frame too dark to see clearly, block the window outside with a sheet of cardboard or similar.
Comment: What kind of window?
Answer: I will take a SWAG: You can drill a hole above the sill plate between the joists through an outside wall. Then insert a piece of tubing that will snugly fit into the hole or a piece of flexible metal pipe. Be sure the outlet points down about a forty five degree angle so the water will be away from the foundation. You can carefully calk where the tube comes out and connect the other end to the pump outlet. In my case I ran it to a drain, made it easy and Ino longer have to add water to keep it from passing out gas.
Comment: Thank you, Gil!
And crip659, there is no floor drain (dirt floor that we're getting redone as well) so that's not an option.
Comment: @Mel if laundry is in the basement, you can drain through the utility sink also. Maybe even the standing pipe for the washing machine.
Comment: I would imagine there is a floor drain or drain pipes where it will be easier than going though a wall/window.
Comment: Yeah, there's gotta be a drain of *some* sort in the basement that you can attach a condensate drain to!

Draining Dehumidifier through window


Service Browser for Zend AMF

Question: I have some questions:

Does Zend AMF has a service browser feature like AMFPHP does? Some people do mention about zamfbrowser, but at the time I'm posting this question, the site is still unavailable.
Is there any possibility to use AMFPHP's service browser with Zend AMF?

Thanks in advance!
Regards, Andree.
Comment: *(reference)* http://framework.zend.com/apidoc/core/Zend_Amf/Server/Zend_Amf_Server.html
Answer: Yeah, the ZamfBrowswer does just that - http://zamfbrowser.riaforge.org/index.cfm
=Ryan
email@example.com
Comment: Ah, okay ! The download link in that site is not working in firefox, so I thought the link is broken. Thanks !
Answer: You can use AMFPHP with Zend_AMF.  I show you how here: http://wesleyalmeida.net/what-ive-learned/how-to-give-zend_amf-a-service-browser-using-amfphp/

Service Browser for Zend AMF


Renaming Toolbar based on the bottom navigator

Question: How do I change Toolbar Titles in different bottom navigation activities, I currently have one displayed in all which is one my manifest
android:label="@string/home"

but since I have four activities on my bottom navigator how can I rename them all on the activities, I tried adding a toolbar it added below the original, home. Tried renaming manifest particular activities doesn't work. Thanks in advance.
I tried setting titles on the activities like this:
   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collections);
        setTitle(R.string.collections);
    }

I want to have something like this, Image One Image two
Answer: You can use setTitle in your activity.
Comment: I tried that. I was wondering should I disable the manifest label? since all are taking from label manifest.
Comment: You can remove from your manifest. The label is displayed by default on-screen when the activity must be represented to the user.


Vue.js component not loading/rendering data when called via URL or F5

Question: I have a Vue.js SPA with some pages that display data from a backend. When I navigate the pages via the navbar, everything works fine, components and data are loaded.
When I'm on the page, e.g. localhost:8080/#/mypage and press F5, the data doesn't get loaded / rendered. Same goes for when I directly navigate to the page via the address bar.
The data gets loaded in this function:
async beforeMount() {
    await this.initializeData();
}

I've tried to call the method in every lifecycle hook, i.e. created, beforeCreated, mounted etc...
In the mounted lifecycle hook I'm setting a boolean property to true, so that the table is only rendered when the component is loaded (done with v-if).
mounted() {
    this.componentLoaded = true;
}

Not sure if this is important, but I've tried it with or without and it doesn't work.
I would really appreciate it if somebody knew whats happening here.
EDIT:
this.applications is a prop and contains multiple applications which contain instances. I want to add some variables from the backend to each application.

console.log(1) gets printed
console.log(2) does not

initializeData: function () {
      let warn = 0;
      console.log("1");

      this.applications.forEach(async application => {
        const instance = application.instances[0];

        console.log("2");

        let myData = null;

        try {
          const response = await instance.axios.get('url/myData');
          myData = response.data;
        } catch (err) {
        }

        let tmpCount = 0;
        let tmpFulfilled = 0;

        myData.forEach(ba => {
            if(!ba.fulfilled){
              warn++;
              application.baAllFulfilled = false;
            }else {
              tmpFulfilled++;
            }
            tmpCount++;
          })

        console.log("3");

        // Assign values
        this.baTotalWarnings = warn;
        application.baAnzahl = tmpCount;
        application.baFulfilled = tmpFulfilled;

        this.componentLoaded = true;
      }

Comment: Did you set up your vue-router to "history" mode?
Comment: @Deda I'm actually building an expansion for an already existing monitoring website (Spring-Boot-Admin). I don't know their router settings nor can I change them.
Answer: Try removing the async and await keywords from your beforeMount, and remove this.componentLoaded from mounted. Set it instead in the then block (or after await) in your initializeData method. I'm not sure Vue supports the async keyword in its lifecycle methods.
Something like this:
beforeMount() {
    this.initializeData(); // start processing the method
}

methods: {
    initializeData() {
        callToBackend().then(() => {
            this.componentLoaded = true // backend call ready, can now show the table
        })
    }
}

Comment: I'm afraid this doesn't seem to work. I had a look at the networks tab in the browser dev tools, and the page doesn't even send the request to the backend.
Comment: @sxz Does initializeData get called at all?
Comment: Yes. I put some logs in there. The method initializeData() gets called, but callToBackend doesn't.
Comment: Then I'm guessing there's something wrong with the backend call. Can you post the contents of your initializeData?
Comment: Sure, I added them to the main question. Thanks for your efforts so far!
Comment: @sxz Hmm, could the problem lie with async forEach? https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop
Comment: I think I found the issue. When the for-loop gets called, the applications prop has a length of 0 - they have not been initialized yet. It seems like the applications only get initialized on other pages, and then passed down to my page. This ofc only works when I navigate to them via navbar. Thank you for your help so far!
Now I only need to find a solution :/


Add fourth box to dynamic drop drop

Question: As you can see from my code, I have taken it from another site.
I would like to add a fourth drop down to the page. It needs to the be first drop down. The type drop down.
The code I have only allows 3 dynamic drop downs, it is basically a state, city and country drop down that I have ammended to suit my needs.
I have added it to a jsfiddle

        Type:
        <select name="Type" id="Type">
          <option value=""></option>
          <option value="Monthly">Monthly</option>
          <option value="Annually">Annually</option>
        </select>

        Box:
        <select name="country" id="country" onchange="setStates();">
          <option value=""></option>
          <option value="Sky HD">Sky HD</option>
          <option value="Sky+">Sky+</option>
          <option value="Sky Standard">Sky Standard</option>
        </select>

    Product :
    <select name="state" id="state" onchange="setCities();">
      <option value=""></option>
    </select>

    Price :
    <select name="city" type="text" id="city" />

The Javascript code
/* This script and many more are available free online at
The JavaScript Source!! http://www.javascriptsource.com
Created by: Michael J. Damato | http://developing.damato.net/ */
// State lists
var states = new Array();

states['Sky HD'] = new Array('Platinum', 'Gold', 'Diamond');
states['Sky+'] = new Array('Platinum', 'Gold', 'Diamond');
states['Sky Standard'] = new Array('Platinum', 'Gold', 'Diamond');

// City lists
var cities = new Array();

cities['Sky HD'] = new Array();
cities['Sky HD']['Platinum']          = new Array('£8.49');
cities['Sky HD']['Gold']          = new Array('£7.49');
cities['Sky HD']['Diamond']          = new Array('£6.49');

cities['Sky+'] = new Array();
cities['Sky+']['Platinum']          = new Array('£8.49');
cities['Sky+']['Gold']          = new Array('£7.49');
cities['Sky+']['Diamond']          = new Array('£6.49');

cities['Sky Standard'] = new Array();
cities['Sky Standard']['Platinum']          = new Array('£8.49');
cities['Sky Standard']['Gold']          = new Array('£7.49');
cities['Sky Standard']['Diamond']          = new Array('£6.49');

function setStates() {
  cntrySel = document.getElementById('country');
  stateList = states[cntrySel.value];
  changeSelect('state', stateList, stateList);
  setCities();
}

function setCities() {
  cntrySel = document.getElementById('country');
  stateSel = document.getElementById('state');
  cityList = cities[cntrySel.value][stateSel.value];
  changeSelect('city', cityList, cityList);
}

function changeSelect(fieldID, newOptions, newValues) {
  selectField = document.getElementById(fieldID);
  selectField.options.length = 0;
  for (i=0; i<newOptions.length; i++) {
    selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
  }
}

// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(function() {
  setStates();
});

Comment: What exactly are you doing?
Comment: Need to add a fourth drop down box, if the user selects Annually the page will show different prices (£89.99, £79.99 for example) At the moment the page is only showing monthly prices
Comment: Unrelated suggestion, you are creating `Array`s but are not using `Array` functionality, you really meant to make `cities` and `states` be of type `Object` (and their inner objects which have keys that are not integers). Most developers would prefer to see the literal forms of `Array` and `Object`: `[1,2,3]` and `{a:1,b:2:3}`. In PHP everything is an array, in JS Array and Object are not the same thing
Comment: Should there ever be a scenario where, given type, box and product, the user can select from more than once price? Sounds to me like you only need three levels of dropdowns, but should be using a different means of displaying the resulting price.
Answer: The script that this is based on is not ideal if I understand your data model correctly. Besides what is mentioned in comments, the State / City scenario has a hierarchy to it, that does not seem applicable to your use case. The list of products appears to be identical regardless of which box I choose, correct? And the combination yields a unique price?
If so, the script you're starting with differs from your desired result in at least two ways:

There is no point in updating the other dropdowns, when another dropdown changes
You should never be able to select the price at all, so this doesn't need to be a dropdown.

I would begin by defining a readable data source, of all the options and their resulting prices:
var prices = [
    { type: 'monthly', box: 'Sky HD', product: 'Platinum', price: '$ 10' },
    { type: 'monthly', box: 'Sky HD', product: 'Gold', price: '$ 20' },
    { type: 'monthly', box: 'Sky HD', product: 'Diamond', price: '$ 30' },
    { type: 'monthly', box: 'Sky+', product: 'Platinum', price: '$ 40' },
    ...
];

After that, define the different filters. For each filtered property, I'll assume there exists a select with a corresponding class.
var options = ['type','box','product'];

With that taken care of, iterate over the options, find the unique values for that option in the data source and populate the dropdowns. Also, add an on change listener to each dropdown.
options.forEach(function(opt) {
    var drop = document.querySelector('.'+opt);
    var unique = Object.keys(prices.reduce(function(x,y) { return x[y[opt]] = 1, x; }, {}));
    unique.forEach(function(value) {
        var htmlOption = document.createElement('option');
        htmlOption.value = htmlOption.innerText = value;
        drop.options.add(htmlOption);
    });

    drop.onchange = function() {
        updatePrice();
    };
});

All that remains is to define updatePrice, which is called each time any of the dropdowns are changed. We iterate through all properties again, and filter out only the prices that match the current selection. If your data source is set up correctly, that should leave you with exactly one match. You could of course add error handling to this to verify that:
function updatePrice() {
    var matches = prices;
    options.forEach(function(opt) {
        var drop = document.querySelector('.'+opt);
        matches = matches.filter(function(price) { return price[opt] == drop.value; });
    });
    document.querySelector('.price').innerText = matches[0].price;
};

Done. Call updatePrice once to set up the initial value:
updatePrice();

This is assuming your scripts are placed last in body. If they're in head, you need to defer the call to updatePrice, and also the setting up of the dropdowns, until DOMReady.
Fiddle
Update: For IE8 compatibility, convenience functions Array.prototype.forEach has been rewritten as regular for loops; Array.prototype.reduce, Array.prototype.filter and Object.prototype.keys has been replaced with functions that roughly mimics their behavior.
IE8-updated fiddle
Comment: WOW! Thanks David, looks perfect to me. Thank you so much. Can I ask one thing, can the price go into an input box? I need to submit the data into a database
Comment: I've changed price to select class and showing in a drop down box. Struggling to get it to work on my page at the moment. Have copied the code to a new page. Not showing any options at the moment
Comment: I have added the javascript in the head and the html in the body.
Comment: @padders01: Oh, but you absolutely need to have the same logic serverside, you can't just accept whatever you receive from the client to be the price. Even if you set the price to a readonly or hidden field, the user can easily manipulate that. You can trust `type`, `box` and `product` to be accurate, because the user can manipulate them anyway, but the price you must calculate on the server as well.
Comment: @padders01: My code above is assuming that the script is in the bottom of `body`. If you want it in head you need to make sure that at least the `options.forEach(...);` block and the final `updatePrice();` call are made in an `onLoad` event.
Comment: I am struggling to make it work with the javascript in the head. Can you help? Sorry
Comment: @padders01: [Updated fiddle with script in head here](http://jsfiddle.net/hx4jwa5p/). Note the `onload` attribute in `body`, and the `setupOnLoad` function in the script.
Comment: thank you so much for this. I am looking at getting it to work. I am struggling at the moment. No idea why. I have used javascript for a few years now. I will keep working at it
Comment: Does all the javascript code need to be in one wrap in the head?
Comment: @padders01: Not sure what you mean with a wrap, but all code that accesses elements in the document (for example the `options.forEach` block since it updates actual dropdowns) has to be executed after the document is loaded. You can't run that code immediately in head, since the elements don't exist at that point. If you place the code in head, that code must be in a function that is called on page load. I have added a fiddle with a working example of that in my previous comment.
Comment: I am really not sure what I am doing wrong, sorry. I have copied all the code from the webpage and pasted into the link below

http://hostcode.sourceforge.net/view/3835
Comment: @padders01: Your code is working for me. What problem are you experiencing?
Comment: There are no options in the drop down menus, nothing there
Comment: hostcode.sourceforge.net isn't working for me (the compile & execute part). I copied your code entirely into JSBin ([here](http://jsbin.com/qekuvohixo/edit?html,output)). Are you seeing the same problem there?
Comment: Right, I have just tried it in Chrome and it works fine. Not working in IE8. Do you know why this would happen? I need it to work in IE8, the work computer only have XP and IE8
Comment: Googling it obect.keys doesn't work in IE8. Any ideas?
Comment: @padders01: [Here is a polyfill for Object.keys](https://coderwall.com/p/q8qacw/object-keys-polyfill). This code utilizes several features of the Array prototype which won't work in IE8 either, such as `forEach`, `filter` and `reduce`. These can all be rewritten as regular for loops with conditions, etc. If you want tidier code, though, I really recommend [es5-shim](https://github.com/es-shims/es5-shim), which will allow you to use all of these features in IE8 (and the `Object.keys` polyfill will be redundant if you use es5-shim).
Comment: Thanks again David. Really appreciate your time helping me. Not sure where to go with that es5-shim but I will have a look at it
Comment: A polyfill adds language features that are not natively supported by the browser. If `.reduce` does not exist on an array, for instance, an `Array.prototype.reduce` polyfill defines that function and mimics the behavior of the standard function. Es5-shim is a collection of polyfills, it tries to make as many EcmaScript5 features as possible available in browsers that are not ES5 compliant, and it does a good job of it, too. So all you have to do is include the es5-shim script file before your other scripts, and you will be able to use `Object.keys` etc, even where it isn't natively supported.
Comment: I've added the es5-shim.js to my page and it still doesn't work :-(
Comment: @padders01: Turns out `add` isn't available on `HTMLSelectElement` either. Change `drop.add` to `drop.options.add` in the code. Sorry, it's been a while since I last spent time supporting old browsers. With that change, everything works when I emulate IE8 locally. I can't show it in JSBin, because JSBin doesn't appear to work in IE8 either.
Comment: Tried that, still doesn't work. You don't need to apologise

I have added it to sourceforge just to show you what I have done

Added the es5shim at the top and changed drop.add to drop.options.add

http://hostcode.sourceforge.net/view/3838
Comment: Hm. Two things: apparently `drop.options.add` doesn't work the way I thought it did, either. I thought I tried it, but now I can't reproduce. `drop.options.add(new Option(value, value))` is what works. Second, Github is not a CDN. They're picky about that, and you won't be able to hotlink the resource from them because of how they set mime types. The github link is for downloading if you want to distribute it yourself, but if you want a CDN, ES5-shim is available on cloudflare: https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.3.1/es5-shim.min.js
Comment: Hi David, still not working

function setupOnLoad() {
    options.forEach(function(opt) {
        var drop = document.querySelector('.'+opt);
        var unique = Object.keys(prices.reduce(function(x,y) { return x[y[opt]] = 1, x; }, {}));
        unique.forEach(function(value) {
            var htmlOption = document.createElement('option');
            htmlOption.value = htmlOption.innerText = value;
            drop.options.add(htmlOption)        });

        drop.onchange = function() {
            updatePrice();
        };
    });
Comment: I host the ES5-shim myself, just for speed I used the hotlink. i have changed it to the one you linked to
Comment: @padders01: I can't see that you've changed the code according to my last comment?
Comment: Must have copied the old code

function setupOnLoad() {
    options.forEach(function(opt) {
        var drop = document.querySelector('.'+opt);
        var unique = Object.keys(prices.reduce(function(x,y) { return x[y[opt]] = 1, x; }, {}));
        unique.forEach(function(value) {
            var htmlOption = document.createElement('option');
            htmlOption.value = htmlOption.innerText = value;
           drop.options.add(new Option(value, value))       });

        drop.onchange = function() {
            updatePrice();
        };
    });
Comment: [This exact document](http://pastebin.com/buBpd7YQ) works for me when I emulate IE8. If it doesn't for you, your problems may be elsewhere. Please provide an error message if you have further issues. If it helps, you may skip es5-shim and use the `Object.keys` polyfill from above, and rewrite the array functions into for loops of your own. Remove code, see which parts work and what fails.
Comment: Thanks again for your help. Copied that code into new document and still doesn't work. Nothing in the drop down menus. The error in IE is Line 37 "Object doesn't support this property or method"
Comment: That's `unique.forEach`, one of the functions that has to be polyfilled. Check the console to see that ES5-shim has been loaded. Your browser may be blocking external sources on local documents. [I uploaded the document here](http://www.davidhedlund.se/dropdowns.htm) if running scripts locally is the culprit.
Comment: So that link you sent me still doesn't work on IE8. Works fine from Chrome. Not sure there is a problem with IE opening the external source. When i put the link into IE it open the javascript file. This is very strange and getting more and more frustrating
Comment: @padders01: That's weird, it works when I emulate IE8, but I guess that's not exactly the same thing. I don't have access to IE8, but see my updated answer. I rewrote the code to not use any functions that es5-shim should be needed for. If any of those were the culprit, it might work better now (not the document I linked to, but the new fiddle in my answer).
Comment: Not worked again, doesn't work in Chrome either.

Added Sourceforge to show how I have entered code onto my page, incase I am doing anything wrong

http://hostcode.sourceforge.net/view/3897
Comment: @padders01: My bad, I wasn't working from the version with script in head. [Updated again, here](http://jsfiddle.net/kpq98qxr/1/)
Comment: That works in Chrome now but still not in IE8. Error on line 35. Object doesn't support this propety or method again
Comment: When running IE8 with Compatibility view (which was defaulted for Intranet sites) it stops it working.Not sure why but it did. I have turn off Compatibility view and now the drop down menus working fine. Thank you so much for your help.
Comment: Can I ask for one more favour? Is it possible to have the price in a input text box? I have tried but it didn't populate
Comment: Hah! Well that explains a lot. I was running IE11, emulating IE8 without being able to reproduce your errors, but *you* were running IE8 emulating IE7 (which is what compatibility view does). Don't use compatibility view, it's terrible. If you turn that off, I'm guessing my old links will work as well. If you want the price in a textbox, the only change to the script is that you shouldn't set the `innerText` property but the `value`. [Fiddle here](http://jsfiddle.net/Lwjbrwj7/). But then I must reiterate that you should never trust the price you receive from the cilent, validate serverside.
Comment: You SIr, are a legend. I can't thank you enough for your help. It's been a week now I think? If i could buy you a drink I would (that's if you drink).
Comment: I can't give you +1 feedback as my reputation is only 14
Comment: Just glad to hear it worked out in the end! I have more +1's than I can count already.

Add fourth box to dynamic drop drop


How can I make the ceiling black, non-permanently?

Question: I have bedroom curtains (double set - one rubber-backed and one sheer) that are letting in too much light where the light sneaks over the top of the curtains. The windows extend to the ceiling. The curtain rails are hung from the ceiling (similar to this installation lifted from this blog).
I'm planning on installing a pelmet, that extends to the ceiling, painted black on the inside (facing the curtains/window), and I think that will cut out a lot of the light. However, there is still a lot of light that hits the ceiling, and then bounces down between the two curtains and gives them a glow.
I'm thinking if I paint the strip of (plasterboard) ceiling between the pelmet and the window a matte black, that should help cut out a lot of those reflections.
However, I have been warned that if I do that, if I ever redecorate the room and remove the pelmet, I will not be able to paint over the black paint and restore it to its white colour.
My questions are:

If I paint part of the ceiling black, am I really making myself a problem later if I decide to restore it?
Is there another way to make the ceiling black on a more temporary basis? (I figure black Contact is not the way to go!)
Comment: We bought an extra black-out curtain and cut it in half.  Then we stuff it on top of the pelmet.  We have two pretty big windows in our bedroom and tons of light hits it and our mornings are pretty dark.  This might not look great but a black ceiling is worse IMO.  Just keep the light from coming in.
Comment: I don't mind when tenets paint. I mind when they use anything other than *'landlord white'*. Especially red or black. It can be covered with enough coats but when you scratch it.... It never goes away.
Answer: You can also look at using removable paint. This answer might be a little late, but I had a similar issue where I wanted to paint my ceilings white, but was looking for a non-permanent solution because the ceilings were wood and the landlord did not want them painted.
I eventually stumbled across tempera paint powder for kid's art, it comes in these big buckets in all different colors. It's pretty easy to mix up and apply. If you are still looking for a solution I was so excited about my solution I even did a video on the process:
https://youtu.be/YETnP1FV1A4
Goodluck!
Comment: Uh, picture of it not there anymore to the landlord's satisfaction? GL getting it out of all the cracks....
Answer: Your pelmet needs a top to it. Other terms are box valance or cornice.
You take a standard valance which is just a curtain rod cover and put a top on it.
Since it's a box with an open bottom that covers the curtain rods and the top of the window opening, it should be a very effective light control device. Paint the inside of the thing matte black, make it light-tight with a weatherstrip between it and the wall and you don't have to mess up the wall or ceiling.
I created mine, not for light control, but for draft control along a 7 foot sliding glass door. The drapery curtain brushes against the underside of the valance top and does a really good job of ending winter heat loss from convective air currents.
Comment: @Oddthinking - I believe that FiascoLab's idea of a box structure is just as valid in your case. Your flat front on the structure simply goes all the way to the ceiling in front of the curtain rod. As suggested you would install a light tight weather strip along the top edge of the front board to seal it up to the ceiling.
Comment: Thanks for your answer. I pondered it for a while before realising why it didn't make sense to me. My windows extend to the ceiling. My curtain rails hang from the ceiling. A box valance only seems to make sense when a window doesn't reach the ceiling and the rails hang from the wall. Sorry, I didn't make that clear in the original question. I have edited it for clarity.
Comment: @MichaelKaras: That would help a lot, because light from coming in the window, bouncing off the ceiling above the curtain rails, and trying to hit me directly in the eye, would be stopped by the pelmet. That's why I am putting a pelmet in. There is still a lot of light coming in the window bouncing off the ceiling above the curtain rails, reflecting back to hitting the inside of the thick white rubber-lined drapes, and coming through the thin sheer curtains. The top third of the curtains glow with reflected light. I am trying to fix that too.
Answer:
I will not be able to paint over the black paint and restore it to its white colour.

It's just paint on drywall. If you decide to remodel, you can paint over it.
You will need to paint the whole wall to make sure the color matches, and it may take an extra coat or two to completely cover the black, but if you do any remodeling, you will most likely be painting the wall anyway.
Covering up the black will be a small amount of extra work. It definitely doesn't make it impossible.
Comment: Agreed, a high quality white paint with high percentage titanium dioxide pigment should cover up that black paint just fine.