Is F Lydian mode in the "key" of C Major?

Question: In most cases (if not all), a piece of music without sharps or flats in the key signature, would be considered in the key of C major or A minor.  This question assumes the context of Western Music since that is the only type I know much about.
The key signature defines which notes (in the absence of accidentals) are available to include in the composition.  So obviously if the key signature has no sharps or flats, any note written on the staff will be one of C D E F G A or B (all natural), which are the notes in the key of C major and also its relative minor (A minor).
But if we change the tonal center from C to another note, without changing the available notes, then we are in a different mode.  For example if we start on F and play a scale using all the notes in C major (resolving back to F), I believe that would be considered the F Lydian Mode (even though the notes are all common to the C major scale and derived from the key of C major).
So does that mean that F Lydian Mode actually belongs to the key of C?  Similarly does each mode in the chart below (all comprised of the notes found in the key of C major/A minor) belong to the key of either C major or A minor?  Certainly the key signature would indicate as much.
I know that the Aeolian Mode is equivalent to the A natural minor scale. This makes me believe that modes must be defined as being derived from either a major or minor parent key.
Comment: Interesting question! I ponder as to whether a piece, say, in F Lydian, should have the key sig. of the parent (C) or the key sig. of F (a Bb) with all the Bbs in the tune marked as B naturals.
Comment: @topomorto most musical terms are overloaded like major, minor, and even the notes. IMO key is a lot easier to convey then the diffrence between the concept of a note used in a set (like the notes of a scale or chord) and  notes on the staff.
Comment: @topomorto every subject has terminology.  It's needed to convey the subject matter. Math and science  has similar overloads especially when you get into the different subsections of each and music is not alone with this issue, but even though you may not like you should use these terms else you get what we had with the "tonal centre" question.
Comment: @ToddWilcox I clicked the link and found that the top rated answer contained this "as opposed to the C-minor scale, or one of the other scale-modes based on C".  Which is the basis of my question - is F Lydian one of the scale modes based on C?  Or is it based on F?  Certainly this question has stimulated many lively discussions ;-)
Comment: I personally try to avoid using the word 'key' *at all* if I want to communicate clearly and unambiguously - it's *overloaded* (meaning different things in different contexts), and in some of those identifiably distinct meanings is still *vague*.
Comment: @Dom true about many terms being overloaded... you'll have noticed before that I'm not such a fan of a lot of 'conventional' music theory terminology, perhaps partly for that reason! I do agree with your answer here BTW.
Comment: I think this is related reading: http://music.stackexchange.com/questions/6445/what-does-it-mean-to-write-a-song-in-a-certain-key
Comment: I think there are different points of view, and my point of view is that F Lydian is a separate key from F minor or F major and all three are based on F. Just because A minor and C major share the same notes, doesn't mean you would consider A minor to be "based on C", right?
Answer: No. A key* is not just a set of notes, it tells you the tonal center**  of a piece and the expected harmony and melody of the piece. If that was the case we wouldn't even distinguish between major and minor as they have the same set of notes as do all 7 modes of the diatonic scale. How you use your harmony and melody will define the key and tonal center by making one note sound like it is more at home than the others.

Take this simple progression that would be more at home in F Lydian rather than C major:

FM7  Dm   Em   C

In general the harmony of Lydian and Major(Ionian) are pretty similar with the distinction being the augmented 4th (in this case B) which will typically come out in the melody and harmony. We start on an F chord and we end on C which takes us right back to F so we feel F as the tonal center. In analysis we would denote this as:

FM7  Dm   Em   C
I7   vi   vii  V

If we truly perceived  C as the tonal center in this progression the analysis would yield:

FM7  Dm   Em    C
IV7  ii   iii   I

We're now looking at the progression as in "the key of C" and it may work in some contexts, but calling F the tonal center makes much more sense. You would want to end your progression on an F major chord.
*Typically when you talk about a key you talk about tonality and typically use the terms major and minor rather than modality and refer to the modes themselves, but the idea is still there.
**Even the phrase "tonal center" when apply to modes is a little fuzzy strange to apply to modes as the tonal refers to tonality, but for continuity I'll use tonal center to describe modes too. Here's an in depth explanation about tonal vs modal for more background about the difference.
Comment: @Dom Two points to mention: 1.) I think if you play through your progression, you won't hear it relative to "F" as a tonal center. The raised 4th incidentally turns the "G" chord into a secondary dominant, which naturally leads to C. So, I don't buy that your progression is "more at home in F Lydian".  2.) I think you should make the distinction between "keys" and "pitch collections". While you're correct that the two are not the same key, the OP's basic premise is actually correct; despite different tonal centers, they share the same pitch collection (F Lydian *is* after all a mode of C.)
Comment: @ToddWilcox Absolutely not; my point was that just because you analyze a piece a certain way on paper using your eyes, doesn't mean that it actually *sounds* the way you've analyzed it. The whole point of analysis is to explain why music sounds the way it does, but too many people get caught up in what it looks like. This is dangerous because you're operating in a vacuum then, and you'll twist the music to justify your analysis. Much music has been written with no existing key or even pitch centers. We need to make sure the notation matches the music, not our personal goals.
Comment: @Dom TBH, I think it obscurs your original point rather than validating / supporting. Just because something *looks* a certain way doesn't mean it necessarily *works* that way. On paper, I could let your progression slide by in F major, but if I *listened* to it, I wouldn't feel right leaving it that way. Since music is ultimately a "heard", we must defer to our ears for guidance. Following paper-vacuum logic, you could argue that there aren't in fact *any* modes and none of it matters anyway; what's to stop you from analyzing it in G mixolydian or something else to justify your reasoning?
Comment: @RockinCowboy In Western Equal Temperament, there are 12 pitch classes. In strictly mono-tonal music, yes, there are 12 possible pitch-class-centers.
Comment: @jjmusicnotes I was in the middle of major edit. See if that address some of your concerns I barely scratched the surface of what I want to write. Also I always find Lydian always comes though more with the melody rather than progression so a different example may be needed.
Comment: So there are actually only 12 notes in Western Music and they key is determined by the tonal center.  So there can only be 12 different tonal centers so only 12 keys?  Is that correct?
Comment: @jjmusicnotes Are you suggesting that our ears will always want major or minor tonality and trying to have a piece in F Lydian just won't work, our ears will force it into either C major or A minor? Or F major?
Comment: @jjmusicnotes - your second comment: maybe the point of 'is it D Dorian, F Lydian, G Mixolydian etc.'  is that although the notes belong to C major (or Ionian), the 'home' is D, F, G etc. Although often, to me, a piece in a mode made from the C major notes  feels like it needs to come home to roost on that C...
Comment: @Tim, it all depends on what you actually do with it. If the melody strongly emphasises, say, A, E and B using a white key collection, if the harmony primarily comes to rest at structural downbeats on E minor, if the modulations (assuming the piece does modulate) are to minor-like A or B, or a major-like G (except that certain melody notes in these keys might be unexpectedly flat), then it might be safe to assume that E is the tonic with a predominant Phrygian modality, and, if E *has* been successfully established as tonic, then ending in C *will* sound wrong. (_more_)
Comment: This isn't really any different than establishing A minor, which *also* uses the white key collection (and note: I don't think anyone really believes that A minor necessarily pulls to a C tonic). When you write tonally, you are, in effect, *creating* tonality afresh in each piece, because your musical ideas (and the constraints they impose) will determine the hierarchy of relationships that you use to establish the tonality. If you unfold the hierarchy implicit in your idea well, then you **will** successfully establish the tonality. (_more_)
Comment: Mode can be part of the musical idea, and modes do place constraints on how you establish the tonality - this is equally true of C major as it is of G Lydian.
Comment: @Patrx2 - did you mean F Lydian / C major? Certainly A minor often doesn't pull to C major - but take Fly Me to the Moon, and it actually does. Probably because of the use of G#, non-existent in C major, A minor is regarded as a different key?
Comment: Yes, sorry, I did. When I was talking about E Phrygian earlier, I had G *Mixo*lydian in mind (as the relative), and flubbed that last comment as a result. However, it takes more than sharping G to establish A minor - it takes setting up a web of root relationships in the harmony, it takes emphasising certain melodic degrees, and it takes emphases on A on structural downbeats. You can actually do a good job of establishing A with fairly minimal reliance on the leading tone, provided the other supporting elements are strong enough. (_more_)
Comment: Conversely, most modes *do* have mutable tones in a similar fashion to the minor. It is possible in Phrygian to raise the leading tone, provided you do it in an Italian or French sixth, which pairs it with ♭2 in the bass (if you want to preserve the sense of the mode). Note that this is a predominant in the minor (a fourth below), but works very well as dominant substitute in Phrygian. If you want to get into this further, I suggest maybe a chat room - we might well outstay our welcome in the comments.
Comment: @Tim, Minor a *fifth* below Phrygian. It's late here, and I'm losing track...
Comment: Thanks for all the info. Sorry I didn't come back - seems if '@Tim' isn't there, I only get to read comments by chance.
Comment: Wow - your answer generated quite a discussion!  I am gaining a much better understanding of the difference between key and mode and I like your example of how the harmony helps establish the mode - not just the notes used in the melody.
Answer: No.
My college music theory professor always explained it this way: Key only means tonal center. If you say it's in the key of C, then you have to specify whether the mode is C major, C minor, or some other mode. He would insist that there is no such thing as the "key of C major". The correct way to say that is this: the key is C, and the mode is major.
So in your example, the key is F and the mode is Lydian. The correct key signature for this mode is a clef with no flats and no sharps. My professor would never refer to this key signature as the "Key Signature of C" or the "Key Signature of A Minor" because he wanted to make clear the distinctions between the slightly ambiguous ways that these terms can be used.
Comment: Although *Key only means tonal center* would be neat, I'm not sure if it quite agrees with the way people actually use the term 'key' - people do talk about major and minor keys, i.e. saying that the keys themselves are major or minor.
Comment: If i'm in the middle of a jam session and I ask "what key are we playing in?" and the answer is just "Eb" with no "major", "minor", "lydian" or whatever after it, I still don't know what to play. From that point of view, I can't use such a simplistic definition of "key" as your college music theory professor. Add to that the fact that when I was growing up, always listening to the classical music station, when they announced what they had just played or were about to play, they usually ended with "in the **key of  **". So I'm programmed to think the center alone is not the key.
Comment: So the notes that would be in the key of F change according to the mode?  Not the same notes?  I suppose that might be correct if you consider that the notes in the key of A in major mode are not the same notes in the key of A in minor mode.  So each key could be comprised of at least 7 different sets of notes and the key signature for the key of F would be different depending on the mode?  I think that is what you are saying and though it seems counterintuitive on it's face - I actually think I am inclined to agree with you.
Comment: I think you've got my intent. This is my old professor's way of impressing upon us the importance of recognizing the tonal center, and then understanding that a composer can build different scales and modes on that tonal center.
Comment: So there are really only 12 keys in western music and each of these has 7 or more modes?  If each key was limited to only 7 modes that would be 84 possible key/mode combinations instead of the 24 commonly thought of - each having one of 15 different "key signatures"?  It's an interesting but perhaps enlightening way to look at it.
Comment: This makes sense. If, at a gig, someone says the next number is 'in C', it's not enough information. We need 'major', 'minor', 'Lydian',etc. to qualify what notes will actually be involved.
Comment: Although, generally speaking, saying the letter name alone presupposes it's major.
Comment: @Tim, OK, that's my point. Generally speaking saying the letter name alone does indeed presuppose that it's the major mode. My professor never failed to point out that this is not the case 100% of the time; for example, when somebody says "F" but they mean "F Lydian".
Comment: @topomorto - do you think that would encompass, say, Dorian, as being minor? Or would it be only applicable to the 'real' major and minor?
Comment: @Tim If a piece truly stuck to the Dorian, I might expect it to be described first and foremost as Dorian - and yet Dorian is seen as one of the 'minor modes', and an answer to http://music.stackexchange.com/questions/16248/understanding-minor-key-harmony states that in minor tonality, all combinations of 6th and 7th scale degrees (from the various forms of the minor scale) can be used. If you were to agree with that, a piece specifically in C Dorian could also be described as being in C minor in a more general sense.
Comment: After reading all the other answers and comments - I am beginning to understand that F Lydian is not a mode of C major just because it's notes are derived from C major.  It's actually a mode of F because F is the tonal center.  I just gave you a plus 1 because I have finally realized that you are correct.
Comment: @RockinCowboy, exactly. And this idea that F Lydian is a mode of F goes all the way back to the Gregorian Chants circa the 8th Century AD. I should have mentioned that in my answer. https://en.wikipedia.org/wiki/Gregorian_chant
Comment: You can always edit your answer for the sake of future visitors to the site who stumble upon it 5 years from now after all the comments are purged.
Answer: F lydian has the same key signature as C major (in other words it has the same notes, the same number of sharps and flats, in this case zero.)
It also has the same key signature as A minor.
However all three are different keys, because they have different tonal centres. A key is named after the note it tends to gravitate to.
A passage in A minor clearly sounds different to C major. And F lydian sounds different again.
Another way of looking at it is that F lydian gravitates towards F, but differs from F major in that has a B natural instead of a Bb (sharpened 4th.) But the previous way of looking at is to me more useful when it comes to drawing out a scale (I play guitar.)
You need to learn to think both in terms of relative keys (which have the same notes) and parallel keys (which have the same tonal centre.) It's true that relative keys can be difficult to distinguish and somewhat subjective: For certain pieces, one person might say it was in C major and another in F lydian (though there are others in which everyone would be unanimous that it was F lydian.) On the other hand, parallel keys, because they have different notes, are far more distinct: nobody is going to confuse F lydian and F minor.

Here are a couple of songs by Lou Reed. Both are based on an insanely simple chord progression, one with C - F and the other with C# -F#  Decide for yourself if they are major or lydian. In my opinion, it is the pull towards F in these songs that prevents this very simple progression from being boring.
Walk on the Wild Side

Heroin
Comment: I'm beginning to think a piece of music that establishes itself firmly in F Lydian would more likely be considered a mode in the key of F as opposed to the a mode of the key of C - even though all the notes are from the key of C major.  Plus 1 for a very simple explanation of your point.
Comment: @RockinCowboy Thanks. I added a couple of examples. For me, Walk on the wild side is definitely F lydian, everything ends on an F. What do you think? BTW, any idea how to reduce those thumbnails to a reasonable size? I wasn't expecting to see them at all.
Comment: Thanks Steve - I will listen to your examples.  I don't know how to reduce the size of the thumbnails - sorry.
Comment: I feel a pull back to C (C# in second example) on those songs.  They seem to want to resolve back to C but I can see where there is some ambiguity there - like it could be either.
Comment: The fact that a piece of music has one flat in the key signature does not mean that the majority of B's are flatted, or even that any are flatted.  There is a strong convention that pieces in major-ish modes should use the key signature of the associated Ionian mode, along with appropriate accidentals, and those in minor-ish modes should use the key signature of the associated Aeolian mode, likewise with accidentals.
Comment: @supercat underrated point.  If I were to write a piece that was pretty much just straight F lydian, I'd probably still write 1 flat in the key signature, as a way of saying "it's in F".  Similarly, for  G Dorian or G Phrygian, I'd write them with 2 flats in the key sig, and an accidentals for E natural/Ab.  Only exception to this is for really really strict modal music played on-non chromatic instruments, with no real functional harmony,  *then* maybe I'd have the key signature as representing the "note palette". Usually though the key signature represents the "key centre" not the "palette".
Comment: Another scenario occurs with pieces in D melodic minor where the sixth scale degree only occurs in rising passages.  There was one like that called something like "Dance of the Spooks" in my piano book.  Although D minor has one flat, an ascending D melodic minor scale is D E F G A Bnat C# D.
Answer: Key signature and note collection notwithstanding, a musical composition that is written in F Lydian is NOT a mode of the key of C major - even though the key signature would be the same as for C major and all of the notes in F Lydian are also in C major.
In fact, the so called "key signature" does not always tell you what key a musical work is written in.  And just because all of the notes in a composition can be found in the C major or A minor scale, the piece may not necessarily be in the key of C major or A minor.
To prove this, let's look at the key of C major and A minor.  I think it would be hard to argue that those two keys are the same.  They are different keys altogether even though they share the exact same notes and the exact same key signature.  The tonal center of A minor will be an A note and the tonal center of C major will be a C note.
It may also be helpful to consider that the key signature for C major is different than the key signature for C minor.  Even though both keys share C as the tonal center – they have different notes and different key signatures.
Although the key signature will often provide a clue as to what key a musical work is written in, it is not the way to tell for sure.   The key to determining the key (excuse the pun) is to find the "tonal center" of the composition.  In other words, which note do the rest of the notes revolve around, start with, or want to resolve (gravitate)  to.  Often the best clue is in the harmony or chord progression which may lead you back to the tonal center.
The bottom line is each key has many different modes.  You can refer to these modes based by the Greek names such as Lydian, Phrygian, Dorian and so on.  Or you can say that it is major, natural minor, melodic minor or harmonic minor.  C major, C natural minor, C harmonic minor and C melodic minor are all modes of the key of C because they all share the same tonal center - C.  However they all have a different set of notes and a different key signature.
What determines the key of a piece is not the notes it contains or the key signature, but the note that establishes itself as the tonal center.
So F Lydian, despite having all the same notes as C major and sharing the same key signature as C major, is actually a mode of the key of F because F is the tonal center.
Comment: @topomorto  F Lydian is a mode of F.  It's not a mode of F major or C anything.   C Lydian, C Dorian, C minor, C major are all modes of C.  All twelve chromatic tones in the Western Music alphabet each can have many modes which can also be construed as different keys.
Comment: @ScottWallace  Complex indeed.  Life and music.  But I do believe music makes life more enjoyable.  Don't you agree?
Comment: Looks good to me - the only thing I'm not quite sure about is that you've said that (a piece in) *F Lydian is NOT a mode of the key of C major*, but you've also said *each key has many different modes*. How are those statements consistent?
Comment: A lot of the confusion here is due to to the hegemony of "major" and "minor" as the only "godgiven" modes.  F Lydian has the same tones as C major; but that doesn't mean it's somehow "defined by" or "subservient to" C major.  Life is complex, and so is music.
Comment: @RockinCowboy- c'mon, do you even have to ask?  Without music I would curl up and die.  Well, maybe not right away, but yeah: music does make life more enjoyable.
Comment: @ScottWallace  I feel the same way about music.  It's the one thing I would never want to have to live without.  I could give up most other things - but as long as I can still create, perform and enjoy music, I will be happy to stick around!
Answer: To me, "mode" is just a word we use instead of "scale" for certain scales. From that point of view, you might as well be asking me if "A minor actually belongs to the key of C major".
To me a key is both a scale and a tonal center. A different tonal center means a different key.
When you start a piece in A minor and modulate up to C major, you are now playing in a different key. From that point of view, F lydian and C major are two distinct keys that just happen to share the same notes (in equal temperment), the same way A minor and C major are different keys that share the same notes.
Comment: I did not think keys and modes were the same thing.  But I could be wrong.
Comment: See my comment to Dom's answer.  According to the idea that the tonal center defines the key, there can only be 12 possible keys in western music because the tonal center could only be ONE of the 12 possible notes (modulation notwithstanding).  But if you take each of 12 possible tonal centers - and each can have 7 or more modes, would that not mean there are more than 12 key/mode combinations?  Or are many of them redundant like the key of F# and Gb?  The clearer things get the more confused I get.
Comment: In equal temperament F# and Gb are the same thing but that still leaves us with 12 possible tonal centers (7 white keys plus 5 black keys on the piano). Then there are seven modes so you could look at it as 84 different possible keys, except the seven modes are not the only possible scales. When you add in other kinds of scales and even possibly microtonality the number of potential keys becomes huge. This is assuming that by "key" we mean a tonal center **and** a scale pattern (or two or three, depending on what exactly you're doing). That's just one way to look at it but it works all right.
Comment: @RockinCowboy If you consider A minor and A major to be two different keys, then you are seeing the scale pattern as part of what makes a key. If you see A major and C major as two different keys, then you are seeing the tonal center as another part of what makes a key. You could take the view that a scale defines the chords used in a key, or instead that that chords that make up the tonality define a scale. Either way, you have a center and a pattern of chords/scales based around that center and that gives you a key. If the pattern is a "mode", it's still a pattern around a tonal center.
Comment: @ToddWilcox - in your second sentence, last comment, did you mean 'If you see A minor and C major...'?
Comment: @Tim No. I meant to show that changing tonal centers (from A to C, in this case) while keeping the same note pattern/scale (major, in this case), is a key change, just as changing note pattern/scale while keeping the same tonal center is also a key change.
Comment: @Tim I thought the same thing and it seems to better illustrate the point to point out that Am and Cmaj are different keys even though they share the same notes.
Comment: @RockinCowboy I was taking it for granted that everyone considers A minor and C major to be different keys. I can't really see how any definition of "key" would be both meaningful among musicians and also consider A minor and C major to be the same "key". One important point: A minor and C major are assembled from the same set of pitches **in equal tempered tuning**, but not necessarily in other tuning systems. So from a more general point of view, they don't even always share the same notes!
Comment: @ToddWilcox It's becoming a little more clear.  Mainly because I read your last comment as if you wanted to point out that even though A minor and C major share the same notes, they are considered different keys.  I'm going to upvote your answer because you make a valid point.  I was not sure I agreed with the idea that "mode" could be considered another word for "key" but now I see your point and agree.
Comment: @ToddWilcox I think we were typing at the same time.  I did not see your last comment until after I posted mine.  Yes I agree that Am & Cmaj are different keys even with the same notes.
Comment: @RockinCowboy Whoa, I wrote my answer late at night and didn't re-read it until just now. It was probably really confusing because I mixed up "key" and "scale". Badly. Edited to fix that.
Answer: Interesting question, Cowboy. From looking at sheet music for 'Scarborough Fair', which is Dorian mode, the convention seems to be to use the key signature of Em and to use an accidental to mark the c#.
I was taught in college that a 'key' is defined by the use of a dominant 7th chord. Minor dominants indicate a mode.
Interestingly, 'Walk on the Wild Side' sounds lydian to me, but uses a C major dominant, but C dominant 7 does not work.
I was taught the some music is ambiguous in that it is subject to more than one correct analysis. The point is to write stuff that people like. Have fun!! ;-)
Answer: let's simplify this and first answer a couple of basic questions about modes and modal music;
(1) All music is modal
(2) A true mode (other than Maj./Ionian or natural minor/Aeolian ) are
    limited to 5 tones and only to 1 octave range, from the tonic to the
    dominant. In other words, 5 tones are not enough to establish either
    major nor minor tonality.
(3) All modes (other than Ionian and Aeolian) have no definite key
    center, the modes can only tend towards major or minor
    characteristics, with the exception of Locrian- which has neither
    maj. nor minor character, such as the diminished modes or all
    symmetrical scales for that matter.
(4) The "key" / characteristic of a mode or modal piece is therefore
    noted by it's own unique modal name- regardless if it's built from
    the parent scale of C-major. In this case F Lydian belongs to the key
    of C-Maj., but only in the sense that it is built from and is the 4th
    of the 7 modes of the C Maj. scale but is not in the "key" of C-
    Major, it is in the mode of F Lydian, F being the tonic note (primary
    tone) that you would be resolving to- in addition to the 4th tone
    (the subdominant) being raised 1/2 step in comparison to the C major
    scale.
(5) Diatonic Harmonic theory and analysis is not to be confused with
    modal Harmonic theory and analysis.
Comment: (2) - I thought the 3rd defined major or minor, as in Dorian and Phrygian as well as Aeolian would be construed to be minor. All 3 accepted minors have the same first five notes, so surely that's enough
Comment: " ...modes (other than Ionian and Aeolian) have no definite key center, the modes can only tend towards major or minor characteristics"   So are you saying that a piece in F Lydian mode is not in ANY key?  "... but is not in the "key" of C- Major, it is in the mode of F Lydian, F being the tonic note (primary tone) that you would be resolving to ..." - So if the song is in F Lydian mode is it in the key of F?  Or just not in any key?
Comment: *A true mode (other than Maj./Ionian or natural minor/Aeolian ) are limited to 5 tones* - can you clarify what you mean?
Comment: Answer to Q.-Nr.2 (Rockin Cowboy): The modes do not have a "Key" signature, that is why it is called a "mode" and not a "key"- if you want to think in terms of "keys" it would be in the key of F Lydian- although there is no actual key center for any of the modes, there is only a tonic (main note) in a mode that one can resolve back to. So, the answer is that there is no key, there is only a reference note that signifies which note the mode will be encompassing.
Comment: Answer to Q.-Nr.3(topo morto): Yes, a true mode (as defined in music theory, ref: Harvard Music Dictionary-etc., also as defined in general) consists only of the tonic to the dominant intervals (1-5) of the normal diatonic (7 tone) scale. In a sense it is only a large fragment of a normal diatonic (aka: heptatonic) scale, not to be confused with a pentatonic scale or the pentatonic modes.
Comment: Con't answer to Q.-Nr.3(topo morto):Of course you can extend the modes by adding the hypo and hyper notes to it or even combine it with other harmonic complimentary modes or scales to extend the mode. In any case the frame work is still the basic 5 notes that belong to any given mode.
Comment: Answer to Q.-Nr.1 (Tim): there are 3 important intervals that determine if a scale is 100% major or minor in relation to it's tonic note;  3rd / 6th / and the 7th. You need at least 7 intervals in relationship to the perspective tonic note in order to determine the true tonality of a scale. So the Dorain, Phrygian and Aeolian have a minor 3rd + a  natural 4th and a 5th degree and therefore it is not enough to create a complete or true minor, or for that matter major scale structure. That is why all the modes only "tend" to be major or minor.
Comment: Con't to Q.-Nr.1(Tim): In modern usage, we have added or extended the modes from the tonic note to the 1st octave, or in other words from the first 5 notes (tonic to the dominant) and added 2 more unique tones from the Hypo-mode extension, for example: from the dominant of C to the dominant ocatve of G, including all the octave notes from the first 5 + the 2 new tones: C-G= Ionian mode + G-D= Hypo-Ionian mode, which then extends the mode out to 7 notes + all their octave notes. Now the modes are simply written (notated) from the tonic to the octave (i.g. C Ionian: C-C).
Answer: http://www.studybass.com/lessons/harmony/keys-in-music/
According to the above website there are only 24 keys in music, 12 major and 12 minor. Therefore, technically, F Lydian is in the key C major, with F as the tonal centre. I get a sense that a key here is referred to a as collection of notes available (except accidentals) to build harmony and melody. I think this makes sense. Essentially, it's just a label, as long as we understand the crux of it here is no point splitting hairs!


Pitches on AP Music Theory examination

Question: I was listening to some sample questions for the Advanced Placement Music Theory examination, given to high schoolers in the United States. I noticed that on a lot of the listening examples, especially the ones featuring piano, the listening track would be consistently one semitone lower than the notated answers. This throws me off when I'm trying to transcribe.
These samples are from 1998. Is this practice still followed in today's exam? Does anyone know why they would do this?
Comment: Maybe it's a 44100 vs 48000 Hz sampling rate error, or an error with tape speed when transferring from analog to digital. :) Let them know of the error.
Answer: I can't speak to past exams, but current exams will give everything at the correct pitch. Among other things, this prevents unduly confusing students with absolute pitch.
Within the curriculum, AP suggests their instructors include something they call "Tonality Switch," where students sing a major melody in minor, or switch from singing in scale degrees to in solfège, etc. But in all of these, the tonic pitch is kept constant.

Pitches on AP Music Theory examination


Approximating the square root of two with fractions

Question: I would like to prove that there exist only finitely many $m, n \in \mathbb{N}$ satisfying $$\left | \sqrt{2} - \frac{m}{n} \right | < \frac{1}{4n^2}.$$
Any thoughts?
Thank you for your help.
Answer: $$|\sqrt{2} - \frac{m}{n}| < \frac{1}{4n^2}\\\implies
|\sqrt{2}n-m|< \frac{1}{4n}\\\implies
\sqrt{2}n-\frac{1}{4n}<m<\sqrt{2}n+\frac{1}{4n}\\\implies
0<|(\sqrt{2}n-m)(\sqrt{2}n+m)|<\frac{1}{4n}(2\sqrt{2}n+\frac{1}{4n})=\frac{\sqrt{2}}{2}+\frac{1}{16n^2}<1.$$
But $|(\sqrt{2}n-m)(\sqrt{2}n+m)|=|2n^2-m^2|$ is an integer, a contradiction.


What does 'foreach(1..4)' mean in Perl?

Question: In Perl, what does foreach(1..4) mean?  Specifically the two periods.  I've been having trouble finding an answer.
Comment: http://perldoc.perl.org/perlop.html#Range-Operators
Comment: This perlmonks post: http://perlmonks.org/?node_id=78752 should help you learn to navigate Perl's docs.
Comment: @admdrew Haha yes unfortunately I've been thrown into the language and have to work on a script that is much higher then my current understanding of the language.
Comment: I've looked in the perl cookbook and on the API.  Just having some trouble getting used to the lingo of perl coming from python.
Comment: @Matt Just my advice on the OReilly cookbooks (I have a few, including the Perl and Python ones) - they can be great resources, but aren't super helpful while you're just starting to learn the language.
Answer: In Perl, 1..4 produces 1 2 3 4 so you're looping through all the numbers from 1 to 4, assigning each value in turn to $_.
Comment: Also, when the list of a `foreach` loop is a single range operator, there's an optimization that avoids creating an actual list (so `foreach (1..1000000)` doesn't create a million-element list).
Answer: .. is one of the Range Operators
Answer: It is known as the range operator.
It creates a range between the two operands...
Comment: In list context it is the range operator.  In scalar context it is the flip-flop operator, and works totally differently.
Answer: foreach(1..4)

It means your loop runs from 1 to 4
or
creates a range between the two operands
Example equals to
my $min = 999;
foreach $item (1, 2, 3, 4)
{
$min = $item if $min > $item;
}
print "Min = $min\n";      # expects Min = 1

What does 'foreach(1..4)' mean in Perl?


Is there any way to Integrate this function?

Question: After 2 change of variables, and a $x = \log(u)$ transformation, I have this integral...
$$\int_0^{\infty } \frac{\alpha  e^x}{\lambda-e^x \lambda+e^{\alpha  x}} \, dx$$
What are some recommendations on how to integrate this?
NOTE: The original integral looked like:
$$\int_{1 }^{\infty } \frac{\alpha  \left(\frac{1 }{x}\right)^{\alpha }}{1-\lambda (x-1 ) \left(\frac{1 }{x}\right)^{\alpha }} \, dx$$
and for the integral to converge $\alpha > 1$.
Finally, when $\alpha = 2$, I did get this expression...
$$\frac{8 \tan ^{-1}\left(\frac{\sqrt{\lambda }}{\sqrt{4-\lambda }}\right)}{\sqrt{(4-\lambda ) \lambda }}$$
Thanks,
Comment: The substitution $u:=e^x$ turns the integral into $$\int_1^\infty\frac{\alpha}{\lambda-\lambda u + u^\alpha}du$$ which is still pretty bad but maybe more tractable. Do you know anything about $\alpha$?
Comment: Yes - for the integral to converge, $\alpha > 1$
Comment: @Tom - I tried that substitution, but didn't make much progress...but then again...Next, I transformed it into the one on top...
Comment: to get a nice closed form you should at least have the transoformed numerator to be a polynomial in $x$
Answer: For integer $\alpha>1$, I got the following:
Take the Mellin transform of the integrand with respect to $\lambda$,
$$
\int_0^\infty \frac{\alpha  e^x}{\lambda-e^x \lambda+e^{\alpha  x}} \lambda^{s-1} \; d\lambda = \frac{\alpha e^{x-\alpha x}}{(-e^{-\alpha x}(e^x-1))^s}\pi\csc(\pi s) = I_{\alpha}(s,x)
$$
now integrate over $x$
$$
\int_0^\infty I_{\alpha}(s,x) \; dx = (-1)^{-s}a\pi\csc(\pi s)\frac{\Gamma(1-s)\Gamma(\alpha-1+s-\alpha s)}{\Gamma(\alpha-\alpha s)}
$$
now take the inverse Mellin transform with respect to $s$ to get something that depends on $\alpha$ and $\lambda$,
$$
G_\alpha(\lambda) = \frac{1}{2 \pi i}\int_{c-i \infty}^{c + i \infty} \lambda^{-s}(-1)^{-s}a\pi\csc(\pi s)\frac{\Gamma(1-s)\Gamma(\alpha-1+s-\alpha s)}{\Gamma(\alpha-\alpha s)}\;ds
$$
we can use the Mathematica command

InverseMellinTransform[((-1)^-s a [Pi] Csc[[Pi] s] Gamma[
      1 - s] Gamma[-1 + a + s - a s])/Gamma[a - a s] /. a -> 2, s, l]

Where the a -> X part can be changed for various values of $\alpha$. This reproduces your result for $\alpha=2$, but that obscures the hypergeometric nature of the result. It also gives results for higher values of $\alpha$ as hypergeometric functions weighted by products of gamma functions.
The results seem to have a pattern
$$
G_4(\lambda)=\frac{3^2}{2^3}\sqrt{\frac{3}{2}}\frac{\Gamma(\frac{4}{3})\Gamma(\frac{5}{3})}{\Gamma(\frac{5}{4})\Gamma(\frac{7}{4})}\;_4F_3\left(\frac{3}{3},\frac{3}{3},\frac{4}{3},\frac{5}{3}\bigg|\frac{5}{4},\frac{6}{4},\frac{7}{4}\bigg|\frac{3^3}{4^4}\lambda\right)
$$
$$
G_5(\lambda)=\pi\frac{4^3}{5^3}\sqrt{\frac{2}{5}}\frac{\Gamma(\frac{5}{4})\Gamma(\frac{7}{4})}{\Gamma(\frac{6}{5})\Gamma(\frac{7}{5})\Gamma(\frac{8}{5})\Gamma(\frac{9}{5})}\;_5F_4\left(\frac{4}{4},\frac{4}{4},\frac{5}{4},\frac{6}{4},\frac{7}{4}\bigg|\frac{6}{5},\frac{7}{5},\frac{8}{5},\frac{9}{5}\bigg|\frac{4^4}{5^5}\lambda\right)
$$
In general it appears that
$$
G_n=C_n\; _nF_{n-1}\left(\frac{n-1}{n-1},\frac{n-1}{n-1},\frac{n}{n-1},\cdots,\frac{2n-3}{n-1}\bigg|\frac{n+1}{n},\frac{n+2}{n},\cdots,\frac{2n-1}{n}\bigg|\frac{(n-1)^{n-1}\lambda}{n^n}\right)
$$
where
$$
C_n=\sqrt{\frac{2\pi(n-1)}{n}}\frac{(n-1)^{n-2}}{n^{n-2}}\frac{\prod_{k=0}^{n-2} \Gamma(\frac{n+k}{n-1})}{\prod_{k=1}^{n-1} \Gamma(\frac{n+k}{n})}
$$
where we see your result in $C_2=2$ and
$$
_2F_1\left(1,1\bigg|\frac{3}{2}\bigg|\frac{\lambda}{4}\right) = \frac{4 \sin^{-1}(\sqrt{\lambda}/2)}{\sqrt{(4-\lambda)\lambda}}
$$
seems to check out for a few numerical examples.


Problem with Pareto distribution and R

Question: I am trying to test this property of pareto distribution: Let f(x) be a pareto distribution
$$
f(x)=\alpha \frac{x_m^\alpha}{x^{\alpha+1}}
$$
so we have the cdf that is
$$
CDF(x)=\int_{x_m}^{x}\alpha \frac{t_m^\alpha}{t^{\alpha+1}}dt=1-\frac{x_m^\alpha}{x^\alpha}
$$
then the probability that $x>x_0$ is
$$
P(x>x_0)=1-CDF(x)=\frac{x_m^\alpha}{x^\alpha}
$$
and so we have
$$
\frac{P(x>x_0)}{f(x)}=\frac{x}{\alpha}
$$
Now i am trying to test it with R.
 library(PtProcess)
 dd<-rpareto(10000,1.5,0.01)
 cdf<-ecdf(dd)
 df<-density(dd)
 ff<-(1-cdf(df$x))/df$y

If i plot ff
 plot(df$x,ff)

I do not obtain the correct straight line. I guess that this is due at the way density() and ecdf() works.  I need this form of the test (an a posteriori evaluation of fd and cdf) in order to perform the same test on a sample of data of unknown orgin. I guess that i need a way to binning the ecdf() function in the same way as hist() is the binning version of density.
So my question is:

Does there exist an equivalent binned function of ecdf() as hist() is the binned function of density()?
or can I simulate ecdf() with hist()?
Comment: It looks like `ff<-(1-cdf(df$x))/df$x` is calculating $P(X>x)/x$ not $P(X>x)/f(x)$
Comment: yes! you right! thanx :)
Comment: but `ff<-(1-cdf(df$x))/df$y` seems does not works too.
Comment: @emauele, there are probably many points in your estimated density that are close to 0 which may cause numerically unstable results (I noticed this when pasting your code). Beyond that, I don't have much insight into the problem.
Answer: By using ecdf and density, you're not actually doing the Pareto calculations, but instead using estimates based on a sample that are, by their non-parametric nature, not guaranteed (read: not going to) have the desired property.
Try the following:
x <- seq(0.1,10,by=0.1)
fx <- dpareto(x, 1.5, 0.05)
Fx <- ppareto(x, 1.5, 0.05)
plot((1-Fx)/fx ~ x)

You'll get the nice straight line out:
Comment: Good, but i need that form in order to perform the same test on a sample of data of unknown origin.
Comment: Since the property characterizes the Pareto distribution, i.e., no other distribution has that property, you could just use a goodness of fit test on the data.  That's fully equivalent to testing for that property, since $(1-F(x))/f(x) = x/a \leftrightarrow x \sim \text{Pareto}$.  Not sure how you'd test for the property directly, w/o going through the Pareto, though.
Comment: Actually the $\alpha$-stable distributions share the same tail behaviour. I would like to use this way because i think that this is the better way for a straightforward measure of the $\alpha$ parameter in a generic $\alpha$-stable distribution.
Comment: The $\alpha$-stable distributions only share that behavior asymptotically as $x \to \infty$, I'm afraid, see https://eldorado.tu-dortmund.de/bitstream/2003/5219/1/47_02.pdf for example, also Johnson, Balakrishnan & Kotz, Continuous Univariate Dist'ns Vol. 1, pp. 603-604 (sorry, Amazon's "look inside" doesn't let you look inside those pages.)
Comment: Yes i know. Where is the problem? You have to see the tails of the distribution. If it is possible, of course.
Comment: It means that for smallish $x$, whatever "smallish" means, you won't see a linear relationship, just something that approaches one in the tails.  Maybe the "almost linear" part of the tail is the upper 0.1 percentile, and the data set has almost no data out there, so you won't actually see anything that looks linear.  It depends on the distribution and the sample size, of course.

Problem with Pareto distribution and R


IE 11 Will not load systemjs

Question: I am working with SystemJS and I have a pseudo-bootstrapper file that I use to check to make sure certain conditions are met before the loading of the main scripts to execute the page load. Here is a snippet of that code.
<code>var obj = document.createElement('script');
obj.src = 'jspm_packages/system.js';
document.body.appendChild(obj);
</code>
This code does NOT execute the script, yet it does load it with a 200 code as evidenced by the network tab within the IE dev tools. There should be a global object "System" created, but it does not exist. Looking through the DOM, the object is properly created and appended to the body.
Does anyone know if this is strictly an issue with IE and SystemJS? I have no idea what's going on. I'm pulling my hair out, as per usual with the demon that is IE. I should note that every other browser works as expected, providing the "System" global variable.
EDIT Further testing has assured that this is not an issue with appendChild, as other scripts using the same method, execute on load just fine.
Answer: Reading this article tells us that your script may not run in IE11. The line in particular which is of interest is:
"Script elements with external resources should no longer execute during appendChild."
This appears to be what's happening.
EDIT: An alternate approach could be taken.
It would be a good idea to do condition checks on the server side before sending the response if you want to change page loading at the system.js level. If that is not possible then I'd suggest doing a redirect after the condition checks instead of appendChild.
Comment: Are there alternative methods for doing this? I feel like this is a common thing to do in web browsers these days with modular scripts.
Comment: There are a couple options. Keeping with the current idea you could try jquery's append() function to see if it does something behind the scenes(you have to load jquery thoughv :-( ).  I will edit my response with to suggest a different approach as well.
Comment: I'm not going to use jQuery for one method. I want a native approach. I will look through jQuery code though to see if they do something that makes it work, though I haven't tried jQuery to see if their append method works in IE for changing src attribute.
Comment: yeah, that's why there was a sad face because if you load jquery then you could have just loaded system.js anyway XD. It is correct to look into the jquery code to compare what it is doing.
Comment: It looks like jQuery uses an eval function on the scripts that are inserted. What doesn't make sense though is that the other script I'm setting the source for executes, the systemjs for some reason is the only one not executing.
Comment: I'm beginning to think more and more that this has to do with SystemJS not IE, at least in regards to IE compatibility with SystemJS.
Answer: The answer is that IE versions < Edge do not support promises. I needed a polyfill for IE 11.

IE 11 Will not load systemjs


neo4j how to count distinct relationships group by node?

Question: I have a graph db of Node User (properties: uid, name) and Relationship Invitation (properties: invitation_id, invitation_time).
The relationship is built when one user invite other users. That means every time one user invites, it will build the same relationship between him and the users he invited.
I want to count the unique invitations of each user.
My cyper query is:
match (u:User)-[r:Invitation]->()
return u, count(distinct r)
order by count(distinct r) desc

Instead of meet my expectation, this query did not drop the duplicates.
So what should be the right query?
Answer: I got the answer by myself just after posting the question:
match (u:User)-[r:Invitation]->()
return u, count(distinct r.invitation_id)
order by count(distinct r.invitation_id) desc


HSQLDB independent for unit testing

Question: I use HSQLDB for JUnit unit testing a set of hibernate classes and queries. In each test's setUp() call I initialize an in-memory hsql database (through hibernate) using the name of the test class and test case to compose the connection string for the in-memory db instance. But in my second test, the ID sequence seems to continue from the first test. I want my tests to be absolutely independent obviously so this surprises me. I'm using @GeneratedValue(strategy = GenerationType.AUTO) for my id's. My intended development and production database is mysql or postgresql but that shouldn't matter here.
Update
I tried a smaller test case, and it turns out that I was wrong. I did create more entities in the secodn test, which resulted in a different id. My bad entirely!
Comment: That's unexpected behavior. Can you post the code from `setUp()` that you are using to initialize the database connection?
Comment: I tried a smaller test case, and it turns out that I was wrong. I did create more entities in the secodn test, which resulted in a different id. My bad entirely!
Comment: Actually, your second test should not depend on the actual value of generated ID. The test should not make any implicit assumptions about its environment.
Comment: I know, I wasn't particularly asserting the generated id, I was investigating an issue as if that id were a symptom.
Answer: Probably the HSQLDB Memory database will be dropped only after the application terminate.
You could bengi a transaction before each test class and rollback it when the test class finished.

HSQLDB independent for unit testing


Como marcar um X em parte de uma imagem ao disparar uma função no JavaScript?

Question: Eu fiz um mapeamento de uma imagem, e com as coordenadas de algumas partes,fiz com que ao clicar em uma parte selecionada, uma função é executada.
Mas eu gostaria de saber como marcar um X ou fazer alguma identificação visual da parte clicada.

      <map name="Map" id="Map">
         <area alt="" title="Janela 1" href="javascript:janela1()" shape="poly" coords="58,138,131,116,136,56,123,44,60,43,51,60,48,94,48,120,50,136" />
      </map>

var clicado1 = false

function janela1() {

    if(!clicado1){
        let janela1 = document.createElement("option")
        janela1.text = "Janela 1 foi adicionada"
        flista.appendChild(janela1)
        valores.push('janela 1')
        //lista.push('janela 1')
                        //ainda precisa marcar um X no local clicado
        clicado1 = true
    }else{
        if (flista.length > 0 && valores.length>0) {
          flista.remove(flista.length-1)
          valores.pop()
        }

        clicado1 = false
    }
}

Comment: Considere informar o que você tentou fazer ou qual parte do código que não está funcionando.
Comment: Fazer o **X** não é o problema. O problema compreender é o que você quiz dizer com identificação visual e qual a plataforma que você pretende implementar esse identificador visual?
Comment: Tipo acontecer alguma animação ao clicar ou alguma alteração na imagem(como um X em cima da parte selecionada), pretendo implementar para Web e mobile.
Answer: Existe uma forma de destacar a parte mapeada usando clip-path do CSS. É só criar um span dentro da mesma div onde está a imagem e usar os mesmos valores do atributo coords nos valores do clip-path, porque as coordenadas são as mesmas, só muda a sintaxe.
Por exemplo, o coords é isso:
coords="58,138,131,116,136,56,123,44,60,43,51,60,48,94,48,120,50,136"

O clip-path ficaria:
clip-path: polygon(58px 138px, 131px 116px, 136px 56px, 123px 44px, 60px 43px, 51px 60px, 48px 94px, 48px 120px, 50px 136px);

Repare que os valores são os mesmos, apenas é preciso separar cada par de valores com uma vírgula e acrescentar o px.
Mas para isso é preciso fazer alguns ajustes no HTML, como colocar a imagem dentro de uma div, alterar o atributo href do map, usar onclick para chamara função entre outras coisas a nível de CSS (veja no código e adapte à sua necessidade).
No exemplo abaixo, clique na área mapeada (ela é invisível, é preciso passar o mouse perto do canto superior esquerdo da imagem para achar a área clicável):

var clicado1 = false

function janela1(e) {
   e.preventDefault();

   var mapa = e.target;

    if(!clicado1){

        let janela1 = document.createElement("option")
        janela1.text = "Janela 1 foi adicionada"
//        flista.appendChild(janela1)
//        valores.push('janela 1')
        //lista.push('janela 1')
                        //ainda precisa marcar um X no local clicado
        clicado1 = true
    }else{

//        if (flista.length > 0 && valores.length>0) {
//          flista.remove(flista.length-1)
//          valores.pop()
//        }

        clicado1 = false
    }

       var coordenadas = mapa.getAttribute("coords");
       var coords_array = coordenadas.split(",");
       var coords_clip = '';

       for(let i in coords_array){
          if(i%2 == 0) coords_clip += coords_array[i]+"px "+coords_array[+i+1]+"px,"
       }

       coords_clip = coords_clip.substr(0, coords_clip.length-1);

        let span = document.createElement("span");
        span.className = "clip";
        span.setAttribute("onclick", "this.outerHTML=''");
        span.style = "clip-path: polygon("+coords_clip+");";

       document.getElementById("container").appendChild(span);
}
#container{
   width: 630px;
   height: 354px;
   position: relative;
}

.clip{
   display: inline-block;
   width: 100%;
   height: 100%;
   background: red;
   position: absolute;
   top: 0px;
   left: 0px;
}

   <map name="Map" id="Map">
      <area onclick="janela1(event)" alt="" title="Janela 1" href="#" shape="poly" coords="58,138,131,116,136,56,123,44,60,43,51,60,48,94,48,120,50,136" />
   </map>

Comment: E como eu posso fazer pra essa parte marcada de vermelho sumir e voltar como estava antes, tipo pra quando clicar de novo remover essa marcação vermelha?
Comment: Dah pra fazer. Quando eu chegar em casa eu atualizo a resposta ok.
Comment: Alterei a resposta.
Comment: Eu resolvi tirar essa parte do select(flista) e deixar apenas o array armazenando quais partes foram clicadas, só que o último detalhe q falta é quando clica novamente pra tirar a parte vermelha essa parte clicada n é removida do array, tem como resolver isso?
Eu coloquei o código todo e expliquei um pouco melhor,só falta esse detalhe de remover do array pra quando clicar em continuar só retornarem as partes que foram selecionadas.
https://pt.stackoverflow.com/questions/421755/como-remover-uma-parte-da-imagem-selecionada-e-ainda-remover-do-array


Recomendações para comentários em uma interface e seus contratos

Question: Diariamente me deparo com esta situação quando vou inserir comentário para uma interface e para uma classe. Fico na dúvida se devo usar os mesmos comentários da interface e seus contratos, na classe e seus métodos.
Já realize diversas pesquisas na web, e os resultados encontrados, não foram muito satisfatórios, pois, quero algo que siga as boas práticas de programação.
EXEMPLOS:
Interface
///
/// Assinatura dos métodos que cuidam da camada de segurança do sistema como um todo
///
public interface ISecurityService
{
    ///
    /// Verifica se as informações recebidas, são validas para login no sistema, e retorna informações
    /// referente ao usuário encontrado
    ///
    /// <param name="typeLogon">Recebe o tipo do login <see cref="TypeLogon"/></param>
    /// <param name="userName">Nome do usuário</param>
    /// <param name="userPass">Senha do usuário</param>
    /// <param name="codusu">Código do usuário. Será retornado pela função</param>
    /// <param name="nome">Nome do usuário. Será retornado pela função</param>
    /// <param name="filusu">Código da filial padrão do usuário. Será retornada pela função</param>
    /// <param name="ususup">Indica se é super usuário. Será retornado pela função</param>
    /// <returns>Retorna os dados no model <see cref="usuario"/></returns>
    usuario UserLogon(
        TypeLogon typeLogon, string userName, string userPass, out string codusu, out string nome, out string filusu, out bool ususup);

    ...

}

Classe
///
/// Implementa os métodos de segurança especificamente para o sistema web
///
public class SecurityClientWebService : BaseService, ISecurityService
{
    ///
    /// Verifica se as informações recebidas, são validas para login no sistema, e retorna informações
    /// referente ao usuário encontrado
    ///
    /// <param name="typeLogon">Recebe o tipo do login <see cref="TypeLogon"/></param>
    /// <param name="userName">Nome do usuário</param>
    /// <param name="userPass">Senha do usuário</param>
    /// <param name="codusu">Código do usuário. Será retornado pela função</param>
    /// <param name="nome">Nome do usuário. Será retornado pela função</param>
    /// <param name="filusu">Código da filial padrão do usuário. Será retornada pela função</param>
    /// <param name="ususup">Indica se é super usuário. Será retornado pela função</param>
    /// <returns>Retorna os dados no model <see cref="usuario"/></returns>
    public usuario UserLogon(
        TypeLogon typeLogon, string userName, string userPass, out string codusu, out string nome, out string filusu, out bool ususup)
    {
        throw new NotImplementedException();
    }
}

Comment: Isto responde sua dúvida? http://pt.stackoverflow.com/a/15566/101
Answer: Seguir boas práticas por seguir é uma péssima prática. Você deve fazer o que é certo para a sua aplicação. Deve pensar porque deve fazer algo. Porque uma prática específica deve ser usada naquele caso. A função do desenvolvedor é pensar, é escolher, é decidir, não é copiar o que outras pessoas fazem em outras situações que raramente são as mesma que você está enfrentando.
Provavelmente não está achando nada na sua pesquisa porque não exista uma verdade universal.
Você tentou fazer das duas formas e percebeu vantagem em alguma delas?
De uma maneira geral eu diria que a maioria da documentação da interface deve ser aproveitada na implementação. Na verdade até que alguém me mostre o contrário eu acho que toda ela deveria ser aproveitada na implementação, o que a implementação pode ter é informação adicional que só seja relevante ali.
Em geral, salvo um bom motivo, não vejo com bons olhos você documentar como uma interface deve funcionar e depois você determinar na implementação que será diferente, me parece uma quebra de contrato fora do código. Excetuando um comportamento extra que deve ser bem pensado se realmente deve existir, a documentação deveria ser igual. Pra mim, na maioria das vezes essa é a boa prática.
Talvez você esteja vendo algum motivo para mudar a documentação, ele pode ser um bom motivo naquela situação, mas pode ser algo forçado, pode ser que ele demonstre que está implementando errado a própria interface, não tem como saber sem o caso concreto.
O que certamente não é certo é mudar a documentação só porque algum manual de boas práticas disse que deveria, o que eu até duvido que exista algo dizendo isto. Mudar por mudar certamente está errado. E mudar a interface (não o código, isto seria impossível, uma mudança tornaria incompatível) me parece um erro conceitual.
Imagine você documentar na implementação que ususup (péssimo nome) deve indicar se o usuário é ativo ou não. O compilador não vai reclamar mas você terá problemas arquiteturais.
Comment: Muito bom, achei que você também ia abordar a quantidade excessiva de parâmetros é uma dica do que está indo errado no design. E também comentários muito longos e prolixos são, normalmente, ignorados.
Comment: @Malkaviano sem dúvida tem essas coisas também. Eu me concentri mais no foco da pergunta mas você tem razão.
Comment: @bigown eu concordo plenamente com o que você disse. Realmente eu não estava procurando por "manual" que possua como deve ser documentado o código. Eu citei boa prática, por não achar outros termos.
Mas eu acho que os livro como o design pattern de padrões de projeto deveria abordar, ou pelo menos citar esse assunto.


CSS and JS 404 On Admin Site Only - New Install

Question: This is a new server build...
me@server:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.3 LTS
Release:    18.04
Codename:   bionic

Apache...
me@server:~$ apache2 -v
Server version: Apache/2.4.29 (Ubuntu)
Server built:   2019-09-16T12:58:48

I downloaded the Drupal 8.7.8 tar.gz and installed using the Standard installation profile into an Apache VirtualHost.  The visitor portion of the site displays and functions as expected, however the admin portion has issues.  The main page, /admin, displays styled.  However, clicking on the various links, Content, Structure, Appearance, etc, result in a page with no style.  Inspect's Network tab shows...
http://my.server/admin/sites/default/files/css/css_<snip-long-random-string>.css?0
...
http://my.server/admin/core/assets/vendor/modernizr/modernizr.min.js?v=3.3.1
http://my.server/admin/sites/default/files/js/js_<snip-long-random-string>.js
...

Still in Inspect on the Network tab, the CSS files show a Status of "(cancelled)" and the JS files are all 404.
Maybe I have something wrong with URL rewriting.  During installation in the "Requirements review" I received the warning about clean URLs - the server is capable but not enabled.  Well, mod_rewrite is enabled and I have the following in my VirtualHost config...
RewriteEngine on
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

With setting RewriteEngine off the visitor site only partially works.  For example, the contact form is 404 while search works but has no CSS.
All other prerequisites passed.
I removed the whole Drupal filesystem and dropped the database.  Another new installation yields the same results.  Further suggesting that this is an Apache config issue.
Your time and help in resolving this is appreciated, thank you.
== Edit ==
The more I investigate the more I feel this is rewrite related.  I moved all of the Rewrite statements into the top <Directory> and the site, visitor and admin, is 100% broken and I now receive the following in Apache's error log...
AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
AH00121: r->uri = /index.php
AH00122: redirected from r->uri = /index.php

The last entry is repeated a number of times.  I have LogLevel debug.
I understand the result but I'm not sure what the Rewrite statements should be and where they belong.  My [current] vhost...
<VirtualHost *:80>
    ServerName [redacted]
    DocumentRoot /var/www/html/test
    <Directory /var/www/html/test>
            Require all granted
            RewriteEngine on
            RewriteBase /
            RewriteOptions inherit
            RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
            RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d
            RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]
    </Directory>
</VirtualHost>

Comment: Did you `RewriteBase /`?
Comment: Yes, it didn't help.
Comment: Does it fix when you turn off aggregate css and js in `/admin/config/development/performance`?
Comment: @NoSssweat, yes it happens with aggregation on or off.
Comment: I meant .htaccess not vhost conf.
Answer: Don't forget AllowOverride All if your Apache is defaulted to AllowOverride None.  The missing directive was prohibiting rewriting from working [properly?] since I had, lastly, moved the rules to .htaccess (where they are in a default installation).  Added it to the "main" <Directory> in my <VirtualHost> and all is well.


Sendmail relay authentication

Question: I'm trying to set up my sendmail to authenticate against a relay (comcast). I'm not seeing any attempts to authenticate at all. I'm trying to just debug how authentication works, and can't connect all the pieces...
I have, in my .mc file:
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`SMART_HOST', `relay:smtp.comcast.net.')dnl
define(`confAUTH_MECHANISMS', `PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/client-info')dnl

And in my /etc/mail/client-info:
AuthInfo:*.comcast.net "U:root" "I:comcast_user" "P:comcast_password"

Now, I know everything is fine with the u/p, as I could authenticate directly through SMTP, using telnet.
There are two things I don't understand.

When AuthInfo records are searched for, they are matched by the target hostname. How? Does it it use the map key (something I would expect), or uses the so-called "Domain" ("R:" parameter that I don't set in my auth-info line)
What is "U:", really? Sendmail README (http://www.sendmail.org/m4/smtp_auth.html) says it's "user(authoraztion id)", and "I:" is "authentication ID". That suggests that my username should be in "U:", actually, but http://www.sendmail.org/~ca/email/auth.html says that "I:" is your remote user name.

The session looks like this:
[root@manticore]/etc/mail# sendmail -qf -v
Warning: Option: AuthMechanisms requires SASL support (-DSASL)

Running /var/spool/mqueue/p97CgcWq023273 (sequence 1 of 399)
email@example.com... Connecting to smtp.comcast.net. port 587 via relay...
220 omta19.westchester.pa.mail.comcast.net comcast ESMTP server ready
>>> EHLO my.host.name
250-omta19.westchester.pa.mail.comcast.net hello [my.ip.add.res], pleased to meet you
250-HELP
250-AUTH LOGIN PLAIN
250-SIZE 15728640
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-STARTTLS
250 OK
>>> STARTTLS
220 2.0.0 Ready to start TLS
>>> EHLO my.host.name
250-omta19.westchester.pa.mail.comcast.net hello [my.ip.add.res], pleased to meet you
250-HELP
250-AUTH LOGIN PLAIN
250-SIZE 15728640
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 OK
>>> MAIL From:<> SIZE=2183
550 5.1.0 Authentication required
MAILER-DAEMON... aliased to postmaster
postmaster... aliased to root
root... aliased to firstname.lastname@example.com
postmaster... aliased to root
root... aliased to firstname.lastname@example.com
>>> RSET
250 2.0.0 OK

[root@manticore]/etc/mail# sendmail -d0.1
Version 8.14.3
 Compiled with: DNSMAP LOG MAP_REGEX MATCHGECOS MILTER MIME7TO8 MIME8TO7
                NAMED_BIND NETINET NETINET6 NETUNIX NEWDB NIS PIPELINING SCANF
                SOCKETMAP STARTTLS TCPWRAPPERS USERDB XDEBUG

Thanks,
  Pawel.
Answer:
if FEATURE(`authinfo') is used, then the hostname in the map entry
  must match exactly the hostname of the ISP mailserver

See at your SMART_HOST + client-info

What is "U:", really?

Well, SMTP Authentication states in pure English

U user (authorization) id
I authentication id
...
User or authentication id must exist as well as the password. All
  other entries have default values. If one of user or authentication id
  is missing, the existing value is used for the missing item.
Comment: In my .cf file, it says: `DSsmtp.comcast.net`, and in my client-info, it says `AuthInfo:smtp.comcast.net "U:*" "I:username" "P:password"`
All of this is literally (except for credentials). I don't see even an attempt to authenticate.
Comment: makemap hash client-info < client-info - yes? /etc/init.d/sendmail restart - yes? And just for test, in client-info "P:username"
Comment: Option: AuthMechanisms requires SASL support (-DSASL)
Comment: I have Makefiles that build my hashmaps. And I don't restart sendmail, as I was running it from command line as with `-q -v` flags.
Comment: yes, the -DSASL was the problem. saw your comment after posting the answer.
Answer: My solution was very simple. Default OpenBSD sendmail doesn't have SASL flag set, and can not do any authentication, even plain text. I actually expected that SASL is only used for "advanced" authentication. My -d0.1 output clearly shows no SASL flag.
For those who have the same issue: this page (http://theory14.wordpress.com/2009/06/16/openbsd-smtp-authtls-imaps-proxy/) vaguely (it's not a step-by-step how-to-fix-OpenBSD-sendmail-for-SASL page) explains on the necessary steps to go through. Basically, -- download userland source, and rebuild sendmail with -DSASL flag.
P.S. I think, the "U:" is really the user that runs sendmail, where "I:" is the user to authenticate to the client.

Sendmail relay authentication


How to make this code repetitive?

Question: Here is the block of code:
<code>{{ Form::open() }}
<input type="number" name="part_number" placeholder="Part Number" />
<input type="number" name="quantity" placeholder="Quantity" />
<input type="number" name="annual_usage" placeholder="Annual Usage" />
<input type="submit" value="Add Part" />
{{ Form::close() }}
</code>
I want to make it so the user can add multiple parts but currently I can only add one.  Should I be using a loop or something?
Comment: Or something.. Correct.
Comment: what would be inside the form??
Comment: What is a "part" and how would you like it to be added with or without page reload?
Comment: if u want it repetitive the you have to use loop.save it in a partial file and include that file inside the loop.
Comment: Note that changing the names to stuff like `name="part_number[]"` allow you to have an array of data.
Comment: Could I bring in javascript?
Answer: You can use this syntax:
<code>@for ($i = 0; $i < 10; $i++)
    {{-- form goes here --}}
@endfor
</code>
See the Blade documentation for more info.
Comment: I got an error undefined i, how do I fix that?
Comment: Can you post your code? This was tested before posting, so it should work.
Comment: @for($i=0; i<0; $i++)
{{ Form::open() }}

{{ Form::close() }}
@endfor
Comment: In your @for($i=0; i<0; $i++), the $i in the condition part is missing a $. It should look like this: @for($i=0; $i<0; $i++)
Comment: thank you vlad that was it.
Answer: No matter what is in the form, I would suggest you take a look at Hogan.js. This is a neat little templating engine which works with mustache.
The latter allows you to write code like this:
<code>{{#list_items}}
    // code repeated for each list item
{{/list_items}}
{{^list_items}}
    // code to be executed if there are no list items
{{/list_items}}
</code>

How to make this code repetitive?


Individual specific variables in McFadden's choice model

Question: From my understanding of McFadden's discrete choice model, individual specific variables such as income should not affect an individual's choice unless interacted with product characteristics.
But in Stata's command asclogit, which claims to estimate McFadden's model, allows individual variables without interacting with product characteristics.
I am finding this command bizarre.
Here is my answer to this question : ASCLOGIT DOES not interact the casevars with the product characteristics . It interact the casevars with ALTERNATIVE DUMMIES. This is done behind the scene. If you need interactions with product characteristics, you need to use clogit and manually generate interactions.
Comment: @Nick Cox As an expert in stata, do you have any comments.
Comment: Sorry, no: I've never used this command.
Comment: hmm, I thought the mcfadden's model is quite popular. I am surprised by the lack of discussion of how stata estimates the model .
Comment: I searched the web though.  I didn't find many discussions.
Answer: Stata's asclogit command formats and handles the interactions behind the scenes, but the interactions between the case-specific variables and the alternatives are performed as part of the analysis with asclogit.
The results of asclogit are the same as the results of Stata's clogit command when the case-specific variables are explicitly interacted with the alternatives.
The asclogit command is simply a convenient version of clogit and there is nothing "bizarre" about it.
Comment: Thanks for the answer. It's quite helpful. But can you explain more the part where you claim stata asclogit handle the interactions behind the scenes. How would stata know how the interactions be done without instructions. For instance, I could have two product characteristics and two demographic variables.And I only want the demo variables to interact with one characteristics. How is this procedure carried out. If possible, can you show the regression results and explain the meaning of the coefficient output. Your answer now has too many hand waving.
Answer: Assume you have the following variables:
Choice = Binary outcome var
ASV1 = First alternative-specific var
ASV2 = Second alternative-specific var
CSV1 = First case-specific var
CSV2 = Second case-specific var
Further assume you have three alternatives per choice set
and that the alternatives are represented by a three-level
multinomial categorical variable named Alt.  Also assume
the choice sets variable is a numeric variable named Choiceset
and the individual respondents are identified by a variable
named ID.
Finally, assume the data set is in long format with one
row of data per alternative and three rows of data representing
one choice set.
For Stata's asclogit code for a McFadden's model you
would not need to perform any additional data management steps (after
the data are in long format). The asclogit code would simply be:
asclogit Choice ASV1 ASV2, case(Choicset) alternatives(Alt) casevars(CSV1 CSV2) vce(cluster ID)

For Stata's clogit the code for a McFadden's model
would require additional data management steps to create the dummy
variables for the alternatives and then to create the interaction
terms before running clogit.  The code for the data management steps and then clogit would be:
*Create dummy variables for Alt.
tab Alt, gen(Alt)

*Now create interactions.
gen Alt2XCSV1 = Alt2*CSV1
gen Alt3XCSV1 = Alt3*CSV1
gen Alt2XCSV2 = Alt2*CSV2
gen Alt3XCSV2 = Alt3*CSV2

* Now run clogit including the interaction terms.
clogit Choice ASV1 ASV2 Alt2XCSV1 Alt3XCSV1 Alt2XCSV2 Alt3XCSV2 i.Alt2 i.Alt3, group(choiceset) vce(cluster ID)

If you replicate these examples with your own data set, you'll see
that the results from both commands are the same and that asclogit
is simply a convenient form of clogit with explicit interactions.
Comment: After going through the documentation and ado files, here is what I find about asclogit : It DOES not interact the casevars with the product characteristics .  It interact the casevars with ALTERNATIVE DUMMIES.
Comment: Thanks for the detailed answer. To make sure I understand it correctly, adding case variables will force all possible interactions with each alternative variables. But clogit gives you more flexibility.


Way to parse Python pandas DataFrame to Matrix Market (MM) Format?

Question: Is there a built-in way to write a Python pandas.DataFrame object (stored as 2x2 numpy.ndarray internally) to Matrix Market (MM) format? I have use cases for both sparse and dense matrices.
When I say "built-in" here I mean built into the pandas package. If not pandas, then is there something that can take a DataFrame or an 2x2 numpy.ndarray and do this?
Answer: I'm pretty sure there's nothing built in to pandas, but if you have the full stack installed you can use scipy:
>>> import scipy.io, scipy.sparse
>>> df = pd.DataFrame({"A": [1,2], "B": [3,0]})
>>> scipy.io.mmwrite("mmout", df)
>>> !cat mmout.mtx
%%MatrixMarket matrix array integer general
%
2 2
1
2
3
0

It'll also work for a sparse case:
>>> scipy.io.mmwrite("mmout", scipy.sparse.csr_matrix(df))
>>> !cat mmout.mtx
%%MatrixMarket matrix coordinate integer general
%
2 2 3
1 1 1
1 2 3
2 1 2

although you'd have to construct a copy.
Comment: In order to properly write a sparse matrix, you need to first remove the `NaN` values. This can be done using `df.fillna(0)`. Then after you convert your `DataFrame` to a sparse matrix: `sparse_matrix = scipy.sparse.csr_matrix(df.fillna(0))` you can remove all 0 values using `sparse_matrix.eliminate_zeros()`, which is an in-place operation.


Git Flow : criar nova hotfix com uma branch feature em andamento, sem perder modificações da branch feature

Question: Quais passos são necessários para "interromper temporariamente" uma branch feature "xxx" em andamento ?
O objetivo é criar uma nova branch HotFix para uma correção de emergência, e retornar para a mesma branch feature/"xxx" no ponto em que foi interrompida, para continuar o trabalho.
1-) preciso "salvar" antes todo o trabalho nesta feature ? tem que dar git add . ? git commit nela ?
2-) Ao criar nova branch HotFix, git flow hotfix start 'minha.hotfix' :

Preciso dar um git checkout pra branch master antes ? Ou, posso criar a HotFix dentro a feature mesmo ?

3-) Após terminar o trabalho na branch HotFix, git flow hotfix finish 'minha.hotfix' :

o git flow já me posiciona na branch develop. Basta dar um git checkout para minha branch feature/"xxx" tudo estará lá exatamente no ponto onde parei antes de criar a branch hotfix ? ou, precisa de mais providências ?
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: A forma mais segura de gerenciar essa situação é a seguinte:

Primeiramente, salve, guarde ou descarte todo o trabalho da sua feature, o que for mais adequado pra você no momento.

Seguindo as definições do GitFlow, você criará uma branch de hotfix a partir da sua branch master.

Em seguida, após a correção for aprovada, ela será enviada de volta para a master e para a sua develop através de uma release.

Depois, retorne normalmente a sua feature e continue seu trabalho.

Caso queira atualizar sua feature já com o hotfix feito, você tem a opção de já baixar as atualizações da sua develop dentro da sua feature.

Aqui tem uma imagem interessante de outra pergunta ilustrando como esse fluxo funciona


Generating synthetic data based on mean, skewness, standard deviation and autocorrelation

Question: Given that I have the mean, standard deviation, skewness and autocorrelation,
How do I generate 1000 years of random data based on the above parameters in python or Matlab?
I know for example I can use Scipy's skewnorm to generate data based on the mean, std and skewness alone. I can also generate data with Autoceralation by developing an AR model. Am just not sure how to combine the two or if there is a much simpler way of doing this?
Answer: First generate independent data X(1), X(2), ... with mean zero, variance 1, and the desired skewness, e.g. from gamma, Weibull, skew-normal or other distrtibution (you will have to linearly transform to fix the mean and variance).
Then you set Z(t) = r*X(t-1) +X(t), where r is your desired autocorrelation.
Then linearly transfrom Z(t) to get the desired mean and variance.
This works if you have defined skew in the standard way that is affine-invariant.


Como desativar o botão "Ver detalhes" na pré-visualização da imagem?

Question: Estou utilizando: http://plugins.krajee.com/file-input
Aqui está um exemplo em jsfidde : https://jsfiddle.net/DTcHh/30000/
Como desativar esse botão:

Aqui está o código:
HTML:
<input id="input-id" type="file" class="file" data-preview-file-type="text">

JS:
$("#input-id").fileinput({ showRemove: true, showUpload: false, showCaption: true, showZoom: true, zoomIcon: false });

Answer: Diretamente pelo plugin eu não consegui remover, consegui utilizando css:
.file-footer-buttons {
    display: none;
}

Somente deixei de exibir a div que contém os botões na parte inferior.
Answer: Adicione as opções:
{'fileActionSettings':{'showZoom': false}
$("#input-id").fileinput({
     fileActionSettings: {
         showZoom: false
     },
     showRemove: true,
     showUpload: false,
     showCaption: true,
     showZoom: true,
     zoomIcon: false
});

Comment: Recomendo então utilizar a solução do amigo @Denis.
Porém, dessa forma.

    .kv-file-zoom {
        visibility: hidden;
    }
Comment: Ele perde controle `fileActionSettings:{showZoom: false}` após de atualizar página.
Answer: Só desativar não faz sentido uma vez que irá passar a ideia que não esta funcionando como deveria.. ou seja "bugado" o que pode ser feito é utilizando um display:none no CSS marcando-o como !important porque certamente vai ler de acordo ao link do css..
.krajee-default .file-footer-buttons {
float: right;
display: none;

}


Download a CSV file straight to the users download folder

Question: Hi I want to have the option on my site for the user to download a CSV file. I have used the code below
 <input type="button" value="Download as CSV file" window.location.href='call_log.csv'  " />

This does work but when the button is clicked the file is opened in another tab on my browser, What I want to happen is a download straight to the users default download folder
I posted this question before and the response was to include headers ie
Content-Disposition: attachment; filename="call_log.csv"
The page is a php file and if I include headers the page does not load but trys to download the whole page .
Surely I cant put headers in the CSV file , can anyone help me please ?
Thanks
Comment: possible duplicate of [Forcing to download a file using PHP](http://stackoverflow.com/questions/1465573/forcing-to-download-a-file-using-php)
Answer: Your server needs to bet set to execute your php script - you're right; there's no need to change that.
What you need to do is send the correct header to the server from your php script. Here's an example from php.net:
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

For your csv file, the correct content type is text/csv


Why can the equation of a line be written as $ (a_2 - b_1)(y - b_1) = (b_2 - b_1)(x - a_1)$?

Question: Normally the equation of a line is written on standard form, slope-intercept form or point-slope form. However, one can equivalently write out the equation of a line on the form $(a_2 - b_1)(y - b_1) = (b_2 - b_1)(x - a_1)$. This form is apparently useful when trying to define all constructible numbers.
Does anyone know an intuitive proof that the equation of a line can be written on this form (i.e. a proof that is not built on 'reverse engineering' the given equation)?
Comment: I think you have a typo.  The first factor should probably be $(a_2 - a_1)$.
Comment: What are $a_1,a_2,b_1,b_2$?
Comment: Yes, you've got the wrong formula.
Comment: @Quasicoherent. Indeed, I've made a mistake when copying the equation. Do you believe that I should correct the errors in my question or leave them be given that AsBk3397 have discussed the errors as part of his answer?
Answer: I think $(a_1,b_1)$ and $(a_2, b_2)$ are two points that line includes. But as indicated, it must be $(a_2 - a_1)(y - b_1) = (b_2 - b_1)(x - a_1)$ and actually this expression is not different from the equation of the form $$y - y_1 = m(x-x_1)$$ where $(x_1,y_1)$ is a point on the line and $m$ is the slope. But notice that if we take two distinct points on the line, say $(a_1,b_1)$ and $(a_2, b_2)$, then we can find slope $m = \frac{b_2-b_1}{a_2-a_1}$ when $a_1 \ne a_2$ (Notice that in this case, you have a line perpendicular to the x-axis, which has a slope angle of $90^\circ$). Then if we take one of these points, $(a_1,b_1)$ and write the line equation with slope, we have $$y-b_1 = \frac{b_2-b_1}{a_2-a_1}(x-a_1)$$ and the result follows.
Comment: The key difference between $y=m(x-x_1)$ and the question's formula is that it allows the line $x=2$ as well as the line $y=2$, so it is complete for all lines, not just functions with lines as the graph. Consider the case when $a_1=a_2$ but $b_1\neq b_2$, then your $m$ is not defined.
Comment: Yes, that's right, I forgot to mention the case where the slope angle is $90^\circ$, thank you for the correction.
Answer: There are at least four ways to write the straight line equation. All are same, nothing is "normal" over other forms.

$ y=mx+c$
$ \dfrac{b_2-b_1}{a_2-a_1}= \dfrac{y-b_1} {x-a_1} $
$x \cos \alpha + y \sin \alpha =p$
$ x/a+y/b=1$

The constants of each form are relatable to each other.
In particular, the second form equates slope between two fixed points and between variable points. The line segments have equal slope.
Try writing the second form into the first form so you can recognize slope and intercept with constants from second form.


MySQL Join table and count distinct users with no reference in another table

Question: I am trying to count users that are NOT referenced in another table... Right now, I have something along the lines of this:
SELECT COUNT(DISTINCT u.id) FROM users u INNER JOIN orders o ON o.assigned!=u.id;

However, it's returning an invalid value. Any suggestions?
Thank you!
Answer: I would suggest using a LEFT JOIN between the two tables and filter the rows without a matching id in the orders table:
select count(u.id)
from users u
left join orders o
  on o.assigned = u.id
where o.assigned is null

See SQL Fiddle with Demo
Answer: Use a left join and count the rows with no match:
SELECT COUNT(*)
FROM users u
LEFT JOIN orders o
ON o.assigned = u.id
WHERE o.assigned IS NULL

An alternative is to use a NOT IN check:
SELECT COUNT(*)
FROM users
WHERE id NOT IN (SELECT distinct(assigned) FROM orders)

However, in my experience the left join performs better (assuming appropriate indexes).
Answer: SELECT COUNT(1) FROM users u
WHERE NOT EXISTS (SELECT * FROM orders o WHERE o.assigned=u.id);

Are you wanting a straight count (like you mentioned), or do you need values returned?  This will give you the count; if you want other values, you should take one of the other approaches listed above.
Answer: Simply use this query, assuming that the id is unique in users table:
select count(*) From  Users as u where u.id not in (select assigned from orders)

Answer: an inner join explicitly looks for rows that match so that isn't the way to go if you are looking for non matched records
assuming that ORDERS.ASSIGNED is matched with USER.ID an outer join could return values from both and show when there aren't matches like so
select
 u.id,
 o.*
 from users u
 full outer join orders o
 on o.assigned = u.id;
if you only want to know which USER.ID don't have an ORDERS record you could also INTERSECT or use NOT IN () eg
select u.id from users u where id not in (select o.assigned from orders.o);


Is there a way to have a proper Facebook dialog width on mobile screens?

Question: The width of the request dialogs doesn't display in a proper way on mobile screens (I'm using an ipod touch with safari), the width is too long and the "Send" button is out of the screen, at right.
Is there a way to make the dialog display fit the mobile screen real estate?
You can test it on the Facebook official mobile test app:
http://www.facebookmobileweb.com/hackbook
Once you are logged, click on Requests and try to send one.
Answer: I tried many ways without success until I followed the steps from:
http://www.johnnypez.com/uncategorized/customising-fb-ui-iframe-dialog-dimensions/
Comment: Unfortunately, that link is now broken and I'm having this problem right now.


Weight least squares fitting using standard error of the mean rather than the variance

Question: I have data of the form ($x$, $y$, $dy$), where $x$ is the independent variable, $y$ is the dependent variable, and $dy$ is the standard error of the mean (SEM) for $y$.  I intend to do a weighted least-squares fit to this data.  This wikipedia article states that the inverse of the variance should be used for the weights.
I know that SEM$^2=\sigma^2/n$, the variance over the number in each sample, but without the number in each sample, I cannot get the variance.  Simply using SEM$^2$ seems valid under the assumption that each point has the same sample size.  If that assumption breaks down, is there any steps to account for the different $n$'s?
I have seen instances where the fit is weighted using simply $1/\sigma$ and also $1/\sigma^2$ but these are not always explicit as to $\sigma$, if it is the standard deviation or the SEM.  Which would apply when? Any references would for added information would be great.
Answer: I found that section 15.2 of Numerical Recipes 2nd ed describes performing linear regression of data with measurement error, $\sigma_i$, and uses this to weight the fit.
Either should work as long as it is made clear what is used.


How to choose resample size when drawing without replacement?

Question: Say I have some second-order statistic $m(x)$ where $x$ is a data vector of length $n$. Let's also assume that the limiting distribution of $x$ is gaussian-ish, but generally unknown, so that the assumptions that enable one to derive the usual error analysis expressions do not hold. In this case, if I want to get an estimate in the uncertainty in the measure of $m$, I will have to simulate it, using a bootstrap or something. So, I generate 1,000 unique realizations of $x$, $x_i$ (1 $\leq$ $i$ $\leq$ 1000), and use the distribution of all $m(x_i)$ to get an idea of the error in $m$
Now, since $m$ is second-order, it is preferable to draw without replacement when generating the 1,000 resamples of $x$. This is all fine, and the bootstrapping routines I've implemented work well. Here is my problem:

I have to choose a size of the resample
If I choose that size to be $n$, then all $x_i$ will be identical since I'm sampling without replacement
So, the resample size must obviously be smaller than the size of $x$

Problem is, if I choose the size of each $x_i$ to be high, say $0.9n$, then my error is going to be very small. If I choose the size to be small, $0.1n$, then the error can blow up. So, I can effectively make the error in $m$ whatever I'd like, which obviously isn't right...
What do I do at this point, while maintaining integrity?!
Comment: Because of this? https://math.stackexchange.com/questions/722952/how-do-you-prove-n-choose-k-is-maximum-when-k-is-lceil-frac-n2-rceil
Comment: How about a sample size of $n$/2 so you can maximise the total number of unique draws? Not an answer, just a thought.
Comment: @Anonymous What makes you say _"Now, since m is second-order, it is preferable to draw without replacement when generating the 1,000 resamples of x"_?
Comment: @Anonymous that's interesting and I didn't know that. Could you point me to a source for that statement. I'd like to understand why that would be true, not least because it could help your problem.
For example, say the duplicate elements in the bag are the culprit, then I would suggest you reduce the bag to the set of unique elements.
Comment: By drawing a subsample, you will incorrectly estimate the uncertainty in your estimate.  This will be *much worse* than any error introduced by ordinary bootstrapping.
Comment: @MossMurderer How does this maximize the number of unique draws?
Comment: @MossMurderer Hmm, interesting. At least that provides *some* motivation. Thanks a lot! Though I do await more answers
Comment: @MossMurderer I thought about this a bit, and I came to some satisfying conclusions - see my answer. Thanks again!
Comment: @Jim Drawing with replacement when computing a second-order statistic, like a dispersion of some kind, can artificially bias the statistic low.
Answer: I'm posting my own answer here because I think it is probably correct, but feel free to please input ideas.
@MossMurderer brought my attention, in the comments to the original question, an interesting proof. That is, ${n \choose k}$ is maximum at $k=n/2$. This means that if I choose my resample size $k$ to be $n/2$, I will be maximizing the number of unique draws $x_i$.
This is desirable for a very simple reason: to preform the bootstrap, I compute the statistic $m$ for each realization $x_i$. Let's call the results of that calculation a vector $M = [m(x_1),... m(x_{1000})]$. The estimated error in the statistic $m$ is then something like $\sigma(M)$. Of course, you only ever use the standard deviation $\sigma$ as a statistic if you can safely assume your limiting distribution to be gaussian.
If we ensure that we maximize the number of unique $x_i$ by setting $k = n/2$, then we have sampled the $M$ space as well as we possibly can, and therefore $M$ will be as close to gaussian as is possible. In this way, the measure $\sigma(M)$ will be most reliable when the length $k$ of each $x_i$ is $n/2$.
I apologize if this is difficult to read - please edit if you feel you are more eloquent than I.
Comment: I don't think this is the right approach. There are two types of error here. Suppose instead of putting 1000 samples in M, you hire all the supercomputers in the universe and use every possible subset. Call the result $P$. Your reasoning is that $P$ is big, so $\sigma(M)$ should be close to $\sigma(P)$. This is flat wrong, but more important, it ignores the desired target of inference! If $Q$ is the "true" distribution of data, i.e. an infinite vector of data-that-might-have-been, then you want something close to $\sigma(Q)$. $Q$ is not $P$!
Comment: I think you should also keep in mind that setting $k=n/2$ might not be enough to guarantee that you sample the distribution over $m$ sufficiently well. You also need enough samples. So if $n$ is very large, say 1 billion but you only generate 1000 realizations, then the value of $k$ might not matter much.
Comment: @MossMurderer Hmm, I suppose that that is another question in itself; how to optimally choose the number of resamples.
Comment: @eric_kernfeld So I am not actually optimizing sampling in any space at all? I sort of see what you're saying... do you see an obvious way to get as close to $\sigma(Q)$ as I can, other than what I've outlined? No doubt that drawing a sample size of $k=n/2$ is better than $k=1$. It is also certainly better than $k=n$, since that would result in $\sigma(M) = 0$... it therefore seems optimal (necessary) to have $1 < k < n$. Would you say that some value satisfying this condition, other than the one I have suggested ($k=n/2$), is more sensibly motivated?
Comment: I agree that it's somewhere in between: $1<k_{opt}<n$. I think there is some better way than taking half the dataset -- but I haven't tried to compute an actual value; hence the bounty.
Comment: When people use this trick to assess cluster robustness, they commonly use 70 or 80 percent of the data. My intuition says that's the right strategy. But, it may depend on all sorts of things, especially on the absolute sample size and on how you measure variability.
Answer: I included a bit of R code as a quick way to test intuitions about the bootstrap and variance estimation. For this data set, the bootstrap will tend to slightly underestimate the variance, consistent with the intuition that sample overlap (caused by drawing with replacement) will reduce the variance. I added an example with N / 2, to go along with your suggestion of maximizing the number of unique samples.
But the difference is very small, and with the bootstrap you don't have to justify the sample size you used for the resampling procedure, which takes less words and less citations to accomplish almost the same thing.
If you really don't want to draw with replacement and are keen on the N / 2 idea, you could take a look at Antal & Tillé's paper on doubled half bootstrap.
<code>library("tidyverse")
library("data.table")

# get the iris data set
dt.iris <- iris %>% data.table

B = 2000
n_sample = nrow(dt.iris)

# look at the true variance for the dataset
var(dt.iris$Sepal.Length)  # 0.6856935
sd(dt.iris$Sepal.Length)  # 0.8280661

set.seed(123)

# bootstraped variance
dt.boot.results <- data.table(i = 1:B, boot_result_var = as.double(NA), boot_result_sd = as.double(NA))
for (i in 1:B) {
  cur.sample <- dt.iris %>% sample_n(n_sample, replace = TRUE)
  set(dt.boot.results, i = i, j = "boot_result_var", value = var(cur.sample$Sepal.Length))
  set(dt.boot.results, i = i, j = "boot_result_sd", value = sd(cur.sample$Sepal.Length))
}
summary(dt.boot.results$boot_result_var)  # mean var: 0.6801
summary(dt.boot.results$boot_result_sd)  # mean sd: 0.8237

# resampled sd (half sample)
dt.res.results <- data.table(i = 1:B, res_result = as.double(NA), res_result_sd = as.double(NA))
for (i in 1:B) {
  cur.sample <- dt.iris %>% sample_n(n_sample / 2, replace = FALSE)
  set(dt.res.results, i = i, j = "res_result_var", value = var(cur.sample$Sepal.Length))
  set(dt.res.results, i = i, j = "res_result_sd", value = sd(cur.sample$Sepal.Length))
}
summary(dt.res.results$res_result_var)  # mean var: 0.6895
summary(dt.res.results$res_result_sd)  # mean sd: 0.8293
</code>


Yii addInCondition

Question: I've tried to get rows from table according to my conditions.
My code:
$conditions = array(
  'id' => array ('148028','118508')
);

$criteria = new CDbCriteria();
foreach($conditions as $key => $values){
  $criteria->addInCondition($key, $values);
}
if(!is_null($limit)) $criteria->limit = $limit;

$rows = Item::model()->findAll($criteria);

These rows exist,but result is empty.
Binding params exist in criteria object.
Log looks like:
system.db.CDbCommand.query(SELECT * FROM `items` `t` WHERE id IN (:ycp0, :ycp1) LIMIT 2)

i think, that params in criteria dont bind to a query.
Is my code right?
Comment: can you please explain what you are trying to do?
Comment: show a sample `$conditions`, what does that variable look like?
Comment: $conditions = array(
  'id' => array ('148028','118508')
)
Comment: have you not turned on [parameter logging](http://www.yiiframework.com/doc/api/1.1/CDbConnection#enableParamLogging-detail)? that will show you the values bound to the statement, in your log. your code looks fine. how have you checked that result is empty? "binding params" are you doing something else to bind? do you have more criteria?
Comment: var_dump, print_r. No, i dont bind smth else
Comment: for me I got this message because, I had put cdbcriteria params after addInContionds(). putting params before addInConditions but after conditions fixed it.
Answer: Try follow this
$criteria->addInCondition('id', array ('148028','118508'));

Comment: although there's nothing wrong with your answer, it wouldn't help, coz user6327 is doing just that in the `foreach` loop
Comment: but this works fine. i find solution, addInCondition is very sensitive to quotes. Thanks, it helped me.
Answer: Try this,
$criteria->addInCondition($key, $values,'OR');
where $key - field name, $values - array of parametrs

Yii addInCondition


How to get AngularJS sanitizer to parse a block of html?

Question: When I'm using sanitizer and ui-router together in a single module it's causing this error:
VM103 angular.js:9101 Parse Error: <!DOCTYPE html>  <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="">

Here is my code in a jsfiddle.
The error occurs with this statement:
var app = angular.module('myApp', ['ngSanitize','ui.router']);

I have found this article which says to define these in separate modules.
Comment: `ui.router` should be module name
Comment: The sanitizer was unable to parse the following block of html:
Comment: hi pankaj i have html in which consist of whole html with js and css in html page how to solve this issue
Answer: The module name is ui.router not ui-router