Which command to know the time when a server has booted up? (boot time history)

Question: I would like to know the time when a linux box has booted up last year. Is there any way to ask the computer at which time it has been booted up ?
thanks.
Answer: Try uptime or last -x.
Comment: Thanks but this gives the actual boot time, what I'm looking for is a list of boot times.
Comment: Yes, that's why I mentioned `last -x`. Depending on your log rotation policy you might need to provide another `wtmp` file e. g. `last -x -f /var/log/wtmp.1`.
Answer: Last should give you the boot times, looking for the reboot or boot usernames.  If need be you may need to find and use the flag that lets you load the older last logs
Answer: Perhaps ps aux | grep init gives you detailed enough information? After a long(ish) uptime it shows you the date the init process was started.
If that's not accurate enough, see /proc/stat and the btime value there. It's the Unix time in seconds when the system was last booted up. To parse it, use your favourite date manipulating tool, for example Perl Date::Manip module:
grep btime /proc/stat | cut -d ' ' -f2 | perl -MDate::Manip -lane 'printf "%s\n", UnixDate(ParseDateString("epoch $_"), "%c");'
In my test server that returns
Mon Jul 19 15:45:12 2010
Which is the last the the server was restarted.
Answer: On Linux, there's the uprecords utility that records all your uptime history. You have to install it first to start recording your uptimes though (i.e. it won't show your past uptimes).


Convergence in $L_{\infty}$

Question: Let $(X,\Sigma,\mu)$ be a measure space and $E_n\in\Sigma$ such that $\mu(E_n)>0$, and we define $f:=a_n\chi_{E_n}$, where $a_n>0$ for each $n\in\mathbb{N}$.
I want to prove that if $f_n\to 0$ in $L_{\infty}$ then there isn't $C>0$ such that $a_n\ge C$ for each $n\in\mathbb{N}$.
So, if there is $C>0$ such that $a_n\ge C$ for each $n$, I want to prove that $f_n$ doesn't converge to $0$ in $L_{\infty}$.
To do this, I want to find an $\epsilon >0$ such that for every $n\in\mathbb{N}$ we have $\left\|{f_n}\right\|_{\infty}\ge \epsilon$.
Can you give me a hint to do this? Can we take $\epsilon = C$?
Answer: You have $\|f_n,L^\infty\|=a_n$. If $f_n\to 0$ in $L^\infty$, then you have by definition $\|f_n-0,L^\infty\|\to 0$, hence $a_n\to 0$ and you can conclude.
Comment: In my own studies I've seen the $L^\infty$ norm denoted by $\lVert \cdot \rVert_{L^\infty}$ - is there any reason you don't use this notation? Or are you trying to achieve something else?
Comment: @DanZimm it's just a question of notation and of habit: my $\|f_n,L^\infty\|$ stands for your $\|f_n\|_{L^\infty}$. In general case, one of acceptable notations is $\|f,Y\|$ for "norm of $f$ in the normed space $Y$". Can come handy if you work with many different spaces at the same time.
Comment: @TZakrevskiy thank you :)

Convergence in $L_{\infty}$


How to get values for certain keys from a list of dictionaries

Question: My Input JSON data:
{
    "data": [
        {
            "config": "current",
            "id": "0"
        },
        {
            "config": "current",
            "id": "1"
        },
        {
            "config": "current",
            "id": "2"
        },
        {
            "config": "current",
            "id": "3"
        },
        {
            "config": "previous",
            "id": "4",
        },
        {
            "config": "previous",
            "id": "5"
        },
        {
            "config": "current",
            "id": "6"
        }
    ]
}

I want to form a dictionary of lists out of above input data based on common key/value pair:
{
    "current": ["0", "1", "2", "3", "6"],
    "previous": ["4", "5"]
}

How can this be achieved using python?
Comment: This is actually an invalid JSON, `"id": "4",` should be `"id": "4"`.
Answer: Assuming you already know how to parse JSON, you can do this:
d = {
    "data": [
        {"config": "current", "id": "0"},
        {"config": "current", "id": "1"},
        {"config": "current", "id": "2"},
        {"config": "current", "id": "3"},
        {"config": "previous", "id": "4"},
        {"config": "previous", "id": "5"},
        {"config": "current", "id": "6"}]
    }

result = {}
for d0 in d['data']:
    ids = result.setdefault(d0['config'], [])
    ids.append(d0['id'])

print(result)
# -> {'current': ['0', '1', '2', '3', '6'], 'previous': ['4', '5']}

dict.setdefault() is used to get the id list if it exists, or if not, set it to a default, which is an empty list here. It's functionally the same as this:
config = d0['config']
if config not in result:
    result[config] = []
result[config].append(d0['id'])

You could also use collections.defaultdict(list) to do the same thing even more easily.
[This explanation is taken from my answer here.]
Comment: Thank you so much @wjandrea. I was trying to do it in a much complex way. Using dict.setdefault() is much easier which i was not aware of.
Answer: jsn = {
    "data": [
        {"config": "current", "id": "0"},
        {"config": "current", "id": "1"},
        {"config": "current", "id": "2"},
        {"config": "current", "id": "3"},
        {"config": "previous", "id": "4",},
        {"config": "previous", "id": "5"},
        {"config": "current", "id": "6"}
    ]
}

current = [x["id"] for x in jsn["data"] if x["config"] == "current"]
previous = [x["id"] for x in jsn["data"] if x["config"] == "previous"]

res = {"current": current, "previous": previous}

print(res) # {'current': ['0', '1', '2', '3', '6'], 'previous': ['4', '5']}

Or the same algorigthm with a function:
def get_ids(json_string, key):
    return [x["id"] for x in json_string["data"] if x["config"] == key]

res = {
    "current": get_ids(jsn, "current"),
    "previous": get_ids(jsn, "previous")
    }

print(res) # {'current': ['0', '1', '2', '3', '6'], 'previous': ['4', '5']}

Comment: You might want to avoid calling it `json` cause that's the name of the [stdlib JSON library](https://docs.python.org/3/library/json.html).
Comment: Ok. Renamed it to `jsn`


Definition of basis in topology

Question: In the definition of a basis on a set $X$ in topology, one of the properties is that, "for any two basis elements $B_1, B_2$ and any point $x \in B_1 \cap B_2$, there is a third basis element $B_3$ containing $x$ and contained in $B_1 \cap B_2$". I am wondering what happens if we change this property to the stronger property of requiring closure under pairwise intersections (and hence, inductively, by finite intersections)? In other words, what if we changed the requirement to "for all basis elements $B_1, B_2$, their intersection $B_1 \cap B_2$ is a basis element"?
Are there any simple/important examples in which the original (i.e. weaker) property holds but the latter (i.e. stronger) property doesn't?
Answer: Well, if $\mathcal{B}$ is closed under finite intersections then it certainly obeys the property that you mention. But not all bases do: e.g. in $\Bbb R^2$ the Euclidean-balls form a base for the topology but they are not closed under intersections.
The point of these properties is that they are necessary and sufficient to define a base.  Being closed under binary intersections is sufficient only.
Answer: Consider $\mathbb{R}^2$ with the usual euclidean topology.
Consider $B_{\epsilon}^q=\{x \in \mathbb{R}^2: \|x-q\|<\epsilon  \}$ where $q \in \mathbb{R}^2$.
It is clear that $\{B_{\epsilon}^q  : q \in \mathbb{R}^2 \mbox{ and } \epsilon>0\}$ is a basis but you do not have that property.
Answer: There are easy examples of bases that have the first property but not the second; open balls in $\Bbb R^n$ for any $n>1$ will do. On the other hand, if you take the closure of any base under finite intersections, you get a base for the same topology that has the stronger property, so in that sense it doesn't really matter which property you use to define bases. The main advantage to using the weaker property, apart from the fact that it is necessary as well as sufficient, is that it often allows simpler descriptions of a base.
Answer: The set of open discs in the plane is a basis for the usual topology, but the intersection of two discs is a disc only in trivial cases.
Answer: This is not an important example. Suppose that the underlying set for the topology is $\mathbb{R}^{2}$. Let the original basis be the collection of open squares with arbitrary orientation. Depending on the two open squares their intersection will be empty or some open polygon, which might have as few as three sides or as many as eight sides.

Definition of basis in topology


How to reduce redundancy in multiple if-elif blocks?

Question: I'm writing a "quiz game" using a GUI package called Draw.py.
I'm new to this and I don't really know how to reduce redundancy of my code.
The code works perfectly but I know it's not completely neat.
Here's what I would like to reduce:
def question1():
    question("Which device would \n you most want to have?") #draws #question
    answer1()  #draws the answer boxes.
    mouseclicks = 0

    while mouseclicks != 1:
        if Draw.mousePressed():   #checks if the user clicks.

            xCoord= Draw.mouseX()   #check x-y coordinates
            yCoord= Draw.mouseY()

            if  xCoord >= 91 and xCoord <= 390 and yCoord >= 400 \
                and  yCoord <= 552:
                ChooseAnswer(88,400,300,150)  #Chosen answer, turns green #when user clicks
                characters["question 1"]["PC"] += 1
                mouseclicks += 1
                answer1()

            elif xCoord >= 601 and xCoord <= 900  and yCoord >= 402 \
            and yCoord <= 550:
                ChooseAnswer(600,400,300,150)
                characters["question 1"]["BJ"] += 1
                mouseclicks += 1
                answer1()

            elif xCoord >= 92 and xCoord <= 388  and yCoord >= 602 \
            and yCoord <= 750:
                ChooseAnswer(88,600,300,150)
                characters["question 1"]["Mr.P"] += 1
                mouseclicks += 1
                answer1()

            elif xCoord >= 602 and xCoord <= 902  and yCoord >= 603 \
            and yCoord <= 750:
                ChooseAnswer(600,600,300,150)
                characters["question 1"]["Diane"] += 1
                mouseclicks += 1
                answer1()

I created a dictionary and everytime the user clicks within certain coordinates one of the keys in the dictionary goes up by one. At the end, the key with the highest value is the winner.
Comment: Esther, have you tried to implement some unit tests for your code? I suggest try to exercise some Test-Driven Development techniques for your coding skill improvement, if you think it can help.
Comment: You can refactor your code for parametrized functions, removing repetitive coed into these functions. Create parameters for what changes.
Answer: What you could do is to create lists of coordinates, arguments for ChooseAnswer and keys of characters like this:
coordinates = [(91, 390, 400, 552),
               (601, 900, 402, 550),
               (92, 388, 602, 750),
               (602, 902, 603, 750)]
answers = [(88, 400, 300, 150),
           (600, 400, 300, 150),
           (88, 600, 300, 150),
           (600, 600, 300, 150)]
keys = ["PC", "BJ", "Mr.P", "Diane"]

and then iterate over coordinates, check which ones satisfy your conditions, and finally call ChooseAnswer with corresponding arguments and increment a value of characters for a corresponding key:
for index, coordinate in enumerate(coordinates):
    if (coordinate[0] <= xCoord <= coordinate[1]
            and coordinate[2] <= yCoord <= coordinate[3]):
        ChooseAnswer(*answers[index])
        characters["question 1"][keys[index]] += 1
        mouseclicks += 1
        answer1()


Are there any pitfalls with having multiple MySQL databases on 1 server node?

Question: I want to prepare my database for sharding in the future. But right now I only need 1 node.
What I'd like to do is to shard the database into virtual shards, say 12 shards, and put all of them onto the same server node for now.
And when I need to scale out, I could just then get a 2nd server and move 6 of the 12 virtual shard onto the new machines.
Are there any pitfalls with having 12 different databases on 1 machine?

Can I still run only 1 MySQL instance to support those 12 databases?
Does having 12 databases result in higher memory usage?
Does this require having 12X as many database connections?
Any other pitfalls?

Thanks.
Answer: Nothing wrong at all. There might be a slight overhead in memory usage, but if you are in a situation where you have to consider sharding, then memory should not be your main problem anyway.
Your applications can use a connection pool. Most MySQL connectors support this mode, and it let's the pool manager decide on the most efficient way to handle the requests. In theory, they could also use one and the same connection (and issue "USE db_name" to change databases), but that can get really confusing for the developers.
Comment: When you said "slight memory overhead" how much would that be? Does going from 1 database to 12 databases increase memory consumption by 12X? Or even just double memory consumption?
Comment: It's hard to tell without actually doing it. MySQL keeps various caches for its databases, including some for the table descriptors. As the tables would now be spread over mutiple database, I would expect some additional cache requirements for these additional databases that have to be kept open. I don't think that anyone could answer this with any precision until you really try it out.


How to log simpletest test results into files using drush test-run?

Question: I would like to save simpletest test results into a log file. What bash commands should I use ?
I tried this command (example) but nothing is saved into /var/tmp folder :
sudo -u apache drush test-run Comment --xml /var/tmp

I use Linux , Drupal 7.12, Drush 4.5
Answer: I don't use drush test-run, but Drush options are always in the form --xml=/var/tmp.
c.f. http://drupal.org/node/1416198
From drush help test-run
 --xml      Output verbose test results to a
            specified directory using the JUnit
            test reporting format. Useful for
            integrating with Jenkins.

Try:
sudo -u apache drush test-run Comment --all --xml=/var/tmp

Answer: Try something like this:
sudo -u apache drush test-run > /var/tmp/whatever.txt

Comment: if I use your example nothing goes into whatever.txt
Comment: I tried this as well but unfortunately this also didn't work.
Comment: Actually what I did was just this: drush test-run > /var/tmp/whatever.txt ... What is the error you get?
Answer: What worked for me finally was:
sudo -u apache drush test-run Comment --xml=/var/tmp >/var/tmp/test.log 2>/var/tmp/test.err

Thanks for help from hiphip and greg_1_anderson :)


How to use sight-reading to develop improvisation skills

Question: I can play a lot of songs on the piano when I see them for the first time as sheet music, including a lot of original jazz arrangements and classical pieces. My sight-reading is pretty good but I do have difficulty in phrases where scales must be played quickly.
What are some practical ways to train my improvisation skills using my sight-reading ability?
Comment: There is lots written here but I'm wondering is there an actual question?
Comment: ok I made it less philosophical
Comment: There are a lot of completely unsupportable assumptions in this non-question.
Comment: My suggestion would be to just work on your improv - that's a large topic in itself. If you're having troubles with comping, chord substitutions or melody treatment, that would probably warrant more questions. Just study the type of improv you want to do, and you'll find that any other skills you already have, like site reading, chops, or theory, will be of great help.
Comment: If I don't challenge myself to learn to play something beyond my current ability, I get bored. I've never worried about not growing as a musician because growth is what made me start playing in the first place. What I worry about is my body aging to the point that I can't grow no matter how motivated I am. I'm curious if there are musicians who have trouble challenging themselves with more difficult material.
Comment: That's a great sentiment, Todd. When I play, though, I also get a lot of satisfaction (both mental and physical) from feeling the instrument, from the tactile feedback and from the resulting music that resounds. Taken literally, it would mean that growth is not a necessity, though it's clear to see that with a little growth, a stagnating musician such as the one in my post can open the door to a new difficulty level, and along with that more substance and satisfaction from playing those higher-level pieces.
Comment: The question is one which I have pondered upon for many years. There are, however, very many degrees of sight reading. I play with guys who can read flys**t, i.e. perfect renditions of pieces. I also play with guys who can hardly read, but will play a piece back in a pretty good state, after a hearing. So, your question has some grey areas which are not making it an absolute. For someone who is an excellent sight reader, there is no reason to learn much, as long as the dots are there. For the other end of the spectrum, which is where I tend to be, a great ear is usually enough. However...cont.
Comment: ...the non sight reader has only someone else's rendition to 'copy', and it may or may not be a good datum point. Same with sight readers - the dots may be accurate...      So, being able to improvise will help in both camps. While playing without dots is probably an easier opportunity to improv., whilst sight reading, looking ahead at the structure and development of the piece, improv. is possible. BUT- unless that reader has heard the piece previously,it's pure supposition that their improv. will go with what's actually going to happen.The 'copier', on the other hand, has heard the piece...
Comment: I'm a relatively poor sight reader myself, so I will not attempt a formal answer, but my understanding is that some skills required for sight reading and for improvisation are common, for example - ability to keep tempo regardless of "mistakes"; thinking ahead; fluent fingering (in the case of the piano, or the equivalent in other instruments); understanding of the harmonic context - and perhaps some more. So working to develop these skills in either context will help in the other context, I gather.
Answer: The question is quite broad, however here are some tips:

Familiarize yourself entirely with scales and arpeggios. As boring as it sounds, it is incredibly important to know your way around a piano. Don't just familiarize yourself with major scales, work with natural, harmonic, and melodic minor, and even the blues scales! It is also a good idea to work with scale modes as well as they come in handy when improvising a song. www.notreble.com/buzz/2011/10/26/a-practical-guide-to-modes-and-scales/
Here is  a good site for learning about all the kinds of scales.
Listen to the kinds of music you want to improvise. If you want to improvise like Chopin, listen to more of his piano sonatas! If you like Dvorak, listen to his piano concerto! Listen to more blues piano pieces if you want to improvise blues. The point is, it really helps when improvising if you know what you want your improvisation to sound like. Same thing in sight reading!
Learn how to modulate keys. Really important. You don't always even need to change keys, but it really helps to know what chords sound good together and which ones are more dissonant so you can appropriately place them in your song.
Familiarize yourself with chords! Not knowing your basic chords will prevent you from creating an impressive improvisation and it helps loads to know some more uncommon ones. www.pianochord.com/list-of-chords
Form a motif. This is the more creative part of improvising that will develop more over time. A motif, if you don't know, is a "brief melodic or rhythmic formula out of which longer passages are developed." Basically it is a theme. They are pretty short and the point of the motif is that you work around it and develop it. You probably won't immediately be amazing at this and that is why it is a skill that develops over time.
Familiarize yourself with the basics of music theory in general. Having a basic understanding of music theory such as time signatures, chord structure, melodic development, etc. will drastically improve your ability to do the techniques listed above.
Practice, practice, practice. This is pretty general, but practice your improvising. It is the only way to actually make physical bounds. It will take time, but with patience and practice, you will become greater and greater at it.

Comment if you have any questions about this answer! Good luck!
Apologies for not having all of the websites as hyperlinks. I only have permissions to make one at a time currently.


p-adic valuation

Question: My question is two-fold. First off, let's define $v_p$ to be the valuation on $\mathbb{Q}$ defines by setting $v_p( \frac{a}{b} p^n)=n$, where $(a,p)=(b,p)=1$. How exactly does $v_p$ extend to $\mathbb{Q}_p$ (if it all)? Is this hard to show?
Secondly, let $\alpha \in \mathbb{Q}_p$ be non-zero. I was wondering how difficult it would be to understand the values of $|1+\alpha^2|_p$. We have $$|1+\alpha^2|_p\leq \max( 1, |\alpha|_p^2).$$ Is there anything more interesting that can be said?
Comment: I may be not understanding something, but how did you arrive to $\;\Bbb Q_p\;$ if not via the $\;p\,-$ adic valuation $\;v_p\;$ on the rationals?
Comment: I was about to answer your question, but I don't know what your definition of $\Bbb Q_p$ is. What are $p$-adic numbers, for you? Do you think of them as infinite series of the shape $\sum_ia_ip^i$, where the $a$'s are from the set $\{0,1,\dots,p-1\}$? If so, the $v$ you want is gotten by telling the lowest value of $n$ with $a_n\ne0$. But there are other ways of thinking of $p$-adic numbers, and maybe you're using one of those?
Comment: Yes, I'm thinking of $\mathbb{Q}_p$ as infinite series $\sum_{i\geq k}a_ip^i$ with $a_i\in \{0, 1, \ldots, p-1\}$.
Answer: With the definition of $p$-adic numbers as (potentially) infinite series $z=\sum_{n=N_0}^\infty a_np^n$ with each coefficient $a_n\in\{0,1,\cdots,p-1\}$, then $v(z)$ is the smallest $n$ with $a_n\ne0$. This value may be negative, but if nonnegative, we say that $z\in\Bbb Z_p$.
The valuation-behavior of the polynomial $1+z^2$ is only somewhat interesting, in that if $v(z)>0$, then $v(1+z^2)=0$, as you know. What is rather more interesting is to compare the valuation of $f(z)$ with the valuation of $z$ when $f$ is a polynomial (or even a power series) with no constant term. And this question is yet more interesting when you look at possibilities for $z$ that lie in algebraic field extensions of $\Bbb Q_p$. For then, if you keep the convention that $v(p)=1$, you'll have all rational numbers being possibilities for $v(z)$. Then the "valuation function" of $f$ will be a concave function (concave downward) whose graph is polygonal. This valuation function is closely related to the Newton Polygon of $f$, which also is defined by means of the "additive" valuation $v$ rather than the (multiplicative) absolute value, which many people find more intuitive.
Comment: Thanks, this is the type of thing I'm trying to learn about. Let $f(x)$ be some polynomial in $\mathbb{Q}_p[x]$ with no constant term. If I understand correctly, there is a way to compare $v( f(x))$ with $v(x)$. How complicated is it to compare the two valuations ? Anyway, one can also take $f(x)\in K_p[x]$, where $K_p$ is an algebraic extension of $\mathbb{Q}_p$ and do the same thing: compare $v(f(x))$ with $v(x)$. However, I'm a little hazy on how one would extend the valuation $v$ on $\mathbb{Q}_p$ to an extension $K_p$. How is this done?
Comment: If you want to e-mail me, I'll be happy to fill you in on a bunch of these things, but I think it better if you use a strong (but not impossible) text like Gouvêa. My general recommendation to you is: do lots of hand computations.

p-adic valuation


Elliptic curve division polynomials equations calculations are not matching

Question: Weierstrass form of elliptic curves is: $y^2=x^3+Ax+B$
The first four division polynomials equations are:
      $ψ_0=0$
       $ψ_1=1$
       $ψ_2=2y$
       $ψ_3=3x^4+6 A x^2+12 B x-A^2$
       $ψ_4=4 y(x^6+5 A x^4+20 B x^3-5 A^2  x^2-4 A B x-8 B^2-A^3 )$
Let  E  be the elliptic curve: $y^2=x^3+7$  (mod 79). Let point P=(9,5)  be the generator of E.
∴    A=0, B=7, x=9, y=5
Substituting, we get:
      $ψ_0 = 0$
      $ψ_1 = 1$
      $ψ_2 = 2y=2×5=10$
      $ψ_3 = 3x^4+6 A x^2+12 B x-A^2=3×9^4+0+12×7×9-0 = 20439 = 57$ mod 79
      $ψ_4 = 4×5(9^6+0+20×7×9^3-0-0-8×7^2-0) = 12662180 = 60$ mod 79
Square of $ψ_2=  ψ_2^2=10^2=100=21$ mod 79     . . . . . .  (1)
Square of $ψ_3=  ψ_3^2=57^2=3249=10$ mod 79    . . . . . .  (2)
Square of  $ψ_4=  ψ_4^2=60^2=3600=45$ mod 79   . . . . . .  (3)
Both Silverman's "The Arithmetic of Elliptic Curves" (exercise 3.7 b) and Washington's "Elliptic Curves – Number Theory and Cryptography" (Lemma 3.5) say:
      $ψ_m^2=m^2  x^{(m^2-1)}  +$ lower degree terms
Applying this equation we get:
      $ψ_0^2=0$
      $ψ_1^2=1^2×9^{(1^2-1)}=1×9^0=1+$ lower degree terms = 1
      $ψ_2^2=2^2×9^{(2^2-1)}=4×9^{(4-1)}=4×9^3=2916=72$ mod 79 + lower degree terms = $72+1 = 73$ mod 79
      $ψ_3^2=3^2×9^{(3^2-1)}=9×9^{(9-1)}=9×9^8=387420489=65$ mod 79 + lower degree terms = $65+73 = 138 = 59$ mod 79
      $ψ_4^2=4^2×9^{(4^2-1)}=16×9^{(16-1)}=16×9^{15}=25$  mod 79 + lower degree terms $= 25+59 = 84 = 5$ mod 79
Above 3 results do not match (1),(2),(3).
I know I am making some silly mistake somewhere, but could not figure out where. Can someone help find the error?
Answer: The question is about the elliptic curve $\, y^2 = x^3 + 7\,$
with point $\,(9, 5)\,$ over modulus $79$ and its division
polynomials. Your calculations are correct for $\psi_n$ and
its square modulo $79$. However your attempt to use

$ψ_m^2=m^2  x^{(m^2-1)}  +$ lower degree terms

was flawed because you did not use the correct lower degree
terms. For the short elliptic curve $\, y^2 = x^3 + B\,$
the complete formulas are
\begin{eqnarray}
\psi_1^2 &=& 1, \\
\psi_2^2 &=& 4x^3  + 4B, \\
\psi_3^2 &=& 9x^8 + 72Bx^5 + 144B^2x^2, \\
\psi_4^2 &=& 16x^{15} + 656Bx^{12} + 6784B^2x^9 + 1024B^3x^6 - 4096B^4x^3 + 1024B^5 \end{eqnarray}
where we have replaced $\,y^2\,$ when it appears by
$\, x^3 + B.\,$ For example,
$$ \psi_2^2 = (2y)^2 = 4(y^2) = 4(x^3 + B) = 4x^3 + 4B. $$
When you substitute the values of $x=9$ and $B=7$ you get the correct results.
For example, $\,\psi_2^2 = 4\times 9^3 +4\times 7 = 2944 = 21 \pmod{79}.$
Comment: Did you ask sage to obtain $\psi_4^2$?
Comment: @reuns No, I used very simple code. For example, using `Wolfram Mathematica` I used `Z[4] = Expand[4*y*(x^6 + 5*A*x^4 + 20*B*x^3 - 5*A^2*x^2 - 4*A*B*x - 8*B^2 - A^3)];` and then `(Z[4]^2//Expand)/.{A -> 0, y^2 -> x^3 + B}//Expand` but I could have easily used `PARI/GP` to do the equivalent.
Comment: @Somos, thanks. What exactly is the flaw? And how did you arrive at the complete formulas from the equation referenced in the two books? (I am not familiar with nor have access to Sage, Mathematica, or anything.)
Comment: @Somos, also there is no B in that equation. How did it show up in your complete formulas?


Só grava o ID 0

Question: Estou com um problema que já tentei de muitas formas, mas o só está gravando o id Zero.
Parte do Botão de cadastrar a rua no bairro
Listagem dos bairros
bairro_lista.php
Parte do Botão de cadastrar a rua no bairro
Listagem dos bairros

<?php
while ($linha = mysql_fetch_array($resultado)) { ?>

 <?php echo $linha['nome']; ?>

  <button type="button" name="addRua" id="<?php $linha['id']; ?>" data-toggle="modal" data-target="#addRua_data_Modal_rua" class="btn btn-warning btn-xs id_cod_bairro" >Cadastrar Rua</button>

<?php } ?>

Parte do Modal onde seta os valores a serem gravados

     <input type="submit" name="fecharRua" id="fecharRua" value="×" class="close" data-dismiss="modal" />

     <form method="post" id="insert_form_rua">
        <select name="tiporua" id="tiporua" class="form-control">
         <option value="Rua">Rua</option>
         <option value="Travessa">Travessa</option>
         <option value="Avenida">Avenida</option>
       </select>

       Digite o nome da Rua
       <input type="text" name="nome_rua" id="nome_rua" class="form-control" />

       <input type="hidden" name="employee_id" id="employee_id" />
       <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
     </form>

     <input type="submit" name="fecharRua02" id="fecharRua02" value="Sair" class="btn btn-default" data-dismiss="modal" />

Parte do javascript onde direciona para gravação

$(document).ready(function(){
 $('#addRua').click(function(){
 var id_cod_bairro = $(this).attr("id");
    $('#insert').val("Cadastrar");
    $('#insert_title').val("Cadastrar Rua");

  });
  $('#insert_form_rua').on("submit", function(event){
    event.preventDefault();
    if($('#nome_rua').val() == "")
    {
   alert("nome is required");
    }
    else
    {
   $.ajax({
     url:"insert_bairro_rua.php?id_usuario=<?php echo $_GET["id_usuario"]; ?>&cod_bairro=id_cod_bairro",
     method:"POST",
     data:{employee_id:employee_id},
     data:$('#insert_form_rua').serialize(),
     beforeSend:function(){
       $('#insert').val("Inserindo Dados...");
       $('#insert_form_rua')[0].reset();

     },
     success:function(data){
       $('#addRua_data_Modal_rua').modal('hide');
       $('#employee_table').html(data);
       $('#insert_form_rua')[0].reset();
     }
   });

    }
  });

insert_bairro_rua.php
Onde grava os dados no Mysql

 <?php
 include("/lib/conexao.php");
 if(isset($_POST["employee_id"]))
 {
   $id_usuario = $_GET["id_usuario"];
   $cod_bairro = $_GET["cod_bairro"];
   $nome_rua = filter_input(INPUT_POST, 'nome_rua', FILTER_SANITIZE_SPECIAL_CHARS);
   $tiporua = filter_input(INPUT_POST, 'tiporua', FILTER_SANITIZE_SPECIAL_CHARS);

      if($_POST["employee_id"] != '')
      {
  $query = "
      UPDATE rua
      SET
      nome='$nome_rua',
      tiporua='$tiporua',
      cod_bairro='$cod_bairro',
      id_usuario='$id_usuario'
      WHERE id='".$_POST["employee_id"]."'"
      ;
  mysql_query($query,$conexao);
      }
      else
      {
  $query = "
      INSERT INTO rua(nome, tiporua, cod_bairro, id_usuario)
      VALUES('$nome_rua', '$tiporua','$cod_bairro','$id_usuario');
      ";
  mysql_query($query,$conexao);
        $message = 'Data Inserted';
      }
 }
 ?>

Só tenho algumas noções destes códigos.
Comment: Provavelmente no seu banco de dados, você não setou sua chave primária como auto incremento
Comment: entendo, mas eu tenho um botão de ver as ruas do bairro e nas informações consegui ver o nome e ID do bairro e das ruas cadastradas nele. Se quiser ver como fiz, eu posto o código.
Answer: No seu botão de cadastro no id está faltando a função echo
Errado:
id="<?php $linha['id']; ?>"

correto:
id="<?php echo $linha['id']; ?>"

Comment: Não deu certo, gravou o ultimo id, mas consegui através de um outro código.

Só grava o ID 0


Passar paramento para Controller

Question: Estou a vários dias procurando uma solução mas não encontrei nada que me fosse útil. O problema é o seguinte, tenho um Conttroller que recebe os dados da View, até aí tudo bem, mas quando eu vou capturar esses dados ele só captura através do método do banco de dados (tabela Usuario) porém queria que ele também guardasse o valor do id em um inteiro.
<code>Public actionResult criar ( Usuario usuario, int id)
{
    //Faz o que tem que ser feito
// Ele só pega o valor no usuario e no id da como nulll

}
</code>
Comment: você poderia exemplificar melhor o que gostaria, pois, não compreendi.
Comment: Então ,no meu controller eu quero cadastrar os usuários ,até aí de boas ,eu consigo porém quando vou cadastrar novamente o usuário com mesmo id ele dá erro(dá erro porque não pode ter dois id iguais) aí estou usando uma lógica para que ele possa receber o id digitado pelo usuário passando ele para o para controle pelo int id ,ai Assim eu possa trabalhar com o valor e manipular
Comment: Quando eu recebo os dados do usuário meu int id está dizendo que não contém valor , se eu deixar publc actionResult criar (int? Id)da como null e não recebo os dados da viu mas com público actionResult criar ( Usuario usuário) ele recebe os dados
Comment: Tente detalhar melhor sua pergunta. > "...só captura através do método do banco de dados..." isso está meio estranho, receber os dados da View no Controller não deveria ter relação com banco de dados, coloque o código da sua View e seu Model, assim fica mais fácil para o pessoal ajudar.
Answer: No id seu campo esta vindo como null por que na sua view no form não há nenhum campo como id, Para isso funcionar você pode fazer da seguinte forma:
<code>@Html.HiddenFor(model => model.Id)
</code>
Faz isto dentro do BegginForm
<code>@Html.BegginForm....
</code>
Que seu valor do id chegará na controller
Comment: Mas dá para pegar o valor do id e do Usuario ao mesmo tempo?no caso Usuario seria o Usuario usuario
Comment: Sim, O ID virá no Usuário e virá na variável do parâmetro
Comment: perfeito,me ajudou muito ,agora consigo trabalhar com os dados ,também estava errando na hora de declara a variável com o mesmo nome.
Comment: Muito bom poder ajudar amigo, Se possivel marque como respondida e de um voto de útil na resposta, Me ajuda muito
Comment: Ainda não tenho pontuação suficiente :(

Passar paramento para Controller


Spring:failed to load applicationContext?

Question: My project has service module which has applicationContext.xml on src/main/resources path.
I run integration test using maven-cargo plugin and dependency looks like
            <plugin>
                <groupId>org.codehaus.cargo</groupId>
                <artifactId>cargo-maven2-plugin</artifactId>
                <version>1.4.8</version>
                <configuration>
                    <container>
                        <containerId>tomcat7x</containerId>
                        <systemProperties>
                            <spring.profiles.active>${spring.profiles.active}</spring.profiles.active>
                        </systemProperties>
                        <dependencies combine.children="append">
                            <dependency>
                                <groupId>org.apache.derby</groupId>
                                <artifactId>derby</artifactId>
                            </dependency>
                            <dependency>
                                <groupId>org.apache.derby</groupId>
                                <artifactId>derbyclient</artifactId>
                            </dependency>
                        </dependencies>

                    </container>
                    <configuration>
                        <properties>
                            <cargo.servlet.port>9090</cargo.servlet.port>
                            <cargo.datasource.datasource.derby>cargo.datasource.driver=org.apache.derby.jdbc.ClientDriver
                                cargo.datasource.url=jdbc:derby://localhost:1527/pryme_common;create=true|
                                cargo.datasource.username=sa|</cargo.datasource.datasource.derby>
                        </properties>
                    </configuration>
                    <deployables>
                        <deployable>
                            <groupId>com.org.common</groupId>
                            <artifactId>services</artifactId>
                            <type>war</type>
                            <properties>
                                <context>common</context>
                            </properties>
                        </deployable>
                    </deployables>
                </configuration>
                <executions>
                    <execution>
                        <id>start-container</id>
                        <goals>
                            <goal>start</goal>
                        </goals>
                        <phase>pre-integration-test</phase>
                    </execution>
                    <execution>
                        <id>stop-container</id>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                        <phase>post-integration-test</phase>
                    </execution>
                </executions>
            </plugin>

I run my integration test as
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class ITCache extends AbstractIntegrationTest {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void testCaches() {
        {
            final String url = "http://localhost:9090/common/rest";
            final Client client = ClientBuilder.newClient();
            final WebTarget target = client.target(url).path("networks");
            final Invocation.Builder builder = target.request().accept(MediaType.APPLICATION_JSON);
            final Response response = builder.get();
            assertStatus(Response.Status.OK.getStatusCode(), response);
        }
        assertNotNull(applicationContext);
        final SimpleCacheManager simpleCacheManager = (SimpleCacheManager) applicationContext.getBean("cacheManager");
        System.out.println("cacheName:" + simpleCacheManager.getCacheNames().toString());
        System.out.println(simpleCacheManager.getCache("genders").toString());
    }
}

and I see error as
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.018 sec <<< FAILURE!
testCaches(com.org.comma.integration.ITCache)  Time elapsed: 0.016 sec  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
        at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
        at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
        at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:319)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:212)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:236)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:134)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:113)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:103)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:74)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251)
        at org.springframework.test.context.support.AbstractGenericContextLoader.loadBeanDefinitions(AbstractGenericContextLoader.java:235)
        at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:118)
        at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
        at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
        at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:250)
        at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
        at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
        ... 31 more
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
        at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
        ... 43 more

Although I do see that file
$jar -tvf integration/target/cargo/configurations/tomcat7x/webapps/common.war | grep app
  2342 Wed Jul 16 16:16:10 PDT 2014 WEB-INF/classes/applicationContext.xml

Comment: try `classpath:/applicationContext.xml`
Comment: can you try dumping classpath at runtime `System.out.println(System.getProperty"java.class.path"));` and see if one of those path has this xml file ?
Comment: no I do not see it in `java.class.path` either, phew! whats the issue?
Comment: can you analyze your `mvn help:effective-pom` if it overrides your `resources`
Comment: I don't know what that means, but here is the output http://pastebin.com/SkZZrXQS
Comment: your file is at `/Users/harith/code/IdeaProjects/comma/services/src/main/resources` ? and which goal you ran ?
Comment: `mvn clean install -pl integration`
Answer: Change your @ContextConfiguration annotation as below
@ContextConfiguration (locations = "classpath*:/applicationContext*.xml")

this will allow the JUnit test case to load the file applicationContext.xml from your classpath


Do notes from non-natural minor scales fit well in the associated major key?

Question: Any major scale contains the same notes as the natural associated minor scale - C major being the easy option contains all the same notes as A minor natural.
But of course we also have other common minor scales. A harmonic minor gives us G# and in the melodic minor scale we also get F#.
I wondered if this means that F# and G# would be the "least controversial" notes to add when playing in C major since they come from variants of the associated minor key? i.e. they'd fit quite nicely without sounding too dissonant?
Answers that don't use complex music theory terminology - or explain what the terms mean - are preferred as I don't know much theory.
Answer: This is going into modal territory. There are also 'minor' scales in some of the modes. Obviously the Aeolian, as mentioned, but Dorian and Phrygian also sport that important minor third from the root. The F# mentioned will appear in the C Lydian mode, although it's perceived as a major mode.That F# can also be thought of as a b5 as in blues.
Actually, any non-diatonic note can and is used in any melody. It is more dependent as to where it's played than anything. Sometimes, a non-diatonic note will work as a main stressed note, sometimes it won't. I say to students "any note, anywhere will fit - if you know what you're doing." A 'wrong' note can be used to make the listener wince, just for a moment, before it's resolved. Very effective it is too! Quick example -  Maria, West Side Story!
There's also the fact that an underlying harmony may be crying out for a non-diatonic note. Take a lot of middle 8s, that end on the dominant (G, in C). That dominant pushes the song back to tonic. But to get there, a secondary dominant ('dominant of the dominant') is used before the dominant. As in C key, sequence at end of mid.8 goes D7-G(7). That D7 will contain a non diatonic F#, but it's waiting to be reflected in the melody right there.
Someone once told me that Star Spangled Banner was written in Lydian because it had that #4 in it. No, it's only modulating slightly!
Hope this is laymannish enough for you.
Comment: @Mr.Boy You're right in saying that major/minor relationships are not "opposites", but should rather be thought of as different *flavors*.
Comment: @mey It would depend on what you're doing with it. A "VI" would need a picardy third in the new key, which would almost sound like voice-leading to "D" depending on how it was prepared. A "VI" would be considered a parallel major of the relative minor and would be considered root movement by mediant relationship.
Comment: @Tim The difference is not academic, but of function. The point of roman numeral analysis is to show harmonic function. If it functions as a V/vi then that's great; you wouldn't label it as III. If it's part of a series of unrelated chords, then you shouldn't use RN analysis and instead just use chord names. Regarding your point about "D", the answer is yes, V/V/II(I) would be correct; you would put the whole motion in the context of D since that is where it's heading. I have analyzed pieces that contained V/V/V/vii°/I.  Yes, I agree, it's obnoxious.
Comment: @jjmusicnotes - clarified! Thanks! Sounds pretty academic- to me! Would your last example end up played as a G#? (#V) I feel that most musos who know their stuff would be just as happy seeing the simplified version, and would instinctively understand where it's going. Obnoxious is one description!
Comment: @mey - letter name seems important, so working back, in C - vii=B, V of=F#, V of=C#, so V of that =G#. That's my tuppenceworth.
Comment: @mey Tim is right here, in this case, it would be G# since the proceeding notes must be sharp in order to show harmonic motion to the leading tone chord. Otherwise, you're building a harmonic progression to Dbb, which doesn't make sense.
Comment: As for G#, another reason might be that it is part of the III major chord (E G# B) which resolves to vi minor. And vi minor is a widely used chord in any given key, in many occasions. Just a thought :)
Comment: It seems I'm reading too much into "associated minor" relationship like they are "opposites" in some way. Rather than that major/minor are just two particular cases of more general modes.
Comment: @mey You wouldn't call it a "III", you would call it a "V/vi".
Comment: @jjmusicnotes: Yes, i think that's clearer. It indicates the exact role of that chord which is the dominant of vi. (What about VI, by the way? ☺rarely found in conjunction with III major,but it always serves as another secondary dominant).
Comment: ie. The dominant of ii or II.
Comment: As a side note, i love to use a picardy third for ending a minor song. Prefer VI much more than vi ☺
Comment: Or should i say "I rather than i" in a minor key.
Comment: @jjmusicnotes - in C, III = Emaj. V/vi = E maj. Is the difference only academic, does it need to show it's a secondary dominant, as that would be apparent, and not make any difference anyway? And if it is necessary, and the next one is II (D) then should that E be called V/V/II? This is out of interest - I just don't understand!
Comment: @Tim: or perhaps Ab? (b6)☺
Comment: Hmm...yes i guess so. The reason why i came up with Ab is because of the circle of fifth... (that's my one cent worth... If there's ever an expression like that... lol).
Comment: Thanks for clarification @jjmusicnotes and @ Tim. though F# is borderline (can be called Gb) but since it has to be worked back to B, which is in the "sharp area" then i should call this chord G# instead of Ab.
Answer: In a-minor:

G# is coming from the dominant of a-minor (E-G#-B).
F# is coming from the subdominant of a-minor (D-F#-A).

Generally, the scale is fitted to the harmonic progression in accordance with where the scale moves. Because of the dominant chord used when progressing from G to A, G is augmented to G# in the ascending scale of a melodic minor (a->b->c->d->e->f#->g#->a) and V-I cadance of the harmonic minor (g#->a where the scale is a, b, c, d, e, f, g#, a). They are untouched in the descending scale (a->g->f->e->d->c->b->a) because we don't need a the dominant as G progresses to F. Melodic minor has also F augmented to F# because the augmented 2nd interval followed by minor 2nd's (e->f->g#->a) is not characteristically used in western classical music (this kind of melodies are common in Turkish and Arabic music but they don't imply any western harmony because they are not polyphonic styles).
Without a context you can relate F# from the dominant (D) of the dominant (G) of C-Major, or subdominant (D) of the minor (A) of the C-Major and G# from dominant (E) of the related minor (A) of C Major. But this is a simple guide that means nothing without context. You can relate those notes to C-Major from many various ways so it doesn't mean much like this.
Comment: check out the harmonic minors. There's never an F# in them. They tend to live in the melodic minors, but then not all the time!
Comment: @Tim Thanks, edited. Pardon my confusion, too much concentrated on the dominant idea. I hope that is fine now.
Answer: Yes it fits well. It is basically the same scale that starts on different notes with the exception of the leading tone of the Harmonic minor which is raised by a semi tone and in the case of the Melodic minor both the Sub Mediant and the Leading Tone is raised when going up and also then lowered when going down (Natural Minor).
Comment: Jazzers might disagree with the last bit.
Answer: Yes, F# can imply the 'dominant of the dominant', G# can lead us to Am, which can be considered an alternative flavour of C major.
But other chromatic notes are equally acceptable, and equally common.  C, C#dim7, Dm7, G7, C is a cliche progression.  As is C, C7, F, Fm, G/C, G7, C.  That's all the chromatic tones except Eb accounted for - and I could easily find a way to fit that in!   Shall we take a different approach and invoke the Blues?  That uses a (sort of) Eb.
Answer:
Do notes from non-natural minor scales fit well in the associated
  major key?

They can, depending on context.

I wondered if this means that F# and G# would be the "least
  controversial" notes to add when playing in C major since they come
  from variants of the associated minor key? i.e. they'd fit quite
  nicely without sounding too dissonant?

Are they somehow the least controversial, or least dissonant? No. In fact, this question doesn't really make sense when you consider the meaning of dissonance.
The fallacy in your assumption is in thinking that notes outside of a given key somehow have a certain amount of "dissonance" inherent to them by virtue of their being outside of the key. This is not the case. A note's dissonance can only be measured against other notes sounding at the same time. Simply put, if there is another note sounding that is a second, seventh, or a tritone away, then there is a dissonance. If it's a third, sixth, perfect fourth, or perfect fifth, then it's consonant.
Therefore, to determine whether a note is dissonant (or "controversial") depends entirely on the other notes in the chord that is being played. In fact, by using the correct chords, any note outside of the key can be made to sound quite consonant. The correct question is in what context (i.e. in what chord) that note belongs to make it consonant, and then what implications that chord has on the chord progression.
In the case of G# in the C major scale, as others have already mentioned, it creates a consonance with E and B to form an E major chord. The result of raising the G to make this chord major is that it acts like a dominant chord, strongly implying an A minor tonality.


Can trusted host settings use an IP address?

Question: I'm working with a test site installed on a server on my network. Since it's only a sandbox, it has no domain name. Drupal being installed in a sub-directory (there are several sandboxes), I access it through an address like this: http://10.156.222.145/d8
However, when I put this in the trusted host patterns, like so:
<code>$settings['trusted_host_patterns'] = array(
    '^10\.156\.222\.145\/d8$',
    '^localhost$'
  );
</code>
I get the error message: "The provided host name is not valid for this server."
Question: is it even possible to configure these settings with an IP address, and if so how?
Comment: Host names don't contain the path - have you tried `'^10\.156\.222\.145$'`?
Comment: That works! I thought I would have to put the exact path.
Answer: Yes using an IP is fine, you just need to make sure you're using a valid host name (I.e. one without the path appended):
<code>^10\.156\.222\.145$
</code>


Logistic regression - power and predictor values

Question: What is power in logistic regression? Is it the ability of the test to reject the null hypothesis when it is actually false?
Second, if you're trying to maximize your statistical power when doing a logistic regression, is it better to use predictor values that are only high or low or a range of predictor values?
Answer: Power by definition is what you wrote.  The ability to reject a false null hypothesis. That is how assertive a model is to say that a predictor x has something to do with the dependent variable y. Power is a probability so closer is it to 1, better it is.
For the second question, there is no fixed answer to this question. It depends on the data. Lets say you are predicting defaulter out of people in which one variable is delay in payment. Now if you are doing a high low categorization you are essentially saying that everybody ( lets say) who is above 90 days has beta = .4 and everybody less than 90 has beta = .15 . In essence you are trying to segregate a 89 day delay from a 90 day delay while a different view could be that both of 'em are same guys. So in my view low/high or range of values should come from curve fitting analysis where you should be watchful of inflections in the curve. Where is it peaking ?? where does it show almost equal behavior in defaulters/non defaulters. The final aim is to multiply the person's delay with the right beta and not an imposed beta.


Diretiva: bloquear duplo click em um botão

Question: Ola,
Eu tenho uma diretiva para bloquear o duplo clique nos botões do meu sistema...
Porem, ao clicar em um botão que esteja "chamando" a diretiva, ele não faz a função dele (ex: se o botão for submit, não acontece o submit).
Eu gostaria de usa-la para vários botões com funções diferentes.
Diretiva

import { Directive, HostListener } from '@angular/core';

@Directive({
    selector: '[blockClicks]'
})
export class NoDblClickMatDirective {

    constructor() { }

    @HostListener('click', ['$event'])
    clickEvent(event) {
        const button = (event.srcElement.disabled === undefined) ? event.srcElement.parentElement : event.srcElement;
        button.setAttribute('disabled', true);
        setTimeout(function () {
            button.removeAttribute('disabled');
        }, 2000);
    }
}

Module Diretiva

import { NgModule } from "@angular/core";
import { NoDblClickMatDirective } from "./nodblclickmat.directive";

@NgModule({
    imports: [],
    declarations: [NoDblClickMatDirective],
    exports: [NoDblClickMatDirective]
})
export class NoDblClickMatDirectiveModule { }

Trecho Html

<button class="btn btn-info" blockClicks>Entrar</button>
Comment: Presumo que testou isso no Google Chrome. Nunca cheguei a pesquisar a fundo, mas há navegadores que não fazem a submissão do formulário se você definir o botão como `disabled`. Se não me engano aconteceu isso um tempo atrás e no Firefox funcionava normalmente, o Chrome bloqueava.
Comment: Hmmm, @AndersonCarlosWoss, vou testar em outros navegadores... Se caso for isso mesmo, eu resolveria como?
Comment: @AndersonCarlosWoss Você está certo, no FireFox funcionou...
Comment: Ouço muito isso :D Geralmente você consegue contornar isso desabilitando o botão no evento `submit` do formulário, mas neste caso talvez você possa verificar se é um botão do tipo `submit` e forçar manualmente a submissão.
Comment: Você acha q setar de disable para readonly possa resolver?
Comment: Um botão não pode ser `readonly`.
Comment: ops, dei uma gafe kkk
Comment: Você pode me ajudar um pouco mais em como eu faria o evento? Eu tinha feito na função do submit, mas como vou usar em varios botoes, eu queria fazer uma coisa generica
Answer: Eu faria algo assim:
import { Directive, HostListener } from '@angular/core';

@Directive({
    selector: '[blockClicks]'
})
export class NoDblClickMatDirective {
    lastClick = 0;

    constructor() { }

    @HostListener('click', ['$event'])
    clickEvent(event) {
        const currentTime = new Date().getTime();
        const ultimoClick = currentTime - this.lastClick;

        if (ultimoClick < 300) {//voce pode adaptar de acordo com o que vc considera um click duplo
            event.stopPropagation();
        }
        this.lastClick = currentTime;
    }
}

Comment: Esta dando essa mensagem no `this.ultimoClick = currentTime` > A propriedade 'ultimoClick' não existe no tipo 'NoDblClickMatDirective'.
Comment: Voce pode me explicar o que pensou, eu nunca fiz diretiva entao nao entendo muito bem as ordens... o 300 sao a quantidade de clicks? o stopPropagation ele impede a função do botao? O q eu consideraria um click duplo por exemplo?
Comment: fiz quase isso que mandou, mas consegui, obrigado


Is it possible to run multiple logistic regression for small sample size?

Question: I have collected data, there are 300 non-injury and only 17 injury. Four categorical variables are significant according to Chi-squire, then I used Multiple logistic regression for significant variables. Three of them are significant again. Does it make any sense? I would like to know whether can I use Multiple logistic regression because only 17 respondent had injured from 317 of the respondents. I used SPSS to analysis of data.
If I can not run it what should I have to do? There is any way to solve it.
Is there any software better than SPSS for this situation, for example STATA software or SAS......
Answer: Yes, it is possible to run logistic regression with 317 observations where 17 are cases.  Due to small sample bias, it would be a good idea to compare your results with exact logistic regression which does not depend on asymptotic results. In Stata you can use <code>-exlogistic-</code>.
Comment: Thank you very much dear Dr.Robert Long. I highly appreciate it.
Answer: Although it may be possible to run a multiple logistic regression on your data, you should be very wary of the results. A major danger that you face is that your model, however well it might fit your present data set, will not generalize to your population of interest. The issues in having such a low number of cases to predictors is covered on this Cross Validated page, with several useful links from that page.


Are there good alternatives to expensive practice facilities in urban environments?

Question: I'm a drummer who recently moved from Rochester NY to Boston, and I'm looking to get my footing in the music scene here. Music is not my full time gig (PhD student by day), and so it's tough for me to justify the generally exorbitant fees for music storage and practice facilities. I live in an apartment complex, so playing in my building isn't really an option. Have any other non-professional musicians out there encountered this practice space problem, and has anyone heard/tried any creative solutions?
Thanks for the help!
Comment: Tough situation, but if you join a band and all go in together on a practice space, your individual cost is lower. Also, if you're a church-goer and are willing to play in worship services, sometimes they'll allow you to come in during the day and practice while staff is in the office.
Comment: What?  a drummer w/o a girlfriend who's not homeless?  (hey, someone had to say it)
Answer: Go get a storage-unit - this used to be my go-to when the other musicians or I did not have the ability to accommodate our practice sessions.
You'll want to shop around  - the availability of on-site electricity can be an issue. Also, be transparent with the owner - you may need to negotiate a somewhat higher-rate for said energy consumption... (Point being not to leave a bad-taste in the owner's mouth [and/or be unceremoniously kicked-out] when they realize you're paying them $70 a month in rent but, consuming $50 a month in electricity) But, luckily, you'll usually find that your cost will be MUCH lower than what your average music-house will charge for storage and time. This is a cost effective solution, even if it's just you renting the unit.
Besides this, there's the issue of noise. You might find that this is less of a bother to the owner and other tenants due to the fact that most of these places are graveyards - people are usually in and out, not coming to the place for either solitude or socializing. If you're still afraid of it being an issue in the urban environment, you can egg-foam the bejebus out of the space.
Finally, your average storage facility has decent security - fencing, a camera system, and they're usually on  the radar of your average beat-cop... Get a beefy, cut-proof lock too.
*Warning: You may be left wanting for a bathroom. :P
Comment: If you can get there,  B
U-Haul Moving & Storage of Route 16 Medford / Somerville
600 Mystic Valley Pkwy · (781) 396-9030  is a famous-ish solid old multistory building.  In fact, once upon a time some oboist had his practice room there.
Answer: A partial solution is a set of pads and earphones.  Not quite the same.  This would be true of electronic keyboard vs piano too.  They are not the same.  You have to spend enough time on each to switch over your reflexes.
Another partial solution are schools that have a music extra-curricular program.  You mmay be able to barter one evening or after school slot per week in exchange for access during the rest of the time.
A third option if it's a renter's market instead of a landlord's market is to see if there are units that the landlord would like people around in one unit, to act as a break-in/vandalism deterant for the rest.  E.g. if there is an industrial strip mall with a chronicly vacant unit, you may be given very low rent -- but you can only play outside of 8-5 M-F
A fourth option:  Check out the universities and see if they lock the doors on their practice buildings.  On my campus the doors were open from 7 a.m. to 10 p.m.  You needed a key outside those hours.  The rooms inside were left unlocked.  This only works for portable instruments, however.  (There was a piano in every room, but nothing else.)


northmost latitude

Question: From the book Astronomy, principles and practice. I cannot solve the second part.
Assuming the Earth to be a sphere of radius 6378 km calculate the great circle distance in kilometers between
London (51◦ 30 N, 0◦) and New York (40◦ 45 N, 74◦ W).
Find also the most northerly latitude reached on the great circle arc.
the great circle distance is given by
$\Delta\sigma=\arccos(\sin51.5\sin40.75 + \cos51.5 \cos40.75\cos74)$
Then I converted the result to radians and used  $d=r\Delta\sigma$ to get 5786km. Then I tried to use the departure equation but logically it does not seem to correspond to the problem.
Comment: i found the great circle distance.Then i tried to picture a spherical triangle but i coudnt.Then i realized that the max altitude is reached halfway the arc.Stil can't find a solvable triangle
Comment: Great! If you include that (including the calculations) there will be a *much* greater chance that your question will be answered. Showing what you've done also tells people something about your level and where you might have gone wrong, and if they know these things, the answers will surely be better. Also, I am the one who downvoted your question, but if you edit it to include your try I will upvote it. Cheers
Comment: ok shall i do it at the comments?
Comment: No, you can edit your question (just below it).
Comment: i wrote down the eq
Comment: Did the book show you a formula something like $\sin(course_1) \cos(lat_1)=\sin(course_2) \cos(lat_2)$?
Comment: no it didn't.The book only shows 4 basic eq (cos,sine,4parts formula and analogue of cos formula)
Answer: I suppose the formulas you can use are the ones on this page:
http://www.diracdelta.co.uk/science/source/s/p/spherical%20triangles/source.html
(except for the area formula, which is not of any use here anyway).
Label the following points on the sphere: $A$ at London,
$B$ at New York, $C$ at the north pole.
Labeling the opposite sides of the spherical triangle $a$, $b$, $c$,
assuming those are all angular measurements in radians,
then $A$ (London) is $b$ radians from $C$ (the north pole)
so the latitude of London is $lat_A = \frac\pi2 - b$;
so $\sin(lat_A) = \cos b$ and $\cos(lat_A) = \sin b$.
We can see then that the great circle formula is just one of the cosine formulas, which you correctly applied.
Once you have the distance $c$ from $A$ to $B$, it is relatively
quick and easy to get the departure angles at New York and London by
applying the sine law to $\triangle ABC$:
$$
\frac{\sin A}{\sin a} = \frac{\sin B}{\sin b} = \frac{\sin C}{\sin c}.
$$
Keep this in mind about the sine law: it's not one big equation, it's actually
three equations, $\frac{\sin A}{\sin a} = \frac{\sin B}{\sin b}$,
$\frac{\sin A}{\sin a} = \frac{\sin C}{\sin c}$,
and $\frac{\sin B}{\sin b} = \frac{\sin C}{\sin c}$.
We usually use only one of the three equations at a time.
You already know $a$, $b$, $C$, and $c$, so you can get $A$ from
$\frac{\sin A}{\sin a} = \frac{\sin C}{\sin c}$ (one equation, one unknown)
and $B$ from $\frac{\sin B}{\sin b} = \frac{\sin C}{\sin c}$.
Either angle $A$ or angle $B$ can help you find the maximum latitude of the great circle, but just one of them will be enough. Suppose we just figured out the angle at $A$.
The trick then is to draw a new spherical triangle with vertices at $A$
and $C$, with the third vertex somewhere along the great-circle path from
$A$ to $B$.  Possible choices for the third vertex are the point
where the great circle crosses the equator, or the point of maximum latitude
itself.
Call the new vertex $B'$ and let $a'$ be the length of the arc
from $B'$ to $C$. The side of $\triangle AB'C$ opposite $B'$ is still
$b$ (the arc from $A$ to $C$ has not changed),
and the side opposite $A$ is $a'$. The angle at $A$ also either has not
changed, or it's $\frac\pi2$ minus the old angle; either way, its sine
is still $\sin A$. So the sine law applied to $\triangle AB'C$ says that
$$
\frac{\sin A}{\sin a'} = \frac{\sin B'}{\sin b}.
$$
If you chose to put $B'$ at the maximum latitude, the angle of
$\triangle AB'C$ at $B'$ must be a right angle; so you have three knowns
($\sin A$, $B'$, and $b$) and one unknown $a'$ to solve for.
Then the latitude of $B'$ is $\frac\pi2 - a'$.
If you chose to put $B'$ at the crossing of the great circle and the equator,
the arc $a'$ is $\frac\pi2$ (the arc from the equator to the pole);
so you have three knowns ($\sin A$, $a'$, and $b$) and one unknown $B'$ to solve for.
Then $\frac\pi2 - B'$ is the angle at which the great circle crosses
the equator, which is also the maximum latitude on the great circle.
Comment: Thank you but i still don't get the part after the angle calculation.My spherical trig knowledge is really basic.Can you be more specific about the calculations of max alt?
Comment: Could you please explain why B' must be a right angle?
Comment: @ArnabChowdhury "If you chose to put $B'$ at the maximum latitude, the angle of
$\triangle AB'C$ at $B'$ must be a right angle" because if it is **not** a right angle, then as you travel along the great circle at that point you are either getting closer to the pole (so the maximum latitude is still in front of you) or you are getting farther from the pole (so the maximum latitude is behind you).

northmost latitude


What is the difference between $signed and signed' in verilog?

Question: What is the difference between $signed and signed' in verilog?
Answer: signed'() does not exist in Verilog. It it exists in SystemVerilog.
IEEE1800-2017 § 6.24.1 Cast operator:

NOTE—The $signed() and $unsigned() system functions (see 11.7) return the same results as signed'() and unsigned'(), respectively.

signed'() exists as feature with casting operator ('())
$signed() exists for compatibility with Verilog


the induction step for proving the binomial theorem.

Question: $$\sum_{k=0}^n {n \choose k} x^{n+1-k}y^k+\sum_{k=1}^{n+1} {n \choose k-1}x^{n+1-k}y^k$$
i would like to know how to add the two summations above together including a explanation of how the limits of the two sums will change.
Comment: Which step do you mean ? Please post it.
Comment: At the link you can see how a sigma sign and a binomial coefficient can be written with Tex-commands: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference?noredirect=1&lq=1
Comment: You can quote the sentence before and the sentence after the paragraph, which are you referring to. This would be helpful for all of us.
Comment: Your question is; How does the whole proof work ? This is not very specific. I would suggest that you concentrate your question on one transformation which you cannot comprehend. I appreciate your effort to improve your question.
Answer: The inductive step involves Pascal's Identity, which is:
${n\choose{k}}+{n\choose{k+1}}={{n+1}\choose{k+1}}$
I will start from the assumption that $(a+b)^n=\sum_{r=0}^{n} {n\choose r}a^{n-r}b^r$
Therefore:
$(a+b)^{n+1}=(a+b)^n \cdot (a+b)$
$=\sum_{r=0}^{n} {n\choose r}a^{n-r}b^r \cdot (a+b)$ (using assumption)
$=\{{n\choose0}a^nb^0+{n\choose1}a^{n-1}b^1+....+{n\choose{n-1}}a^1b^{n-1}+{n\choose n}a^0b^n \} \cdot (a+b)$
$=a\cdot{\{{n\choose0}a^nb^0+{n\choose1}a^{n-1}b^1+....+{n\choose{n-1}}a^1b^{n-1}+{n\choose n}a^0b^n \}} + b\cdot{\{{n\choose0}a^nb^0+....++{n\choose n}a^0b^n \}}$
$={\{{n\choose0}a^{n+1}b^0+{n\choose1}a^{n}b^1+....++{n\choose n}a^1b^n \}}+{\{{n\choose0}a^nb^1+{n\choose1}a^{n-1}b^2....++{n\choose n}a^0b^n \}}$
(combine like terms)
$={n\choose0}a^{n+1}b^0+\{{n\choose1}+{n\choose0}\}a^{n}b^1+\{{n\choose2}+{n\choose1}\}a^{n-1}b^2+\{{n\choose3}+{n\choose2}\}a^{n-2}b^3+...+ \{{n\choose{n-1}}+{n\choose{n}}\}a^1b^{n}+{n\choose n}a^0 b^{n+1}$
$={n+1\choose0}a^{n+1}b^0+{n+1\choose1}a^{n}b^1+....+{n+1\choose{n}}a^1b^{n} + {n+1\choose n+1}a^0b^{n+1} $ (using Pascal's Identity)
$=\sum_{r=0}^{n+1} {n+1\choose r}a^{n+1-r}b^r$
Answer: I think what you mean is the crucial 'trick' in the inductive step that allows you to sum the factorials:
$$\left(\frac{k}{r-1}\right)+\left(\frac{k}{r}\right)=\left(\frac{k+1}{r}\right) \;\;\;\;\;\;\;(*)$$
Am I right? If not do let me know! Here's why $(*)$ is true:
$$\begin{align}\left(\frac{k}{r-1}\right)+\left(\frac{k}{r}\right)&=\frac{k!}{(r-1)!(k-r+1)!}+\frac{k!}{k!(k-r)!}\\ &=\frac{rk!+(k-r+1)k!}{r!(k-r+1)!}\;\;\;(**)\\&=\frac{(k+1)k!}{r!(k+1-r)!}\\ &=\left(\frac{k+1}{r}\right)\end{align}$$
All we did was put the two factorials on the left onto the same denominator in (**). Is that what you need? Cheers!
Comment: (so I wrote the above while @rishi posted, sorry if any redundancy, just spelling out the identity he cites)
Comment: No its not what i need help on I've changed my question to be more specific
Comment: right, so I've explained how to turn the two summations you have into one (this comes from being able to sum the binomial coefficients as per the argument shown), except that I have used $(r,k)$ like the proof in the link you provided and not the $n,k$ in your new version. If this wasn't what you wanted then sorry!


Is $C^\infty_c(\mathbb{R})$ closed under differentiation

Question: I'm curious about the properties of the space of smooth functions with compact support, $C^\infty_c(\mathbb{R})$. Specifically, I'm interested in whether this space is closed under the operation of differentiation. If we take a function $f$ that is in $C^\infty_c(\mathbb{R})$ and differentiate it, is the resulting function guaranteed to also be in $C^\infty_c(\mathbb{R})$, regardless of the support interval of $f$ potentially changing?
Could anyone provide references for further reading on this topic?
Thanks for any insights!
Answer: Say $K$ is the compact support of a smooth $F$. Let $f$ be the gradient of $F$. Is $f$ also supported on $K$ and therefore compactly supported?  Yes. Simply because on $K^c$ $F$ is identically zero, by definition, and the derivative at points there may be computed by only working on $K^c$ - it being open! - and the derivative of zero is zero. So $C_c^\infty$ is closed under differentiation.


Posterior probability when data consists of $k$ largest of $N$ samples

Question: Given an underlying unknown distribution, I sample $N$ numbers. From those $N$ numbers I take the highest $k$ numbers. How do I model the posterior probability from those $k$ numbers.
I know I can do it if I just get any random $k$ numbers. I would have a prior and update my belief that is posterior based on the observed data, but how do I further exploit the knowledge of top $k$ ?
I have very basic knowledge about prior and posterior. Any resource to guide me through would be heplful as well.
An example of my problem is, I know $N(0, 1)$ to generate 1000 random samples from $N(0, 1)$. I take the top 10 numbers from the 1000. I want to understand how my posterior would be different when I just get any 10 random numbers from the 1000 samples from the estimate when I know that I got top 10 numbers.
Comment: Posterior probability of what? Is this a Bayesian problem where the underlying unknown is parametrized with unknown parameters and you are looking at the posterior probability of these parameters? (That's what I'd think from the first 3 paragraphs, but the last paragraph does not mention any unknown parameters). If my understanding is correct, do you have some specific case in mind?
Comment: Mean and variance both are unknown? The current title is somewhat misleading (this would be the posterior probability (distribution) _of_ the mean and variance (based on this ordered set , not the posterior probability of o)) - I suggest something in the lines of "Posterior probability when data consists of $k$ largest of $N$ samples"
Comment: Yeah my underlying distribution in this case is a normal distribution with a particular mean and variance and I am trying to estimate it. I want to estimate the parameters given the scenario above. In sum, I want to know how to write the probability of a given number of being at i-th index if N draws have been made from underlying distribution.
Answer: Let us take your example of a Normal sample: if you observe the $k$ largest Normal values of a Normal $\mathrm{N}(\theta,1)$ sample of size $N$, the likelihood of this sample is
$$\ell(\theta|x_1,\ldots,x_k)=\Phi\left(\min_{1\le i\le k}\{x_i\}-\theta\right)^{N-k}\,\prod_{i=1}^k \exp\left\{-(x_i-\theta)^2/2\right\}$$where $\Phi$ is the Normal cdf. Once you have derived this likelihood, business (or rather bayesness!) proceeds as usual: the posterior distribution is
$$\pi(\theta|x_1,\ldots,x_k)\propto\pi(\theta)\Phi\left(\min_{1\le i\le k}\{x_i\}-\theta\right)^{N-k}\,\prod_{i=1}^k \exp\left\{-(x_i-\theta)^2/2\right\}$$
This is not a closed-form likelihood but it can be handled through simulation, either using a simple Metropolis-Hastings algorithm with a numerical computation of the Normal cdf, or using a Gibbs sampler that generates $N-k$ latent Normal variates constrained to be less than $\min_{1\le i\le k}\{x_i\}$.


Inception module backpropagation - how to get the input error?

Question: I'm implementing an Inception module from scratch, specifically this version with dimensionality reduction, and I'm not sure about how to calculate the input error delta when doing the backpropagation pass.
This is the layer/module structure:

Now, what I'm doing right now is:

During the forward pass, keep track of the activity/activation for each intermediate step
Compute the input error delta for each of the 4 "pipelines" individually (using the intermediate activity values when needed from step 1)
Sum the 4 input error delta tensors (one for each pipeline) to get the global input error delta for the whole module

I'm not sure about the last step though, so my questions are:

Is it right to just sum the 4 input error deltas or should them be averaged together according to some criteria? Any other advice or something I'm doing wrong here?

I couldn't find anything about it on the internet, everyone is just using TensorFlow or some other library that has automatic differentiation, so I'm not sure about what's exactly happing there behind the scenes.
Thank you for your help!
Answer: Forgot to post an answer, yeah the gradients to the input layer should just be summed together, as the inputs were just propagated independently to each separate channel. Here is my implementation of this inception layer in C#/cuDNN, as a reference.


Fermat's Last Theorem near misses?

Question: I've recently seen a video of Numberphille channel on Youtube about Fermat's Last Theorem. It talks about how there is a given "solution" for the Fermat's Last Theorem for $n>2$ in the animated series The Simpsons.
Thanks to Andrew Wiles, we all know that's impossible. The host tells that the solution that appears in the episode is actually a near miss.
There are two near-miss solutions and they are:
$$3987^{12} + 4365^{12} \stackrel{?}{=} 4472^{12}$$
$$1782^{12} + 1841^{12} \stackrel{?}{=} 1922^{12}$$
Anyone who knows modular arithmetic can check that those solutions are wrong, even without a calculator. You can check that $87^{12} \equiv 81 \pmod{100}$ and $65^{12} \equiv 25 \pmod {100}$, while $72^{12} \equiv 16 \pmod {100}$. So we have:
$$
81 + 25 \stackrel{?}{\equiv} 16 \pmod {100}
$$
$$
106 \stackrel{?}{\equiv} 16 \pmod {100}
$$
which is obviously wrong.
For the second example it's even easier. We know that LHS is an addition of an even and odd number, and the RHS is even number, which is impossible, because we know that the addition of an even and an odd number will provide an odd number.
But what's made me most interested in this is the following. Using a calculator I expanded the equations and I get:
$$3987^{12} + 4365^{12} \stackrel{?}{=} 4472^{12}$$
$$63976656349698612616236230953154487896987106 \stackrel{?}{=} 63976656348486725806862358322168575784124416$$
$$1211886809373872630985912112862690 \stackrel{?}{=} 0$$
And you'll immediately conclude that those numbers aren't even close, their difference is a 33-digit number. But bearing in mind that we are working with really, really big numbers, it's probably better to take relative difference. So we really want to find the ratio of LHS and RHS:
$$
\frac{63976656349698612616236230953154487896987106}{63976656348486725806862358322168575784124416} \approx 1.00000000002
$$
Somehow that's impressive, but if take a look into the second example the things start to get more interesting:
$$
1782^{12} + 1841^{12} \stackrel{?}{=} 1922^{12}
$$
$$
2541210258614589176288669958142428526657 \stackrel{?}{=} 2541210259314801410819278649643651567616
$$
As we can see the first 9 digits are exactly the same and the apsolute difference is: $700212234530608691501223040959$. But if we take a relative difference or ratio we'll get:
$$
\frac{2541210258614589176288669958142428526657}{2541210259314801410819278649643651567616} \approx 0.9999999997244572
$$
And this is pretty amazing, because if we make comparison using smaller number this is the same as comparing $10\, 000\, 000\, 000$ and $10\, 000\, 000\, 001$
Probably there are many more, probably infinite amount of such "close" examples, but are there any known examples? Is there any list of them?
And as user17762 commented it would be nice to find a bound $\phi(n) = \inf\{\left| x^n + y^n - z^n\right| : x,y,z \in \mathbb{Z}\}$, although I would be more interested in finding the ratio bound, such that the ratio is closer to $1$
Also as user17762 pointed Taxicab can be used to provide a really close examples for $n=3$, but what about other values for $n$?
Comment: An interesting question would be a bound for
$\phi(n) = \inf \{\vert x^n+y^n - z^n \vert: x,y,z \in \mathbb{Z}\}$ for each $n$. And there is a really close one for $n=3$, $10^3 + 9^3 = 12^3 + 1$, which means $\phi(3) = 1$.
Comment: A quicker way to dispatch with $3987^{12} + 4365^{12} = 4472^{12}$ is to work mod $4$, rather than mod $100$:  $3987^{12} + 4365^{12}\equiv1+1=2$ mod $4$, while $4472^{12}\equiv0$.
Comment: You miscalculated the first example.  Looks like you typed 4465 instead of 4365.  In actuality it's a very good approximation.
Comment: That would be a more scientific way of asking, while mine is more like trivial. Also it would be better to use ratio, because for example $x=y=z=1$, would always give a difference of $1$, but obviously we aren't interested in that. Note that in this example the ratios is $2$.
Comment: How do you feel about Pythagorean-triple near misses?  $540^2+360^2\cong 648.99922958\ldots$.  And $540^2+360^2+1^2=649^2$. ${}\qquad{}$
Comment: @user17762  Also as you pointed out the Taxicab numbers can give a close solution for $n=3$, but the ratio will differ. So for example we know that: $255^3 + 414^3 = 167^3 + 463^3$, but if we make a little modification we can get:

$$255^3 + 414^3 = 444^3$$

The difference would be $10935$ and the ratio $\approx 1.0001$
Comment: @MichaelHardy That's what I'm talking about! ;) That's a great example of Fermat miss. But as I've alreadt noticed all this near misses have small exponents, does small-exponents misses are more regular or nobody have studied large exponents? Or even better my assumtion is wrong?
Comment: @BarryCipra Even quicker is working modulo $3$. Each term in the LHS is divisible by $3$, the RHS isn't.
Answer: The following shows that for $n=3$ the ratio can be as close to $1$ as we like.  For any positive integer $m$ let:
$a = 3m^3 + 3m^2 + 2m + 1$
$b = 3m^3 + 3m^2 + 2m$
$c = 3m^2 + 2m + 1$
$d = m$
Then it is readily shown that $a^3 = b^3 + c^3 + d^3$.  If we focus on the 'wrong  solution' $a^3 = b^3 + c^3$, the ratio of LHS to RHS is:
$$\frac{a^3}{b^3+c^3}=\frac{a^3}{a^3-d^3}=\frac{1}{1-(d/a)^3}$$
Since $a$ increases much faster than $d$ as $m$ is increased, we can make the ratio as close to $1$ as we like by choosing a sufficiently large value of $m$.  With $m=10$, for example, we have:
$$\frac{a^3}{b^3+c^3} = \frac{3321^3}{3320^3+321^3} = \frac{36627445161}{36594368000+33076161}=1.0000000273$$
Answer: Noam Elkies gave many examples, as the output of a very fast algorithm for finding almost-solutions to arbitrary 3-variable homogeneous equations, in
http://arxiv.org/abs/math/0005139
The table on page 15 lists 37 examples for Fermat's Last Theorem with exponent between $4$ and $20$.  Elsewhere in the article there are near-solutions of $x^\pi + y^\pi = z^\pi$ and many other interesting things.
Answer: There are "almost" solutions of $a^3+b^3=c^3.$ If $3$ does not divide $a+b,$ and $a+b$ is factored out of $a^3+b^3,$ you get the equation $a^2-ab+b^2=T^3$ and there are solutions of this equation. What's interesting is that Furtwangler's and Vandiver's theorems (from the classical approach to FLT) are still applicable.
Answer: It is believed that $a^3 + b^3 = c^3 + k$ has solutions in positive integers a, b and c except when k = 0 (part of FLT, and very non-trivial proof by Gauss if I'm right) or k = 4 (modulo 9) or k = 5 (modulo 9), which are both trivial.
On the other hand, for many k, even quite small ones, it is very hard to find solutions, and solutions might never be found for some small k.
Comment: I think [Euler first proved](https://en.wikipedia.org/wiki/Proof_of_Fermat%27s_Last_Theorem_for_specific_exponents#n_%3D_3) the $n=3$ case of FLT (i.e. $k=0$ here). Gauss did $n=5$, apparently, among other people.
Answer: $$
\begin{align}
& 360^2+540^2 \approx (648.99922958\ldots)^2 \\[10pt]
& 360^2+540^2 + 1^2 = 649^2
\end{align}
$$

Fermat's Last Theorem near misses?


The join construction with spheres

Question: I'm trying to prove the following exercise (from http://math.stanford.edu/~ralph/fiber.pdf, page 70 of the pdf).
If $*$ denotes the join construction of Milnor, we have that $S^{n} * S^{m} \cong S^{n+m+1}$. I'm not able to find an homeomorphism. Does someone know what could be the homeomorphism or have an intuition about this ?
Thank you.
Answer: Join is associative. So by induction $S^n=S^0*S^{n-1}=...=S^0*...*S^0$(n+1 times)
Now we have $S^n=S^0*...* S^0$($n+1$ times), $S^m=S^0*...*S^0$($m+1$ times) and so $S^n*S^m=S^0*...*S^0$($n+m+2$ times) $=S^{n+m+1}$
Comment: You are completely right, so simple. Thank you.

The join construction with spheres


Drush makefile downloading 7.x Dev instead of stable

Question: I have drush makefile that I use to kick off new Drupal installs:
my_profile.build
core = "7.x"
api = "2"

projects[drupal][version] = "7.x"
; ... grab install profile

When I run drush make my_profile.build it downloads the 7.x-dev version of core instead of stable. I knew that I code force the download of dev versions with projects[drupal][version] = "7.x-dev" but how do I make sure that it only downloads the stable version of a project? My drush version is 5.7.
Comment: Use projects[] = drupal this will download the latest stable version of drupal as long as you specify the core version using core = "7.x"
Answer: To always specify the latest major version of Drupal, just use
projects[drupal][version] = 7

For modules and themes, just omit the version. For example:
projects[views][type] = module

Answer: Just put the exact version in the makefile:
projects[drupal][type] = core
projects[drupal][version] = "7.23"

Since it's auto selecting -dev (which isn't the default stable is) it sounds like your drush.rc file is tweaked to make -dev a default option ...


Can I use the session service directly instead of via the request?

Question: The Drupal documentation on sessions mentions that sessions can be accessed via the Request object:

Session data is accessed via the
\Symfony\Component\HttpFoundation\Request::getSession() method, which
returns an instance of
\Symfony\Component\HttpFoundation\Session\SessionInterface. The most
important methods on SessionInterface are set(), get(), and remove().

However I've also dicovered there is a session service.
In a class where I need to use dependency injection and I do not by default have access to the Request object, do I still need to access the session via the request, or can I use it directy? Loading the Request instead and then accessing the session feels like adding overhead.
I have tried below code, which seems to be working fine. So then why do most examples and even the documentation still demonstrate the Request way? Am I missing something, or is there a risk in this approach?
class MyForm extends FormBase {

  /**
   * The session.
   *
   * @var \Symfony\Component\HttpFoundation\Session\Session
   */
  protected $session;

  /**
   *
   * @param \Symfony\Component\HttpFoundation\Session\Session $session
   *   The session.
   */
  public function __construct($session) {
    $this->session = $session;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('session')
    );
  }

  function somefunction() {
    $this->session->get('value');
    $this->session->set('value', 'somevalue');
  }

}

Answer: ... is there a risk in this approach?
If you have multiple requests you could get the wrong session object. Drupal moved a lot of things out of the request object, like routing and even the path info, but they didn't implemented a stacked session service and instead kept the session object in the request stack.
If you want to inject this service there is already a property in FormBase with getter and setter methods.
This works injected or not (see the comments at the top of the class):
$session = $this->getRequest()->getSession();

Comment: For example in a test you could mock a session or another module could run your form in a sub-request with a different session than the main request.
Comment: Thanks, I was not aware that the Form already had a method to access the request; that is obviously the cleanest way. I still don't fully get how there can be more sessions for a single user, I'd say that all requests are part of the same session. I can, however, understand that second tabs and AJAX requests might alter the contents of the session.


Server-Ip address is not getting displayed in snmp-trap messages

Question: my problem is about Ip Address which I am receiving on the windows system snmp-trap messages,is some thing like that UDP: [192.168.1.150]:1029->[0.0.0.0]:0
while same trap message on linux system has been displayed as
UDP: [192.168.1.150]:1030->[192.168.1.23]

Now,if you observed carefully these two ,its clearly shown that server ip is not coming in windows traps-Ip([0.0.0.0]:0).what would be the possible reason?please anyone can help me about understanding this & can provide the solution for this problem.
Answer: Try running tcpdump on both machines to record your snmp messages.
What version on snmp are you running? Is the 0.0.0.0 supposed to be the linux box?
Then this would be a linux vs windows issue....
Comment: How is this not useful..? Irrelevent? @Chris S


"must issue a starttls command first" when MSSQL emails via Microsoft Online

Question: I have written a stored procedure in MSSQL Server 2008 R2 which sends emails when my Application logs errors. It works fine on servers at our office but when I ran it on our remote servers I got
<code>must issue a starttls command first
</code>
So maybe there is a setting somewhere which is different between the two servers, and that's why it's working on one and not the other. How do I set the server so that it issues a "starttls commaned first"?
Answer: I believe your "must issue a starttls command first" error message is coming from the mail server which you are transmitting your e-mail to. It may be set up to only accept encrypted connections for message transmissions. You could verify this by trying to telnet into the mail server and mimicking the SMTP protocol exchange which might look somewhat like this:
putty -telnet mail.example.com 25
<code>> 220 mail.example.com Microsoft ESMTP MAIL Service ready at Wed, 29 Jun 2011 11:57:31 +0200
< helo test
> 500 5.3.3 Unrecognized command
< helo test
> 250 mail.example.com Hello [22.214.171.124]
< mail from:<email@example.com>
> 250 2.1.0 Sender OK
< rcpt to:<email@example.com>
> 250 2.1.5 Recipient OK
< data
> 354 Start mail input; end with <CRLF>.<CRLF>
</code>
In this example, lines beginning with ">" are mail server replies and lines beginning with "<" are what you need to type to get the replies. Replace mail.example.com with the mail server you are using. If you will see "must issue starttls first" anywhere in the exchange, then this is it.
If you are using the Database Mail configuration wizard of SQL Server 2008 to define your mail server account settings along with the sp_send_dbmail stored procedure to send the mail, you simply will need to make sure that the "this server requires a secure connection (SSL)" checkbox is checked in the account's properties.


Flutter web renders elements on the screen too large

Question: Flutter web seems to render the elements on the screen way too large. Everything, from text, to Containers, to form fields, is massive. It is like everything has been zoomed in. It doesn't look good. I thought setting the visual density of the theme to VisualDensity.compact or VisualDensity.adaptivePlatformDensity would fix it, but it doesn't seem to. Running the app on a very large iPad Pro does not enlarge the elements. Why might this enlargement happen? I work on another Flutter app that is not enlarged on web and am unsure of what the key difference is that is causing the different rendering behaviour.
Comment: Instead of editing your question to add the answer, you should answer it in the "answer" section
Answer: This ended up being due to setting my mac display to "Scaled" with "larger text" in system preferences. It seemed to affect the web version and not the mobile simulators; I guess because the simulators are not under the mac display settings; they are their own device.
The fix was to set it to "Default for display":


Term by term integration

Question: Let $D \subset \mathbb{R}^{d} $ be open. For $u,v \in C_{0}^{\infty}(D)$, we define
\begin{eqnarray*}
\mathcal{A}(u,v)=\sum_{i,j=1}^{d} \int_{D} \frac{\partial u(x) }{\partial x_{i}}\frac{\partial v(x) }{\partial x_{j}} \nu_{ij}(dx)
\end{eqnarray*}
Here $\nu_{i,j}\,(1\leq i, j \leq d)$ are Radon measures on $D$ ( they are not necessarily positive ) such that for any $\xi=(\xi_{1},...,\xi_{d}) \in \mathbb{R}^{d} $ and any compact set $K \subset D$,
\begin{eqnarray*}
\sum_{i,j=1}^{d} \xi_{i} \xi_{j} \nu_{ij}(K) \geq 0,\,\,\nu_{ij}(K)=\nu_{ji}(K),\,\,1\leq i, j \leq d
\end{eqnarray*}
I want to prove $\mathcal{A}(u,u) \geq 0 $ for all $u \in C_{0}^{\infty}(D)$.
Proof (unfinished)
Devide $\mathbb{R}^{d}$ into cubes with sides parallel to the axis and of side length $\delta >0$. Denote by $\{ C^{1},...,C^{l(\delta)} \}$ those cubes whose closures are contained in $D$. $l(\delta)$ depends on $\delta$ and values in $\{1,2,...\}\cup\{\infty\}$. Take a point $\eta^{(k)}$ from each cube $C^{k}$ and put $\frac{\partial u(\eta^{(k)}) }{\partial x_{i}}=\xi_{i}^{(k)}$.
Then for all $u \in C_{0}^{\infty}(D)$
\begin{eqnarray*}
\mathcal{A}(u,u)&=& \sum_{i,j=1}^{d} \int_{D} \frac{\partial u(x) }{\partial x_{i}}\frac{\partial u(x) }{\partial x_{j}} \nu_{ij}(dx)\\
&=& \sum_{i,j=1}^{d} \left( \lim_{\delta \searrow 0}  \sum_{k=1}^{l(\delta)} \xi_{i}^{(k)} \xi_{j}^{(k)} \nu_{ij}(C^{k})  \right)\\
\end{eqnarray*}
I think if "$\lim_{\delta \searrow 0}  \sum_{k=1}^{l(\delta)} \sum_{i,j=1}^{d} \left| \xi_{i}^{(k)} \xi_{j}^{(k)} \nu_{ij}(C^{k}) \right|<\infty $" then we can interchange
$\sum_{i,j=1}^{d}$ and $\lim_{\delta \searrow 0}\sum_{k=1}^{l(\delta)}$.
Since $u \in C^{\infty}_{0}(D)$,
\begin{eqnarray*}
\lim_{\delta \searrow 0}  \sum_{k=1}^{l(\delta)} \left|  \sum_{i,j=1}^{d}  \xi_{i}^{(k)} \xi_{j}^{(k)} \nu_{ij}(C^{k}) \right|&=&\lim_{\delta \searrow 0}\sum_{k=1}^{l(\delta)} \sum_{i,j=1}^{d} \xi_{i}^{(k)} \xi_{j}^{(k)} \nu_{ij}(C^{k}) \quad {\rm(by\,assumption)} \\
&=&\int_{D} \sum_{i,j=1}^{d} \frac{\partial u(x)}{\partial x_{i}} \frac{\partial u(x)}{\partial x_{j}} \nu_{ij}(dx)< \infty \\
\end{eqnarray*}
Hence we can interchange $\sum_{i,j=1}^{d}$ and $\lim_{\delta \searrow 0}\sum_{k=1}^{l(\delta)}$. we get
\begin{eqnarray*}
\mathcal{A}(u,u)&=& \sum_{i,j=1}^{d} \int_{D} \frac{\partial u(x) }{\partial x_{i}}\frac{\partial u(x) }{\partial x_{j}} \nu_{ij}(dx)\\
&=& \sum_{i,j=1}^{d} \left( \lim_{\delta \searrow 0}  \sum_{k=1}^{l(\delta)} \xi_{i}^{(k)} \xi_{j}^{(k)} \nu_{ij}(C^{k})  \right)\\
&=& \lim_{\delta \searrow 0}   \sum_{k=1}^{l(\delta)} \left(  \sum_{i,j=1}^{d} \xi_{i}^{(k)} \xi_{j}^{(k)} \nu_{ij}(C^{k})  \right) \geq 0\\
\end{eqnarray*}
Is this proof correct? Can I get your opinion?
Comment: Need to replace one $u$ by $v$ in the integrand in the definition of $A(u,v)$.
Answer: Strictly speaking not an answer to your question but a solution that I think is essentially correct. Write $D$ as the union of an increasing sequence of compact sets $K_1\subset K_2\subset\cdots\subset K_n\subset\cdots$. Because of the property $\sum_{i,j=1}^d u_i(x)u_j(x)\nu_{ij}(K_n)\ge 0$ for each $x\in K_n$, $u_i(x)u_j(x)$ and $\nu_{ij}(K_n)$ have the same sign on $K_n$. The result now follows (via inner regularity) from the fact that $\sum_{i,j=1}^d\int_D u_i(x)u_j(x)\nu_{ij}(dx) = \lim_{n\to\infty}\int_{K_n}\sum_{i,j=1}^du_i(x)u_j(x)\nu_{ij}(dx)$.
Comment: Thanks! I will try to understand you told.

Term by term integration