How to think of chord extensions when soloing over chords?

Question: Guitar player here.  I have been learning about chord extensions and how they can be used to color to a basic progression or when playing a solo.  However as I was doing research on this it seems that a common way to think of them is not as an extension of a chord but rather two chords being played simultaneously.  For example a Dm over a G would make a G9.
This seems like a potentially powerful concept that makes it possible to reuse triads and tetrads in a solo band or improvisation situation.  For example over a G7 you could play an Am arpeggio rather than thinking about a G13.  However I find this quite daunting as the sheer number of possibilities across all keys is a little overwhelming.
Is this an effective way to think of and practice working with chord extensions? Or are there down sides to this?  Should I focus on practicing extended arpeggios or understanding which triads and tetrads extend a particular chord?
Answer: Not sure how Am over G7 gives G13. And this is maybe the stumbling block. Yes, some triads do fit with others to produce extensions. But what's wrong with just using the originals and adding extensions?
A lot of chords are made by the 'stack of thirds' as in G7 - G B D F. Add an A, and we have G9. Add C and it's G11, an E and it's G13 (generally sounds better without the 11). So it's neither complete stacked thirds nor two chords piggy-backed.
To me, it makes more sense to actually know what constitutes a chord, and work from there. The amount of extra information to know (and learn!) is perhaps slightly less than knowing what other chord is needed to produce an extension to the existing chord.
Then there's changes: ♭5, ♯5, ♭9, ♯9, as common examples. It's going to be better, surely, to think in terms of 'what note gets sharpened?' rather than 'what's the new chord I need to find the notes of before I play an extension?'.
Comment: To me in practice, G11 = F6/G, and it's used like a Gsus4. The third is not played. If you play the theoretical third, it sounds wrong for the song and basically ruins the harmony. Similarly, in a 13 chord the 11 is left out, because the meaning is never to be a sus chord, its role is to be a dominant seventh - with a major third and a seventh, but with extra flavor. Leaving out the 9th makes the difference in taste between 9 and 13 clearer. The systematic theoretical definitions for 11 and 13 chords just aren't very good chords in practice, and the de-facto definitions are different.
Comment: @NenadK - both John and I point out (individually) that G13 is better without the 11 (C). Personally, with me it often gets played without the 9 as well. That's another problem - extensions *do not* need every note to be played as well - playing an 11 doesn't have to have 5,7 and 9 all in there. So the idea of two piggy-backed chords falls down at that point too.
Comment: @NenadK I'd just like to add that the reason the 11 is not a good addition to a 7th chord is the minor 9th interval between the 3rd and the 11th creates a very strong dissonance that doesn't resolve well. However making it a 7sus4 by replacing the 3rd with the 4th is a good option and 9 and 13 work great on 7sus4 chords.
Comment: @JohnBelzaguy - I always think of 11 chords as 7ths and 4ths. After all, 7+4=11...
Comment: G7 = (1, 3, 5, b7) and its relative ii is (9, 11, 13) and this is the definition of a 13th chord.  We don't normally play the 11 but it's in the definition.
Comment: Am gives G13 by adding notes A,C,E. You point out the same in your example of stacking thirds. Your answer makes sense especially when considering the alterations. As you say thinking about which chords align seems like an extra step already but I can't even begin to get my head around how this would work with all the alterations.
Comment: Why didn't I think of that?
Comment: @JohnBelzaguy - I think of 13 similarly - 7+6=13.
Comment: @piiperiReinstateMonica - I agree that the theory of 'stacked thirds' works uo to 9ths, then goes awry. 11s and 13s should be special cases, but some players seem to think that all other 'thirds' must remain to make it 'authentic'. My reply contains double l...
Comment: @ggcg - and that's my beef. Theory is supposed to reflect reality. With extension 'rules' it doesn't. Don't know anyone who plays an X13 with 1,3,5,b7, ,9,11,*and* 13. (Certainly not most guitarists...) Do you??
Comment: I sure do.  But I am not sure you are talking about "theory" and extensions as opposed to basic definitions.  I would say that "In theory" and "by definition" the 13th chord IS (1, 3, 5, b7, 9, 11, 13) but some instruments don't have enough degrees of freedom to play it.  Forget about not having 7 fingers, I don't own a 7 string guitar (a prerequisite for this).  Don't judge the validity of this one what a guitarist can/can't do, ask a pianist.
Comment: @ggcg - I am that pianist, (also guitarist, both for many decades!) and I treat the whole thing with a great dollop of salt. Never felt that there's a compunction to play all the notes in a 13th chord, for example. Some are far more important than others, and it gets me wondering whether there are more apposite names.
Comment: Fair enough, it's a free country.  But the 11th on the V moves back nicely to the 7th of the I while the 3rd of the V moves up to the I.  I find that the movement V7 --> I maj7can be empty and is missing the classic strong sounding cadence.
Comment: This G11 issue has been discussed extensively here: https://music.stackexchange.com/questions/20560/proper-symbol-for-this-chord-1-5-7-9-11/20568#comment169516_20568
Comment: @Tim Makes sense. Also, my understanding is that when dealing with enharmonics the chord is named based on its harmonic function. So when forming a G9 by playing a Dm over a G in a dominant context, harmonically it's all still a G9. Then, knowing that the 3 & 7 degrees are the defining degrees for a chord, it is the 3 & 7 of the G9 I need to target. If I'm thinking of a Dm it would make it harder to find the 3 & 7 of the G9. This seems like another good reason to stick with your recommended approach.
Answer: Because of the way upper extensions are added to chords there is usually a way to touch on the basic chord plus the extensions within one scale. When you're talking about more advanced soloing concepts the modes of the ascending melodic minor scale can be very useful in this regard. A few examples are for dominant chords that are 9, #11, 13, a melodic minor scale built on the 5th gives you R 9 3 #11 5 13 b7. A melodic minor scale built on the m2 is great for altered chords and gives you R b9 #9 3 b5 b6 b7. There are several other of these modes that are useful for other types of chords.
Triads that incorporate upper extensions can definitely be used for color and melodic material. My preference is for major triads in general, for example: a triad built on the 2nd for a 7#11 chord (say D over a C7#11) or a triad built on the m6 for a 7alt chord (say Ab over a C7alt). Your choice of Am over a G13 is not ideal however because it contains the P4. An A major triad with the #11 would be better. Like you said the number of triads contained in any upper extension chord can be daunting, say a G13#11 contains G, Bo, Dm, F+, A, C#o and Em so it's better to narrow it down quite a bit if you want to incorporate them.
Bottom line, soloing is a very personal thing so educate yourself on different approaches and concepts but decide for yourself what the best way is to conceptualize them.
Answer:
Is this an effective way to think of and practice working with chord
extensions?

If you are able to see chords as combinations of other chords, it can help you play just the right notes that make the difference and add the right taste. The 9 chord being a combination of major + minor triads is a common example - if the rest of the band is playing a plain C major, you can make it a C9 by playing a G minor or Gm6. And if you know that Gm6 is equivalent to Em7-5 (just with a different bass note), you have lots of options all over the fretboard for building the C9 chord. Actually, Gm6/C has all the same notes as C9.
"Where's the nearest full C9?"
What fingerings do we have for a full C9 chord? This is probably the most commonly used one:

Or if you want something different, you might put together something like this:

I don't particularly like the sound of that option. But anyway, to sum it up, all two of your options are here:

If those are the only ways  you know for handling a C9, you may feel a bit uncomfortable and restricted. There must be a better way, this can't be how guitarists have to do it?!
Well OK there's this third alternative fingering I just discovered, but haven't used:

"Where are the nearest components of a C9?"
It's almost never necessary to play all of the theoretical notes of a chord. If you just want to add the juicy notes of a C9 in a solo, or play C9 flavor with fewer notes, and if the bass is already done somehow, for example if there's a bass instrument, or if you just played it a second ago and it's still echoing in the harmonic context, why not dissect the chord and play a Gm, Gm6 or Em7-5 instead. Now we have many more options all over the fretboard. All sorts of different ways to do a C9. (there are probably errors and omissions in the animation, but you get the idea)

Try strumming or arpeggiating one of these Gm6 or Em7-5 chords:

If those shapes don't look familiar, here are the corresponding plain G minor chords:

Learn the generic pattern, not all cases separately

However I find this quite daunting as the sheer number of
possibilities across all keys is a little overwhelming.

Here's where your problem might be. First of all, you don't learn all combinations in all keys separately as hundreds of special cases. You learn the generic pattern relative to the chord's root and relative to the tonic. To make a 9 chord, you play a minor triad or a minor sixth rooted a fourth below or a fifth above the original chord's root. From C you go --> Gm6. From A you go --> Em6. The trick is to keep track of the important strategic locations. Where is the tonic note? Where's the relative major/minor's tonic note? Where are the third and seventh of the currently playing chord? Everything that happens, is relative to these strategic locations. You learn the generic pattern, not each and every possible instance and variation of it.
Here is one generic pattern for seeing the minor triad over something with the root note on the low E string. Notice that it doesn't say which frets these are. The pattern is the same all over.

You learn the tricks one at a time
And secondly, you don't try to learn them all in one step. You eat the elephant one little piece at a time. Slowly. First you learn and practice the generic pattern for one chord trick, in one familiar song, in one familiar key. Just ONE. And when you get that one small step done, you are happy, because you achieved something. Then you take another small step, but only after you've taken the first step. Do not watch Youtube videos, they just distract your focus away from taking small steps. I don't personally know any great jazz players, but I'm sure they all learned everything they know one step at a time.
Some other chord substitution tricks where you can superimpose different chords relative to a chord's root note to make a larger chord:

A C maj9 chord can be seen as a G major chord over a C major chord, or as G6/C or Em7/C. If the bass player is playing a C, just find any G major or G6 or Em7 chord anywhere on the fretboard, to add the money notes.
An 11 chord is a major or major six chord rooted a whole-step below the root (i.e. on the seventh). To do C11 you play Bb or Bb6 over a C bass note. This is used like a Csus4 or C7sus4 chord. (Actually you can even do Bbmaj7/C for the same thing, even though there's an A note in there.)
On a dominant seventh chord, play a dim or dim7 chord rooted on the dominant seventh chord's third or its seventh, or one half-step above its root (which have the same notes). Practice this in songs where there's a dominant seventh chord doing a V - I motion. (which should be nearly every song ever written)
On a dominant seventh chord, prepare the listener for the strong dominant by first making it an 11 chord, then a 9, and then the dim7 trick explained above
On a dominant seventh chord, play major triads from the half-whole diminished scale of the dominant's root. For example on a written C7 and bass note C, arpeggiate A major, F# major, Eb major triads. (if you add together the notes of those triads and the bass note C, you get the C half-whole diminished scale)

By the way, this chord-combination thing can be used for thinking about modes as well. For example in "regular" A minor you have A minor and D minor chords, but in A Dorian you have A minor and D major. In regular C major you have C major and D minor, but in C Lydian you have C major and D major.
Comment: Not wishing to be confrontational, but how does knowing a chord is a combination of a couple of chords, compared with knowing the make-up of the named chord help any more? Then you have two separate facts to remember, whereas knowing the make-up of a somewhat complex chord is more homogenous.
Comment: @Tim If I think "where's the nearest full C9", I can't come up with enough alternatives from which I could select a few notes to use. But if I transform the question to "where's the nearest Gm or Gm6 or Em7-5", it's a lot easier, because those simpler chords are much more easily within reach. Actually I combine closely related chords to "equivalence groups" for this exact reason. Maybe some fretboard virtuosos can see all the notes of wide chords all over the fretboard, but I find myself searching for these helper patterns. I added two pictures, is it more understandable now?
Comment: @NenadK What you target is entirely your artistic choice. You can't target the 7 of Gm, because it doesn't have a 7. The 7th of C9 is the 3rd of Gm, and you should have that relationship clearly in your mind, because it's the note that makes the C9 a dominant-seventh type chord. In improvisation and soloing it should be you driving the chords instead of the chords driving you. You're responsible of knowing where you're placing the harmonically important notes at all times. Do you _want_ to make it a C9? If you want to make it, say Cmaj9, where do you place your notes to do that?
Comment: Great explanation. How do you get your head around target notes? In your first example if the band as a whole is playing a C9 and you are playing the Gm how do you keep it straight that the 3 of the Gm is really the 7 of the C and it's the 3 & 7 of the full extended chord you should be targeting?
Comment: @NenadK I'm not sure I understand what you're asking. Whichever note you want to emphasize is your target note. If you want to emphasize the 3 and 7, then have them as your target notes. Or do you mean, how to remember which of the strings has which note of the Gm? That's what you have to know about each chord pattern - which of the "dots" is which note of the chord. I have it in my mind already as a starting point - when I search for the nearest Gm, I look for the most easily reachable G or Bb and use the appropriate inversion based on that location. Or is that what you mean?
Comment: That is what I mean.  But I'm suggesting that playing a Gm over a C to make a C9 means that it's harmonically a C9 and it is the 3 & 7 of this full extension that need to be targeted.  Not the 3 & 7 of the Gm.  Then you would have to do more mental math to figure out that it's really the 3rd degree of the Gm is  the 7 of the C9 and the 3 isn't even there.  You can't just straight target the 3 & 7 of the Gm.
Answer: What you are talking about is sometime referred to as Poly-chord theory (at least that's what my guitar teacher called it in the 80s).
A simple example is any major triad and the minor triad played on its 3rd, these create a Maj 7.  Consequently X maj and the minor on its 3rd are chord substitutions for each other.  If you are interested is a very dense guide to poly chords, extensions, etc, pick up Ted Greene's book Chord Chemistry.  There isn't mush missing in there.
As for being "daunting", I am not sure how key signature has anything to do with complexity.  Most of these relations are "relative" to the tonic of the chord.  Don't think of G7 and Amin think I7 and ii, now the I can be anything.  Once you get the extensions and substitutions memorized in a relative sense you should be able to grab them on the fly anywhere.
They way we build up chords and their extensions is from the major scale but taking every other note, or stacking 3rds.  Rewrite the Major scale as,
1, 3, 5, 7, 9, 11, 13
And there you have it.  A common device is to meld triads whose roots are separated by a 3rd.  Like (1, 3, 5) + (3, 5, 7) = Maj 7th.  Another very common one is (5, 7, 9) + (7, 9, 11) = Dom 7th played on the V of the key (where it belongs).  This gives rise to the familiar "Leading tone cadence".  The authentic cadence is V --> I, most of us probably play V7 --> I as a default but in terms of poly chords you can think of the leading tone resolution as representing the V7 --> I sound.  The only real avoid note is the 4th, but then again we do occasionally like the sound of an 11th chords.  So, in theory, you can add pretty much any two chords together and create something "harmonious".
Take for example (1, 3, 5) + (5, 7, 9) = Maj 9 a perfectly nice chord.  Just a Major 7th with a 9th on top.  Sounds beautiful and there are no awkward intervals.  This means you can harmonize the I with the V and people don't normally go there.  However add the 7th to the V chord are get (1, 3, 5) + (5, 7, 9, 11) = Maj 11.  This is not out right illegal but the 11th (aka the 4th) is an avoid note as it really wants to become the 3.  As part of the chord movement V7 --> I, inserting this in between wouds create a suspended resolution.  Dwelling on the 11 would probably start to get awkward.  As another cautionary tale consider using the V triad as an extension to the I in the Blues.  Here we usually (but not always) play dom 7 chords on the I, IV, and V.  The V triad contains the Maj 7 of the I chord.  This would definitely conflict with the I7 but could be made to work, for example as part of the Be Bop scale.  In dealing with dom 7 chords a minor or diminished triad on the 3rd is a better choice.
Again, I cannot stress enough that there are not that many options and you don't need to consider them in every key.  You want to learn them in a relative sense and just move the group to different positions on the neck.  As far as practicing I'd say anywhere you invest your time will produce dividends.  Pick one and work for a while.  In my opinion, and this is where I spend most of my time, it helps to completely rewrite the changes to common tunes using substitutions that are based on extensions, i.e. poly-chords.  This way you immediately go there.  Using relative 3rd, relative minor, secondary dominant, or tri-tone, the idea is to develop in your hand as well as your mind the fact that for any chord X all these other options are "attached".
Answer: Yes, 'playing the extensions' is a perfectly valid technique.  But, in practice, it might not result in anything much different to playing 'the scale of the chord', unless you make a conscious effort to treat the base chord as 'avoid notes'.


Proving that $H$ is a subgroup of $\mathcal{S}_n$.

Question: Question. Suppose $n>2$. Let $$H:=\{f\in\mathcal{S}_n: f\cdot 1=1\ \text{and}\ f\cdot2=2\}.$$ Is $H$ a subgroup of $\mathcal{S}_n$?
Attempt. $H$ describes all the permutations that leave $1$ and $2$ fixed. The order of this group is $(n-2)!$. Since this is a divisor of the order of $\mathcal{S}_n$; by Lagrange, we conclude that $H$ is a subgroup.
Satisfied with this reasoning?
Comment: You need to revise your understanding of Lagrange's theorem.
Comment: @Shaun re-read, apologies.
Comment: Why was this downvoted? Who voted to close as off topic? It has a clear attempt!
Comment: @Shaun I don't think mocking people is productive :) Let's help each other learn
Comment: @William I think you misunderstood my comment. I think this is a high quality question.
Comment: Hint: Use the [one-step subgroup test](https://en.m.wikipedia.org/wiki/Subgroup_test).
Answer: Please correct me if I'm wrong, but this is my best shot.
The solution, I believe, is simple. Consider $a, b \in H$. Since both fix 1 and 2, then $ab$ fixes 1 and 2. (Closure.) Since $a$ fixes 1 and 2, $a^{-1}$ must fix 1 and 2, as well. (Inverses.) The identity fixes 1 and 2. (Identity.) That proves it's a subgroup.
Your reasoning, while more sophisticated, mistakenly reverses the statement made by Lagrange's theorem. Lagrange states that a subgroup's order must divide the order of the group. It doesn't say that there exists a subgroup of each divisor of the group's order.
Comment: Ah yes, I see the error of my ways now. Thank you very much for putting me on the right track.
Comment: @thesmallprint glad to help. I imagine you're doing this for a course and as someone who has been out of school a while, man do I miss what you're doing right now :) enjoy.


Showing the person logged in on rails with devise gem

Question: I'm trying to set up a "finish signing up page" in rails.
So the plan is that the admin makes them an account with just an email and a password then sends them a link to log in and change their information. But I can't work out how to print out an update information form.
I'm trying
class Users < ApplicationController
 def update
   @current_nav_identifier = :signup
   @user.current_user = User.current_user
 end
end

and I was hoping that the form I have made will print out the update section so the user can update their information.
However this doesn't happen, The @user.current_user = User.current_user throws an error so I changed to @user = User.new but this doesn't work because I don't want them to have access to add new users, they should only be able to change their information
The idea is that when they sign in for the first time using the generated password they are redirected to this page so they can update their information. This web app is invite only
Any ideas
Comment: What you are required for ?
Comment: Do you know about the authentication gem available in rails named 'Devise' ?
Comment: sorry forgot to mention thta
Comment: Doesn't look like you have gone through the gem docs. It's worth spending sometime on external libraries before you use them.  current_user is a helper method available in controllers and views. And if you want to create a form for the current user, just use form_for current_user and in your controller ensure you have before_action :authenticate_user which will take care of redirecting to whatever path you specify. I'm on phone so couldn't format my comment well. Hope that helps
Answer: Go with the gem devise. A very popular gem for authentication in rails application.
gem 'devise'

Refer Here
Comment: I'm using devise, sorry I forgot to mention that in the main question
Comment: Why you have created the signup controller ? Any specific reason behind the same.
Answer: Devise provides a current_user method so if you need an @user instance variable to create a form for, and you're sure they're logged in, you could use this in the controller:
@user = current_user

Then you can build a form for them with something like:
<%= form_for @user do |f| %>
  ...
<% end %>


Change a table cell data in mysql

Question: I am failing to figure how to change a particular cell data of a mysql database table.
For instance:
MyDB database has 3 tables
"Table1"
"Table2"
"Table3" etc.
Table 3 has 3 columns: ID | Title| Deadline
Each column has several rows (content created)
"Table3"
 ID | Title| Deadline
 1  | abc  | 30
 2  | def  | 45
 3  | ghi  | 30

etc.
So, let'say I want to change 30 with 60 from Deadline where row ID is 3, how do I do this?
When I type UPDATE Table3 set deadline = '60' WHERE Deadline like 30;
it unfortunately also changes the  "30"  of the row where ID 1.
Many thanks for your clarification.
Roman
Answer: You wanna change the row ID with 3, then mention that in the where clause.
update table3
set deadline=60
where id=3;

Answer: Try this
UPDATE Table3
SET deadline=60
WHERE id=3;

Change a table cell data in mysql


Java enumerations vs. static constants

Question: I'm looking at some Java code that are maintained by other parts of the company, incidentally some former C and C++ devs. One thing that is ubiquitous is the use of static integer constants, such as
class Engine {
    private static int ENGINE_IDLE = 0;
    private static int ENGINE_COLLECTING = 1;
    ...
}

Besides a lacking 'final' qualifier, I'm a bit bothered by this kind of code. What I would have liked to see, being trained primarily in Java from school, would be something more like
class Engine {
    private enum State { Idle, Collecting };
    ...
}

However, the arguments fail me. Why, if at all, is the latter better than the former?
Comment: +1 for making constants `final`.
Answer:
Why, if at all, is the latter better
  than the former?

It is much better because it gives you type safety and is self-documenting. With integer constants, you have to look at the API doc to find out what values are valid, and nothing prevents you from using invalid values (or, perhaps worse, integer constants that are completely unrelated). With Enums, the method signature tells you directly what values are valid (IDE autocompletion will work) and it's impossible to use an invalid value.
The "integer constant enums" pattern is unfortunately very common, even in the Java Standard API (and widely copied from there) because Java did not have Enums prior to Java 5.
Comment: +1 because you are the only one mentioning self-documentation. If you have an method, that accepts (or returns) an int, that represents some code, you have without doc or source no chance to conclude to the semantics of the int. But the enum has a name for each value and the signature is directly (via type) connected to the enum.
Answer: An excerpt from the official docs, http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html:

This pattern has many problems, such as:

Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.
Brittleness - Because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
Printed values are uninformative - Because they are just ints, if you print one out all you get is a number, which tells you nothing about what it represents, or even what type it is.

And this just about covers it. A one word argument would be that enums are just more readable and informative.
One more thing is that enums, like classes. can have fields and methods. This gives you the option to encompass some additional information about each type of state in the enum itself.
Answer: Because enums provide type safety. In the first case, you can pass any integer and if you use enum you are restricted to Idle and Collecting.
FYI : http://www.javapractices.com/topic/TopicAction.do?Id=1.
Answer: By using an int to refer to a constant, you're not forcing someone to actually use that constant.  So, for example, you might have a method which takes an engine state, to which someone might happy invoke with:
engine.updateState(1);

Using an enum forces the user to stick with the explanatory label, so it is more legible.
Answer: There is one situation when static constance is preferred (rather that the code is legacy with tonne of dependency) and that is when the member of that value are not/may later not be finite.
Imagine if you may later add new state like Collected. The only way to do it with enum is to edit the original code which can be problem if the modification is done when there are already a lot of code manipulating it. Other than this, I personally see no reason why enum is not used.
Just my thought.
Comment: However, adding a new state would probably require other changes in the code (meaning handling of that new state). So the scenario is not very likely. Legacy code is probably the only place where this approach is appropriate.
Answer:
Readabiliy - When you use enums and do State.Idle, the reader immediately knows that you are talking about an idle state. Compare this with 4 or 5.
Type Safety - When use enum, even by mistake the user cannot pass a wrong value, as compiler will force him to use one of the pre-declared values in the enum. In case of simple integers, he could even pass -3274.
Maintainability - If you wanted to add a new state Waiting, then it would be very easy to add new state by adding a constant Waiting in your enum State without casuing any confusion.
Answer: The reasons from the spec, which Lajcik quotes, are explained in more detail in Josh Bloch's Effective Java, Item 30.  If you have access to that book, I'd recommend perusing it.  Java Enums are full-fledged classes which is why you get compile-time type safety.  You can also give them behavior, giving you better encapsulation.
Answer: The former is common in code that started pre-1.5.  Actually, another common idiom was to define your constants in an interface, because they didn't have any code.
Comment: But that practice also encourages the use of inheriting those constants, which is a bit ugly. :(
Comment: @David: it's the least of the problems that "integer constant enums" cause.
Comment: @Michael: But a problem none the less.
Comment: @David, yes, and that's why they also introduced "import static" after 1.5.
Answer: Enums also give you a great deal of flexibility. Since Enums are essentially classes, you can augment them with useful methods (such as providing an internationalized resource string corresponding to a certain value in the enumeration, converting back and forth between instances of the enum type and other representations that may be required, etc.)

Java enumerations vs. static constants


Is there some relation between characters in representation theory and multiplicative characters?

Question: A character of a group representation is obtained by taking trace of each matrix in this representation.
The word character is often used in the sense that it is a homomorphism from a group to $(\mathbb C\setminus\{0\},\cdot)$ (sometimes with some additional properties). This kind of characters arises, e.g., in Pontryagin duality or as Dirichlet characters in number theory.
Is there some relation between these two (frequently used) meanings of the world character, or is it just a coincidence that the same word was used for both of them?
Comment: BTW only now I found out what [your gravatar](http://en.wikipedia.org/wiki/File:3-adic_integers_with_dual_colorings.svg) is. (But I have to admit that I don't know anything about the mathematics behind it.)
Comment: Good work, detective. :-)
Answer: A $1$-dimensional representation of a group is a continuous homomorphism into $\Bbb C^\times$: in particular it is equal to its own trace (once we identify $\mathrm{GL}_1(\Bbb C)\cong\Bbb C^\times$). So the group homomorphism definition of characters is the $1$-dimensional case of the trace-of-a-representation definition. To copy myself:

The homomorphisms $G\to \Bbb C^\times$ are actually not the whole story of character theory, but are a very tidy chapter in it. If $V$ is a vector space (over $\Bbb C$) and $G$ finite, the homomorphisms $G\to  GL(V)$ from $G$ into the general linear group of invertible linear maps are called representations, which are essentially the ways to equip $V$ with a linear $G$ action. If $\rho$ is a representation, then the map given by $\chi_\rho:G\to \Bbb C:g\mapsto\mathrm{tr}\,\rho(g)$ (the trace of the linear map associated to $g$, which is independent of basis or coordinate choice for $V$) is called a character.
If $V$ is one-dimensional (in which case we call $\rho$ and $\chi_\rho$ one-dimensional as well) then $\rho=\chi_\rho$ and the characters are multiplicative. Note that $\mathrm{tr}\,\rho(e_G)=\dim\,V$ shows the dimension can be directly computed from the character, so there is no ambiguity with respect to what dimension a character may have. With a distinguished basis we have $V\cong \Bbb C^n$ in an obvious way, so we can write $GL(V)$ as $GL_n(\Bbb C)$, in which we are working with matrix representations specifically.

(Over here.)
Comment: Why just finite groups?
Comment: @Andrea - Erm, because I didn't want to bother writing "continuous" I guess.
Comment: @Andrea So far I have only learned about linear representations of finite groups. But maybe later I'll try to understand at least basics of some of other [branches of representation theory](http://en.wikipedia.org/wiki/Group_representation#Branches_of_group_representation_theory).
Comment: Well, it seems to me that given any group $G$ and *any* homomorphism $\rho:G\rightarrow\Bbb C^\times$, then $\rho(g)=\text{tr}(\rho(g))$.
Comment: @Andrea, right. When a topology on $G$ is assumed and $G$ is infinite, I am not used to the noncontinuous homomorphisms $G\to GL(V)$ being admitted under the label "representation," though I have not studied representation theory this far anyway. Is it standard to accept noncontinuous homomorphisms as representations?
Comment: @anon : I was pointing out that the identity is purely algebraic, but I guess that you have a point here. I'm not properly a group/representation theorist, so I'm not able to give a qualified answer to your question whether (rephrasing) there exist interesting non-continuous representations. If memory doesn't betray me, all the representations I encountered this far are continuous. Should we maybe ask in SE? :)
Comment: @Andrea If you want, of course. I was speaking about the meaning of the word representation when applied to topological groups. According to [PM](http://planetmath.org/TopologicalGroupRepresentation.html) for instance, the homomorphism must be continuous by definition, and if my memory doesn't betray *me*, other sources also use this definition. Although technically if we only talk about group representations and not topological group representations we drop the continuity convention, so I guess I don't need to bother saying the homo is continuous. But hey.


Proving a Sequence's Uniform Convergence

Question: Another homework problem that's been giving me headaches for about a week now.
Prove that the following sequence of functions $(f_n)$ converges uniformly on the interval $[1,2]$:
$$f_n(x) = \frac {nx^2 - 2}{x^4 + nx}.$$
Then, find the following integral on the same interval and justify your answer:
$$ \lim_{n\to\infty} \int_1^2 \frac {nx^2 - 2}{x^4 + nx}\mathrm dx.$$
Any help on this would be appreciated.
Answer: Hints:
1) $$ f_n(x) = x\left( \frac{ 1 - \frac{2}{nx^2}}{1 + \frac{x^3}{n}}\right)$$
2) Since $f_n \to f$ uniformly on $[a,b]$ then $$ \int_a^b |f_n(x) - f(x)|dx \leq (b-a)\cdot \sup_{x \in [a,b]} \{|f_n(x) - f(x)|\}$$
might be a useful inequality.
Answer:
We can identify the pointwise limit: it's $f(x)=x$
$f_n(x)-f(x)=\frac{nx^2-2-x^5+nx^2}{x^4+nx}=-\frac{2+x^5}{x^4+nx}$. So if $x\in [1,2]$, $|f_n(x)-f(x)|\leqslant \frac{2+2^5}{n}$.
Justify we can put the limit under the integral.
Comment: If we know the pointwise limit is x, can we simply take the integral of said limit over the interval? Is that legal?
Comment: Yes: we can bound the difference of the integrals by the length of the interval times the supremum norm of the difference.
Answer: $f_n(x) = \frac {nx^2 - 2}{x^4 + nx}$.  So make a guess that $f_n \to x$.    Then try to prove that for all $\epsilon \gt 0$, there exists natural $N$ such that $n \gt N, x \in [1,2] \implies |f_n(x) - x | \lt \epsilon$.
Well $\frac{nx^2 - 2}{x^4 + nx} - x = \frac{nx^2 - 2 - x^5-n x^2 }{x^4  + nx} = $ top and bottom of $x$ term multiplied by $x^4 + nx. \ $ Then $ =  -\frac{x^5 + 2}{x^4 + nx}$.  Clearly this can be made arbitrarily small, but let's prove it. Max of $|x^5 + 2|$ on $[1,2]$ is $M_1 = 2^5 + 2$.  So $|f_n(x) - x | = |\frac{x^5 + 2}{x^4 + nx}| \leq \frac{M_1}{x^4 + nx}$  Since $[1,2]$ is an all positive interval we have that $nx \lt x^4 + nx$, so we have $RHS \lt \frac{M_1}{nx}$.  And for any $n$, the minimum of the denominator is $1\cdot n$, so we have $\frac{M_1}{nx} \lt \frac{M_1}{n}$.  Choose $N$ small enough so that $M_1/N \lt \epsilon$.


PCL: calculate the xyz for a point in mm

Question: I am using the kinect sensor and here is what I want to do. After I capture a IR frame and created a point map, I want to be able to calculate the X,Y and Z coordinates, of any point I want, from the kinect in millimeters (or any other real measurement).
For example: When I chose one random point from the cloud, it will tell me that it is 2000 mm in front, 100 mm on the left and 350 mm up. This way I can know the position of the point in the real word.
Any idea how to do this?
Comment: OpenNI grabber provided by PCL outputs points with coordinates in meters. Doesn't this suit your needs?
Answer: If you are using the Point Cloud Library, and you seem to be, the point picking callback will allow you to build on PCLVisualizer to register a function to deal with a point (e.g. printing it out) when it is clicked:
http://docs.pointclouds.org/1.2.0/classpcl_1_1visualization_1_1_p_c_l_visualizer.html#ae8d38a6277cbab766b4e4c5e9c9b4e66
For more complex operations using the Point Cloud Library you probably need to get into VTK which is underneath the visualizer.


Which of these rotation matrices represents a positive rotation in three-space about the y-axis?

Question: This is what Wikipedia says:
\begin{bmatrix}
\cos \theta & 0 & \sin \theta \\
0 & 1 & 0 \\
-\sin \theta & 0 & \cos \theta \\
\end{bmatrix}
This is what I think it should be:
\begin{bmatrix}
\cos \theta & 0 & -\sin \theta \\
0 & 1 & 0 \\
\sin \theta & 0 & \cos \theta \\
\end{bmatrix}
Which is correct?
The convention used on the Wikipedia page for the other two transformations suggests that they are using a different standard for rotations about the x axis and the z axis than they are for rotations about the y axis.
Comment: Wikipedia is fine. Let us see: Put the x-axis on the floor, pointing to your right, the y-axis pointing up from the floor towards you. Then the z-axis, following the rule of the right-hand, which is used as a way to agree on a positive orientation, should be pointing to your back. So, to achieve a counterclockwise rotation, as the angle increases from zero, the z-coordinate should go to negatives first. Try rotating [1,0,0].
Comment: You forgot to mention whether you're multiplying these matrices with row vectors or column vectors.
Answer: It's, for all practical purposes, a matter of opinion in this case.  It depends on where you are measuring $\theta$ from, and different people have different conventions in $3$-space.
Comment: Their rotation matrix measures $\theta$ as clockwise rotation in the $x-z$ plane if $z$ takes the place of the $y$-axis in the conventional Euclidean plane.  However, if you switch the axes labels, their convention makes sense.  Your matrix is more more widely accepted, but theirs isn't strictly wrong.
Comment: Here is where it is in Wikipedia: https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations The convention they use for the other two transformations indicates that they are using a different standard for rotations about the x axis and the z axis than they are for rotations about the y axis.
Comment: That is not really the case. If the y-axis is pointing towards you, as wikipedia is asking, then the z-axis should be pointing down so that it agrees with the positive orientation of the coordinate system.
Comment: @ABC at which point?  I'm just speaking from what I've seen, I could be wrong about accepted convention.
Comment: As a convention angles are measured positive counterclockwise from the positive part of the x-axis, while the axis of rotation is pointing up towards you, from the plane of rotation. In addition the positive orientation of the axes should satisfy the rule of the right hand. Then if the x-axis is to the right, and y-axis is up from the plane, then the z-axis should be pointing down (or rather back, like the negative part of the usual y-axis in a plane).
Comment: The z-axis is normally up from the plane though.
Answer: Talking about 'matters of opinion' is misleading. It's not a matter of opinion - it's a matter of mathematical convention due to the cyclic right-handed nature of the xyz co-ordinates.
See: Why is rotation about the y axis in $\mathbb{R^3}$ different from rotation about the x and y axis.


Detecting outliers in non-linear data

Question: Is there a way to detect outliers in data that would fit a non-linear shape? For example, I have data that fits an exponential decay with an obvious outlier. I have simulated data with an example of this:

I want to know the index locations of where these outliers occur in the real data and currently I am doing this by applying an exponential decay fit to the data then finding the residual of each point the fit. I then find if any points go over a certain threshold that I find as some multiple of the standard deviation of the residuals and find any point with a residual over that threshold. Is there a better way to find outliers in a model like this?
Here are the points used in the above array:
<code> [10., 8.46481725, 7.16531311, 6.0653066,
 5.13417119, 4.34598209, 3.67879441, 3.11403224,
 2.63597138, 2.2313016 , 1.88875603, 1.59879746,
 1.35335283, 1.14558844, 0.96971968, 0.82084999,
 0.69483451, 0.58816472, 25, 0.42143844]
</code>
Answer: Residuals can be useful, but there are a few things to watch out for.
Your data might be heteroskedastic, i.e. the magnitude of residuals varies with the x-value. In this case, what counts as a "large" residual might depend on the x-value. (This is an issue even with linear relationships.)
You might also need to think about the potential for errors in the measurement of the x-value. For example, if y=2x, mismeasuring x by 1 will always cause an error of 2 in your prediction of y. But if y=2^x, mismeasuring x by 1 can cause very small or very large errors in predicting y, depending on what x is. Strictly speaking this isn't heteroskedasticity, but the results look very similar.
One common trick is transformation - either of the whole function, or of the residuals. In the example you give, I'd consider a log transformation, which will convert your exponential relationship to a linear one; depending on the sort of errors you encounter, it may or may not remove heteroskedasticity.
You can also look at neighbour-based ways to identify outliers. For example, for any given data point P, pick the closest n neighbours to the left and to the right, characterise the range of y-values in that neighbourhood, and then check whether P is consistent with that range.
...and there are many other methods, all the way from "eyeball it on a scatter plot" up to elaborate machine-learning methods like neural nets and SVMs. It's hard to give a definitive answer to your question since it depends on so many factors.
Comment: Can you explain how a neural net and SVM would be useful for the question posed?
Comment: Glen: I doubt they would be useful for the specific example given. I mentioned them in the context of the OP's more general question about detecting outliers with non-linear data. I'm aware that both NNs and SVMs have been used for outlier detection, but I'm not the right person to go into detail about that - I don't claim familiarity with those methods, just awareness that they exist.

Detecting outliers in non-linear data


TcpClient don't receive any data with ajax call

Question: I'm struggling to find out why TcpClient don't receive any data in server side if it has called through ajax.
However, if I put breakpoint in my server side code it works fine even if I have called it with ajax.
I also investigated to find out if my JavaScript function is asynchronous but it seems my JavaScript function is fine.
JavaScript function:
$('#btnGO').click(function () {

        var url = 'Home/Command';
        var data = { Location: $('#Location').val() };

        $.when($.getJSON(url, data)).then(function (result) {
            $('.Console').html(result);
        });

});

Server side:
TcpClient tc = new TcpClient("Host Address", 23);
return Json(tc.Connected + " " + tc.Available, JsonRequestBehavior.AllowGet);

Output if I put breakpoint in serverside:

true 22

Output if I don't put breakpoint in serverside:

true 0
Comment: I think you'd want to call `GetStream()`, and then call `Read()` on the returned `NetworkStream`. `Read()` is blocking, and won't allow your action method to return prematurely. Right now, there are no blocking calls to prevent your action method from instantly returning (faster than your tcp client receives data), which is why you get 22 when you put in a break point - it doesn't instantly return. It seems awkward that your UI responsiveness depends on somebody sending data to your API via a socket though....
Comment: Okay, let me emphasize this more: It's really strange what you're doing. Your UI will be waiting for a client to send data to your API via a socket.

Having said that, check out the following link: https://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read(v=vs.110).aspx
Comment: @Steve'saD Thank you. Please write your comment as answer, so I can choose it.
Comment: I did. If you tell me what you're actually trying to do - i.e. what app you're trying to make - I may be able to point you in the right direction
Comment: Your first sentence makes me think you just want to send data from javascript, to your api/endpoint. You don't need a socket for that, just put a model in your signature and let mvc/web api do it's model binding....
Comment: @Steve'saD No, I was try to execute some `telnet` commands with `tcpclient`. For the problem in my question `NetworkStream.Read()` solved my problem. However, when I used `NetworkStream.Write()` thread didn't wait for `Write()` to be done. So I had to use Thread.Sleep(1000) after `NetworkStream.Write()`
Comment: oh okay. The docs say that Write is also blocking, so you shouldn't need to sleep the thread.... you should make sure you're doing it right: https://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.write(v=vs.110).aspx
Comment: @Steve'saD I do believe that `Write` blocks until it writes to buffer. I don't think it waits until end point receives message and send response. That is why if I immediately call `Read` after `Write` I receive nothing.
Answer: I think you'd want to call GetStream(), and then call Read() on the returned NetworkStream. Read() is blocking, and won't allow your action method to return prematurely. Right now, there are no blocking calls to prevent your action method from instantly returning (faster than your tcp client receives data), which is why you get 22 when you put in a break point - it doesn't instantly return. It seems awkward that your UI responsiveness depends on somebody sending data to your API via a socket though....
let me emphasize this more: It's really strange what you're doing. Your UI will be waiting for a client to send data to your API via a socket. Having said that, check out the following link: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream(v=vs.110).aspx


Sum of discrete and continuous random variables with uniform distribution

Question: Could you tell me how to find the distribution of $Z = X+Y$ if $X$ is a random variable with uniform distribution on $[0,1]$ and $Y$ has uniform distribution on $\{-1,0,1\}$?
$X$ and $Y$ are independent.
I know how to find distributions of sums of random variables if both are discrete or both are continuous. But here we have a mix.
I guess I should consider $P(Z<-1) = P(\{X<-1, Y<0\} \cup \{X<0, Y<-1\})=0$
$P(Z \in [-1,0)) = P(X \in [-1,0), Y=0 \ \text{or} \ X \in [0,1), Y=-1 \ \text{or} \ X \in [-2, -1), Y=1) = \frac{1}{3}$
$P(Z \in [0,1)) = P(X \in [0,1), Y=0 \ \text{or} \ X \in [1,2), Y=-1 \ \text{or} \ X \in [-1, 0), Y=1) = \frac{2}{3}$
$P(Z \in [1,2)) = P(X \in [1,2), Y=0 \ \text{or} \ X \in [2,3), Y=-1 \ \text{or} \ X \in [0, 1), Y=1) = 1$
And so $P(Z \ge 1) = 1$
Is that correct?
Comment: Are you assuming (or have you been told) that $X$ and $Y$ are independent but you have opted to not share this information with us?
Comment: I'm so sorry. Yes, they are independed. I haven't noticed that I forgot to write this.
Answer: You can extend the convolution method for summing continuous independent variables if you identify the "density" of a discrete variable as a sum of Dirac deltas. Here you find that the density of $X$ is $1_{[0,1]}$ while the "density" of $Y$ is $\frac{1}{3} \sum_{i=-1}^1 \delta_i$. So you now need to compute the convolution:
$$g(x) = \frac{1}{3} \sum_{i=-1}^1 \int_{-\infty}^\infty \delta_i(y) 1_{[0,1]}(x-y) dy \\
= \frac{1}{3} \sum_{i=-1}^1 \int_{x-1}^x \delta_i(y) dy$$
By the definition of the Dirac delta, the $i$th summand is $1$ if $i \in (x-1,x)$ and zero otherwise. So exactly one summand will be $1$ if and only if $x \in (-1,2)$, so the density here is $\frac{1}{3} 1_{(-1,2)}$.
In this case this is pretty much the same as the other answer; this method is nicer in more complicated examples.
Answer: Notice, that events $Z \in [-1,0)$, $Z \in [0,1)$ and $Z \in [1,2)$ have empty intersection. But the according to your solution:
$$P(Z \in [-1,0)) + P(Z \in [0,1)) + P(Z \in [1,2)) > 1$$
which clearly could not be correct.
So lets count, the desired probabilities once again, using the fact that X,Y are independent:
\begin{align}
P(Z \in [-1,0)) &= P(X \in [0,1))P(Y=-1) = 1\times\frac{1}{3}=\frac{1}{3}, \\
P(Z \in [0,1)) &= P(X \in [0,1))P(Y=0) + P(X = 1)P(Y=-1) = 1\times\frac{1}{3} + 0\times\frac{1}{3} = \frac{1}{3}, \\
P(Z \in [1,2)) &= P(X \in [0,1))P(Y=1) + P(X = 1)P(Y=0) = 1\times\frac{1}{3} + 0.\times\frac{1}{3} = \frac{1}{3}.
\end{align}
Of course $P(Z < - 1)= 0$, but we have already counted
$$P(Z \geq 1) = P(Z \in [1,2)) + P(Z \geq 2) = \frac{1}{3} + 0.$$
Comment: In you count the distribution function :
$$P(Z \leq z) = \frac{1}{3}P(X \leq z+1) +  \frac{1}{3}P(X \leq z) +  \frac{1}{3}P(X \leq z-1)$$
for all $z \in [0,1]$, you should see that Z has uniform distribution on $[-1,2]$.
Comment: I see where I made a mistake, in the second summands we only take one value of $X$, because the probability that $X$ has values outside $[0,1]$ is zero. Thank you!
Comment: I have one more question, though. Is this distribution continuous?


Como interromper o envio do fomulário com JavaScript?

Question: Tenho um formulário usando o form.CheckValidity para verificar campos vazios e não envia-los.
No entanto preciso também que ele compare e não submeta formulários com campos de senhas diferentes.
Tentei de tudo que sabia e não está dando certo. Ele verifica, mas envia o formulário.
Meu código:

(function() { 'use strict';
  window.addEventListener('load', function() {
    var forms = document.getElementsByClassName('needs-validationss');
  var senha1 = document.getElementById("senha1").value;
  var senha2 = document.getElementById("senha").value;
  console.log(senha1);
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false || senha1 != senha2) {
          event.preventDefault();
          event.stopPropagation();
    }
    form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">`<form class="needs-validationss" action="123.php" novalidate>

          Nova senha:
          <input type="password" class="form-control" name="senha" id="senha" required size="15" maxlength="15" required>

            Por favor, insira sua nova senha.

          Repetir nova senha:
          <input type="password" class="form-control" name="senha1" id="senha1" required size="15" maxlength="15" required>

            Por favor, repita sua nova senha.

            Por favor, insira duas senhas iguais.

        <button type="submit" id="btnVerify" class="btn btn-outline-dark">Trocar senha</button>

    </form>

A função funciona bem enquanto os campos estão vazios. Mas quando, preenche ele envia mesmo as senhas estando diferente.
Comment: tenta trocar o  tipo do botão de "submit" para "button" e adiciona um evento de click "onclick" chamando uma função que verifique as senhas e de estiver ok, faz o submite: "document.getElementById("form1").submit();"
Comment: Se eu trocar o botão, como eu chamo essa função maior?
Comment: coloquei uma resposta, testa lá.,
Comment: Testei, JavaScript é algo muito chato kkk
Answer: Tenta trocar:
<button type="submit" id="btnVerify" class="btn btn-outline-dark">Trocar senha</button>

Por:
<input type="button" value="Trocar senha" id="btnVerify" class="btn btn-outline-dark" onclick="verficaEenvia()">

e adiciona a função verficaEenvia:
    function verficaEenvia() {
        var forms = document.getElementsByClassName('needs-validationss');
        var senha1 = document.getElementById("senha1").value;
        var senha2 = document.getElementById("senha").value;
        // forms.checkValidity() === false ||
        if (senha1 != senha2) {
           alert("senha1 != senha2");
        } else {
           alert("senha1 == senha2  e submeteu");
           document.getElementById("form1").submit();
        }
    }

Testa aqui
Comment: Também não deu. Ele nem envia assim.
Comment: Testa de novo s2, coloquei um link para você testar.
Comment: obrigado! Ajudou muito
Answer: Adiciona return false; depois dessa linha event.stopPropagation();
Comment: Coloquei o return false; e envia mesmo assim.
Answer: Depois que clicar no botão e o JS fazer a verificação dos dados, se por acaso não estiver dentro do esperado de um return false na função
Veja esse tutorial na página 211: https://www.caelum.com.br/download/caelum-html-css-javascript.pdf
Comment: Olho agora!!!! Valeu


Get all WooCommerce products within own plugin

Question: Within a plugin how do I get products using wc_get_products()? Or is there another way to do it?
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
      // Put your plugin code here
      add_action( 'woocommerce_loaded', 'generate_product_qr_codes');
}
function generate_product_qr_codes {
$args = array(
    'post_status' => 'publish',
    'limit' => 100
  );
  $products = wc_get_products( $args );
}

The problem is that not products is returned (empty array).
Answer: Try this
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
        // Put your plugin code here
        add_action( 'woocommerce_loaded', 'generate_product_qr_codes' );
    }

    function generate_product_qr_codes() {

        $args        = array( 'post_type' => 'product', 'posts_per_page' => -1 );
        $products    = get_posts( $args );
        echo '
$products:-';
        print_r( $products );
        echo '
';
    }

Comment: Thank you so much. I had no idea it was a post in the db.

How do I mark your answer as the one solving it for me?


Servidor não atualiza a página após alteração dinâmica

Question: Gero uma página através de:
app.get('/conteudo', (req, res) => {
    res.send(conteudojson);
}).

Dinamicamente, o conteudojson é alterado e listado novamente o "/conteudo":
app.get('/conteudo', (req, res) => {
    res.send(conteudojson);
}).

Porém, ao acessar "/conteudo", é mostrado somente a primeira interface gerada e não a alterada com alteração do conteudojson.
Somente depois que eu paro o servidor com CTRL+C e inicio novamente o servidor que a alteração do conteudojson é listada em "/conteudo".
Abaixo o código:
const editarIndicador = (dados, app) => {
    let key = dados.chave
    console.log('Dentro de Edição')
    firebird.attach(optionsInd, function(err, db) {
        var optionsIndicador = {
            "chart": {
                "title": `${dados.editarTitulo}`,
                "subtitle": `${dados.editarSubtitulo}`
            },
            "width": dados.editarLargura,
            "height": dados.editarAltura   }
        let opcoes = JSON.stringify(optionsIndicador)
        if (err) {
            throw err;
            console.log('Erro:', err)
        }
        let SQL = `update
               TBL_INDICADORES
               set DESC_INDICADOR ='${dados.editarDescInd}' ,
               MODELO ='${dados.editarModeloIndicador}',
               BUSCARDADOS ='${dados.editarDados}',
               OPTIONSIND ='${opcoes}'
               where KEY = ${key}`
        console.log('SQL: ', SQL)
        db.query(SQL, null, function(err, result) {
            db.query(`SELECT * FROM TBL_INDICADORES WHERE KEY=${key}`, function(err, result) {
                console.log('Ultimo registro Alterado', result);
                function fx(v) { return v }
                app.get('/indicadores', (req, res) => {
                    res.send(result);
                })
                db.detach();
            });
        });
    });
    return true
}

No console, é mostrado que foi alterado o conteúdo passado pela SQL.
Porém, com res.send(result) não lança o novo conteúdo em "/indicadores", que possui o conteúdo da primeira listagem.

Abaixo o código:
const editarIndicador = (dados, app) => {
    let key = dados.chave
    console.log('Dentro de Edição')
    firebird.attach(optionsInd, function(err, db) {
        var optionsIndicador = {
            "chart": {
                "title": `${dados.editarTitulo}`,
                "subtitle": `${dados.editarSubtitulo}`
            },
            "width": dados.editarLargura,
            "height": dados.editarAltura   }
        let opcoes = JSON.stringify(optionsIndicador)
        if (err) {
            throw err;
            console.log('Erro:', err)
        }
        let SQL = `update
               TBL_INDICADORES
               set DESC_INDICADOR ='${dados.editarDescInd}' ,
               MODELO ='${dados.editarModeloIndicador}',
               BUSCARDADOS ='${dados.editarDados}',
               OPTIONSIND ='${opcoes}'
               where KEY = ${key}`
        console.log('SQL: ', SQL)
        db.query(SQL, null, function(err, result) {
            db.query(`SELECT * FROM TBL_INDICADORES WHERE KEY=${key}`, function(err, result) {
                console.log('Ultimo registro Alterado', result);
                function fx(v) { return v }
                app.get('/indicadores', (req, res) => {
                    res.send(result);
                })
                db.detach();
            });
        });
    });
    return true
}

Comment: Só com esse código que postou não tem como ajudar.
Comment: Entendo LeAndrade. Postarei todo o código abaixo. Mas a minha dúvida é quando utilizo nodejs com expresse e lanço um res.send() há como sobrepor o que foi gerado pelo send()?
Comment: você está usando uma função, precisa dar o return, não é isso?
Comment: Não precisa de return. Ele seta no app a rota. quando uso                 ´`app.get('/indicadores', (req, res) => {
                    res.send(result);
                })`´
Comment: Cara tá bem estranho esse seu código pra falar verdade, vc pega o json atualizado de onde? E quando dá **res.send(conteudojson)** vc simplesmente joga na tela o json, nã está dando para entender.
Comment: Amigo por sua pergunta ser muito vaga, penso que o efeito que voce quer é que quando voce muda seu arquivo o servidor mude tambem na url, para isso voce pode usar a ferramenta [nodemon](https://nodemon.io). Basta seguir a documentação e toda vez que seu sistema tiver alteração nos arquivos o servidor vai ser recarregado.
Answer: Bastou usar o nodemon para atualização dinâmica da página.


Why are random effects coefficients assumed to come from a Gaussian distribution?

Question: I am learning about mixed effects models from here. The linear mixed effects model can be represented as
$$
\mathbf{y} = \boldsymbol{X\beta} + \boldsymbol{Z\gamma} + \boldsymbol{\varepsilon}
$$
Here is my understanding:
Intuitively, I understand the random effect part is some "fine tuning" on fixed effect, i.e., change the intercept and other coefficients by certain amount according the grouping options.
In addition, $\boldsymbol{\gamma}$ is a long vector and has many degrees of freedom, so in order to avoid over fitting we have constraints on $\boldsymbol{\gamma}$, where as stated in the web page:

We nearly always assume that: $\boldsymbol{\gamma} \sim \mathcal{N}(\mathbf{0}, \mathbf{G})$

Why we have the Gaussian constraint? Do other constraints on $\boldsymbol{\gamma}$ exist in mixed effects models?
Comment: https://cran.r-project.org/web/packages/hglm/vignettes/hglm.pdf "The package fits generalized linear models with random effects, where
the random effect may come from a conjugate exponential-family distribution (Gaussian, Gamma, Beta or inverse-Gamma)." @Firebug
Comment: Related (if not duplicate): [Are group effects in a mixed effects model assumed to have been picked from a normal distribution?](https://stats.stackexchange.com/questions/158499/)
Comment: @Firebug I think Generalized Linear Mixed Effects means we use link function to predict binary count etc. variables, instead of changing the $\gamma$
Comment: @Firebug thanks for the link!! the answer helped me a lot. The only reminding part is do we have other constraints on $\gamma$ in addition to normal distribution.
Comment: True, it's an interesting question and one I wouldn't know how to answer if asked. I'm expecting Generalized Linear Mixed Effects modelling to come into play.
Comment: You're right again haha; the obvious case is the logistic one.
Comment: @amoba Seems cool looking at the examples, but I don't think I could find an usage for this machinery so easily. I'll remember this next time I perform mixed effects modeling.
Comment: I would think it's a reasonable assumption because of the central limit theorem.  Estimates within a group are averages for some sub-group, and the distribution of averages usually tends to be normal.
Answer: It's because of the mathematics.
Multivariate normality gives some really slick results. These were the first ones worked out theoretically. When you have normal or gaussian variables then maximum likelihood methods turn out to use least squares methods and only means and covariance matrices are needed to make all the estimates.
The methods of computation worked well when our forebears had only electomechanical desk calculators to work with. There were some shortcut methods to compute covariances and to invert matrices, particularly those that had standard patterns, eg, diagonal or block-diagonal.
Comment: thanks and I agree to your points. But could be more specific? what exactly are nice properties, could you describe it in formula?
Comment: I don't think I can add anything. I recommend standard texts on linear models.


Show that $\int_0^1 f(x)g(x)\,dx=0$ for all $g\in C([0,1])$ implies $f=0$ almost everywhere

Question: Let $f\in L^1([0,1])$ be an absolutely integrable function. Show that if $f$ satisfies
$$\int_0^1 f(x)g(x)\,dx=0$$
for all continuous function $g\in C([0,1])$, then $f=0$ a.e.
First consider the case that $f$ is bounded, let $M$ be a bound of $f$. Notice that $C([0,1])$ is dense in $L^{1}([0,1])$, thus we can find a sequence of continuous functions $g_n\in C([0,1])$ such that $\|g_n-f\|_{L^1}\to 0$. Then the claim easily follows from
$$\int_0^1 f^2(x)\,dx=\int_{0}^1 f(x)(f(x)-g_n(x))\,dx\leq M\|f-g_n\|_{L^1}.$$
I don't know how to show the case that $f$ is not bounded?
Comment: Instead of approximating $f$, try to approximate $sgn (f)$ (its sign) in a bounded way. If $f = r e^{i \theta}$ is complex-valued, try to approximate $e^{-i \theta}$ instead.
Answer: The boundedness of $f$ is not necessary. The fact that $C[0,1])$ is dense in $L^1$ implies the existence of such a sequence $g_n$ independently of boundedness restrictions on $f.$
Now $f$ itself may not be square integrable, but for fixed constant $R>0$ the maximum of $f$ and $R$ is. Your argument proves that at least the latter function is 0 almost everywhere; the arbitrariness of $R$ then leads to the conclusion that $f$ itself is 0 almost everywhere.
Comment: If $f$ is not bounded, how to estimate $\int_0^1 f(x)(f(x)-g_n(x))\,dx$
Comment: OK I have added a paragraph to clarify this.
Comment: I guess that you mean the minimum of $f$ and $R$. $\int_0^1 fg=0$ does not implies $\int_0^1 \min(f,R)g=0$, I don't think the same argument works
Comment: I really mean the maximum, which is a bounded continuous function and therefore 0 a.e. by your argument.
Answer: For any fixed $f\in\mathcal{L}^{1}([0,1])$ we can define a linear functional $\mathscr{l}_{f}:C([0,1]) \rightarrow \mathbb{C}$ by $$\mathscr{l}_{f}(g)= \int_{0}^{1}g(x)\, f(x) \, dx$$ It is easy to see that $\mathscr{l}_{f}$ is bounded, since indeed $$|\mathscr{l}_{f}(g)|\leq \int_{0}^{1}|g(x)| \, |f(x)| \, dx\leq \sup_{x\in[0,1]}|g(x)| \cdot ||f||_{\mathcal{L}^{1}([0,1])}$$ yielding $||\mathscr{l}_{f}||_{*}\leq ||f||_{\mathcal{L}^{1}([0,1])}$
Moreover we can find a sequence of continuous functions approximating $sgn(f)$, thus by using dominated convergence theorem we can actually prove that $$||\mathscr{l}_{f}||_{*}=||f||_{\mathcal{L}^{1}([0,1])}$$
Now the claim says that $\mathscr{l}_{f}(g)=0$ for all $g\in C([0,1])$, but this can only happen if $\mathscr{l}_{f}\equiv 0$ i.e if and only if $$||f||_{\mathcal{L}^{1}([0,1])}=||\mathscr{l}_{f}||_{*} =0$$ i.e iff $f\equiv 0$ almost-everywhere on $[0,1]$
Comment: We can find a sequence of continuous functions approximating $\text{sgn}(f)$, can you say this more clearly? in which norm? $L^\infty$ or $L^1$ norm? Since the space of continuous functions with sup-norm is complete,  we cannot approximate $\text{sgn}(f)$ by continuous functions unless it is continuous.
Comment: Do you mean that we replace  the sequence $g_{n_j}$ by its truncated sequence $g'_{n_j}=\max(\min(g_{n_j},1),-1)$?
Comment: The maximum and minimum of two continuous functions is always continuous, and the new sequence converges to the same limit, so we are done. But the proof is not very natural,  it there a better proof?
Comment: First you say $sgn(f)$ is in $\mathcal{L}^{1}([0,1])$, in which continuous functions are dense. So you pick $\left\{g_{n}\right\}_{n\geq1}\subset C([0,1])$ such that $||g_{n}-sgn(f)||_{\mathcal{L}^{1}([0,1])}\rightarrow 0$. Then we can extract a subsequence $\left\{g_{n_{j}}\right\}$ such that $g_{n_{j}}\rightarrow sgn(f)$ pointwise a.e.
Comment: Now we have a subsequence $g_{n_j}$ converges to $\text{sgn}(f)$ pointwise, but how to deduce that $\int fg_{n_j}$ converges to $\int f\text{sgn}(f)$? It seems that we need the sequence $fg_{n_j}$  to be dominated.
Comment: Well, maybe i should had required a bit more of our $g_{n}$'s. Namely that $||g_{n}||_{\infty} \leq 1$ for all $n\geq 1$. Do you agree that this can be done?
Comment: Well, that works as long as we remain continuous.
Answer: One way is to approximate $1_E$. We shall show that
$$\int_{[0,1]} f1_E\,dx=0$$
for every measurable subset $E$ of $[0,1]$.
$f$ is absolutely integrable,  thus uniformly integrable. That is  for every $\varepsilon>0$, we can find a $\delta>0$ such that
$$|\int_{[0,1]} f1_{E}\,dx|\leq \varepsilon$$
for every measurable set $E$ with $m(E)\leq \delta$.
Now suppose that $E$ is a measurable subset of $[0,1]$. By the regularity of Lebesgue measure, we can find an open set $U$ and a compact set $K$ with $K\subset E\subset U$ such that $m(U\setminus K)\leq \delta$, thus
$$|\int_{[0,1]} f1_{U\setminus K}\,dx|\leq \varepsilon.$$
By Urysohn's lemma,  we can find a continuous function $g$ with $1_{K}\leq g\leq 1_{U}$. Then we have
$$|\int_{[0,1]} f1_E\,dx|=|\int_{[0,1]} f(1_E-g)\,dx|\leq |\int_{[0,1]} f1_{U\setminus K}\,dx|\leq \varepsilon.$$
Then claim then follows by sending $\varepsilon$ to zero. To finish the proof, we can use the following equality
$$\int_{[0,1]}|f|\,dx=\int_{[0,1]} f1_{f\geq 0}\,dx-\int_{[0,1]}f1_{f<0}\,dx=0.$$


Verifying representativeness of a sample, after simple random sampling

Question: I just used the standard formula to determine the sample size of a sample to match the mean of a pupulation with an error margin  of 3 percentage points and with a 90% probability.
I know would like to check that the mean of my sample is actually within the 3% margin of error of the mean in the population.
To do so I am taking the population and appending the sample, identifying observations in the sample with a dummy called sample. Then I run the following regresion:
reg var1 sample
And I am testing wheter the coefficient for the dummy variable sample is less than 3 percentage points. To do so I am using a one sided t test.
But this is only ok when the coefficient of the dummy variable "sample" has the "right" sign. I would like to test the joing hypoithesis that the coefficient of the dummy variable sample is greater than -3 and lower than 3.
Does anyone have any insight on how to do this test?
Thanks in advance.
Comment: I don't follow at all, because you have no need to make inferences about the population mean: you have stated you know it!
Comment: Your question admits a direct mathematical implementation: you know the population mean $\mu$, you know the sample mean $m$, and the margin of error is $0.03|\mu|$. Why aren't you just checking that $|m-\mu|\le 0.03|\mu|$?  That's a calculation with two numbers, nothing more.
Comment: That would make no sense.  A test of hypothesis concerns the population mean $\mu$, not the sample mean $m$.  It uses the sample mean to draw conclusions about $\mu$, that's all. Your question asks whether two *numbers*--the mean of *this particular sample* and the mean of the population--are sufficiently close. If that's what you really mean to ask, then the answer is obtained with a few keystrokes on a calculator, not any statistical test.
Comment: Thanks, I might be missing something, but don't I need to check wheter  |m−μ| is STATISTICALLY significantly less than 0.03|μ|?
Comment: What I mean to say is that: with this particular sample, when making inference about the mean of the population, y get that the mean of the population with 90% probability in a confidence interval. Is the true mean + - 3% in that confidence interval? If this is the case, then the sample is representative with the desired precision...
Answer: 1) Why not just use confidence intervals?
2) For reference, the test you want here (asking whether a constraint on beta would hold or not) is a straight up Lagrange multiplier test, where your constraint function is
$$
\beta_{\mathrm{sample}}^2 - 9 = 0
$$
Comment: Shouldn't there be an inequality in the LM test?
Comment: Yes. And no. Technically the LM test is for whether or not the constraint $h(\theta) = 0$ binds, and the direction of  integration over $\lambda$ determines the direction of the inequality.

Edit: Or, I should say, the inequality determines the direction of integration.


jquery charts from returned json data

Question: I have got json data out of my database using mysql and php and now would like to pass it back using $.ajax function and create a spline charts out of it dynamically any help or examples will be appreciated.  also for multiple blood test the date repeated, how can i show only one date with multiple blood test results.
here is my php code
<code>header('Set Access-Control-Allow-Origin: *');
header('Content-type: application/json');
require_once"conn.php";

if($_SERVER['REQUEST_METHOD']=='GET'){

//recieve credentials from the user
$nhsno = mysqli_real_escape_string($conn, $_GET['pnhsno']);

//check the variables recieved are not empty
    if($nhsno != ''){

        $sql = "SELECT date,name,tname,value FROM examination e, testresults t, examtype ex, testname tn
        WHERE e.patientnhs_no = '$nhsno' and e.etype_id = '1' and
        e.examination_id = t.examination_id and e.etype_id = ex.etype_id and t.tname_id = tn.tname_id ";//create an sql statement
        $result = $conn->query($sql);//run sqlm statement
        $row = $result->fetch_assoc(); //fetch row of data

    foreach ($result as $row){
        $return[]=array('date'=>$row['date'],
                        'name'=>$row['name'],
                        'test name'=>$row['tname'],
                        'value'=>$row['value']);
    }
}
}
$conn = null;
echo json_encode($return);

?>
</code>
and here is my json output
<code>[{"date":"2004-07-05","name":"blood test","test name":"t3","value":"6.8"},  {"date":"2004-07-05","name":"blood test","test name":"t4","value":"29"},{"date":"2004-07-05","name":"blood test","test name":"tsh","value":"0.01"},{"date":"2004-07-05","name":"blood test","test name":"thyroglobulin level","value":"0.5"},{"date":"2005-06-15","name":"blood test","test name":"t3","value":"5.2"},{"date":"2005-06-15","name":"blood test","test name":"t4","value":"30"},{"date":"2005-06-15","name":"blood test","test name":"tsh","value":"0.02"},{"date":"2005-06-15","name":"blood test","test name":"thyroglobulin level","value":"0.5"}]
</code>
Comment: Which library are you using to create the charts...
Comment: canvas jquery charts
Comment: charts.js or any other that I can get a spline chart
Comment: You need to contruct your json response depending on the javascript library that you are going to use...see this sample: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/spline-symbols/
Answer: Because you mixing a lot of things, and you fetch 1 row before the loop.
It should be something like this:
<code>$result = $conn->query($sql); //run sqlm statement
//Do not need this!
//$row = $result->fetch_assoc(); //fetch row of data
//And $row = $result... not opposite.
while ($row = $result->fetch_assoc()) {
    $return[] = array('date' => $row['date'],
        'name' => $row['name'],
        'test name' => $row['tname'],
        'value' => $row['value']);
}
</code>

jquery charts from returned json data


JPG user photos not displaying in Drupal 7

Question: In D7, when I upload a photo to a user profile page, the image displays if the original extension was a *.png file, but not if it was a *.jpg file. Uploading the files places them in sites/example.org/files/pictures, which indicates that the permissions are correct. But jpg files don't diplay on users' profile or forum posts. Instead the words "username picture" is displayed.
In admin/config/people/accounts, enable user pictures is enabled. However, I did not add a existing image field in admin/config/people/accounts/fields.
Basic page, articles and forum has an image field (field_image), with allowed extensions png, gif, jpg, jpeg.
Answer: "username picture" is likely the alt text applied to the image. So it's trying to render an image, but failing because the web server can't find it. If you check the page source, is it trying to show the image with a .png extension instead of .jpg? If not, is the path correct?
If either the extension or the path are wrong, this could be a problem with the template. Perhaps it was hard coded in the past and settings have changed since?


Botched my site upgrade

Question: I tried following the directions drupal provides for upgrading a site, but something went wrong. Now I can't log into the admin page (and the site is in maintenance mode). I'm getting the following errors:
Notice: Undefined index: bluemarine in drupal_theme_initialize() (line 100 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _drupal_theme_initialize() (line 145 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in _theme_load_registry() (line 283 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Undefined index: bluemarine in theme_get_setting() (line 1166 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Undefined index: bluemarine in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Warning: array_keys() [function.array-keys]: The first argument should be an array in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).
Warning: Invalid argument supplied for foreach() in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).

And then a second error:
Warning: Cannot modify header information - headers already sent by (output started at /home1/osuskite/public_html/includes/common.inc:2567) in drupal_send_headers() (line 1018 of /home1/osuskite/public_html/includes/bootstrap.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'osuskite_drupal.cache_token' doesn't exist: DELETE FROM {cache_token} WHERE (expire <> :db_condition_placeholder_0) AND (expire < :db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => 0 [:db_condition_placeholder_1] => 1316109148 ) in cache_clear_all() (line 169 of /home1/osuskite/public_html/includes/cache.inc).
Notice: Undefined index: bluemarine in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Notice: Trying to get property of non-object in template_preprocess_maintenance_page() (line 2433 of /home1/osuskite/public_html/includes/theme.inc).
Warning: array_keys() [function.array-keys]: The first argument should be an array in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).
Warning: Invalid argument supplied for foreach() in template_preprocess_maintenance_page() (line 2436 of /home1/osuskite/public_html/includes/theme.inc).

From what I could surmise, there error is being caused by Acquia Marina. I have downloaded the latest version and put it into the themes directory, but the error didn't change.
Any help would be appreciated. Googling this issue only pointed me to hundreds of other sites with the error instead of a solution.
EDIT: Truncating the SQL caches did nothing.
Answer: Switch to a stock D7 theme - clearing the cache is not enough if there's a bug in your theme as the buggy code is still going to reload.

Either use drush (highly recommended) to change your default theme to another, or...
Use the techniques mentioned here (should apply to D7): http://drupal.org/node/200774 or...
Rollback to your D6 code/database, disable the borked theme, and then retry the upgrade.
Comment: Thank you so much for pointing out drush. I had to disable a few themes and modules, but I have access to my site now!

Botched my site upgrade


Show inverse is well-defined and bounded

Question: I am trying to solve the following problem:
Consider the operator
$$T:L^2(-1,3)\rightarrow L^2(-1,3),\ Tx(t):=tx(t).$$
Let $\lambda\not\in [-1,3]$. Prove directly that $T-\lambda I$ is invertible, and that $(T-\lambda I)^{-1}$ is bounded and defined on all of $L^2(-1,3)$.
$\textbf{My attempt:}$ Since $(T-\lambda I)x(t)=x(t)(t-\lambda)$ it's clear that the inverse would be
$$(T-\lambda I)^{-1}=\frac{1}{t-\lambda}.$$
Furthermore, since $t\in [-1,3]$ and $\lambda\not\in [-1,3]$ there are no issues with singularities of $(T-\lambda I)^{-1}$.
As for showing it is bounded and defined on all of $L^2(-1,3)$ I figured I would start showing that it is defined on $L^2(-1,3)$ since if I succeed with this boundedness should follow from that. $\textbf{Here is where I'm struggling:}$ I want to show that for $x\in L^2(-1,3)$ that
$$\int_{-1}^{3}|(T-\lambda I)^{-1}x(t)|^2\ dt<\infty$$
My idea is to consider some fixed $\lambda\in\mathbb{R}\setminus [-1,3]$. Then I would think that
$$\begin{align*}
\int_{-1}^{3}|(T-\lambda I)^{-1}x(t)|^2\ dt &= \int_{-1}^{3}\frac{1}{|t-\lambda|^2}|x(t)|^2\ dt \\
&\leq\underset{t\in [-1,3]}{\sup}\left(\frac{1}{|t-\lambda|^2}\right)\int_{-1}^{3}|x(t)|^2\ dt \\
&<\infty
\end{align*}$$
I'm not sure whether this approach is right. I assume that since $\lambda$ is fixed and $t\in [-1,3]$ then $\frac{1}{|t-\lambda|^2}$ should attain its supremum within the interval $[-1,3]$ and it should be finite, right? If this is correct, is there a more clever way of doing this?
Thanks in advance.
Answer: For $\lambda<-1$, then $|t-\lambda|\geq-1-\lambda>0$ for $t\in[-1,3]$. For $\lambda>3$, then $|t-\lambda|\geq\lambda-3>0$. So for $\lambda\notin[-1,3]$, there is a positive number $\eta_{\lambda}>0$ such that $|t-\lambda|\geq\eta_{\lambda}$, so $\sup_{t\in[-1,3]}1/|t-\lambda|^{2}\leq\eta_{\lambda}^{-2}<\infty$.


how to implement jquery image gallery in drupal theme tpl.php files?

Question: I am new to Drupal 7's theme system. i am creating a custom theme that have image gallery inside it.but i have no idea for implementing jquery image gallery in drupal theme tpl.php files. i searched many tutorials about image gallery in drupal theme. but most of them just show implementation of image gallery using views and gallery related modules. can anybody know tutorials series that show how to add js files in theme tpl.php file from scratch? and what kind of drupal variables are use for gallery purpose.
Comment: Where in your theme are you trying to place this gallery (in a block, in a node, on every page)? Also - what image gallery plugin are you trying to use?
Comment: i wana implement image gallery without any plugin.as in blue masters theme. http://drupal.org/project/bluemasters
Answer: If you want the bluemasters rotator exactly, you need to copy their javascript and css that apply to the rotator element (image_reel) and install it in your theme. The following instructions would also be relevant for other slideshow scripts with obvious substituions.
First, you need to add the rotator script from bluemasters to your theme. The name of the file is bluemasters.js and is in bluemasters/js/ in the theme folder.
To install it in your theme, you could just add it as a script tag in your page.tpl.php file in your template, ex:

There are much better ways of adding this, using drupal_add_js and page_preprocess functions but this is the easiest way to make sure it is loaded on every page.
Next, you're going to need to isolate the css bluemasters is using to create their slider. From their css file, it looks like all of the css for the front page slider is in one block in the file, starting with the comment 'Front-page slider'
/*
 * Front-page Slider
 */
.main_view { float: left; position: relative; }

...etc.

Grab that and add it to your theme's css file.
If you've got these two files added to your theme correctly, then anywhere the image_reel class exists (with the following structure) on your pages, their code will convert it into a slideshow. The exact structure (from their demo file) is just a list of links like this:

You can add this code in as a block or on a page or in your template directly and it will create the same slider effect.
Comment: @Code_Jamer - correct, there are much better ways of adding this, ex. using drupal_add_js and page_preprocess functions but per OP's question from 3 years ago, this is how you could add it to page.tpl.php.
Comment: @schnippy Why to add the JS script in page.tpl.php file? Aren't tpl.php files just for html and markup? Correct my understanding please.


How to Read a boolean flag pass through CLI in vanilla rust

Question: I want to pass boolean flags to a program in rust.  However, I do not want to use any external crates.  How would I do something like that?
Example:
Command: cargo run -- -t
output: -t flag enabled
Comment: You have to just use Argv.
Comment: I never mentioned any library. Argv is just the way arguments are passed to programs in many languages, C and C++ included.
Comment: please note the word vanilla in the title.  I dont want to use any libaries.
Comment: Oh, a google search turned up a library named argv, or I miss-read it.
Answer: To hand-roll your CLI, you want to use the std::env module which has the args() function:
https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html
use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    dbg!(args);
}

So now all you want to do is whether or not the list of arguments contains -t Let me know if you have trouble with that part.
Answer: You can roll your own argument parsing by simply consuming std::env::args() (skipping the first element) until you run out of elements.  For each element you either alter some state or you signal an error if the argument is unexpected.
Here's a simple example that matches the behavior desired in your question:
#[derive(Debug, Default)]
struct Arguments {
    pub test: bool,
}

impl Arguments {
    pub fn parse<S: AsRef<str>>(args: impl IntoIterator<Item=S>) -> Result<Arguments, String> {
        let mut r = Arguments::default();

        for arg in args {
            match arg.as_ref() {
                "-t" => r.test = true,
                x => return Err(format!("Unknown argument: {}", x)),
            }
        }

        Ok(r)
    }
}

fn main() -> Result<(), String> {
    let args = Arguments::parse(std::env::args().skip(1))?;

    if args.test {
        println!("-t flag enabled");
    }

    Ok(())
}

This basic template can handle a wide variety of use cases.  If using this kind of template, note the following:

You should use a proper error type instead of String.
You can customize the default state of Arguments by removing the Default derivation and implementing Default yourself.
It's a bit more work to handle flags that take arguments themselves (like --foo bar).  You have to manually loop over a mutable iterator using Iterator::next() so that you can pull more elements out of the iterator within the loop.


Calculating the derivative of ${10^x-1 \over x}$ using the limit definition

Question: I've been stuck for the last couple of hours trying to calculate the derivative of $$f(x) ={10^x-1 \over x}$$
With the limit definition of the derivative: $$\lim \limits_{h \to 0} \frac{f(x+h) -f(x)}{h}$$
I just can't get rid of $h$, I think I'm missing an important formula here.
Answer: Follow the limit definition of derivative
$$\begin{align}
f'(x) &= \lim_{h\to 0} \frac{\frac{10^{x+h}-1}{x+h}-\frac{10^{x}-1}{x}}{h} \\
 &=  \lim_{h\to 0} \frac{10^x(x(10^h-1)-h)+h}{h} \cdot \frac1{x(x+h))}
\end{align}$$
Now you can split limit over sum and use $\lim\limits_{h\to 0} \frac{a^h - 1}{h} = \ln a$ to get:
$$\dfrac{10^x (x\ln(10)-1)+1}{x^2}$$
Answer: $\frac{f(x+h)-f(x)}{h}=\frac{\frac{10^{x+h}-1}{x+h}-\frac{10^{x}-1}{x}}{h}=
\frac{x10^{x}(10^h-1)+h-h10^{x}}{x(x+h)h}=\frac{1-10^{x}}{x(x+h)}+\frac{x10^{x}}{x(x+h)}\frac{10^h-1}{h}$.
You know first term converges to $\frac{1-10^x}{x^2}$. For the second term use the same argument as for first part and l'hopital's rule for $\frac{10^h-1}{h}$.As both parts have finite limit, the limit of the product is the product of the limits.
Comment: Then you could argue that $\frac{10^{h}-1}{h}$ is the derivative of $10^{x}$ at $x=0$.
Comment: "and l'hopital's rule for $10^h-1\over h$" - If they're using the limit definition of a derivative they probably haven't learned about L'Hopital.


What scale do you play over V7#9?

Question: In Mark Levine's Jazz Theory Book (section about tritone substituion), he says (paraphrased):
When the tritione substitution contains the 7th in the melody,

you can add a #9 to the chord.

So a Bb7 is replaced with a E7#9, where the #9 is a G, major 3rd G#
Which would give you V7#9 a tritone up from the V in a ii - V - I.
I don't remember him talking about a mode this chord belongs to?
Is this the same as a V7b9 using the half-whole dim scale?
What mode best fits this chord? Assuming "best fit"  is similar to playing Mixolydian on a Dominant Seventh.
Comment: Chromatic, it's got every note.
Answer: The E half-whole diminished scale would work, but it's probably not the first choice unless you're specifically looking for that diminished sound. I'll stick with the example you described, where the progression B♭7 – E♭Maj is being played with a tritone substitution: E7♯9 – E♭Maj. Here are some chords that will sound good over E7♯9:

E Altered scale: E F G A♭ B♭ C D E (this is the 7th mode of F melodic minor)
E Phrygian ♭4 scale: E F G G♯ B C D E (this is the 3rd mode of C harmonic major)
E Diminished scale: E F G A♭ B♭ B D♭ D E
E Phrygian Dominant scale: E F G♯ A B C D E (this is the 5th mode of A harmonic minor)
E Mixolydian ♭9 scale: E F G♯ A B C♯ D E (this is the 5th mode of A harmonic major)

The harmonic major scale is less common but has some really cool sounds. This video provides a nice overview of the harmonic major modes.
Something worth pointing out is that, if you want, you can think of the E Altered scale as B♭ lydian #4 (the fourth mode of F melodic minor). These two scales have the exact same notes. Another thing to mention is that the E Mixolydian ♭9 scale & the E Phrygian Dominant scale don't contain the ♯9 note (i.e., don't contain a G). These scales would still sound good over E7♯9, but if you're sticking strictly to the scale then you'll be missing that ♯9, which is probably in the melody if ♯9 is written into the chord. One simple solution is simply to add the ♯9 into the scale whenever you want to reference the ♯9 note. Doing this could be important if you want to reference the melody. The ♯9 often appears in chord symbols because the note is being played in the melody.
All of these scales would also sound great over an E7♭9 chord.
Comment: There's something wrong with the notes of the "E Diminished" scale in your list. It starts as a half-whole but ends as a whole-half. Apart from that, the diminished scale (whole-half) is not really a great choice over a dominant chord (with the same root) because it has a *major* seventh instead of a b7.
Comment: Thanks @MattL for pointing out the typo! I've fixed it and it should now correctly show the dominant seventh.
Comment: I've also edited to add the phrygian dominant scale, which might be another option (though it doesn't have the `♯9`).
Answer: I like to use the Jazz minor (which is the same as the ascending Melodic Minor, the Major scale with a b3) of a half step above, it always works (e.g. for a D7+9 play an Eb Jazz Minor where the root of your chord is the major 7 of the scale).  Let me know what you think.

What scale do you play over V7#9?


Rails 3 U.S. State Flag Gem?

Question: Is there a gem for rails to grab state flags so I don't have to download them all? Basically what I want to happen is when a user selects submits the form, there is a picture of his state flag next to his order confirmation on the next page. Any suggestions?
Thanks in advance!
Answer: Presumably you have the user's state available as a parameter in the form submission. Perhaps then you can write a little code to use that state to look up a flag at a freely available source such as Wikipedia
i.e.
<code>AL => </code> http://en.wikipedia.org/wiki/File:Flag_of_Alabama.svg
That's a quick and dirty solution.  If you wanted to host the flags yourself, there are plenty of single mosaic images of the flags available.  A little math based on the state can give you offsets into the composite image and then you can slice and dice the piece you want out of it and render it back to the user.

Rails 3 U.S. State Flag Gem?


Equivalent to 'Minimum' meaning 'Closest to zero'?

Question: If we refer to the Minimum of a set of numbers, we mean the lowest number.  Min(12, 7, 18) = 7 and Min(5, -8) = -8.
Is there a technical term for the 'number closest to zero'?  e.g. where fn(5, -8) = 5 and fn(-5, 8) = -5
Similarly, what would be the opposite be (e.g 'number farthest from zero')?
I am aware that there are two solutions in some situations, e.g. fn(5, -5) and that any application of this would have to bear that in mind.  However, this question is just about whether or not there is some existing terminology for this function.
Comment: "minimum/maximum in absolute value"? ... Alternatively, some use the convention "smaller/larger" for comparing size (vs "lesser/greater" for comparing order on the number line). Under that convention, "smallest" and "largest" would convey the idea you describe.
Comment: "distance" or "unsigned distance"
Comment: @Blue I like the term 'absolute minimum'.  If a more official/sourced answer doesn't turn up, that's something I would be happy to use.  Interestingly, my first thought was `Smallest` and `Largest` but they seemed a bit informal which is what prompted me to ask this question.
Comment: @user619894 `"distance" or "unsigned distance"` - That just leads me to ask 'distance from what?'  It would probably need to be 'minimum distance from zero' in order for it to be clear, which is a bit of a mouthful.
Comment: how about  "size"?
Comment: @HappyDog: "absolute minimum" would be my choice, too; but note that it's sometimes considered synonymous with "global minimum" for functions. (See, eg, [this Khan Academy lesson](https://khanacademy.org/math/ap-calculus-ab/ab-diff-analytical-applications-new/ab-5-5/a/absolute-minima-and-maxima-review).) ... BTW, although I'm one of the smaller/larger conventioneers, I wouldn't assume this of a reader. Given that I'd expect to define terms *anyway*, I might go ahead and introduce, say, "$\operatorname{absmin}(a,b)$", explicitly advising the reader not to confuse it with "global minimum".
Comment: @HappyDog: If "smallest" and "largest" are too casual, you could always go with "smallimum" and "largimum". Latin suffixes make everything seem formal. ;)
Comment: Also the 'magnitude' of a number refers to how far it is from zero. So you can say 'the number with the largest magnitude' and 'the number with the smallest magnitude'. As you noted, these need not be unique, but you can then talk about e.g. an element having minimum magnitude.
Comment: @Blue In the end, I went for one of your suggestions - Absolute Minimum/Maximum, which I think has a good foundation in the mathematical term 'Absolute' whilst also being neatly descriptive in an informal way.  If you want to write an answer containing this suggestion then I will accept it.  If I don't hear back after a while then I'll write my own answer, so that I can close this question down.  Cheers.
Comment: @HappyDog: Darn. I was rooting for smallimum/largimum. :) ... Go ahead and write-up your own answer, so we can throw more reputation points your way.
Comment: @Blue - Done!  (...plus a bit more text so I'm allowed to post the comment)
Answer: For the number closest to 0, smallest absolute value, or smallest norm.
For the one farthest from 0, largest absolute value, or largest norm.
Comment: That sounds promising.  Can you cite a source for those being used as formal terms, or are they just some suggestions of your own?
Comment: My own suggestions.  However, the definition of "absolute value" is pretty unambiguous, and I don't think there is any ambiguity from the choice of norm for real numbers, so it seems concise and clear to me.
Comment: I didn't pick this answer in the end, but I think - in the absence of anything official - it is a good alternative that some people might prefer.  +1
Answer: Note: None of the suggestions in comments or answers include references that indicate that there is an established term for this, so in the absence of anything more official I will be adopting the names described in this answer.  I would consider changing my answer if anyone is able to post any alternatives which include appropriate citations.

Thanks to various discussion in the comments, in particular a suggestion from @Blue, I eventually settled on the following terms:

Absolute Minimum - In a set of numbers, the number closest to zero, regardless of sign.
Absolute Maximum - In a set of numbers, the number furthest from zero, regardless of sign.

These fit with the standard definitions of these terms in the sense that the result is the Minimum (or Maximum) of the Absolute values for each number in the set, and therefore feels like it fits well with standard terminology.
Note that Absolute Minimum is sometimes considered synonymous with the Global Minimum for functions, for example in this Khan Academy lesson.  If you are in a situation where this might cause confusion (or in any context where you would expect to define your terms) you should advise the reader that Absolute Minimum should not be confused with Global Minimum.


How do I add the "- Any -" option for the published status on exposed filters?

Question: I need to add the - Any - option for the published status, on exposed filters.

I can't use it, as when I try to add it, I get the following error.

You must select a value unless this is an non-required exposed filter.

How can I add - Any - as option?
Answer: As the screenshot shows, the filter is set as Required. This means the users need to select a value for that filter that, being a filter for the published status, can only get Yes and No as values.
If you want to allow users to select - Any - as value for that filter (which isn't really a value for the published status, but a value that tells the view not to filter the nodes basing on their published status), you need to deselect the checkbox that is shown to the left of Required.


Como criar Pojos com as anotations de maneira rápida?

Question: Tenho um banco de dados com muitas tabelas, tenho que criar o Pojo de cada tabela? Se sim, tem como automatizar?
Answer: Projeto Web, brother?
Se estiver usando JPA com provedor Hibernate, a IDE Eclipse for Java EE tem uma funcionalidade para criação de entidades a partir de tabelas, basta selecionar o projeto com o botão direito ir em JPA tools e escolher Genereted Entities from tables. Apartir disto, abrirá uma janela de configuração para o procedimento. Claro, seu projeto terá que estar conectado ao banco de dados em questão, o persistence.xlm também deverá estar de acordo.
Answer: Sim, pelo Eclipse você pode fazer engenharia reversa da sua tabela para uma entidade JPA.
https://www.eclipse.org/webtools/dali/docs/3.2/user_guide/tasks007.htm