What techniques and methods govern how melody can suggest a certain harmony?

Question: In The Art of Strict Musical Composition, Volume 2 chapter 3, by Johann Philip Kirnberger (student of Bach) he writes "Here it must be stated first that every good melody is based on a proper harmony, and that the melody cannot be smooth where this is nor found or felt, no matter how correct or singable their individual progressions may be…"

However Kirnberger does not go on to explain the exact techniques and methods on how to imply a certain harmony with melody. So that is my question. How does one suggest a harmony with melody? Are there any books/treatises that discuss the matter?
I have heard and am in the process of reading Figuring Out Melody by David Fuentes. It seems like a ground-breaking book in terms of music theory pedagogy that answers my very question. However I am still interested in this question as I would like to hear from other authors, sources and music theorists on the matter.
Thank you.
Comment: I began to draft a rather long answer but then realized I was assuming from the example in the question that you are presuming an 18th-century style as Kirnberger would (or Bach, the other composer you reference).  Is that true?  Do you want to know how to imply harmony in 18th-century style?  Because this question seems to me to be very style-dependent.  The types of harmonies that Bach or Mozart would assume or imagine given a particular melody are in many cases quite different from what a jazz pianist or a modern pop artist might consider.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/126689/discussion-on-question-by-curioussam-what-techniques-and-methods-govern-how-melo).
Comment: @Athanasius Hi. Yes, I would like to know how to imply harmony in 18th-century style. By harmony I understand you mean the relationship between different chords, keys and so on... Correct?
Answer: You reference Kirnberger so the following is regarding his era of the early part of common practice.
An important concept is the association of scale degrees with certain harmonies. For example the leading tone is associated with dominant chords like V and viio. While the leading tone is in the iii chord, that chord isn't really the strong harmonic identity associated with the leading tone. The associations aren't all simple, one to one, but there were conventions.
Also, it helps to think of these scale degree associates in regard to movements. In other words, you should not, for example, consider the leading tone in isolation, but the movement of it, like the leading tone ascending to the tonic. That movement would be strongly associated with some form of V I. But, if the leading tone descended to the submediant, solfege LA, the associated harmony would not be a movement to the tonic I chord.
Scale harmonizations like the rule of the octave pack a lot of these associations into very compact examples of scale step movements and their harmonizations.

However Kirnberger does not go on to explain...

A lot of old treatises are like that. But maybe we can try to explain ourselves. In the first bar of example 3.7, the line in solfege is DO RE LA MI. So, what is the bad harmony implied? Using some scale harmonization in the treble from Quantz, and the general association of LA with some kind of subdominant chord, the line suggests I V IV I where the V IV is a "bad" retrogression. From a voice leading perspective the leap up to LA followed by MI seem a bit odd instead of stepping down to SOL.
It would have been helpful to see the example corrected. I think one way to "fix" it would be...

...initally the F4, solfege FA might seem to imply a IV subdominant chord. What could be more natural than the subdominant scale degree being associated with a subdominant chord? This is where the progression of tones, not tones in isolation, along with a foundation in good patterns like the rule of the octave help.
There are two important movements in the "fix." DO RE and FA MI which are often harmonized as I V & V7 I which together is the very sensible progression I V V7 I.
If you combine scale harmonizations with a simple rule of thumb to treat melodic leaps as chord arpeggiations, you should have a very practical method for associating melodic movement and harmony. I don't mean to say all melodic leaps are chord arpeggiation. Certainly that is common, but it's not how all leaps get harmonized. Just think of it as a basic rule of thumb.

A few reading suggestions:

Callahan, Techniques of keyboard improvisation in the German Baroque
Gjerdingen, Music in the Galant Style
Sanguinetti, Art of Partimento
Kostka, Tonal Harmony, chapters Non-Chord Tones and Levels of Harmony
Quantz, Versuch, chapter XIII embellishment of simple intervals, English translation of just the musical examples

I have David Fuente's excellent book. I'd recommend it, but you already know about it.
The point of this reading is to understand how a conceptual harmonic framework - voice leading schemata, bass lines, etc. - were filled in, embellished, "realized", etc. with figuration, melodic details.
When you ask for methods and techniques to make a melody suggest harmony it's really just the reversal of the process of melodically elaborating a harmonic framework. The historic sources covered in the reading above make clear the process started with basic harmonic material like bass lines and voice leading frameworks which were then elaborated melodically. This makes sense, because while a harmonic framework can be unchanged, it can be melodically elaborated in countless ways. The melodic aspect is much more variable than the harmonic. With enough practice harmony and melody with become two sides of the same coin.
It may not seem like it, but you probably should start doing lots of harmonic analysis including non-chord tone labeling. Do harmonic analysis of everything you play. Even if you don't write it out, think it. Analysis will force you to grapple with recognizing which melodic tones are actual harmonic tones and which are embellishing tones. You can't really know how a melody suggests a harmony if you can't look at a melody and determine what are the essential harmonic tones. Practice that through analysis of real scores, then apply it in your writing.
Comment: Hi @Michael Curtis, first of all thanks for answering.
"...Scale harmonizations like the rule of the octave pack a lot of these associations into very compact examples of scale step movements and their harmonizations." My issue with the rule of the octave and other harmonic analyses is that they give no insight into intra-beat horizontal movement.
Comment: "...There are two important movements in the "fix." DO RE and FA MI which are often harmonized as I V & V7 I which together is the very sensible progression I V V7 I." This is starting to answer my question, yet how would you then go on to explain neighbor tones, passing tones, suspense, different interpretations and all the other myriad of potential note combinations.
Yet it seems Bach could easily imply the harmony he wanted at will, while still having the previously mentioned features included.
Comment: "...Certainly that is common, but it's not how all leaps get harmonized. Just think of it as a basic rule of thumb." It is difficult for me to consider my question answered, as it seems this is a sizable issue at play that may not be able to be completely answered here. That is also why I also ask for any material for further reading on my specific question. Thank you.
Comment: For "intra-beat" and non-chord tones, look up the historic term _diminution_. The general idea is a harmonic skeleton to which beat divisions and melodic embellishments are applied. The skeleton is often conceptual, implied but not the actual notation. Look up _harmonic reduction_ for more detail. Also, look up _harmonic rhythm_. Often the skeleton moves at some consistent pace, like one chord change per beat, and that conceptual skeleton is filled in with various melodic embellishments, which move with faster rhythms than the harmonic rhythm. I'll edit my answer with reading suggestions.
Comment: "My issue with the rule of the octave and other harmonic analyses is that they give no insight into intra-beat horizontal movement" The reading about the historic sources explains this was taught not written but orally from master to student. But some treatises did cover it.
Comment: "A few reading suggestions..." Thank you for the many books to sink my teeth in. I have already acquired Gjerdingen's and Sanguinetti's by the way. :)
I don't want to sound arrogant but I don't agree with you. I have an issue with how you're framing it. I think what I'm trying to get at is: Melody suggests a harmonic skeleton → the harmonic skeleton sounds unambiguously → the harmonic skeleton is embellished upon. With how you frame it the first step is missing.
Comment: "it's really just the reversal of the process of melodically elaborating a harmonic framework." I completely reject this statement. Reason being that a good tonal melody can always suggest the harmonic skeleton, whereas a harmonic skeleton alone leaves you no clues towards the actual melody of a piece. Exactly which tones suggest the harmonic skeleton in the melody? Which intervals? And when pieces get ambiguous? And how to sound an embellishment without it intervening and accdientally suggesting a different harmony?
Comment: "It may not seem like it, but you probably should start doing lots of harmonic analysis including non-chord tone labeling…"
"For "intra-beat" and non-chord tones, look up the historic term diminution..."
Yes, I already try to employ harmonic analysis as much as possible. There can be some tricky spots though. But again I believe harmonic analysis won't really help me with my issue.
Comment: "The reading about the historic sources explains this was taught not written but orally from master to student." Interesting. Is there anywhere I can read more on this? Is it still being taught strictly orally today? Do you know which treatises covered it?
Thanks again Michael for taking the time. I hope not to sound too stubborn.
Comment: I think _Music in the Galant Style_ is the best place to start. It's great reading just for the history. He really tries to paint a picture of how the music fit into society and pedagogy. It might be too dense if you don't already know quite a bit of art and social history. As far as I know the oral instruction is all but forgotten. These recent works about partimento are starting to revive interest, like in Callahan's dissertation. I don't mind your questions, but at this point you have about a year of deep reading!
Comment: I think you're aware of the tension, but I'd like to point out that the premise rests on turning Kirnberger's intent backwards. Kirnberger's point seems to make melody antecedent to harmony—"you can't have a good melody without a good harmony." When he says that the bad melody fails to "suggest" a good harmony, I wonder very much what the German phrase was that led to that translation. There is a chain of redefinitions:
1. Kirnberger: "Harmony first, melody second."
2. CuriousSam: "Melody first, harmony second."
2a. Ok, no big deal; we're just describing the practice of harmonization. ...->
Comment: -> Bach/Riemenschneider can give you 371 reasons why you can do "melody first, harmony second. But...
3. Certain aspects of a melody *suggest* a given harmonization. I think that's a difficult premise to deny. Consider the Schenkerian I V I drive of the Westminster Chimes: Mi do re so / so re mi do! However, I feel like it might be hard to find historical sources that lean on the "suggested" harmony as an end in itself. I feel like Kirnsberger (or Bach) would say "This melody suggests this harmony..." and then either harmonize the melody accordingly, or subvert the expectation with an ->
Comment: -> ... unexpected harmony for interesting results. That said, although I can't help point to sources, I wouldn't give up hope. I think of the "unaccompanied" works, like Bach's famous violin Sonatas and Partitas, which are billed as "senza basso." As a violin teacher I've often advised students to understand or communicate the *implied* chordal accompaniment behind the linear melody. The assumption is not that the harmony (the "basso") has been escaped or is irrelevant; it's that it's hidden. In fact, you could still argue convincingly... ->
Comment: -> that it's the absent harmony from which the melody is derived (how about the Chaconne—you can't *have* a Chaconne without a chord progression!). In that sense, Bach answers the question, "How do you make a melody suggest a harmony? By writing the harmony first, then the melody, then removing the harmony." ;-)
Comment: @AndyBonner, it seems like you have enough to add to post an answer.
Comment: Hehe Thanks Michael; I left it as comments (on a bountied question) because it's still not what the question asks for: I'm just thinking out loud, not providing a survey of primary sources.
Answer: I apologize for the following somewhat rambling and long answer.  Editing it down would take more of my time, and I'm not really sure whether I'm even addressing what you're interested in.
What you're asking is a really complicated question to explain in any depth, so hopefully some of this gets at the kind of stuff you're thinking about.  Since your comment clarified that you're interested in 18th-century style and melody, that's what I spend most of the time on here.

First, let me begin by acknowledging your question gets at the heart of a real hole in current music theory pedagogy, which tends to emphasize harmonic (and, to a much lesser extent, rhythmic) concerns over melodic ones, along with deemphasizing dynamics, articulation, tone/timbre, and a variety of other musical parameters.
That said, the closest match to what I think you're trying to get at in music theory curricula tends to be covered within the notion of tonal counterpoint.  While books on that subject don't often make melody-writing the central focus, the very idea of counterpoint (as opposed to simple voice-leading) presumes the notion that lines (i.e., melodies) are important as part of creating a musical texture.  Implicit in the concept of tonal varieties of counterpoint is that the melodies are coming together to generate tonality, which is intimately tied in with harmonic structure.
Michael Curtis's great reading suggestions are a place to start, though you end up there (as with most "tonal counterpoint" books) with a focus on eighteenth-century European style, often even in very specific places within Europe.  Because if you really want a detailed method to use melodic implication to outline harmony, you probably need to specify a very particular musical style, as the potential harmonic implications of a melody as harmonized by Mozart may be quite different from the possible ways that a jazz composer or a modern rock band might view the same melody (and the types of harmonies that might work with that melody).
But from the framing of your question -- which utilizes an 18th-century source -- I'm going to assume that's where you want to begin.  Again, tonal counterpoint sources tend to revolve around this style too.
While you have repeatedly said in comments that you "reject the premise" that composers utilized "harmonic skeletons," if you're talking about the 18th century, it was very much part of the grammar of how to compose, along with other things.  (I would, however, qualify that to say that they weren't really "harmonic" in sense of how we now understand "harmony" as triads and chord progressions -- more like patterns of bass lines and figured bass and cadential idioms and such.)
Yes, obviously it is possible to imply harmony via melody.  But it's not always an exact match.  In reality, composition in the tonal styles of the 18th century was often more like a sort of crossword puzzle (to use an analogy): the horizontal melodies and bass lines had to interconnect with the underlying implied harmonies.  Neither the vertical nor horizontal methods could work well without the other.  They were generally composed together (with exceptions in certain genres that might start with a predetermined melody or predetermined bass line).  A melody may have been composed with possible harmonies in mind, then filling out the harmony may have led to changes in melody, and the same interplay and interweaving continuing as if you're filling in a crossword puzzle, sometimes making errors horizontally or vertically and then fixing them until all the bits align well.
To try to summarize how to imply harmony with the use of melody is a difficult task.  Michael Curtis gets at some of it with his Do-Re-Fa-Mi example.  But let me begin by laying out a few tendencies and guidelines to begin:

Harmonic rhythm (i.e., how often and where chord changes occur) and phrasing are important to consider when beginning to draft a melody.  Having unidiomatic harmonic rhythm is often the place I've seen students struggle the most with in imitation of 18th-century style.  It's not enough to string together tonic-predominant-dominant-tonic.  You need to have a consistency to where chord changes occur (often on relatively strong beats) and how often chord changes occur (which can vary, but often does so in predictable and idiomatic ways).  Students who learn harmony from chorale style often have a completely wrongheaded idea that every melody note should match up with a chord.  Instead, outside of Bach chorales and hymn style, most melodies go for several notes or even many measures while retaining a sense of the same underlying harmony.  Harmony changing every quarter note (or even faster) in 18th-century style for extended sections of a piece is quite rare.  (And when it does seem to change faster, it's often in idiomatic diminution patterns that are articulating a broader pattern of harmony like a sequence moving at a slower pace.)  If you want to craft a good baroque or classical melody, you must have a sense of how a phrase functions, how to use sequences, how to create cadences, etc. melodically.  If you don't do this, the harmony you match with it won't sound right, regardless of what harmony the notes may "imply" in some sort of abstract sense.

Cadences in 18th-century style are very strongly determined in potential melodic motions, so you don't have much choice as to what melodies will do there.  This is one place the question's notion of using the root or third of a triad is important.  If you scan a lot of music from that era, you'll almost never see a cadence to tonic ending on scale degree 5.  It's almost always to 1 or 3.  On the other hand, such rules are not universal, as most of 18th-century music was written before notions of the triad were strongly held as they are today, so composers didn't often think in those terms.  Cadences had melodic patterns that were often first used centuries before and determined long before "tonal" harmony was a thing.  So, while authentic cadences are almost never to scale degree 5, half cadences are very frequently to scale degree 2, i.e., the fifth of the V chord.  This begins to get at the problem you'll start to encounter if you try to generate "rules" for articulating harmony through melody -- it's a very complex process that does have guidelines, but they're very dependent on lots of stylistic idioms.

It's obviously not as simple as matching a particular scale degree to a particular harmony.  Again, melodic idioms often create large parts of the usable melodic language of 18th-century style.  Books like the Gjerdingen and Sanguinetti you were discussing with Michael try to capture some of the different melodic patterns that were taught and elaborated (e.g., through diminution, but also through other variants like chromaticism) while outlining common harmonic phrase frameworks.

Since there are entire books written about this that only scratch the surface, I can't possibly summarize it all here.  But to give a sense of where this starts: certain melodic motions determine harmony more specifically (and key as well).  Semitones are often quite important in this regard.  An upwards semitone motion tends to imply a "dominant to tonic" type motion (where various dominant chords may be substituted, or a "deceptive cadence" style resolution to a local "submediant" chord may also work), effectively a "ti-do" in modern solfege.  This may or may not be in the primary key; using it on another note in the scale is an effective method at modulation.

The other primary semitone motion is "fa-mi."  A descending semitone motion generally is used to also create a local sense of dominant-tonic and again can be used with chromaticism to elicit a local tonicization or modulation.  On occasion, the descending melodic semitone can imply "le-sol" and is helpful in creating a minor mood too (usually pointing toward V instead of i).

While semitone motions aren't the only way, they are a useful example of seeing the strongest power of melody to drive harmony.  If you want to learn to modulate in a melody, learn to use ti-do and fa-mi to other keys.  If you want to learn how to articulate a key (or modulation) clearly in two-voice counterpoint, combine these into a tritone that resolves to your destination key.  (The tritone resolution will uniquely identify the local key, which is important for strong harmonic implication and clear resolution.)  That's the way the baroque and classical composers would have viewed all of this, not as notes from "chords," but as melodic idioms that have specific resolutions -- and from those resolutions come harmonic implications.

Beyond cadences, which had very regulated and expected harmonic and melodic patterns, earlier parts of phrases were often conceived by utilizing stock melodic patterns and variants on them which had strong stereotypical harmonic patterns through their repeated usage.  At other times, a melody might be crafted to go along with standard harmonic patterns that follow, for example, an ascending or descending bass line (very common idioms).  Even though a skilled composer would develop variants of these ideas to the point that you might not even recognize them as variants, many phrases are based in these patterns that students would practice over and over again.  Melodies that conformed to these patterns would just "sound right" because they reflected stereotypical harmonic patterns in the language of the time.  A composer could literally come up with dozens or even hundreds of ways to vary
a melodic pattern over these stereotypical harmonic sequences (once you understand the skeleton), to the point that writing a melody in this manner becomes instinctive.

Another question that comes from the Kirnberger example in the question and which was brought up in comments is how to deal with non-harmonic tones.  The brief answer is: that's why introductory books on harmony and counterpoint spend so much time on regulation of dissonance.  Non-harmonic tones in 18th-century style primarily occur on weaker beats or off beats.  They are rarely leapt to or leapt from.  (Doing so tends to emphasize them and make them feel more likely to be chord tones.)  If they are leapt to or leapt from, there are often idiomatic guidelines about when this happens.  For example, escape tones (one of the very rare examples where you leap from a dissonance in 18th-century style) almost always occur on an offbeat with a rise by step and then a leap down by third.  It's quite rare to see escape tones that do other things (though they do occur).  Appoggiaturas, where you leap to a dissonant tone and then almost always resolve down by step, also tend to occur in idiomatic locations and in relationships to clear unambiguous potential underpinning harmony.

And the details can go on and get very complicated very fast.  The general grammar of non-harmonic tones in this style highlights suspensions, weak-beat passing tones, and weak-beat neighbor tones.  But even among these, there are subtleties.  For example, descending accented passing tones occasionally occur.  In the 18th century style, ascending accented passing tones are rarer.  Lower neighbors (and I'm talking about complete neighbor tones here) are much more common than upper neighbors.  Accented (or relatively accented) neighbor tones are quite rare.  Suspensions are quite common but tend to occur in certain parts of phrases, over certain harmonies (or in sequences), and are prepared and resolved correctly (which involves not only proper melodic and harmonic context but also correct rhythms and durations).  A lot of these naturally follow from melodic idioms that don't disturb underlying harmony in certain contexts.  When the more rare types of dissonance occur, it's usually where the implied harmony is very clear (by use of idiomatic progressions and idiomatic melodic elements), so more freedom can be used with non-harmonic tones.

To summarize the last couple points: the regulation of dissonant notes that are non-harmonic is arguably much more important in the creation of a melody that strongly implies a good harmonic progression than the consonant notes.  If you don't understand how to regulate dissonance, you can't differentiate between which notes of the melody sound like "part of the chord" and which don't.  And, as I've tried to get at here, it's not just about putting chord notes on strong beats (though that's a large part of it).

Let's go back to the Kirnberger example in the question.  What's wrong with this melody?  Again, let's start with harmonic rhythm.  Melodies at the time of Kirnberger want to have a clear sense of harmony articulated on strong beats, with possible faster harmonic rhythm at times (usually governed by more strict rules, i.e., following idiomatic patterns like cadences, sequences, etc.).  When you begin a melody C-D in 4/4, presumably starting on tonic (without other context), the D is either going to be a passing tone or articulate some other chord.
I'll consider C major as the putative key here (though with this beginning, I suppose A minor isn't out of the question, but it raises similar problems).  In that case, in 18th-century style, basically the only way to harmonize Do-Re out of context is tonic-dominant.  Various dominants could be used depending on what happens next, but that's basically what this implies, assuming a harmonic rhythm on the quarter note.
But really, what we want to feel in 18th-century style with such a progression is a return to tonic on the 3rd beat (relatively strong beat), effectively making a sense of "static" harmonic rhythm that "remains" on tonic overall, despite a brief divergence to dominant on a passing chord or something on beat 2.  And that's about the only place where dominant can go.
None of that can happen with an A on beat 3.  Michael's chosen "fix" works because it effectively uses an idiom -- a double-neighbor or changing tone -- that circles around the return to tonic on beat 4.  This is actually closer to a later 18th-century idiom and would generally occur with a more spread-out harmonic rhythm over 2 bars or 4 bars rather than in a single bar (particularly as an opening to melody), or it could be part of a pattern of sequential "climbing" notes I suppose in diminution.  (Lots of melodic weirdness and weakness can sometimes be overcome by repeating a melodic figure a number of times in sequence.)
But perhaps I'm getting bogged down in details.  The problem with the Kirnberger melody is that it doesn't have any rules for creating an effective underlying and consistent harmonic rhythm, which therefore doesn't allow the correct elucidation of the rules governing the regulation of dissonant notes.  Which means we can't tell which notes are supposed to be supporting a "strong" underlying chord vs. perhaps a passing tone or neighbor tone or some other non-harmonic thing.
The first rule of 18th-century melody writing is to articulate the difference between harmonic and non-harmonic tones effectively.  To do so, one needs to adopt all the harmonic rhythm and idiomatic progression guidelines that I (and Michael) have been discussing.  When I look at the Kirnberger example I see a melody that starts on tonic, maybe?  Then a potential passing tone on D that suddenly leaps away (a no-no -- don't leap from a note dissonant with the underlying implied strong harmony; also stepwise motion followed by a leap in the same direction is somewhat unusual idiomatically in 18th-century style when ascending, unless there's strong harmonic support, which there obviously isn't here).  Then -- huh?  What to harmonize A with?  IV?  Really?  Then leap down to E, which implies I.  According to the "rule" articulated in the question about emphasizing chordal thirds and roots, this should work well to create a sense of IV-I, but it absolutely is unidiomatic melodically in this case for 18th-century style.  (Again, these "rules" aren't so simple to articulate.)
Then we leap up to the leading tone B, which notably doesn't resolve (thereby denying that semitone motion which is so critical to using melodic to articulate harmony).  And then we just fall down through the notes of a V chord, maybe?  (In general, too many leaps are in this melody: unless the melody is a general arpeggiated pattern with "multiple voices" embedded, i.e., compound melody, 18th-century style tends toward more stepwise motion, particularly to connect harmonies.)  Except if our harmonic rhythm in the first bar was supposed to be every quarter note, 18th-century harmony wouldn't generally "put on the brakes" a measure later to have the same chord implied over three notes.  Which means retrospectively any sort of potential harmony for the first bar makes no sense whatsoever.  (If anything, we generally see acceleration of harmonic rhythm through a phrase in 18th-century style, getting faster when approaching a cadence; the slow-down that happens here is quite rare and weird.)
I'm trying to give you a sense of some of the concerns that need to go creating a sense of harmony from melody come together.  Yeah, it's really quite complicated.  And this is in a relatively well-studied somewhat circumscribed style of 18th-century music.  If you start asking how melodic implications can generate harmony in jazz or pop music, there are completely different stylistic factors at play (though elements of harmonic rhythm, phrase structure, use of dissonance, etc. are still going to be important in how to match melody to harmony in many other styles too).
I think most textbooks shy away from trying to explain the way to create melody because the details do get complicated so fast.  And, unlike with the basic "rules" that are taught about harmonic progressions and voice-leading, the "rules" of melody writing beget many complexities that have to do with not only the scale degrees of the notes and their rhythms, but also placement in metric accent (coupled with harmonic rhythm), agogic accents (i.e., accents created by duration), accents created by shift in melodic register, placement of non-harmonic tones and relationship to the consonances around them, etc., etc.
There's a reason why so-called "species counterpoint" was often taught (and studied by many composers in the 18th century): if you work on creating smooth melodies that are consonant on strong beats, that can get you a long way.  Then you introduce diminution, which teaches you patterns to build in shorter note values and non-harmonic tones around a skeleton of consonant strong beats.  With a good teacher, you learn to do all of this in the context of many, many good cantus firmi/basslines that a student will gradually absorb with idiomatic cadential motions, etc.  Then you start learning how to "spin out" ideas, to write connecting sequences that fill in parts of phrases or modulate to other keys.  Then you learn how to interpolate those within the stock phrases and progressions and patterns you've been learning.  Along the way, you begin to see the use of things like "tendency tones" (those semitone motions I discussed) and other melodic idioms.
And only then, after you've truly mastered the harmonic grammar of 18th-century style, are you really ready to understand how to write a melody that can articulate the harmony in that style.  Because while what you say is certainly possible -- one can of course write a melody that implies a clear harmony, as Bach and others did -- doing so requires the knowledge of the complexity of the underlying harmonic language and the way melodies interact with it.  I keep using the word "idiom" and "idiomatic," because a musical style really is like learning a language.  (And 18th-century composers would often spend quite a few years learning this language because composing in it.)
Of course, if you just want to restrict your harmony to a few chords and simple modulations (maybe with some standard sequences), you can write simpler stuff and create effective melodies through strongly regulated harmonic tones.  If you look at the stuff Mozart wrote when he was a kid, you can see how that works.  But those pieces are often just strings of idioms with predetermined cadential motions and standard phrase lengths.  Not that they aren't good music -- but they're using a rather simplified "grammar."
I could go on, but honestly the best study I can recommend is to look at melodies from whatever genre/style you're trying to imitate.  And, if possible, start with "simple" examples.  If you were trying to learn 18th-century melodic/harmonic interactions and implications, I'd start with a detailed study of pieces such as from the Bach notebooks, or early Mozart pieces if you want to understand later 18th-century style.  Observe how bass lines create cadences and underpin harmonic motion.  Notice how melodies complement them.  Spend a lot of time looking at two-voice counterpoint to see how it implies harmony without filling in a lot of chord notes.  Forget Roman numerals and almost everything you may have learned about them, because they didn't exist in the 18th century and obscure a lot of how 18th-century music works harmonically.  Instead, notice the intervals and rhythms used.  Notice how long phrases are, how motives are spun out, when sequences occur (and what types).  Couple this with the sorts of exercises and patterns discussed in the Sanguinetti book, learn to extemporize in the style at the keyboard, to fill in voices within given structures (like figured bass, two-voice skeletons, and partimenti), and then you may begin to get a sense of the knowledge an 18th-century composer was working with to write a melody that articulated harmony in a masterful way.  One (unfortunately) cannot become Bach overnight.  But, frankly, it's a lot easier to learn how to write melodies like Bach to first learn the principles of two-voice counterpoint and implications in that style than to start with melody alone.  Once you understand the many constraints and restrictions that are created with how melodies and basslines have to interact to create coherent phrases, you can understand you to write a melody that implies harmony by itself.
But perhaps you're not looking for something quite so focused on a specific historical style.  In that case, the "rules" for melody to articulate harmony generally become more diffuse in later music.  Greater freedom of dissonance usage means less predictability in terms of what constitutes a "chord tone" vs. "non-chord tone" in a melody, which means accompaniment is more important in fleshing out the harmony that is implied by a melody.
For simpler styles, it's easier to summarize the rules for implying harmony in many pop melodies of today: generally put chord tones in stronger metric positions, and as you note, the root and third of a triad are often better at determining chords than the fifth in many cases.  But to write an effective song melody, you probably would want to learn the harmonic patterns of today -- although most singers and even many pop song composers don't necessarily realize it, there are many stock patterns to create 4-bar or 8-bar phrases with standard harmonic rhythms.  You can create variants of those, but often the melody "feels right" when it's generated to work with something like that.
Comment: Hey @Athanasius. Wow, what a lengthy answer! Just wanted to post a comment so you know I'm still here; in the meantime I will be reading your answer so I can comment appropriately. Thank you!
Comment: Everytime I come up with a draft of a response to your answer I keep feeling its inadequate and I start from scratch.
Still here, just still thinking about how to respond...
Comment: I think I thought of a response that's not awful:
Do you think there are rules of how melody implies harmony that are global? As in not idiomatic like you said, but spanning across all genres? C-E-G perhaps will always imply a C major chord, regardless of style or period?
Comment: @CuriousSam - No.  I don't think chords are "global."  I don't think scales are "global."  While Western music has become a dominant system around the vast majority of the globe in the past century, it's nowhere near the only possible musical system.  So, within that broader perspective, tonality (and its various styles) is a cultural construct.  Just like language.  Asking whether a certain melody will imply a certain harmony regardless of style or period is (to me) like asking if a certain set of sounds can imply the meaning "red" to speakers of all languages... which isn't a "global" rule.
Comment: And by the way, if you have questions or objections or whatever to what I wrote in this answer, by all means, feel free to let me know.  And, to extend beyond my last comment, I *do* think it's reasonable to say certain melodies can suggest certain common harmonies in most standard Western tonal styles.  But I also think to do this well in most styles, you need to understand how harmony works in that style at a reasonably good level.  It's our *expectations* about harmony in a particular style that allow a melody to suggest a particular specific progression.
Comment: "And by the way, if you have questions or objections or whatever to what I wrote in this answer, by all means, feel free to let me know." Thank you kindly :). It's just, I feel there is so much there that responding to it directly is very difficult with a character limit.
"No. I don't think chords are "global." I don't think scales are "global."" What about the harmonic series? Doesn't that de facto make certain melodic combinations (which spell out the overtone series) imply chords? Also a lecture by Leonard Bernstein talking about musical universals: https://youtu.be/8fHi36dvTdE?t=2479
Comment: Also am I wrong to say that pentatonic scales be found across all cultures globally?
Comment: Bernstein's Norton lectures are interesting, though they're hardly science. He was guided by Chomskian linguistic theory that was all the rage at the time, but the theory makes assumptions about brain structure that haven't really been shown to be true as the field of cognitive science has developed. Also, I guess most cultures have some variety of pentatonism, but the scales vary quite a bit.
Comment: As for the rest, you're assuming music that has vertical structure, i.e., harmony. Western music is an *aberration* in the emphasis on harmony. The *vast majority* of world musics are monophonic/heterophonic/use drones. To say that their melodies imply chords or sometimes even harmony *at all* would be to misunderstand how the music is structured. Even the harmonic series presumes a 1-dimensional oscillator. Cultures that primarily use gongs and 2D/3D oscillators for instruments don't necessarily structure scales around intervals from the harmonic series.
Comment: "Bernstein's Norton lectures are interesting, though they're hardly science. He was guided by Chomskian..."
"Even the harmonic series presumes a 1-dimensional oscillator. Cultures that primarily use gongs and 2D/3D oscillators for instruments don't necessarily structure scales around intervals from the harmonic series."
I find these answers so cool and interesting. (1/2)
Comment: (2/2) "And by the way, if you have questions or objections or whatever to what I wrote in this answer, by all means, feel free to let me know." Is it alright with you if I keep asking questions here?
Comment: I just left a comment in the chat related to your question.  That would be a more appropriate place to continue this discussion.


Azure Application Gateway backend hostname matching errors

Question: Application gateway gives me an error:
'Backend health': 'The Common Name (CN) of the backend certificate does not match the host header of the probe.' for both backend instances.
But if I try to access scale set instances directly, the certificate is valid:
https://apitestss000000.mycorp.local/
and
https://apitestss000001.mycorp.local/
look fine and valid in browser
HTTP setting is set to 'Pick hostname from backend target.' If I set it to 'Override with specific domain name' and type in one of the hostnames like 'apitestss000001.mycorp.local', there is no error for this host, but still error for the other. Looks like 'Pick hostname from backend target' picks the wrong hostname from the scale set.
Answer: It sounds like you self-signed your certificates.  That will be problematic for anything not on your domain/using your Enterprise CA and PKI setup, which includes Azure health probes.  You'll either need to upload the public root cert in the Azure portal, or get certificates signed by a 3rd party CA that Microsoft probes trust.
Comment: Public root cert of our CA is uploaded to "HTTP settings".
Answer: I had the same issue where I only updated the certificate on the WAG and when the cert expired I got this error. Then I researched and found that when cert update is needed it needs to be updated in the WAG as well as the web servers. Same cert updated in the web servers, problem resolved.


Why can run Java program manually in a Docker image but not as an ENTRYPOINT

Question: I created an openjdk-11 alpine docker image and copied my jar into it. My Dockerfile is like this:
FROM pwittchen/alpine-java11
VOLUME /tmp
ARG JAR_FILE
COPY ${JAR_FILE} /opt/app.jar
ENTRYPOINT ["java", "-jar", "/opt/app.jar"]

If I run:
docker run -it image

then
Error loading shared library libjli.so: No such file or directory (needed by /usr/local/share/jdk-11/bin/java)
Error relocating /usr/local/share/jdk-11/bin/java: JLI_Launch: symbol not found
Error relocating /usr/local/share/jdk-11/bin/java: JLI_PreprocessArg: symbol not found
Error relocating /usr/local/share/jdk-11/bin/java: JLI_ReportMessage: symbol not found
Error relocating /usr/local/share/jdk-11/bin/java: JLI_StringDup: symbol not found
Error relocating /usr/local/share/jdk-11/bin/java: JLI_MemFree: symbol not found
Error relocating /usr/local/share/jdk-11/bin/java: JLI_InitArgProcessing: symbol not found
Error relocating /usr/local/share/jdk-11/bin/java: JLI_AddArgsFromEnvVar: symbol not found
Error relocating /usr/local/share/jdk-11/bin/java: JLI_List_add: symbol not found
Error relocating /usr/local/share/jdk-11/bin/java: JLI_List_new: symbol not found

But if:
docker run -it --entrypoint /bin/sh image

Then I can execute directly in the shell:
$ java -jar /opt/app.jar

And works.
Why running as ENTRYPOINT makes the libjli.so library shadow and try relocating JLI*?
Comment: Since I can not comment... There is problem with musl and jdk, You can notice that Alpine is dropped from tags for openjdk docker images https://hub.docker.com/_/openjdk/ You can try a different distro with libc
Comment: Is this really a problem with libc? Because I'm using openjdk no oracle-jdk and being able to run the program manually from shell makes me think this is not a problem of libraries but about permissions or environmental variables. No ideas?
Comment: Adding to the previous comment, I tested using the https://github.com/frol/docker-alpine-glibc with the same result, what makes me think this is not really a problem related to absence of libc.
Comment: 3d party glibc is not a solution in some cases .. Try ubuntu/debian, or centos/rhel image for example
Comment: that is not really and option, all this exercise to make my app work on Java 11 was to reduce the docker image size using jlink to 50MB, if I use a sid or slim image I will end with more than 100MB. And then, it's better to stick with the old friend openjdk8-alpine image.
Answer: The problem is in musl. When you execute directly from the shell musl is able to read the Library PATH but when you execute using CMD and/or ENTRYPOINT musl is not able to resolve the Library Path.
I was able to find this after reading and old issue already solved in openjdk8-alpine. Then this is a regression.
https://github.com/docker-library/openjdk/issues/77
To solve, first create a file ld-musl-x86_64.pat specifying where are the libraries required by musl. The file contents look like this:
/lib
/usr/lib
/usr/local/lib
/usr/local/share/jdk-11/lib/jli

The copy the file to the docker image in the build stage. My new Dockerfile looks like this:
FROM pwittchen/alpine-java11
VOLUME /tmp
ARG JAR_FILE
#Copy the configuration file with the Library path!
COPY ld-musl-x86_64.path /etc/ld-musl-x86_64.pat
COPY ${JAR_FILE} /opt/app.jar
ENTRYPOINT ["java", "-jar", "/opt/app.jar"]

Finally working.


Does a nonnegative random variable whose expectation goes to zero converge to zero in probability?

Question: Let $X_n$ be a nonnegative random variable such that $\mathbb{E}[X_n]\leq \frac{\alpha}{n}$ where $n \in \mathbb{N}$. Clearly, as $n \to \infty$, $\mathbb{E}[X_n] \to 0$. Is it possible to show that $X_n \to 0$ in probability?
My try:
To show $X_n \to 0$ in probability, one needs to show $\text{Prob}[|X_n-0|\geq \epsilon]$ for any $\epsilon>0$. Since $X_n$ is a nonnegative random variable, one can write Markov's inequality as the following:
$$
\text{Prob}[|X_n-0|\geq \epsilon]=\text{Prob}[X_n\geq \epsilon]\leq \frac{\mathbb{E}[X_n]}{\epsilon} \leq \frac{\alpha}{\epsilon n}
$$
No matter how small $\epsilon$ is, one can get convergence in probability. Am I right?
Is there any way to get convergence in mean square($\ell_2$).
Comment: Your proof of convergence in probability is correct. You don't even know that second moments exist so you cannot prove mean square convergence.
Comment: @Kavi Rama Murthy: What if we know $\mathbb{E}[|X_n-\mathbb{E}[X_n]|^2]\leq \sigma^2$ for some $\sigma>0$?
Comment: @Sepide You still cannot say it converges to zero in mean square sense. Recall mean square error is bias^2 + variance. You need the variance to go to zero.
Answer: Answer for the question in your comment above: Let $X_n$ take the values $0$ and $n$ with probabilities $1-\frac 1  {n^{2}}$ and $\frac 1  {n^{2}}$ respectively. Then $EX_n=\frac  1n$ and $E(X_n-EX_n)^{2}=1-\frac 1 {n^{2}}$ is bounded but $X_n$ does not converge in mean square.


In Django, how can I pre-populate an edit form from a model/child, but save submission as new instance?

Question: I'm trying to prepopulate a ModelForm and an inlineformset_factory with an instance of a Model, BUT when the user submits the form, I need to create a new instance of the Model and it's related child records.
Example Model:
class Artist(models.Model):
    artist = models.CharField(max_length=100)

class Song(models.Model):
    artist = models.ForeignKey(Artist)
    song = models.CharField(max_length=200)

I want the user to see an edit form based on an instance of Artist, along with an InlineFormSet for that Artist's related Songs. The form will be prepopulated with the existing data and the user can change the artist's name and the song names. However, when the user submits the form, I don't want to overwrite the existing records. Instead, I want to create a new instance of Artist and add new Songs for this new artist.
I have tried setting the primary key of artist to None before saving - and this forces a new instance of Artist. However, I lose the ForeignKey relationship between Artists and Songs.
Example View:
def edit(request, artist_id=None):
    if  artist_id == None:
        artistsubmission = Artist()
    else:
        artistsubmission = Artist.objects.get(id = artist_id)
        artistsubmission.pk = None

    if request.method == 'POST':
        form = ArtistEditForm(request.POST, instance=artistsubmission)
        formset = SongFormSet(request.POST, instance=artistsubmission)

        if form.is_valid() and formset.is_valid():
            form.save()
            formset.save()
            return HttpResponseRedirect('/success/')
    else:
        form = ArtistEditForm(instance=artistsubmission)
        formset = SongFormSet(instance=artistsubmission)

    return render_to_response('edit.html', {'form':form, 'formset':formset})

Answer: You can iterate over the individual forms in your formset, change what you need to and save.
if form.is_valid() and formset.is_valid():
    artist = form.save()
    for f in formset.forms:
        song = f.save(commit=False)
        song.artist = artist.id
        song.save()

Comment: Thanks - I think I could make this work with a modelformset, but not an inlineformset. It would require that I loop through songs, set the initial value, then perform a save on each item. That feels like I'd be recreating a lot of the inlineformset capability. If I'm missing the something, I'd appreciate any additional advice. Thanks ;)
Comment: I'll mark this as the answer and post a different question about inlineformsets once I work through this. Thanks again.
Comment: but this means your model for song is valid without artist which is a bit weird...
Answer: I think the easiest way to do this would be to set default values by passing a dictionary in as the first argument to the form.  You can get all of a model instance's fields by:
d_initial = Artist.objects.filter(pk=artist_id).values()[0]

This is the dictionary that you'd pass in to the form.
form = ArtistEditForm(d_initial)

If you've excluded anything from the form, you might want to remove it from the dictionary. Same for id. But this should produce a form that has all the values from the existing instance, but will save to a new instance.
Comment: Thanks - this works really well for the model, but not for the inlineformset_factory. It seems inlineformset_factory will not take initial values.
Answer: I had a similar problem and I solved it like this:
def edit(request, artist_id=None):
    if artist_id == None:
        artistsubmission = Artist()
    else:
        artistsubmission = get_object_or_404(Artist, id = artist_id)

    if request.method == 'POST':
        form = ArtistEditForm(request.POST, instance=artistsubmission)
        formset = SongFormSet(request.POST, instance=artistsubmission)

        if form.is_valid() and formset.is_valid():
            artistsubmission.pk = None

            artist = form.save(commit=False)
            artist.id = None
            artist.save()

            for f in formset.forms:
                song = f.save(commit=False)
                song.artist_id = artist.id
                song.id = None
                song.save()
            return HttpResponseRedirect('/success/')
    else:
        form = ArtistEditForm(instance=artistsubmission)
        formset = SongFormSet(instance=artistsubmission)
    return render_to_response('edit.html', {'form':form, 'formset':formset})

Answer: I found this snippet which I think was more what you were looking for.
http://www.djangosnippets.org/snippets/1246/


Anyway to pass a preexisting JSON object to an OPTION in jQuery/JS?

Question: What the title says.
I know I can do
<option data-value='{"name":"rajiv","age":"40"}'>a</option>

to manually pass through individual variables, but let's say I have a preexisting JSON, is there a way I can do something like
<option data-value='PrexistingJSON'>a</option>

In my code, I'm doing this on AJAX success (appending options to my select)
Here is the snippet:
.....

success: function (result) {
    $.each(result, function (i) {
        $('#select').append($('<option data-value=\'' + result[i] + '\'></option>').val(result[i].ID)
        .html(result[i].LastName + ", " + result[i].FirstName);
});

.....

Where result[i] is my JSON object. I am getting [object Object] returned when I try to access it with $('#assign_employee option:selected').data("value");.
Could anyone help me out?
Comment: Try with + JSON.stringify(result[i]) +
Comment: @juvian Oh my, of course! I must have had some serious tunnel vision I can't believe I overlooked stringify. That got it working - thank you so much!
Comment: Happens :). Glad you got it working
Answer: A big thanks to @juvian. I simply had to stringify my object. Here is the working code:
.....

success: function (result) {
    $.each(result, function (i) {
        $('#select').append($('<option data-value=\'' + JSON.stringify(result[i]) + '\'></option>').val(result[i].ID)
        .html(result[i].LastName + ", " + result[i].FirstName);
});

.....

Comment: Now you understand the difference between JSON and Javascript objects, right?


Como exibir uma matriz graficamente?

Question: Tenho uma matriz Tabuleiro[][] tabuleiro = New Tabuleiro[20][20].
Ela contém objetos de uma classe ainda não implementada, que terá alguns valores, como por exemplo a cor da célula e um marcador de posição.
Gostaria de saber se é possível exibir graficamente essa matriz, por exemplo, os campos do tabuleiro, da seguinte forma:

Ou seja, que representar graficamente essa matriz, de forma bem básica mesmo.
Comment: Bem vindo ao SO em Português! Visite a Central de Ajuda (http://pt.stackoverflow.com/help) para entender melhor como realizar as perguntas! Do modo como colocou, sua pergunta esta muito ampla, e um simples "Sim, é possível." a responderia mas obviamente te deixaria insatisfeito. Seja mais específico com relação ao seu problema e nos mostre o que tentou para podermos auxiliar melhor.
Comment: A questão é que não sei nada de interface gráfica. E queria saber um método fácil para representar essa tabela de forma gráfica.
Comment: Então, Eduardo, como o colega já comentou a sua questão está muito ampla. Há diversas formas de desenhar algo parecido. Uma imagem, aliás, não deixa de ser uma matriz bidimensional de pixels. Sugiro que você edite a pergunta pra *ao menos* fornecer mais informações sobre o que deve ser "desenhado" em cada posição da sua matriz (onde está o código da classe "Tabuleiro"?). Além disso, se você "não sabe nada" de interface gráfica, não vai ser com uma questão que suas dúvidas serão todas resolvidas. Que tal começar com algo mais simples, e ir postando suas dúvidas aqui aos poucos? :)
Comment: Você pode, por exemplo, tentar desenhar uma unidade dessa classe: http://zetcode.com/gfx/java2d/basicdrawing/
Answer: Você consegue criar um panel e definir o tamanho dele, por exemplo 50x50.
Aí, você faz um loop dentro de outro loop, para conseguir fazer as linhas e colunas da matriz e cria para cada posição um panel novo.
for(int i = 0; i<n_linhas;i++){
   for(int j=0; i<n_colunas;j++){
       //cria um novo panel, define borda,tamanho,posição inicial
}

A posição inicial do panel, você leva em consideração o tamanho que você definiu, e o tamanho de cada panel. Aí você define a posição inicial como sendo width: i*height,j*width.

Como exibir uma matriz graficamente?


Closure of interior of a set is equal to the closure of the set if and only if the interior of the set is not empty.

Question: I'll denote the interior of set A as $int(A)$ and it's closure as $\overline{A}$.
I want to show that $\overline{int(A)} = \overline{A} \iff int(A) \ne \emptyset$
For the first part, I tried to write:
$(\Rightarrow)$ If $\overline{int(A)} = \overline{A}$ then for $a \in \mathbb{R}$ there exists a sequence $(a_{n})$ such that $\lim a_{n} = a$ and also there exists $\epsilon > 0$ such that $(a - \epsilon, a+\epsilon) \subset A$.
I don't know what to do from here. I can see that if $int(A) = \emptyset$ the sequence and the neighbourhood won't exist, but how do I get there?
And for the second part I wrote:
$(\Leftarrow)$ Suppose that $int(A) = \emptyset$, then for $a \in \mathbb{R}$, $\nexists$ $\epsilon > 0$ such that $(a-\epsilon, a+\epsilon) \subset A$, so there is no sequence $(a_{n})$ such that $\lim (a_{n}) = a$ then  $\overline{int(A)} = \emptyset$.
Here I don't know how to conclude as well, was trying to find a contradiction by showing that $\overline{A} \ne \emptyset$.
Comment: The title of your question isn't the same as the claim you are trying to prove
Comment: You should fix the typo in the statement. But one direction is false.
Comment: Sorry about the typos, just fixed them.
Comment: As I said, one direction is false. However, if you assume $A\ne\emptyset$, then you can see (by contrapositive?) that $\implies$ is easy.
Comment: If $A=\overline {int(A)}$ then $A$ is called a regular closed set. If $B=int(\overline B)$ then $B$ is called a regular open set. Another example of a non-regular closed set with non-empty interior is $[0,1]\cup \{2\}$ in the space $\Bbb R.$
Comment: Suppose $A=\varnothing$ then $\Rightarrow$ is false.
Answer: $A=\mathbb Q$ is an example where the interior is empty but $\overline{int(A)} \neq \overline{A}$. $A=\mathbb Q \cup (0,1)$ is an example where the interior is not empty and $\overline{int(A)} \neq \overline{A}$. So there is no  valid result of this type.
Comment: We also have $A=\bar A=int(A)=\overline {int(A)}$ when $A=\emptyset.$


String muting technique for 4-8 fingered tapping

Question: I've been experimenting with two-handed tapping for a while now, and have recently picked up on tapping techniques which involve multiple fingers on both hands. My question is this - what are some good ways to mute unused strings without the use of a hair band or other string dampener? I have experimented with a few methods:

Exclusively trying to use my second, third and fourth fingers on my fretting hand and muting with my first finger - I have long fingers and have been playing for over 10 years so the stretching isn't an issue, but this feels clunky and doesn't work well around frets with loud natural harmonics where my first finger rests (or on lower frets with massive gaps between frets)
Low action on my guitar so as to not brush other strings by accident - makes playing unwanted frets by accident likely
High action on my guitar so I don't play any frets by accident - makes playing deliberate frets difficult
Playing with a slow metronome - this is helping but I don't know if I'm picking up bad habits or using bad technique so would like some direction before committing
High noise gate - turning off and on in the middle of a song just for some quick tapping is a bit difficult, especially considering my poor balance combined with having to concentrate

Some examples of the kind of stuff I am attempting is the end of the solo from Beat It by Michael Jackson or the following intro from Sequoia Throne by Protest the Hero:
<code>        T  T     T  T     T     T     T     T     T
D#|----------------------17-------------------------|
A#|----17----15-17----15----15----15-17-------14-17-|
F#|-------16-------16----------16-------12-15-------|
C#|-14----------------------------------------------|
G#|-------------------------------------------------|
D#|-------------------------------------------------|

        T  T     T  T     T     T     T     T     T
D#|----------------------17-------------15-17-15----|
A#|----17----15-17----15----15----15-17----------17-|
F#|-------16-------16----------16-------------------|
C#|-14----------------------------------------------|
G#|-------------------------------------------------|
D#|-------------------------------------------------|
</code>
I've got a good grasp of tapping using one finger on my picking hand, and assuming I can use my first finger as an anchor with my fretting hand or the strings are next to each other I can just about work around two fingers with my picking hand. Any more complex than this (having a floating-fret-hand-first-finger or more than two fingers on my picking hand without the strings next to each other) and my technique turns to mush without the crutch of a hairband mute. Any technique advice would be greatly appreciated.
Answer: First off, I've never heard of or experienced any disadvantage to playing with a metronome set to a slow tempo. Definitely do that whenever you're learning anything if you want to develop the best technique and timing.
Regarding muting, you should be using both hands to mute. For the "fretting" hand, as you say, your first finger is one of your best mutes, along with the extra flesh of your other fingers. Generally my fretting hand muting while I'm tapping is identical to my fretting hand muting when I'm strumming. So if you have fretting hand muting down fairly well, then you should be able to use that.
For the "picking/strumming" hand, your palm and thumb should be rested on the lower strings to mute them while your "fretting" hand is muting the higher strings.
Making sure you land your taps cleanly on the fret and string you want and only that fret and string is also an important part of the technique.
When recording, wrapping something around the strings near the nut is not only perfectly acceptable, it's a good idea for any guitar recording that doesn't use any open notes. It's not a crutch or a cheat, it's a production technique. Obviously in a live situation it just looks awkward.


How to set the access of a menu page for all?

Question: function onthisdate_menu() {
  $items = array();

  $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $items;
}

what access I need to set to let all the users see the page?, because I am looking that page as admin and I get an message "access denied"
Answer: If you set access callback to TRUE, all users will have access to the menu router item. That means ALL users.
 $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'access callback' => TRUE,
    'type' => MENU_SUGGESTED_ITEM,
  );

However, setting 'access arguments' => array('access content'), and omitting 'access callback' => TRUE, is the best way - check your permissions settings. You should be getting an access denied error at example.com/node page as well.
If you don't set an access callback, it would be user_access and the access argument will be passed to that function.
Comment: @HellCoder This is the answer to "How do I make a menu item accessible to all the users?" The fact that page returns a 403 error message is another matter, for which another question has been asked.
Comment: i've set access callback to TRUE, but right now I am in mysite.com/blog - and still getting an error access denied
Comment: is it a drupal-generated access denied page or a regular Apache/Nginx/etc-generated one ?
Comment: drupal access denied message
Comment: Access denied

You are not authorized to access this page.
Comment: Check your `menu_router` table whether the description is what you expect -- my educated guess would be that another module also implements this path. Or you simply forgot to rebuild your menu.
Comment: why my access callback is set to 0 When i set it to true in the module?, i've cleared the cache, maybe is there something more that I'need to put to make work this?


Como recuperar as categorias vinculadas a um post?

Question: Subi no Github (https://github.com/fabiojaniolima/larablog-beta) um pequeno projeto em Laravel, algo bem inicial. Pretendo o mais breve possível arrumar as rotas, estruturar os métodos, etc.
Liberei este código prematuro pois me deparei com um problema que não estou conseguindo resolver sozinho. Explico logo abaixo.
Montei um esquema de Categorias, este esquema será utilizada pela tela de Biblioteca, Cursos e Posts. Já estou conseguindo cadastrar as categorias e também vincular um post a mais de uma categoria, bem como desfazer o relacionamento (post <=> categoria) ao excluir o post. O problema está no momento de editar um post, não estou conseguindo neste momento remontar toda a estrutura de categorias pre-selecionando as vinculadas ao post.
O método utilizado para editar o post está localizado em App\Http\Controllers\Painel\PostController:
public function edit(Post $post)
{
    $categorias = Categoria::all()->toHierarchy();

    return view('painel.posts.cad-edit', compact('post', 'categorias'));
}

Conheço Laravel a pouco tempo, logo não conheço muito bem seu funcionamento. Ao final deste projeto irei liberar o mesmo sobre uma licença MIT, bem como utilizar este para disponibilizar alguns de meus livros, artigos e cursos gratuitamente.
A ideia das categorias é algo parecido com: imgur.com/a/itX71
Comment: Pelo que vi do git hub tens uma relação de muitos para muitos entre post e categorias, isto vai ajudar: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many, https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships . O primeiro link ajuda-te a saber como obter os posts de cada categoria (e vice-versa) e o segundo é para fazeres update a essa relação, com `attach/detach`
Comment: Esse edit não seria para mostrar o registro na tela antes da alteração? `public function edit(Post $post)`?
Comment: Sim. Quero listar o post, bem como a categoria a qual ele está associado e todas as outras categorias cadastradas, permitindo que o "autor" altere a categoria associada. Algo parecido com o que existe no Wordpress: http://imgur.com/a/itX71
Answer: Se você quer listar as categorias relacionadas ao post. Você pode chamar o método do model que diz quem são as categorias associadas a ele.
Tipo:
public function edit(Post $post)
{
    $categorias = Post::find($id)->categorias;

    return view('painel.posts.cad-edit', compact('post', 'categorias'));
}

desta maneira ele retornará as categorias relacionadas a este post em especifico!
Comment: quero listar todas mas marcando as relacionadas.
Comment: Então o que pode ser feito é você retornar todas as categorias com o Categorias:all() gerando um array com todas as categorias e fazer um for verificando se as categorias retornadas do Post estão contidas umas nas outras e fazer uma marcação, isso pode ser feito já diretamente na view, você retorna as listas e pimbas! Você pode usar o in_array do Php!


Update entity properties fetched with entityTypeManager()->getStorage

Question: I am loading all entity types I need to update like below
$current_fruit = \Drupal::entityTypeManager()->getStorage('fruit')->loadByProperties(['status' => '1']);

Then I update them in a way that I loop through the object and if particular value is matched I update some properties.
Thing is I am wondering is it possible to not loop through all of them, but just use some "magic" get method to find entity within loaded entities and then updated it, or is the foreach best method to do this?
Something like
$fruit = $current_fruit->name->getByValue("Apple);

and then I could just use
$fruit->set('price', $40);
$fruit->save();

Answer: You can actually use loadByProperties as that filter, you just need to extend your search:
$apples = \Drupal::entityTypeManager()
  ->getStorage('fruit')
  ->loadByProperties([
    'status' => '1',
    'name' => 'Apple'
  ]);

If you need to filter an existing, broader list, then just use foreach, array_filter, etc; Drupal doesn't have any special methods for it.
Comment: Yeah if you need to get a full list for other purposes, then filter that list into another array separately, you'll just need to use vanilla PHP functions. I don't know if that 2nd query would be cached, my instinct would say not
Comment: Was thinking this would be loading entites too many times. Like it was already loaded in $current_fruit  or is this second time loaded from cache so its ok to load it again with that method?


How to change a class to all divs?

Question: I have this memory game I'm trying to add a button that will reveal all of the cards and flipped them again.
all the cards that are flipped are with class flipped. The problem happens when one of the cards is already flipped or hidden, then the function flips it as opposed to the other cards.
How can I fix that?
function revelCards() {
  var revelCard = document.querySelectorAll('.card');
  for (var i = 0; (i < revelCard.length) ; ++i) {
    if (revelCard[i].classList.contains('flipped')){
      revelCard[i].classList.remove('flipped');
    } else {
      revelCard[i].classList.add('flipped');
  }
}

Comment: What is `revelCards()` supposed to do? Should it reveal all cards no matter their current state?
Comment: without if statement?
Comment: At the very least you're missing a closing curly brace
Answer: You should simply remove the if sentence, like this:
function revelCards() {
  var revelCard = document.querySelectorAll('.card');
  for (var i = 0; (i < revelCard.length) ; ++i) {
      revelCard[i].classList.add('flipped');
  }
}

Now flipped Cards will remain flipped and all others will flip.
Answer: The issue is that your loop just flips based on the current CSS.
However, one of them is flipped manually, so the loop just toggles the CSS.
To fix this, you could store the flipped value in a variable. Before going into the for loop, you could manually toggle (reset) the variable.
Alternatively, you could ignore the value that has been already set. This means that the CSS is not toggled again.
In either case, you would need a reference to the manually-modified original.
Comment: You could store the one flipped manually in a variable , when it is flipped (not , sure how you do it) for example: `onClick(event){this.flipped = event.target }; ` then in the loop above,
just check `if(card!==this.flipped) \\do the class update`
Answer: If I understood it correctly, you have a set of "cards" whose content you want to show then hide. If I'm right, you could try doing something like this:

window.onload = ()=>{
  let btn = document.getElementById('toggle');
  btn.addEventListener('click', ()=>{
    let cards = document.querySelectorAll('.card');
    let flippedCards = [];
    for(let i = 0; i < cards.length; i++){
      // remember all the cards that are already flipped
      if(cards[i].classList.contains('flipped')){
        flippedCards.push(i);
      }
      // flip all the cards
      cards[i].classList.add('flipped');
    }
    // flip all the cards again after 1 second (1000ms)
    setTimeout(()=>{
        for(let i = 0; i < cards.length; i++){
          cards[i].classList.remove('flipped');
        }
        // return the cards to their original state
        flippedCards.forEach(elem =>{
          cards[elem].classList.add('flipped');
        });
    }, 1000);
  });
};
.container {
  display: flex;
  margin-bottom: 5px;
}

.card {
  transition: background-color 0.3s ease-in-out;
  background-color: red;
  width: 50px;
  height: 50px;
  margin-left: 5px;
}

.flipped {
  background-color: green;
}

<input type="button" value="flip cards" id="toggle">

Also, here's a working example :)

How to change a class to all divs?


Allow Anonymous User to Access Form

Question: I'd like to create a form with Drupal that all users can access, but every time I try to access the form without being logged in, I get this error:
<code>Access denied

You are not authorized to access this page.
</code>
How can I allow all users to access the form?
Comment: Not enough information.
Comment: @IvanJaros What specific information would you need in order to solve the issue?
Comment: First, what kind of form you are talking about ? A node form, a contact form, a custom form that you implemented in PHP? Did you configure the permissions/route access (in case of a custom form) and if so, how exactly?
Comment: It's a contact form made with the form module in Drupal.
Comment: What's the actual name of the module? https://www.drupal.org/project/form is a Drupal 6 module. Is it the Contact module? Your own module?
Comment: Show us your code. Is this your own customized module?
Comment: Sorry for not being clear before. I'm using the Contact module that comes packaged with Drupal 8.
Answer: Select People -> Permissions, scroll down and adjust the permissions of Contact.
Comment: I adjusted the permissions and it still doesn't work.
Comment: Use users' personal contact forms needs to be set to be accessible by anonymous users.

Allow Anonymous User to Access Form


Manifest merger failed with multiple errors

Question: Estou com o AndroidManifest.xml acusando de erro.
Fora isso na linha 17 acusa de erro:

Top level element is not completed

<action android:name="android.intent.action.MAIN" />

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name="org.view.activityAcessar" />
    <activity android:name="org.view.activityMenu"></activity>

    <activity android:name="org.view.activityAcessar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

Modifiquei porém o erro continua.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity
    android:name="org.view.activityAcessar"
/>

<activity android:name="org.view.activityMenu">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Answer: O arquivo AndroidManifest.xml é o arquivo principal do projeto, onde  ficam todas as configurações. Ele obrigatoriamente deve ficar na pasta raiz do projeto, contendo todas as configurações necessárias para executar a aplicação, como o nome do pacote utilizado, o nome das classes de cada activity e várias outras configurações.
Verifique corretamente a estrutura do seu AndroidManifest.xml. Veja abaixo um exemplo:
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="br.com.exemplo.oimundo"
   android:versionCode="1"
   android:versionName="1.0">

   <application android:icon="@drawable/icon" android:label="@string/app_name">
      <activity
         android:name=".OiMundo"
         android:label="@string/app_name">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Tente adaptar corretamente seu AndroidManifest.xml para que ele sem ocorrência de erros.
Leia mais sobre estrutura do arquivo do manifesto na documentação.
Sugiro que você leia um pouco também sobre regras e convenções para nomenclatura de classes, pacotes, métodos, variáveis e constantes em Java


Implementing i18n string translation in a custom module?

Question: I have a custom module I've built which essentially acts as a repository of custom CTools keywords that users can arbitrarily define. The issue I'm facing is I need to be able to translate these user-defined strings, so I think I need to implement string translation using the i18n_string module.
I have never worked with translation or localization before, so I'm a bit lost with regards to going about how to implement this. I think I'm on the right path with i18n_string though. Can someone experienced with i18n provide examples that I can look at so I can learn the proper way to implement this?
Comment: My understanding is you can't wrap variables with t()?
Comment: Do you need this process to be automated or are you going to translate yourself the keywords through your admin interface?
Comment: So I want to set up an automated way to translate all the current values of the keywords. So if some site maintainer alters a keyword, they just go to the translate interface, select the module, and say "translate keywords" or something to that effect.
Comment: Mmmh I'm not sure but I'm afraid the modules that can be translated through i18n have been translated manually and their translation can be downloaded by i18n. I think that way because there are some modules for which there is no translation available... Don't you think?
Comment: That doesn't really make any sense to me. User defined strings are regularly translated in fields, views, etc... So that means there is a way to tap into that process. That's what I'm looking to do here.
Comment: I'm sorry I certainly misunderstand your question and, according to your reputation, you surely know more about Drupal than me. Sorry I couldn't help further :-(
Comment: Why wouldn't you use the t() function in your module? The i18n's translate interface would automatically grab the strings in the t() function and give the users with the appropriate permissions the option to translate them. Unless I'm missing something pretty basic here...
Answer: Exactly, you can't wrap variables with t(). They will get printed, but they won't be translatable. I had a form that saves a user-defined string and wanted that string to be translatable from Drupal's translation interface.
Messed around quite a while with i18n_string() and its attribute $name (a $textgroup and a $context glued together with :).
Finally got it: You can provide your own $textgroup via hook_i18n_string_info() and later provide any other custom string as $context (maybe take your module's name to keep things clean).
If you have more than one string in your module pay attention to have every single one of them glued with another custom string to the prior context (textgroup:context:string_1, textgroup:context:string_2, ...).
Here comes a working example:
/**
 * Implements hook_i18n_string_info().
 *
 *   This is the most interesting thing here. You create a new
 *   textgroup your strings will be identified with. Here it's
 *   simply: Custom modules.
 *   When you set the i18n-string later you then only add another
 *   string as context like 'custommodules:any_other_string'.
 *   See the markup example in the form below.
 */
function MYMODULE_i18n_string_info() {

  $groups['custommodules'] = array(
    'title' => t('Custom modules'),
    'format' => FALSE,
    'list' => TRUE,
  );

  return $groups;
}

/**
 * Example form.
 */
function form_example() {

  // Just for testing, the first form element prints the translated
  // string, so you simply can test it after translation by switching
  // your page's language and see it working. This also demonstrates how
  // you will print the string everywhere else.
  $form['markup'] = array(
    '#markup' => i18n_string('custommodules:MYMODULE:string_1', variable_get('user_defined_string', 'Bempo Kohm'), array('update' => TRUE)),
  );

  $form['string'] = array(
    '#type' => 'textfield',
    '#title' => t('A beautiful and pure string'),
    '#default_value' => variable_get('user_defined_string', 'Bempo Kohm'),
  );

  $form['button'] = array(
    '#type' => 'submit',
    '#value' => t('Action'),
  );

  return $form;
}

/**
 * Example form submit handler.
 */
function form_example_submit($form, &$form_state) {

  variable_set('user_defined_string', $form_state['values']['string']);
}


cannot find symbol Workbook.close()

Question: I saw multiple questions with this header but didn't get my answer.
 private void createHandBackFile(XSSFSheet sheet, String programId, XSSFWorkbook workbook) throws IOException {
    String output = "C:\\Users\\muddassirr\\Downloads\\Personal\\STORE\\Output";

    File file = new File(output + File.separator + programId);
    if (!file.exists()) {
        file.mkdirs();
    }
    int noOfColumns = sheet.getRow(0).getPhysicalNumberOfCells();
    for(int i = 0; i < noOfColumns; i++) {
        sheet.autoSizeColumn(i);
    }
    FileOutputStream outputStream = new FileOutputStream(new File(output + File.separator + programId + File.separator + "HAND_BACK.xlsx"));
    workbook.write(outputStream);
    outputStream.close();
    workbook.close();
}

There is no compilation error. But As I run I get runtime error saying
java: cannot find symbol
symbol:   method close()
location: variable workbook of type org.apache.poi.xssf.usermodel.XSSFWorkbook

Comment: Check your class path and look for duplicate imports of different versions of the POI libraries. [This is not allowed.](https://poi.apache.org/faq.html#faq-N10204)
Comment: `cannot find symbol` must be a compilation error. Isn't it?
Comment: possible dup of https://stackoverflow.com/a/33802626/3694269
Comment: Which version of POI are you using?
Comment: Take a look at https://stackoverflow.com/a/34283033/4405757
Comment: @user7 its runtime error
Comment: @user7 3.17 version I am using
Answer: I got the answer. This dependency was missing in pom.xml

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.17</version>
    </dependency>

Comment: @AxelRichter actually I had changed to 3.17.

cannot find symbol Workbook.close()


Compiling SASS in ExpressJS vs Grunt

Question: I know you can compile SASS in a ExpressJS app via code like
<code>app.use(
    sass.middleware({
        src: __dirname + '/sass',
        dest: __dirname + '/public',
        debug: true
    })
);
</code>
but why would one choose this method instead of compiling SASS with GruntJS? Are there any advantages?
Answer: So when you start you server, node-sass will see if the .css file in the dest file path has changed.  If it has, then it will compile the .scss file in the src file path.
Using grunt or gulp will allow you to not only compile scss to css, but also compile coffeescript to js and compress json, html, ect.  Moreover, you can initialize these actions upon any saved changes to the filepath specified in the grunt or gulp file.  So you can get a live reload on your browser when changes happen to any of these file types.
To do this, run your node server and in another tab, run your grunt / gulp process.

Compiling SASS in ExpressJS vs Grunt


Not able to click on action buttons on SliverPersistentHeader when user scrolls up

Question: I am building a Flutter app that uses SliverPersistentHeader and I added some action buttons overlay that SliverPersistentHeader. But the app got a problem in which the action buttons are not able to click when the user scrolls up. I don't want to use the SliverAppBar because I can't put card widget overlay it. So I use SliverPersistentHeader instead because it is able to place a card widget overlay it.

As you can see this is the output that I tried to pin the SliverPersistentHeader. So that user will able to see the action buttons when scrolling up. But unfortunately, I am not able to click on that action button.
Below is the code. Note that I wrapped SliverrPersistenHeader inside NestedScrollView and DefaultTabController
SliverPersistentHeader(
        delegate: MySliverAppBar(
       /// pass data by here

        expandedHeight: 230,
       ),
    pinned: true,
    floating: true,
 ),

Here is the SliverPersistentHeaderDelegate class.
@override
Widget build(
  BuildContext context, double shrinkOffset, bool overlapsContent) {
const Color _devider_color = Color(0xff425262);
final _actionButtonColor = Theme.of(context).cardColor.withOpacity(0.7);
return Stack(
  fit: StackFit.expand,
  overflow: Overflow.visible,
  children: [
    Image.network(
      clanProfile.mainImage == null ? _clanLogo : clanProfile.mainImage,
      fit: BoxFit.cover,
    ),

    Positioned(
      top: 0,
      left: 12,
      child: InkWell(
        onTap: () {
          Navigator.pop(context);
        },
        child: SafeArea(
          child: Container(
              height: 50,
              width: 50,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                color: _actionButtonColor,
              ),
              child: Icon(Icons.arrow_back_ios)),
        ),
      ),
    ),
    Positioned(
      top: 0,
      right: 12,
      child: SafeArea(
        child: Row(
          children: [
            InkWell(
              onTap: () {
                Navigator.of(context).pushNamed(MembersListPage.routeName,
                    arguments: MembersListPageArguments(
                      members: members,
                      masterId: masterId,
                    ));
              },
              child: Container(
                height: 50,
                width: 50,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(25),
                  color: _actionButtonColor,
                ),
                child: Icon(Icons.info),
              ),
            ),
            PaddingSmall(isHorizontal: true),
            Visibility(
              visible: isClanMaster && true,
              child: Row(
                children: <Widget>[
                  InkWell(
                    onTap: () {
                      Navigator.pushNamed(
                              context, EditClanPagePage.routeName,
                              arguments: EditClanPagePageArgument(
                                  clanPageModel: clanProfile))
                          .then((Object message) {
                        if (message == 'Success') {
                          load();
                        }
                      });
                    },
                    child: Container(
                        height: 50,
                        width: 50,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(25),
                          color: _actionButtonColor,
                        ),
                        child: Icon(Icons.edit)),
                  ),
                  PaddingSmall(isHorizontal: true),
                  InkWell(
                    onTap: () {
                      generateInviteLink().then((value) {
                        _showInviteDialogue(
                            context: context, message: value);
                      });
                    },
                    child: Container(
                      height: 50,
                      width: 100,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(25),
                        color: _actionButtonColor,
                      ),
                      child: Text(
                        'Invite ',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    ),
    Center(
      child: Opacity(
        opacity: shrinkOffset / expandedHeight,
        child: Text(
          name,
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w700,
            fontSize: 23,
          ),
        ),
      ),
    ),
    Positioned(
      // top: 60,
      top: expandedHeight / 1.3 - shrinkOffset,
      left: constants.padding_large,
      right: constants.padding_large,
      child: _buildUserDetailOverlayContainer(),
        ),
      ),
    ),
  ],
);
 }

The reason that I used SliverPersistentHeader over SliverAppBar because I want to put a card overlay it.
Here how it looks like
Answer: It's hard to say, because the example of your code is not full. But I think that the last widget in the stack, goes on the widget with buttons row.
Try to swap them.


Place a link at top AND bottom of each node

Question: I made some code to put a button/link at the bottom of a node. But it would be nice to place this link also at the top of the node. Would this be possible?
This is the code that places a button at the bottom of each node:
function hook_node_view($node, $view_mode, $langcode) {
    $node->content['links']['job'] = array(
        '#links' => array(
            array(
                'title' => t('Apply'),
                'href' => 'jobs/apply',
            ),
        ),
    );
}

Answer: You are placing your link in the links object of the $content array which will generally, unless a template file overrides it, render all it's content in one place.
If the one link you have added visually covers your needs, the other one should be placed within the $content array, with a 'light' #weight property (0 for instance) along with the rest of the array's items (body, fields, etc).
the code could look something like this:
$node->content['top_link'] = array(
  '#markup' => ''.t('Apply').'',
  '#weight' => 0,
   );

Comment: This is a perfect answer, thank you very much. Simple and easy, but very usefull to me!


Does the tenor voice have a falsetto that begins at D4?

Question: I, a tenor, remember learning to sing a certain hymn years ago. It went up to D. It felt high way back then. Nowadays it is not high at all. I would probably transpose it so that the highest note would be F#4.
Something happens at D4. I go into some kind of falsetto voice. I do think the real falsetto begins at eg Ab4 or Ab4. My teacher told me this but had no good answer about what is going on.
Does the tenor voice have a falsetto that begins at D4?
Comment: I don't think we can be that precise - vocal ranges are never that standardised - and break points will vary considerably.
Comment: There is a lot of confusion and misleading information regarding vocal ranges and sound production, a lot was developed for pedagogical purposes but it not scientifcally accurate about the physiology of singing. For example, the idea of "passagi" is a principle we can all experience: singing lower feels different to singing in the middle of our range, and singing at the upper end again feels different. This is perhaps a useful distinction for teaching purposes. But you do not use a different physical method of sound production in each range. Falsetto *is* a different physical method of sound
Comment: production – but it doesn't have a direct relationship with a pitch range. You can sing falsetto at a range of pitches, which will most often overlap with pitches you are capable of producing using your normal siging voice (called the "modal" voice). So the idea that falsetto "starts" at a certain pitch doesn't have a clear meaning. Now, if you think you should be able to sing D4 in your modal voice, but you always end up slipping into falsetto, you need to strengthen or get more familiar with using your normal voice, using all the proper techniques of good sound production, at that pitch
Comment: There's an overlap for some, others switch within a note or two.
Comment: @JudyN your two comments would make a good answer.
Comment: You mean that it is more like a "passage" rather than something that happens at a certain note? This falsetto is just what some refer to as the primo passagio?
Comment: Ok I see. People often talk about it as a certain but it is not how it works for me
Comment: the problem is: teachers talk about falsetto without defining it. Sometimes I wonder if they use head voice and falsetto as synonyms.
Answer: Your question makes about as much sense as "does a race car have a third gear that begins at 75km/h"?  There is no fixed minimum pitch for falsetto for tenors in general, and not even for any certain tenor in particular.
I have a range of about an octave where I can choose to switch to falsetto or not (or transition into it smoothly over a somewhat smaller range), and a large part of a singer's development is extending the reach of their registers and blending and matching their characters so that you don't have the sound quality hacked into disjoint pieces in the middle of phrases but can choose and/or mask your breaks.
Answer: It seems that YOUR voice may have a falsetto that starts at D.  But which D are we talking about, and are you sure you're a tenor?   D just above middle C is top-of-the-range for a bass or maybe a baritone, but routine for a tenor.  The next D up is remarkable for a tenor, and the F♯ above most unlikely in full voice!
So, I guess we're talking about the lower one.  Perhaps your voice has a tenor quality but you're just beginning to find its range.
Comment: It says D4 in the question
Comment: I can easily sing up to F#4.


Atiyah's definitions of Topological Quantum Field Theory

Question: According to Atiyah, a TQFT is a functor from the category of cobordisms to the category of vector spaces.
How does this definition relate with the physics of quantum mechanics?
What does the category of cobordism in the above definition represent physically?
Comment: To complement Qiachu Yuan's comment, in a TQFT you assign a Hilbert space to a manifold, the quantum Hilbert state space. Each cobordism represents a spacetime and the induced operator is time evolution. A TQFT is a toy model for quantum gravity. There are no local degrees of freedom and the theory can only keep track of changes in the topology, e.g. no metric or matter fields.
Comment: How does it create a model for quantum gravity?
Answer: A cobordism between two manifolds represents some kind of evolution from one state space to another state space. In quantum mechanics we have an evolution in a continuous time parameter. In order to get a TQFT that describes this, choose

0-dim topological manifolds, i.e. points, as objects (or "the point" as the only object)
1-dim cobordisms of the points as arrows,
add a Riemannian structure to the 1-dim cobordisms, which equips them with a length.

Now a TQFT on this category will be a functor that

associates a (finite or infinite dimensional) vector space $H$ to the point,
associates a linear operator $U(t): H \to H$ to every (or the) interval of length $t$ such that
$U(t s) = U(t) U(s)$ (functoriality).

For infinite dimensional vector spaces we would need to assume that they are (complex) Hilbert spaces. And we would in addition have to assume that the linear operators that are associated to cobordisms are unitary operators. Then the TQFT is identical to the Schrödinger picture of quantum mechanics. Rays in the vector space $H$ represent the state of a physical system and the operators $U(t)$ represent the evolution of the system from one state at the time 0 to the time $t$.
Edit: In the physical interpretation of TQFT the vector spaces represent state spaces of the physical systems which is not the same as physical space. A point in a state space represents all information that is necessary to completely describe the physical system at hand.
Answer: John Baez has written various things about this. Briefly, cobordisms should be thought of in terms of time evolution: you have two manifolds which represent space, and a cobordism between them represents time evolution. Of course to be more physically realistic one should put a Lorentzian structure on the cobordism and make the two manifolds spacelike slices, but I guess the point of the adjective "topological" is to ignore these extra details for the sake of mathematical simplicity.
Then the functor to $\text{Vect}$ is supposed to be a simple version of a functor to $\text{Hilb}$ (the category of Hilbert spaces) assigning to a manifold the Hilbert space of states on it, and assigning to a cobordism a linear operator representing time evolution. Again, to be more physically realistic one should demand that the operator be unitary and indeed there is a notion of unitary TQFT (but many TQFTs of interest to mathematicians are not unitary).