To what extent is music theory just giving us a language to describe/break down music, or does it really have significant "scientific content"?

Question: For instance, you can always chop up notes into chord tones vs non-chord tones; and then separate non-chord tones into passing tones and neighbor tones. These are very much just classifications.
Thus, it seems that, to a large extent, music theory is only giving us a language to describe music. It doesn't seem to have significant "scientific content" in the sense that "music theory predicts what is good music". That is, it isn't true that "only music written according to XXX theory sounds good to an untrained ear". I emphasize "untrained" because people can be trained to prefer one style of music over another.
Comment: Perhaps unfortunately, a computer CAN take the rules of 'music theory' and output music that could be mistaken if not for Mozart certainly for one of his lesser imitators. A quick Google found this - from 9 years ago. It's come along since then. [https://phys.org/news/2011-12-mozart-machine-software-music-classical.html](https://phys.org/news/2011-12-mozart-machine-software-music-classical.html)
Comment: Define "good music".
Comment: I wouldn't put the word "only" in front of "giving us a language to describe music". Any amount of language to describe music is something significant in my opinion.
Comment: There is absolutely no requirement to predict what is good music in order for the theory to be scientific.  No science predicts "good" versus "bad"
Comment: An excellent question, one that also has wider application in the distinction between "is" and "should".
Comment: You can train me to _analyze_ Carrie Underwood, but you cannot train be to _prefer_ it!
Comment: If you're comfortable on a stringed instrument, pluck out some harmonics. Years ago I asked my music teacher a similar question, and he did exactly that (on an electric bass), and only said "remember - the theory follows these."
Comment: @9072997 I agree with you. Yes, the music theory recommendations at this relatively high level -- such as avoiding chaotic/disorderly composition, avoiding pure monotony, etc -- almost certainly has scientific content. I guess my question, then, should be modified to ask "at what level of detailedness does this stop". For instance, I'm raeding the recommendations by counterpoint tutorials, and most of the recommendations in there (beyond trying to stay harmonious) appears to be rather arbitrary to me. I don't even know whether humans have an innate preference for polyphonic texture.
Comment: The science of art? Describing is knowing, and knowing is science. Language can also explain impressionism and poetry.
Comment: If you want to hear something that was predicted theoretically before it was done on real life, try searching for music in 19 Tet (or 22, 53, etc)
Comment: Expecting music theory to predict or judge "good music" seems like expecting science to explain the "meaning of life." That's expecting too much from these things.
Comment: Let's do an experiment. We will compose 2 sets of short "songs". The first, our control, will consist of 8 sets of 3 randomly chosen pitches in the audible range. The second, based on music theory, will be generated by picking a major key at random, then playing 4 chords in that key at random, and repeating the same 4 randomly chosen chords a second time. I hypothesize that the 2nd set of "songs" will be statistically preferred by people of all cultures.
Comment: @ojs: great point. I believe things like that is truly science - it is about how our auditory organs (ears and brain) work. However, it seems like much of other parts of music theory (much of it is based on 18th century European music) does not seem to be like that.
Comment: @ggcg I meant "scientific" in the sense of predicting if something is "pleasing to the ear", which can be inferred from large scale experiments (involving many listeners).
Comment: You have no right really to define that specific thing as the scientific question or goal.  Just because Theory cannot predict what is "pleasing to the ear" doesn't mean that Theory is not scientific, it could mean that you posed a non-scientific question.  But I would recommend reading about Helmholtz because he does try to apply physics to music theory and come up with an explanation of what is objectively "pleasing".  Though I think it's off mark.
Comment: @ggcg we don't need to get too excited about this, but scientific theories (under certain views of science) need to be falsifiable. Thus they have to make predictions that can be falsified. Apart from predicting "what is pleasing to the ear", what other falsifiable predictions do you have in mind?
Comment: My point is that Music Theory never made the claim you claim it did!
Comment: That is worth getting excited about.
Comment: @ggcg oh I never said music theory made such claims. I'm just exploring what music theory can and cannot do. There is nothing personal here.
Answer:
It doesn't seem... that "music theory predicts what is good music"

I agree. And why would it? That's not what theories are there for at all. Like, the theory of Newtonian mechanics isn't there for judging what kind of behaviour of stuff in the real world is good behaviour or bad behaviour – that's not for physicists to judge, the world is just as it is. Likewise, music is just how it is, regardless of whether it conforms to some particular theoretical framework.
However, that's almost completely orthogonal to

It doesn't seem to have significant "scientific content"

Hardly anybody is going to dispute that Newtonian mechanics has significant scientific content. It is enormoursly valuable, even though it's not always right. Why? Because it

Is very simple, clear-cut, and therefore excellent for reuse. This goes both in a scientific sense: gives us a way to precisely tell when we're leaving the domain of Newtonian physics – and in an engineering sense: allows us to easily build all kinds of useful stuff and be confident that it'll actually work without the billions of trial&error iterations you'd need to cover the entire space of buildable machines.
Does apply to a quite big domain of physics: everything that's big or warm enough for quantum effects to decohere, and slow and light enough for relativity not to matter. Granted, that does exclude a vast amount of physics, but it happens to include lots of what we're actually dealing with day-to-day and is interesting/powerful/emergence-friendly enough to allow us to build anything from skyscrapers to mars rockets.

Newtonian theory is not "the" theory of physics, it is one physical theory. Unfortunately, by contrast, the term "music theory" is often used synonymously with common practice, or even "the harmonic style of 18th century european musicians". That is a musical theory, one which I personally think is extremely useful much like Newtonian theory is a very useful physical theory, but it most definitely isn't the theory to end all theories.
In fact, right now there is a lot of discussion about this, captured in Adam Neely's excellent video:

The term music theory should really get divorced from its singular focus on common practice. But when people use this to argue that music theory as a whole is obselete, I have to disagree strongly. On the contrary, music theory is an amazing tool to guide us into future musical developments, we just need to use it as such. Not as a dogmatic law book to judge already written music against.
Comment: I disagree with the "why would it?"-Part. You are right in that theories don't judge wether something's good or bad. But the biggest quality of a scientific theory is being able MAKE PREDICTIONS at all.
Could you elaborate in your answer what predictional capabillities are in fact there?
Comment: @ikegami yes, though FWIW I actually disagree with 12tone's take on the subject (as well as [with Philip Ewell](https://musictheoryswhiteracialframe.wordpress.com/2020/04/24/beethoven-was-an-above-average-composer-lets-leave-it-at-that/), who features in Adam Neely's video). Namely, Common Practice and Beethoven in particular really do deserve their "outstanding" status, IMO. Some of that is down to my personal taste and my feel that Beethoven's music should if anything be _more_ preserved and passed on to new generations – music education does have a _conservation_ role to play. ...
Comment: ...By that same argument, it should also preserve and perpetuate other traditions; in particular I feel Arabic and Indian traditional music should be taught more in Europe, African traditional music more in the Americas. — But moreover, CP theory really does have some aspects that make it particularly suited as a first theory to learn, in a way that is _quite_ analogous to Newtonian mechanics as the first physics theory to learn. And those are purely mathematical, not cultural features, for which it doesn't, shouldn't matter that they happen to have been developed first by white Europeans.
Comment: @Quantumwhisp music theory allows you to predict that something you compose according to its laws will sound in a way that _doesn't feel out of place_ in the sound æsthetic of whatever style you're aiming at. Which is typically correlated with "sounding good" to you and/or your audience, but also allows putting more focus on exactly what parts are actually _supposed_ to stick out.
Comment: I think that the analogy can be taken a step further: theoretical physics can determine relationships, quantities, existences, or what-have-you that can be tested through application. Similarly, what we can discern from "theoretical music" can be tested by writing a new song. In both instances, if the experiment turns out in a different way than expected, theory can *also* help explain why that is.
Comment: +1 even we always find critics - also by composers - about other writers - based on their contemporary *music theory* of good and bad music.
Comment: [Another video on the topic](https://www.youtube.com/watch?v=z-ehoBvAepo) (this one by 12tone)
Comment: (lol, it's actually mentioned by the video you linked)
Comment: Going from your point that Newtonian mechanics is _one_ of many theories within Physics, I kind of like the notion of "Common Practice _Theory_" as one theory within Music... within just "Music" not "Music theory."
Comment: @leftaroundabout I appreciate your answer. The wording of my original question may have caused confusion. Music theory can have predictive power in the sense of predict whether certain compositions are more likely to sound nice to a large sample of human beings. While each judgment will be subjective, whether people on average prefer something, or not, is objective. This is just like how you can predict a stone will fall onto the ground using the theory of gravitation, or how you can predict a kid will more likely prefer sweet candies, rather than bitter food, based on evolution theory.
Answer: You seem to take it for granted that we use twelve half-tones per octave, construct scales from seven of these half-tones, stack thirds into chords, arrange these chords into progressions, etc... and that all seems trivial to you.
It is not.
(Western) music theory describes how to pick a very small subset of all the frequencies you could generate on musical instruments, and how to combine these few frequencies into structures to achieve predictably consonant melodies with harmonic arrangements that match the melody and create a sense of motion, suspension or resolution... and how to move beyond the simplest combinations without getting lost in the wilderness of complete dissonance immediately. If you stick with the simplest guidelines of music theory, you are guaranteed to get something that probably sounds bland, but not dissonant, and that's not nothing, if you consider that very few cultures in the history of mankind ever developed a concept of chords.
Comment: This. To [anti-paraphrase Arthur C. Clarke](https://en.wikipedia.org/wiki/Clarke%27s_three_laws), _any sufficiently established technology won't be distinguished as technology at all_.
Comment: I agree. As I acknowledged in my response to the comment by @9072997, I think my question should be better worded as "which parts of music theory has predictive content". Some parts of it certainly does.
Answer: It's a broad generalization that discussion of "music theory" usually refers to Common Practice Tonality, or related ideas of scales, chords, modes, and so forth. These ideas are primarily descriptive and often subjective in their application.
However, there are music theories currently being studied and developed that attempt more objective/mathematical descriptions of music. And if not predictive, they are at least more objective in their application and study.
For example, in Music Through Fourier Space: Discrete Fourier Transform in Music Theory, Emmanuel Amiot writes,

The cutting-edge research is currently focused on the other component of Fourier coefficients, their directions ... [which] appear to model some aspects of tonal music with unforeseen accuracy.

Authors such as Amiot, Guerino Mazzola, Moreno Andreatta, Jason Yust, Carlos Agon, and Dmitry Tymoczko have written extensively on this and related subjects using algebraic, set theoretic, group theoretic, and category theoretic techniques.
There is also much research in neuropsychological aspects of music perception. Diana Deutsch has published extensively, especially in the area of musical illusions and perfect (absolute) pitch. She also wrote the textbook "The Psychology of Music", currently in its third edition.
Daniel Levitin is another major researcher in the area of music perception and cognition. From his Wikipedia entry:

As a cognitive neuroscientist specializing in music perception and cognition, he is credited for fundamentally changing the way that scientists think about auditory memory, showing through the Levitin Effect, that long-term memory preserves many of the details of musical experience that previous theorists regarded as lost during the encoding process. He is also known for drawing attention to the role of cerebellum in music listening, including tracking the beat and distinguishing familiar from unfamiliar music.
Comment: Thanks Aaron. This is rather eye opening to me.
Answer: The theory of music is a very wide subject, and most of it describes what happens rather than describes what must happen. It is a method of explanation that makes music make more sense (usually!).
There are certain aspects which must be adhered to - for example, in a piece in 4/4, each bar will contain the equivalent of 4 beats. Otherwise, it's not 4/4!
True, it does give us a language with which to describe music - which is very useful, and generally unequivocal, which should be the point of any language, for communication purposes.
As far as formulae for creating 'good' musc is concerned, theory can't do that. Music is far more an art than a science, so theory remains firmly theory, and won't become law. There are, however, well tried and tested ideas, which we can recreate, with subtle differences, that produce 'good' music.
Over periods of time, however, composers have eschewed the theory, to produce different music, some of which has found approval, despite 'not following the rules'.
Comment: "Over periods of time, however, composers have eschewed the theory, to produce different music" And one reason music theory is similar to science is that these new musics eventually get their own music theories, because as long as music exists, people will want to understand it.
Comment: *Analyzing music is very analytical and a "left brain task"; creating music is very inspirational and a "right brain task". To what extent do you agree?* This is another example of **opinion based**.  I agree that analysis based on the structural terms is left brain job, but not the kind of Hoffmanntal's analysis of Beethoven's 5th. I agree composing is more right brain activity but lot of fugue writing or sonatas can be the work of left brain hemisphere, especially 12 tone and serial compositions. This point could even be proofed statistically.
Comment: At the risk of sounding more ignorant than insightful, music theory, inasfar as it's a "scientific discovery of why things sound good", is almost a psychological science. "This sounds good", after all, isn't a scientific fact, it's a psychological fact -- it sounds good *to people in particular*, and an alien species would not be able to discover the general statement "it sounds good", but they may be able to discover the statement, "it sounds good to people", or maybe more specifically "to this group of people". So to that extent, understanding music is as much about understanding ourselves.
Comment: Very much appreciate your answer, and also very much agree. There is one more thing lingering in my mind: it seems that the set of great composers and great music analyzers are different people. Of course, this could be a small sample issue, or it could be not even true (due to my limited knowledge of music). However, this observation prompts to me wonder whether analyzing music is a very different skill than creating music. Analyzing music is very analytical and a "left brain task"; creating music is very inspirational and a "right brain task". To what extent do you agree?
Comment: @TKoL I think we are entirely on the same page here. By "this sounds good", I am restricting attention to homo sapiens. Snakes can also dance with music, but unfortunately we do not include them.
Answer:
It seems that, to a large extent, music theory is only giving us a language to describe music. It doesn't seem to have significant "scientific content" in the sense that "music theory predicts what is good music".

That is largely correct. There are some musicological studies that do attempt to examine and explain innate preferences, and the results of those studies are very relevant to music theory (and arguably form part of it) - but the enjoyment of music is largely subjective, and music theory cannot determine what is "good music". If you see any theory work saying that "A is better than B", you can take that as a shorthand for "audiences familiar with the genre of music we are writing about tend to prefer A to B".
Comment: I agree. If you know of any accessible materials (videos > books) on musicological studies that explore our innate preferences, I would love to learn!
Answer: "For instance, you can always chop up notes into chord tones vs non-chord tones; and then separate non-chord tones into passing tones and neighbor tones. These are very much just classifications."
This is not a great example to start with, as it presumes that chord tones had meaning in the first place.  A better example would be "why are chords generated from the pattern (1, 3, 5) to start".  By they way, what's wrong with classifying things?  The class division has meaning.  Are you opposed to major versus minor?
There is a tremendous amount of information to unravel to get to an answer.  Any fast and loose claims that it is or is not scientific are probably quite thoughtless.
There is great significance in the structure of the diatonic scale and the significance of the I, IV, and V chords within that scale.  They are in fact related to the natural harmonics in a harmonic sequence.  This is the type of sequence you get for a vibrating string or standing waves in an air column.  In contrast the natural harmonics of plates and other vibrating system do NOT follow this sequence.  Many musicians go through life thinking that all vibrating system obey f_n = n*f_1 but that is not the case.  There are many exotic "overtone" sequences.  So why then does most of Western music seem to gravitate towards the "harmonic sequence"?  It could have something to do with biology and how we are constructed (by evolution).  Our ears, and brain, are naturally tuned to this series of tones.  The nerves in the ear will self excite in the harmonic sequence when a pure tone is introduced, this is called aural harmonics.  The brain will think it hears a "fundamental" that is NOT present in the acoustic field that excites the ear due to a process called fundamental tracking.  Both of these phenomenon seem to suggest that nature has favored the harmonic sequence above all others.  Why?  I really do not know but would guess that it has to do with our use of vocal calls to communicate and the fact that our throats (or throat + head + vocal_chord system) are approximately described by tubes, which obey this sequence.
If we had evolved differently we might actually detest harmonics and the natural sequence of tones produced by them, e.g. the (1, 3, 5) which is the foundation of the major triad and the diatonic scale.
Much of what the general population finds "pleasing" about music (or in contrast "unpleasant") is related to combinations of tones that have supporting harmonic structure.  The German physicist Herman Helmholtz set out to provide a physics based explanation for the concepts of consonance and dissonance, as well as devices like authentic and plagal cadences.  His thesis was that these things are not merely one of many choices but essentially mandated by physics.  You can read about it in the text "On the Sensations of Tone" which is still in print today.  This is the foundation of musical acoustics and psycho acoustics.
Based on his work it might seem that the rules of music theory are in fact grounded in real science and are the only rules any human would arrive at given enough time and opportunity to explore all possible avenues.  However, I do not think this is true.  For one thing Helmholtz started with the premise that Western music theory was in some sense superior to that of other cultures, if it even existed in other cultures.  In other cultures, Indian music comes to mind, different scales are used that do not necessarily have tones related to the harmonic sequence.  They also lack the use of multi voice harmony, which is really where the rubber meets the road with respect to true "theory", e.g. the rules of harmony.  Harmony is what creates the opportunity to hear dissonance and the need to resolve it to consonance with a resolution.
I know this is not really what you are asking about but I do not think it is possible to completely separate these concepts.  We need to correctly identify them to understand how they are related but we cannot divorce them from one another completely.
The specific ideal of chord tone versus non-chord tone is significant as much of music has developed over the centuries or millennia so that we tend to favor harmonizing melodies in such a way that the notes are a chord tone.  That is rather than letting the melody move over a drone, if the notes leave the set of notes in one chord we move along with it by changing chords to support the melody.  This type of process creates the feeling of movement.  That does not mean that musicians MUST move with the melody by changing chords.  The composer that holds a chord while the melody moves in and out of the chord tones is choosing to say something.  They are creating a tonal landscape that may produce a feeling of conflict (that is not negative).  Whereas the composer who move chords with the melody is creating a feeling of support.  The fact the these two different approaches create different feelings in most listeners indicates the importance of having a language that helps us distinguish them.
The rules of Western music theory have evolved over time to reflect what might be considered best practices, those ideas that seem to work more often than not.  That doesn't make a perfect system, and it needs to evolve as we learn and create more.  But the fact is that it is a good starting point for developing musical ideas.  Artists that go to university will learn about color, light, shadow, perspective, etc.  And these are all very scientific.  But they don't tell the painter how to paint.  They merely provide the painter with a rubric for developing a visual piece that would indicate to the observer that there is a light source somewhere off in the distance, not seen in the painting.  The painter is not saying "the rules of light and color tell me what and how to paint" but they are saying "if I want to convince a person that the following things are true here is the trick I need to play".  That is how theory is used in the arts.  If a painter wants to destroy the idea of perspective to make a political statement then they can choose not to use the mathematically precise techniques that create realistic perspective.  Music theory works in much the same way.  The rules as we know them have some grounding in physics but as artists we are fee to break the rules at any time.  I might want to make the listener feel a sense of emptiness at the end of a song.  To do this I might choose NOT to end on I, or I might end on a suspension.  Music theory doesn't say "you must always end with a V7-->I with the I voiced in root position and Do in the melody" it does say "The aforementioned device creates the strongest sense of resolution from among all possible chord progressions".  That last statement is on pretty firm ground (but perhaps still only in terms of a general consensus).
"Thus, it seems that, to a large extent, music theory is only giving us a language to describe music. It doesn't seem to have significant "scientific content" in the sense that "music theory predicts what is good music". That is, it isn't true that "only music written according to XXX theory sounds good to an untrained ear". I emphasize "untrained" because people can be trained to prefer one style of music over another."
So, first of all "... a language to describe..." is exactly what any theory does.  I think you might be misusing these terms.  The foundation of music theory is vocabulary.  But that vocabulary is significant.  Even before we had a false theory of gravity, replaced by another which is probably also false, we had a rubric for explaining planetary motion based on observation.  Most of science is in fact "stamp collecting".  We observe, take notes, and develop recipes for recreating things that work.  Just because someone can come along and be contrary, stating "well I don't like what everyone else likes" doesn't mean that the rubric is useless.
Second, your use of "trained" versus "untrained" is deceptive.  The whole point of music theory is to provide a set of practices for producing music that would appeal to widest audience.  The greatest works of music throughout history were written for the masses (or masses, i.e. masses attending masses).  These "rules" are not based on what one or two musicians thought was best but what gets the most people in the door to pay for your music.
Comment: I learned a lot from your answer and appreciate your patience. I think there is a lot of miscommunication and misunderstanding, but that is largely due to my inaccurate wording of the question.
Comment: Well I hope it helped somewhat.
Answer: To paraphrase an old TV ad, "Music theory can't tell you why someone composed a piece, but it can tell you how it was done." This is more useful than it seems at first. If you hear something you like (or something close to what you like), you can learn how to get the same (and similar) effects. By studying lots of music, you can selectively choose the things you want to put together. Music theory can tell you how to assemble ideas musically (smoothly, roughly, lots of dissonance, very consonant, one melody, many melodies, voice, bassoon quartet, etc.). Whether it's good is subjective, music theory can tell you if you composed what you wanted, not if you like it.
Knowing lots of theory (and lots of music), one can tell if you have a new idea or are just copying something.
Whether or not something is "good" is not so simple. One can judge by cleverness of technique (objective), whether one enjoys listening (subjective, individually), or whether the music sells well (objective measure of collective subjectivity).
Comment: Why? To paraphrase Dr Edward Hewitt, "It gives one a good set of values to rebel against." One cannot avoid the unknown, only the known.
Comment: That's a nice way to look at it, _music theory as a means to actually assemble musical ideas_.
Comment: Knowing lots of theory should lead one to the conclusion that everything is just a copy of the canonical form.
Comment: I appreciate the answer. Asking whether music theory has "predictive power as a scientific theory" isn't really questioning whether it is useful (which I think is obviously true). Scientific theories aren't all useful. Not all useful approaches are scientific.
Answer: It seems like you are connecting "theory" to "science" but theories are not limit to science. There are theories in art too (color theory, poetics, etc.)
I think a general split you can make in music is "acoustics" for parts of music treated in a scientific way and "aesthetics" for music as art.
To some extent music theory is largely about giving names to musical elements. But in terms of theory this brings us into a philosophical realm of categorization. Certain aspects of music theory rely on careful categorization. For example, a basic harmony concept is chord roots move by descending fifths. Categories for chord types and non-chord tones are essential aspects of analyzing harmony and creating a theory of chord progression rather than mere objective labels.
That kind of music theory is historically from the time of the Enlightenment. Some is for even earlier times. That kind of philosophical thinking pre-dates our modern sense of science. To me it's more aligned with aesthetics than science.

"music theory predicts what is good music"

That's just flat out wrong. Theory doesn't do that.
Sure, music theory provides a kind of catalog of aesthetic ideas - things like: syncopated rhythms are... exciting, etc. - but that doesn't necessarily lead to "good music." Too many musical elements need to be integrated to make a final whole work and there is no theory for how to do that. An obvious pitfall in art that relies on such ideas at the risk of being cliche.
Comment: For me "color theory" is the first thing that comes to mind in art. But "poetics" would be another example, theory in literature.
Comment: Theory, when connected with science, means something altogether more rigorous than theory used in any other way though. Then actually "Theory (by science)" IS limited to science and there are no theories in art. I think your answer would be improved by connecting it to a non-science version of the word - since I believe a part of the answer is that one should not assume music theory to have scientific properties. I find when people use "in theory..." to mean "I never tested this" to be a rather sad pervesion of the word, but language fortunately belongs to everyone, not only scientists ;-)
Answer: This is very similar to an aspect of English grammar. We talk about descriptive and prescriptive grammars. I'll briefly discuss grammar and then move on to music.

A descriptive grammar tells us how people talk
A large body of text/speech can be analysed and rules derived from it. Usually there is a distinction between so-called Standard English and various dialects.
Example
Don't say anything (standard) and Don't say nothing (dialect)

A prescriptive grammar tells us how people should talk
Example
Don't say anything (correct) and Don't say nothing (incorrect)

In music similar distinctions apply, however there are different genres of music.
Example
In classical music theory, parallel fifths are prohibited, both in counterpoint and harmony.
In rock guitar, parallel fifths occur all the time, especially in power chords.
A classically-trained musician might classify power chords as incorrect. A rock musician would be lost without them.

Answer
In my opinion, musical theory can be either prescriptive or descriptive but you have to distinguish what theory you are talking about.  There are different theories for different genres of music.
Comment: Parallel 5ths do occur in some classical harmony as we've had questions on the site in the past. It's really only disallowed in polyphony as seen in counterpoint to make the voices as independent as possible. This can be seen in modern music today and while it's not the typical goal it can happen.
Comment: @Dom - Thanks for pointing that out. I was aware but didn't want to go down that rabbit-hole!  In fact, when one learns classical theory at music school, one is usually prohibited from using parallel fifths in basic exercises. Of course this doesn't stop real composers from using them. I was generalising to some extent however, and there is a parallel with prescriptive English grammar  where different grammarians disagree about what to prescribe.
Answer: Music theory is a descriptive science of the psychology of hearing music. Music theory takes the evidence that we have (like the fact that the octave sounds like one note, or that a small second sounds dissonant), and builds a more or less coherent model that summarizes what we see into relatively few and easy-to-remember rules.
Note that while music theory really only cares about how we perceive music, quite a large fraction of it also has very strong connections to physics and mathematics. For instance, the fact that we use 12 semitones to split the octave is connected to the fact that 219 is almost the same as 312. The same mathematical coincidence is the reason why the fifth is so important for harmonics. I could go on like this for quite a while. The point is, that many of the rules that comprise music theory can be shown to derive directly from mathematical and physical facts. So, music theory is not just about psychology, it also has a basis in more rigorous sciences.
Comment: @leftaroundabout Thanks for the edit. I always forget which sites offer Latex formulas and which don't.
Comment: I certainly agree that certain aspects of music theory -- such as what you have mentioned -- is very much science and is grounded in science. My question should be edited to ask "what parts of music theory has scientific content and what parts is purely arbitrary and/or specific to 18th century European music", I think.
Comment: @JLi Well, you can count everything to do with rhythm and structure as being down to psychology. You can count pretty much everything to do with harmonics as somehow grounded in math/physics. But psychology permeates even these parts (there is no physical foundation for the notion of a leading tone, for example). The part that's pure physics is the different sounds of the different instruments. Like an electric guitar having a very different sound when played around the 12th fret, as compared to playing near the neck.
Comment: I agree. By the way, I'm (somewhat) familiar with the "science" of harmonics, but not at all familiar with the science of rhythm and structure (connecting them to psychology). If you have any references I would really appreciate it.
Comment: @JLi Sorry, no references. I'm a physics guy, and I know the limits to that discipline. And I believe that anything in music theory that cannot be explained with math/physics, must be down to either psychology or the biology of the ear and hearing nerve themselves. The processing of the sound signals in the hearing nerve is already bordering on psychology again, there is not really a sharp distinction.
Answer: Excellent Question! This is is what confused me as I started music. A little background, I started with music at the (late) age of 24 years. I remember, I had no instrument at hand, and never played one before. So, the first thing that came to my mind: read about music theory, so that I have a good knowledge when it comes to the applied parts, i.e., playing an instrument. Bad idea, it was confusing, I could hardly make sense of it. I was a student of mathematics and computer science, so, acquiring knowledge "theoretically" seemed to be a natural approach. However, let me add, even in math you cannot approach a topic "purely" theoretical, you have to have some ideas about the concept that are described.
First, let us clarify what we mean by a theory. A theory should adequately describe a phenomenon, and should allow predictions and conclusions. However, as plausible as all this is, let us see what theory means in different branches of science.

Formal Logic

A theory in this sense starts with axioms, involving primitive notions, and rules of inference. By this, you can derive new facts. Here, what a theory is, is fully formalized. The idea stems from geometry, back to the axioms stated by Euclid, and attempts to formalize mathematics in the 19th and 20th century.

Natural, Social and Empirical Sciences

As already mentioned, Newtonian mechanics is a theory, for sure. I some sense, it could be understood in the first sense. But not every physical theory had been, and it is not clear if this is possible, formalized in the strict sense of logic mentioned before. However, every physical theory is formulated in the language of mathematics. But if we look at, for example, psychology, what makes a theory gets quite blurry. For example, Prototype theory, as least as presented in text books, is almost useless behind a basic level. For example, how to make predications based on these ideas in the same way as, for example, in Newtonian mechanics, or how to apply this theory, for example, in software engineering, either to predict how programmers form concepts of program code, or to model concepts in code? I do not see that it helps. I have a minor in psychology, and in my studies I have seen all kinds of theories of how the mind works, or certain things are processed when performing a task. Some of these theories are more predictive, for others it is not that clear what they predict. Other are very broad, for example, Chomsky's Generative Grammars. Anyway, psychologist are aware of these shortcoming, Behaviorism was once a way to deal with it, Mathematical psychology is the goal to formulate psychology like physics, or even more like an axiomatic systems as outlined above. You might also look up Cognitivim and Experimental Psychology.

Music

I am really not an expert on music. But to make the connection to my initial thoughts: Music Theory is not a theory in all of the senses outlined above. First, you need to know music to apply music theory, there are no axioms, nor rules of derivation on its own. In this sense it is more descriptive. Not so much to predict things, I would not even say to make sense of music, but more to describe what is there, reveal structures and to have a language.
There are, however, attempts to derive music theory from physical principles. Guess everyone is aware of the overtone series and frequencies ratios, which somehow explain consonances and dissonances. This goes back to Pythagoras, but the first more serious and broad approach was undertaken by Hermann von Helmholtz. And psychologists later tried to link physical objects and sensory sensations to musical sensations, see for example Levelt & Plomp. I once wrote a little program to demonstrate how unpleasent certain close frequencies sound,

I think the analogy to grammars mentioned here works also quite well. A grammar, for example, for english, or german, is descriptive. However, as mentioned before, a universal grammars has been proposed in context of the nature vs nurture debate and cognitivism. Let me add that there were attempts to derive music theory from the idea of "a universal grammar in all of our heads", see A Generative Theory of Tonal Music, a somewhat different viewpoint than merely the physical one.
Answer: Good question! That's why I think it's ridiculous to close here questions and criticizing answers as opinion based, except questions referring to historical theories related to their writers that can be proofed concerning their original content and concern.
All mathematical and physical fundamentals of course are scientific and proof able (measures, rhythm, waves, harmonics, even temperatures etc.)
Temperature is a good example: we can proof their basics, their historical development ... but not their psychological effects as e.g. the characteristics of the modes or keys. But we can discuss the discussions of their discussion. If we have our own meaning and make a statement about this theme it is called opinion based but if you cite a medieval monk - or pope! - you are scientific.
Answer: Music Theory is by all common sense is a way to describe and understand the mechanics of the numbers, harmonies, structures and ideas. Theory uncomplicates extended full jazz chords, time signatures and musical emotions that are created by the composer in order for Other musicians to get a fix on the piece. It IS by all accounts a language. If you know & comprehend music theory, you can hear a director say "Hey...That's a flat 5 on the Bass there".
Answer: "It doesn't seem to have significant "scientific content" in the sense that "music theory predicts what is good music"."
It has everything to do with it.
Octaves sound alike despite being double or half the frequency - the brain interprets dissonance/consonance as an integer multiple of ƒ.
What frequency (ƒ) between a note and its octave also sounds dissonant/consonant?... or rather the most dissonant/consonant?
It's the ƒ that is halfway - and that note is denoted as the fifth... it marks the harmonic increment of keys ... keys are to incrementing musical harmony as the number 1 is the numerical distance between adjacent integers.
The other notes between the octaves are fractions of fractions of distance between the octaves.
The reason the halfway note is denoted as the fifth is that the hand has four fingers. If each successive finger is allocated for one note then the fifth note would be starting over at finger #1 – the fifth note marking the beginning of the next key, the next harmonic increment.
In other words if we had 7 fingers there would be seven notes with fractional ƒ increments between the tonic and midway note (1.5x the ƒ of the octave).
Comment: To be fair and accurate there are humans who do NOT interpret octaves as the same note.  This has been measured scientifically.  It is a fairly recent discovery (last 5 years or so) and indicates that we may be culturally brain washed into accepting this.
Comment: @ggcg Neat! https://news.mit.edu/2019/perception-musical-pitch-cultures-0919
Comment: Yeah I was surprised


Alternar cores na tabela com PHP

Question: Tenho um código que exibe uma tabela em lista dos ID's registrados, e pra enfeitar, o código faz com que exiba 1 em 1 alternando as cores entre branco e cinza.

COR -> Branco
COR -> Cinza
COR -> Branco
COR -> Cinza ...

Como posso fazer com que uma estrutura de repetição while faça a mesma coisa?
<?php
   $sqln = mysql_query("SELECT * FROM post ORDER BY id DESC LIMIT ".$inicio.",".$max."");
   $num = mysql_num_rows($sqln);
   for($i = 0; $i < $num; $i++){
     $tituloP = @mysql_result($sqln, $i, "titulo");
     $n = $i + 1;
     $d = $i % 2;
     if($d == 0){$cor = "cinza";}else{$cor = "claro";}
     print '
 align="center">'.$tituloP.'
';
   }

?>

Não sei se faz diferença, só que agora estou utilizando mysqli.
<?php
   $sqln = mysqli_query($conn, "SELECT * FROM post ORDER BY id DESC LIMIT ".$inicio.",".$max."");
   mysqli_close($conn);
   while($num_q = mysqli_fetch_array($sqln)){
      $tituloP = $num_q['titulo'];
      print '
'.$tituloP.'
';
   }
?>

Comment: [Como mudar o fundo das linhas de uma tabela alternadamente? Com suporte pra navegadores antigos](http://pt.stackoverflow.com/q/173/91)
Comment: Não poste o código fonte como imagem.
Comment: Obrigado pela ajuda @rray, mas já consegui resolver o problema com a resposta do Kup
Answer: Podes fazer o mesmo, mas colocas um counter,
$index = 0;
while(...) {

    if($index%2==0){ echo 'class="branco"'; }
    else { echo 'class="cinza"'; }

    $index++;
}

Comment: Muito obrigado @kup
Answer: É possível fazer somente com CSS utilizando o seletor :nth-child().
Remover rotinas de formatação do seu código PHP facilita a leitura e a manutenção

tr:nth-child(even) {
  background-color: #fff;
}
tr:nth-child(odd) {
  background-color: #999;
}

 Number
 Name

 1
 Eve Jackson

 2
 John Doe

 3
 Adam Johnson

Alternar cores na tabela com PHP


Python, cant overide a method

Question: I have this code it will print "1" from the class parent_model_admin even I specified  super(admin_base, self).test() method, How do i print "2" in admin_base but through in admin class ?
class theme():
    pass

class parent_model_admin():

    def test(self):
        print("1")
        pass
    pass

class admin_base(theme,parent_model_admin):
    def test(self):
        print("2")
        pass
    pass

class user(parent_model_admin):
    def test(self):
        print("3")
        pass
    pass

class admin(user, admin_base):
    def test(self):
        super(admin_base, self).test()
        pass
    pass

hai = admin()
hai.test()

Comment: if i'm understanding you correct, why not just `print("3")` in `admin` class?
Comment: The issue here is called Method Resolution Order (MRO).  See the answer to the duplicate question for details of how this works.
Answer: Change the admin class to:
class admin(user, admin_base):
    def test(self):
        super(user, self).test()
        pass
    pass

Use super(user, self).test() instead.
Full code:
class theme():
    pass

class parent_model_admin():

    def test(self):
        print("1")
        pass
    pass

class admin_base(theme,parent_model_admin):
    def test(self):
        print("2")
        pass
    pass

class user(parent_model_admin):
    def test(self):
        print("3")
        pass
    pass

class admin(user, admin_base):
    def test(self):
        super(user, self).test()
        pass
    pass

hai = admin()
hai.test()

Output:
2

Python, cant overide a method


pseudo Anova Table for a GLS regression

Question: I fit a couple of GLS models, using the nlme pakage (gls() function), and I would like to obtain the pseudo ANOVA table as described by Griffis & Stedinger (2007). nlme doesn't calculate the pseudo Anova table. Despite I can understand the method described by Griffs and Stedinger, I am unable to program this. I am wondering if there is any R package that allows obtain this table.
Any help would be appreciated.
Answer: I'm not sure what the definition of "pseudo ANOVA table" is but you can obtain a comprehensive ANOVA for a gls fit in R using:
require(rms)
f <- Gls(....)
anova(f)

Comment: Griffis & Stedinger (2007) use the term pseudo, because the way how calculate the sum of squares is not the traditional one as that used in OLS.
Comment: It would be interesting to compare that with the simpler Wald partial $\chi^2$ test approach that most people use.

pseudo Anova Table for a GLS regression


Javascript to show price with 2 decimal places

Question: I have a form that has 5 fields for a user to put how much they want to pay for 5 separate items.  I then have it automatically totaling it at the bottom.  Since this total goes to a payment gateway I need to force it to round to 2 decimal places.
Can someone tell me how to change the code to do this?  I am a newbie with this.
Here is the code I have:

<input type="text" id="pay1Student1Total" name="data1" onKeyUp="calculatepay('pay1');" />

<input type="text" id="pay1Student2Total" name="data2" onKeyUp="calculatepay('pay1');" />

<input type="text" id="pay1Student3Total" name="data3" onKeyUp="calculatepay('pay1');" />

<input type="text" id="pay1Student4Total" name="data4" onKeyUp="calculatepay('pay1');" />

<input type="text" id="pay1Student5Total" name="data5" onKeyUp="calculatepay('pay1');" />

Total:
<input type="text" id="pay1payTotal" onKeyUp="calculateTotal();" value="0"/>

Comment: possible duplicate of [JavaScript: formatting number with exactly two decimals](http://stackoverflow.com/questions/1726630/javascript-formatting-number-with-exactly-two-decimals)
Comment: Did my answer do what you were looking for? If so, could you please toggle the check button next to it? It won't hurt, promise!
Answer: You can use the toFixed(2) function in JavaScript to convert numbers to a fixed value.
It's used like this:
payTotal.value.toFixed(2)

So if the input value is 1, it'll look like 1.00
Comment: When I made this change to the code it did not work.  I think I may have added to the wrong location.  Where in the code do I add this?
Answer: You can use .toFixed() method :
var x = 5.1232;
console.log(x.toFixed(2));

Answer: Use this : toFixed(2); It will round to two decimal places
Answer: var x = 5.1232;
console.log(Number(x.toFixed(2)));
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: You can use Math.round(num * 100) / 100
Comment: Not sure how to use this method either.  I tried to add this also and it did not work.  Where in the code do I add this?  Thanks.


Drush site install break when a custom commerce feature is enabled, why?

Question: The D7 site i'm working has a feature that includes two custom product types, amongst other things.  A custom feature gets auto-detected and added as a dependency because it contains a rule on one of the product types.  Another feature added to the site install profile contains the permissions to those types.
After i exported the features and tried to install the site again, it breaks because:

the product types are do not get created, i expect this log entry to show but does not:
WD features: Rebuilding feature_name / commerce_product_type
Which, i'm guessing, is when the types get created from the feature.  That log entry shows on a successful build (see below).
consequently, the permissions feature causes a fatal error when trying to insert the types permissions into the db, since they don't exist and not defined by a module (from commerce_entity_access_permissions).

The solution for the fix is to manually remove the auto-detected feature with the rules.
I assumed that there's something wrong with that feature but can't think of what.  Has anyone experienced something like that?
Comment: You may want to check your PHP memory. For some reason Commerce installs use a lot of it. If you are running out, your PHP log should tell you.
Comment: no such log entry found... would that also show in the drush output by any chance?
Comment: The location of the PHP error log is given by the configuration variable 'error_log'. If you are running phpinfo, it will display the value in the 'core' section.
Comment: cool, that's where i looked.
Comment: I think i found a small bit of what could be the problem.  When i manually reordered the feature's dependencies, i got a different error.  I moved the commerce_features above the custom one, and the commerce_product_types feature component was recognized.  The new error doesn't break the site install.  More to come when i figure out a better solution then re-ordering the feature's dependencies.
Comment: Still not sure why yet, but reordering dependencies work.  The other error i was seeing was from a custom module that was also added to the feature (auto-detectedly, not that this fact matters though...).  Once i moved it below the rest, the site install was successful.
Answer: It seems to be a problem with Features and how Drush site-install processes.  Basically, features_include() is called after each feature is enabled during the site install.  Somehow (but most likely due to the ordering of the dependencies), the commerce_features module gets enabled after my custom feature.  As such, features_include(), which has already ran and cached its data, skips calling commerce_features_features_api(), which is crucial for my custom product types, included in yet another custom feature, to be created.
I opened an issue at http://drupal.org/node/1334438, see for more details and follow-ups.


Unit Testing with Nunit, Ninject, MVC2 and the ADO.Net Entity Data Model

Question: I'm trying to get my head around using Nunit, Ninject, MVC2 and the ADO.Net Entity Data Model.
Let's say I have have a ProductsController instantiating a SqlProductsRepository class.
public class ProductsRepository : IProductsRepository
{
    public MyDbEntities _context;

    public ProductsRepository()
    {
        _context = new MyDbEntities();
    }

    public IList<Product> GetAllProducts()
    {
        return (from p in _context.Products select p).ToList();
    }
}

public class ProductsController : Controller
{
    public ActionResult ProductsList()
    {
        ProductsRepository r = new ProductsRepository();
        var products = r.GetAllProducts();

        return View(products);
    }
}

I'd like to be able to perform unit testing on ProductsRepository to ensure this is returning the correct data but i'm not sure how to write the Test Class.
Every tutorial/document I've read so far points me to creating a Mock object using IProductsRepository and then injecting and testing the Controller.
This seems, to me, to bypass the concrete implementation.
MyDbEntities comes from an ADO.Net Entity Data Model .edmx
Answer: You're exactly right- mocking the repository does bypass the concrete implementation.  That's the point.
Unit testing is not the same thing as functional testing. Your mock object can be set up to return whatever you explicitly define, then you test to ensure that constant inputs from your mock lead to expected results.
Comment: Ok, i'm with you. My intention was to inject a representation of the db to replace the context in order to test the repository methods themselves.
Would this not be a good thing to do?
Comment: You could do that, but that's really what mocking is for. The idea is that you want to have coverage for each major path of your business logic code, so wire up a mock in each test to return results that test those paths.  This will make your tests small and tight.
Comment: Cheers. I guess I've got a mix up in the terms used. How would I go about creating the Mock in order to test the repository?
Comment: Depends on what mocking tool you use.  The syntax is similar between them.  What you're doing with the mock is creating a "fake" object where you "lock" methods on the mock to return the same result every time.  Look into NMock and Moq, those are the .NET-based mocking tools I've seen and used before.
Answer: It sounds like you're wanting to create an integration test for ProductsRepository rather than a unit test, since you'd be testing against the database so that you can check it's giving you the right data.
It's when unit testing the Controller that you'd want to mock the ProductsRepository.
In my integration tests for ProductsRepository, I'd be doing the obvious things like
public void TestProductsRepository()
{
  var context = new MyDbEntities();

  // add a new product

  var products = context.GetAllProducts();

  // check products contains new product
}

Comment: I'd like to test more complex methods in the repository such as:

GetProductByBrandNameAndProductTypeAndProductName(string brandName, string productTypeSysName, string productName)

To ensure this is returning the correct data. I thought this might be a valid unit test
Comment: That's definitely a valid thing to test, but I probably wouldn't describe it as a unit test because your repository is having to integrate with Entity Framework to get the result.
Answer: With your two classes (ProductsRepository, ProductsController), you should have two sets of tests. One set of tests for each class.
When (unit) testing the ProductsController, you should mock its dependencies (in this case, the IProductsRepository). Bypassing the concrete implementations of the dependencies is the point.
There will be a completely different set of (integration) tests to validate that the ProductsRepository can hit the database and return correct data. In these integration tests you won't mock anything, since what you're testing is the interaction between a real repository with the actual database.


Class active no menu include

Question: Em minhas páginas PHP utilizo um include para chamar um arquivo que contém meu menu:
<?php include("menu.php"); ?>

Arquivo com menu:

Hosting

SHARED HOSTING

FREE HOSTING

CLOUD HOSTING

RESELLER HOSTING

DOMAINS

Servers

CLOUD VPS

DEDICATED SERVERS

ORDER SLIDER

Quando o menu está ativo fica com essa class
class="current-menu-item"

Como faço para inserir a class active apenas no menu acessado?
Answer: Faça o menu.php assim:
<?php
    /**
    * Verifica o script ativo e compara com $script indicado;
    * Se a comparação for positiva, imprime a CLASS;
    * Se a comparação falhar, retorna FALSE.
    * @return string|boolean
    */
    function setClass($script = NULL){
        $ativo = str_replace('/','',$_SERVER['PHP_SELF']);
        if($ativo == $script){
            echo 'class="current-menu-item"';
        }
        return FALSE;
    }
?>

<a <?=setClass('testing.php')?> href="testing.php">Hosting

<a <?=setClass('hosting-shared.php')?> href="hosting-shared.php">SHARED HOSTING

<a <?=setClass('free-hosting.php')?> href="free-hosting.php">FREE HOSTING

<a <?=setClass('cloud-hosting.php')?> href="cloud-hosting.php">CLOUD HOSTING

<a <?=setClass('reseller-hosting.php')?> href="reseller-hosting.php">RESELLER HOSTING

<a <?=setClass('domains.php')?> href="domains.php">DOMAINS

Servers

<a <?=setClass('cloud-vps.php')?> href="cloud-vps.php">CLOUD VPS

<a <?=setClass('dedicated-servers.php')?> href="dedicated-servers.php">DEDICATED SERVERS

<a <?=setClass('order-slider.php')?> href="order-slider.php">ORDER SLIDER

Answer:
Isso é uma outra opção sem uso de PHP!

Uma vez é algo visual acredito que possa ser tratado no lado do cliente, usando Javascript/Jquery.
Por exemplo:
var pagina = window.location.pathname.split('/')[ window.location.pathname.split('/').length - 1 ];

$('.menu').find('a[href="'+pagina+'"]').closest('li').addClass('current-menu-item');

Supondo que essa isto:

Hosting

SHARED HOSTING

FREE HOSTING

CLOUD HOSTING

RESELLER HOSTING

O JQuery irá buscar pelo a que possua href igual à página que o usuário está acessando, então irá localizar o li mais próximo e então adicionar a classe current-menu-item nele.
Basicamente funcionará assim:

Encontra qualquer elemento de  classe menu
Encontra a com href igual a variável pagina
Encontra li mais próximo
Adiciona classe current-menu-item

Class active no menu include


Are there any special rules when making a substitution in an integral?

Question: Please consider the integral:
$$\int_{-a}^{a}x^2dx=\frac{2a^3}{3}$$
I would like to know why I can't make the substitution:
$$u=x^2$$
When I make the substitution, the limits of the integral will be the same, and the integral itself will be zero, which is the wrong answer. So why does this simple change of variables not work as I have expected?
Please note that I do not want help solving the integral, I know how to solve it several ways. My question is why does this specific attempt at a solution not work?
Comment: Things like this are the stupidest problems you would probably expect to be much more simple, but no, just because $x^2=(-x)^2$, everything breaks down.  $\displaystyle\overbrace{\left(\ddot{\stackrel{\quad>}{\frown}}\right)}_{\begin{align}\hline\qquad\end{align}}$
Comment: Does this answer your question? [Why does this $u$-substitution zero out my integral?](https://math.stackexchange.com/questions/829939/why-does-this-u-substitution-zero-out-my-integral)
Comment: See Theorem 12.12 of [this](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&cad=rja&uact=8&ved=0ahUKEwjOioWK8aLQAhXBsY8KHU2BB2IQFggkMAE&url=https%3A%2F%2Fwww.math.ucdavis.edu%2F~hunter%2Fintro_analysis_pdf%2Fch12.pdf&usg=AFQjCNEmMJtZTsn77hCX7usEqHyQ7sQYIg). Also [this](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=8&cad=rja&uact=8&ved=0ahUKEwjOioWK8aLQAhXBsY8KHU2BB2IQFghJMAc&url=http%3A%2F%2Felib.mi.sanu.ac.rs%2Ffiles%2Fjournals%2Ftm%2F34%2Ftmn34p25-28.pdf&usg=AFQjCNGk6YxCJXQBuNDvbcYbTsdOtTLZIA) may be of interest.
Answer: This is a great question, and I find that variants are often poorly understood. Let's carry out the substitution completely. Since $a$ clearly doesn't matter, I'll suppose that $a = 1$ for simplicity.
$$ \int_{-1}^1 x^2 dx = \frac{1}{2} \int_{-1}^1 x \cdot 2x dx.$$
In this form, we substitute $u = x^2$, so that $du = 2x dx$. Then in the integral, we have
$$ \frac{1}{2} \int_{-1}^1 \underbrace{x}_{\pm\sqrt u} \cdot \underbrace{2x dx}_{du}.$$
To complete the substitution, we need to substitute $x = \pm \sqrt u$. I write $\pm$ to indicate that sometimes we have $x = \sqrt u$ and sometimes we have $x = - \sqrt u$. In particular, when $x$ is negative, we choose the negative square root, $x = - \sqrt u$. This ambiguity is very important.
Namely, for $x$ in $[-1, 0]$, we have that $x = -\sqrt u$ and for $x$ in $[0, 1]$ we have that $x = \sqrt u$. Then to perform the substitution, we split the integral into these two intervals and handle each separately.
$$\begin{align}
\frac{1}{2} \int_{-1}^1 x \cdot 2x dx &= \frac{1}{2} \int_{-1}^0 x \cdot 2x dx + \frac{1}{2} \int_{0}^1 x \cdot 2x dx \\
&= \frac{1}{2} \int_1^0 (- \sqrt u) du + \frac{1}{2} \int_0^1 \sqrt u du \\
&= \frac{1}{2} \int_0^1 \sqrt u du + \frac{1}{2} \int_0^1 \sqrt u du \\
&= \int_0^1 \sqrt u du = \frac{2}{3} u^{3/2} \bigg|_0^1 = \frac{2}{3}.
\end{align}$$
The exact nature of the substitution is very important. This causes some introductory texts to state that substitutions must be injective. But a careful analysis shows otherwise. $\spadesuit$
Comment: @mixedmath: your substitution is injective; that's why you can do what you did. Substitution comes from the equality  $$\int_a^bf (x)dz=\int_{g (a)}^{g (b)} f (g (t))\,g'(t)\,dt, $$which requires  $g $ to be injective on $[a,b] $ to hold.
Comment: Thanks very much. I think this is one of those examples of me learning a topic in high school, which was not a fully rigorous treatment, and then going through the next 10 years thinking I understood it in full detail when really I did not! Thanks again.
Comment: I don't even understand why you (and others) present substitution this way. This isn't even a substitution to me; it's a clever symbolic manipulation. A *substitution* would involve substituting something for a *variable*, in this case $x$. So if you want $u = x^2$, then you have to solve for $x$ and then substitute that into the integral, which incidentally forces you to determine the sign of the square root at the first step: $x = \sqrt{u}$, $dx = \frac{du}{2\sqrt{u}}$ etc...
Comment: @Mehrdad Sometimes it is about which way comes out better for the audience.
Comment: @mixedmath: but what you are doing is splitting your integral in two halfs, and in each if them your substitution is injective.
Comment: @MartinArgerami   [The point](https://math.stackexchange.com/a/4637590/21813) is that it is unnecessary to *separately* ensure injectivity, since ending up with injectivity on every interval of application of the change-of-variable theorem is a *consequence* of successfully expressing the given integrand in an amenable form. $\quad$ Furthermore: [an example](https://math.stackexchange.com/a/2518470/21813) of a non-injective integration substitution that works validly and perfectly.
Comment: It is not necessar that the substitution function be injective. Indeed, that is part of the point of this answer. For more on the often-thought necessity of injectivity, see [this answer](http://math.stackexchange.com/a/470460/9754) to http://math.stackexchange.com/q/470411/9754
Answer: I like Alfred's point but I would say it slightly differently.  The $dx$ at the end is not just the "other end" of the integral delimited on the left by $\int$.  It's also not just the indicator of which variable is being integrated.  It's part of the integral itself.  In other words, we don't integrate functions $f(x)$ so much as forms $f(x)\,dx$.
When we make a substitution, we have to substitute fully the entire form from one involving $x$ to one involving $u$.  When integrating $x^2\,dx$, if we substitute $u = x^2$, we must substitute for $dx$ in terms of $u$ and $du$.  Since $\frac{du}{dx} = 2x$, we write $du = 2x\,dx$.  Thus $dx = \frac{1}{2x}\,du = \frac{1}{2\sqrt{u}}\,du$.  So
$$
 \int x^2 \,dx = \int u \frac{1}{2\sqrt{u}}\,du = \frac{1}{2}\int \sqrt{u}\,du
$$
That's different from $\int u\,du$.
I think you were just switching the differential from $dx$ to $du$ without substituting.  You can avoid this mistake if you remember that $dx$ and $du$ are part of the integral.
Comment: -1: for two reasons. The "integral of a form" point of view might fit some areas of math, but it is definitely orthogonal to many others ( I don't see how you would describe the dual of $C [0,1] $ by thinking of integrals as "integrals of forms"). More importantly,  this does not answer the question; the OP clearly knows how to do substitution, and is asking what happens with the limits in his example.
Answer: It´s supposed, when using substitution to evaluate a definite integral, that you reverse substitution before apply limits. As you choose to substitute $u = x^2$ and so $du = 2x dx$, you have to "adjust" the integral before perform that substitution:
$$\int_{-a}^a x^2 dx = \frac{1}{2} \int_{-a}^a \underbrace{x}_{u^{1/2}} \cdot \underbrace{2x dx}_{du} $$
As it´s planned to reverse the substitution, it´s better avoid to adjust the limits of the integral and evaluate it as an indefinite integral:
$$\begin{align}
 \frac{1}{2}\int u^{1/2} du=\frac{1}{2}.\frac{2}{3} u^{3/2} + C=\frac{1}{3} u^{3/2} + C
\end{align}$$
Reversing substitution, i.e. $u = x^2$, and applying limits:
$$\begin{align}
 =\frac{1}{3} {(x^2)}^{3/2}\bigg|_{-a}^a  =\frac{1}{3} x^3 \bigg|_{-a}^a =\frac{1}{3} a^3 -\frac{1}{3} {(-a)}^3 =\frac{2}{3} a^3
\end{align}$$
Comment: It's still hazardous to apply indefinite integrals outside of their domains. And $(x^2)^{3/2} = x^3$ only when $x$ is positive. Altogether I think it's really far better to split the integral into two parts, one for $[-a,0]$ and one for $[0,a]$, at the very beginning and avoid all these pitfalls.
Comment: It's interesting that in the end this comes out to the same value as if we did the integral without any attempt at substitution, because some of its intermediate steps are not right. For one thing, the interval of integration is not adjusted for the substitution; if $u=x^2$ then setting $u=a$ is not the same thing as setting $x=a$; and setting $u=-a$ does not work at all within real analysis.
Comment: @DavidK , thank you for your comment. The reason why it comes out the same value is because I didn't replaced the limits on _u_.They were replaced after sbstitution was reversed to _x_. But you are right on mentioning those limits were not adjusted when substitution was done, so I edit my post to better affording, using, now, an undefined integral.


Converter ArrayList em Object[][]

Question: Como fazer a conversão de um ArrayList para um Object 2D.
Meu Código Atual:
ArrayList<String> a = null;
    a = new ArrayList<String>();
            a.add("ABC");
            a.add("DEF");
            a.add("1");
            a.add("1");

//Converter para Object 2D
int n = a.size();
System.out.println("Tamanho do Array: "+n);
Object[][] data = new Object[n][];
for (int i = 0; i < n; i++)
    data[i] =    a.toArray();

Desse jeito eu consigo pegar o primeiro valor do ArrayList, porém ele se repete em todas as posições, acredito que o motivo é porque não estou solicitando outras posições do arraylist na linha data[i] =    a.toArray();, tentei alterar essa linha para data[i] =    a.get(i); mais nesse caso recebo o erro "Type mismatch: cannot convert from String to Object[]"
Comment: Então falta muita informação aí, sem entender o problema completamente não tem como responder isso.
Comment: O que deve ter na segunda dimensão?
Comment: @Maniero, no meu arraylist eu obtenho os dados de uma tabela do banco de dados com a seguinte estrutura (Unidade Metálica, Aço, Tempo de Forno, Uniformidade). Eu preciso que cada linha recebida seja armazenada em um object 2D, mais estou sem nenhuma ideia de como fazer isso.
Comment: Ok, vou atualizar a pergunta.
Comment: Esta pergunta tem cheiro disso: https://pt.meta.stackoverflow.com/q/499/132
Comment: @VictorStafusa, você está correto, estou pensando em uma forma de apresentar melhor o meu problema.
Answer: ArrayList<String> a = null;
a = new ArrayList<String>();
a.add("ABC");
a.add("DEF");
a.add("1");
a.add("1");

//Converter para Object 2D
int n = (a.size() + 1) / 2;
System.out.println("Tamanho do Array: " + n);
Object[][] data = new Object[n][n];
int temp = 0;
for (int i = 0; i < data.length; i++) {
    for (int j = 0; j < data.length; j++) {
        data[i][j] = a.get(temp);
        temp++;
    }
}

for (int i = 0; i < data.length; i++) {
    System.out.print("[");
    for (int j = 0; j < data.length; j++) {
        System.out.print(" " + data[i][j] + "");
    }
    System.out.println("]");
}

Converter ArrayList em Object[][]


Is it correct to delay a Task using TimeSpan.FromTicks?

Question: My program needs to constantly perform many repetitive calculations as fast as possible. There are many tasks running parallelly which cause CPU utilisation is at 100%. To let users slow down processing overload(a little under 100% of CPU, depending on hardware), I added
await Task.Delay(TimeSpan.FromMilliseconds(doubleProcessingCycleIntervalMilliseconds));

to heavy processing methods. This works perfect as far as value of doubleProcessingCycleIntervalMilliseconds is at least 1 ms.
For users who have high-end computers(calculations speed will take less than one millisecond), I wanted to add same option for delay but instead of milliseconds using ticks. So now code looks:
if (ProcessingCycleIntervalOptionsMilliseconds == true)
{
   await Task.Delay(TimeSpan.FromMilliseconds(doubleProcessingCycleIntervalMilliseconds));
}
else
{
   await Task.Delay(TimeSpan.FromTicks(longProcessingCycleIntervalTicks));
}

When walue of longProcessingCycleIntervalTicks is at least 10000 ticks(=1ms) program works perfect. Unfortunately when values go under 1ms(0 for doubleProcessingCycleIntervalMilliseconds which I can understand) or under 10000(i.e. 9999 for longProcessingCycleIntervalTicks) program becomes not responsive. So literally difference of 1 tick below 1ms hangs the program. I don't use MVVM. (Just in case: I checked Stopwatch.IsHighResolution gives true on the development computer)
Is it possible/correct to use
await Task.Delay(TimeSpan.FromTicks(longProcessingCycleIntervalTicks));

in .NET 4.5.1 ? If yes, then how to determine when user can use it?
Comment: Windows is not a realtime operating system, and its precision is not that accurate. So, you can not use ticks, you can not even use ticks below ~15 ms. You should change your design.
Comment: By using a while or for you are dedicating full CPU time to the loop, You will be blocking any other tasks happening on that core/CPU and will result in really crappy performance. You need a way to manage what is being processed so that the OS can still do all the other stuff it needs to do. By using events the CPU will do a small task (very quickly) then the OS will report back what has happened and then the program can request that another function be processed. This sounds long but all happens in probably a 100000th of a second - it really does not require many clock cycles...
Comment: Can you give some more information on what these tasks are, and how they're being kicked off? If you're running into issues with thread saturation, you could implement a TaskScheduler (http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(v=vs.110).aspx) that could limit the degrees of parallelism. It's hard to say without understanding more of what it is you're trying to do.
Comment: Inside of several async Tasks are methods which are looped/constantly repeated till Task is cancelled. Methods monitor prices and react according to predefined conditions. They should perform as fast as possible(depends on user's hardware) but keeping CPU usage level little below 100%. Parallelism is limited to numer of cores.
Comment: By looped I hope you don't mean using `while`'s or `for`'s...
Comment: Yes methods are in while(!token.IsCancellationRequested)
Comment: @Michael Coxon "By using a while or for you are dedicating full CPU time to the loop" That's why I used Task.Delay.
Comment: @L.B Actually when I use 10000ticks which is 1ms, all is ok.
Comment: @as74 sorry, *You think* you sleep 1 ms, it is actually much more than this, as I said ~15 ms, depending on the system.
Comment: I really think there is a major bug lurking there. I just played around with some test projects and yes, 9999 (fortunately not 666 :-) ) seems to be a magic number, even if the underlying hardware/OS supports it.
Very strange, not really annoying as you shoudn't use the clock that way and typical M$.
Answer: Your intention is not to keep CPU utilization below 100%. Your intention is to keep the system responsive. Limiting CPU utilization is a misguided goal.
The way you do this is by using low priority threads. Use a custom task scheduler for your CPU bound tasks.
Timing in Windows has limited accuracy. Thread.Sleep cannot work with fractional milliseconds. .NET rounds them away before handing over to Sleep.
Answer: You might be better off looking at the way you are performing the tasks rather than trying to sleep them.
The best way I can think of is by using a task manager to manage each task independently (such as a background worker) and then thread collections of tasks.
This would enable you to manage how many tasks are running instead of trying to 'slow' them down..
i.e
public class Task<returnType>
{
    public delegate returnType funcTask(params object[] args);
    public delegate void returnCallback(returnType ret);

    public funcTask myTask;
    public event returnCallback Callback;

    public Task(funcTask myTask, returnCallback Callback)
    {
        this.myTask = myTask;
        this.Callback = Callback;
    }

    public void DoWork(params object[] args)
    {
        if (this.Callback != null)
        {
            this.Callback(myTask(args));
        }
        else
        {
            throw new Exception("no Callback!");
        }
    }
}

Then you need a manager that has a Queue in it of the tasks you want to complete, call myQueue.Enqueue to queue, myQueue.Dequeue to run the tasks. Basically you can use the already built-in Queue to do this.
You then can create a Queue of task managers full of tasks and have them all run asychronously, and stack nicely on the CPU as they are event driven and the OS and .NET will sort out the rest.
EDIT:
To continuously run tasks you will need to create a class that inherits the Queue class, then call an event when something is de-queued. The reasoning behind why I say to use events is that they stack on the CPU.
For a neverending stackable 'Loop' something like this would work...
public class TaskManager<T> : Queue<T>
{

    public delegate void taskDequeued();

    public event taskDequeued OnTaskDequeued;

    public override T Dequeue()
    {
        T ret = base.Dequeue();
        if (OnTaskDequeued != null) OnTaskDequeued();
        return ret;
    }

}

In your function that instantiates the 'loop' you need to do something like...
TaskManager<Task<int>> tasks = new TaskManager<Task<int>>();

Task<int> task = new Task<int>(i => 3 + 4, WriteIntToScreen); // WriteIntToScreen is a fake function to use as the callback

tasks.Enqueue(task);

tasks.OnTaskDequeued += delegate
{
   tasks.Enqueue(task);
   tasks.Dequeue.Invoke();
};

// start the routine with
tasks.Dequeue.Invoke(); // you call do some async threading here with BeginInvoke or something but I am not gonna write all that out as it will be pages...

To cancel you just empty the queue.
Comment: Agreed with the fact that if you are adding a delay to your operation, then you are seriously doing something wrong.
Comment: I can not manage numer of running tasks. If user wants to start using some functions they must be started. If his computer is not efficient enough then he can use delay to still perform what he wants but at the cost of lower speed.
Comment: Not sure if I fully get what you mean here. Can you please explain what you need to do fully as you did not mention the system would need to scale depending on how the user was using the application. i.e... are they multiple calculations that need to be run depending on what calcs the user starts?
Comment: The program constantly monitors market. Let's assume there is 20 instruments. For each of them user wants to start monitor prices plus other factors, calculate them all and react. Calculations can not be driven by events, that's why they are constantly repeated(looped till cancelled/stopped by user).


Get selected dropdownlist value inside a repeater control

Question: I have dropdownlist inside of a repeater control that I'm trying to get the value of and I'm getting "Object reference not set to an instance of an object". I am not sure what else to try.  Thanks
ASPX CODE:
   <asp:Repeater ID="GeneralRepeater" runat="server"
             OnItemDataBound="GeneralRepeater_OnItemDataBound"
                onitemcommand="GeneralRepeater_ItemCommand">
            <HeaderTemplate></HeaderTemplate>
            <ItemTemplate>

                 <asp:DropDownList ID="GeneralDDL"  AppendDataBoundItems="true"  DataTextField="DiagnosisCode"
                  DataValueField="DiagnosisCode" runat="server" AutoPostBack="True" />

            </ItemTemplate>
            <FooterTemplate></FooterTemplate>
            </asp:Repeater>
        </asp:Panel>

CODE BEHIND:
protected void GeneralRepeater_OnItemDataBound(object sender,
                                               RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item ||
            e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DropDownList myDDL = (DropDownList)e.Item.FindControl("GeneralDDL");
            Diagnosis oDiagnosis = new Diagnosis();
            DataView dv = new DataView(oDiagnosis.GetDiagnosis());
            myDDL.DataSource = dv;
            myDDL.DataTextField = "DiagnosisCode";
            myDDL.DataValueField = "DiagnosisCode";
            myDDL.DataBind();

        }
    }

protected void cmdSave_Click(object sender, EventArgs e)
{
    string ProductSelected;
    string FeatureSelected;
    string SectionSelected;

    foreach(RepeaterItem dataItem in GeneralRepeater.Items)
    {
         ProductSelected = ((DropDownList)GeneralRepeater.FindControl("GeneralDDL")).SelectedItem.Text; //error Object reference not set to an instance of an object.
    }
}

I having problem on Saving the selected value..
Answer: What i find in the code is you are looping through the generalrepeater items. You are accessing the repeater item as dataItem.  I tried out this code out here and ideally your code should say
foreach(RepeaterItem dataItem in GeneralRepeater.Items)
{
  ProductSelected = ((DropDownList)dataItem.FindControl("GeneralDDL")).SelectedItem.Text; //No error
}

instead of
foreach(RepeaterItem dataItem in GeneralRepeater.Items)
{
   ProductSelected = ((DropDownList)GeneralRepeater.FindControl("GeneralDDL")).SelectedItem.Text; //error Object reference not set to an instance of an object.
}

Comment: I haven't tried this, but I think ecoGreen is right. Though "dataItem" might be a bit of a misnomer.


How to give exec code meaningful location to show if exception?

Question: The code given to exec below will pass without compile errors, but will result in an run-time error at "error" statement:
globs = {}

exec('''
def main():
    print('Hello Python')
    error  # Makes run-time error
''', globs)

globs['main']()

The error message is:

    Traceback (most recent call last):

      File "C:\work\sandbox.py", line 11, in
        globs['main']()
      File "<string>", line 4, in main
    NameError: name 'error' is not defined

The location information of only File "<string>", line 4, in main is not very useful, for example when trying the locate the origin of the code which can be from a file.
Note that the above is a simplified example to show the issue.  In the actual program the code defines several functions that are executed at different locations in the main program.
Is there some way to provide the code from exec with another location than "<string>", so this other location is shown if an exception occurs in the exec code?
Comment: I reopened because the duplicate question is not the same (it asks how to get the "line 4" in code).
Comment: I'm not sure the duplicate actually answers this question, which seems to be about passing something more useful than "" as source for the code executed by `exec`.
Comment: If someone can give me a use case for `exec(...)` in Python, I would appreciate it.
Comment: @interjay (and AndreLaszlo comment): Thanks for reopening, since the duplicate handles the case where `exec` itself causes the exception, but this is not the case in this question, since the exception does not occur until later when a function in the `exec` code is called
Comment: Related question: [python - File "" traceback with line preview - Stack Overflow](https://stackoverflow.com/questions/47183305/file-string-traceback-with-line-preview). If the code does come from a physical *source file* then it helps, but otherwise not really.
Comment: Does this answer your question? [How do I set the filename of a module in Python so that exceptions that occur in the module use that filename?](https://stackoverflow.com/questions/12977578/how-do-i-set-the-filename-of-a-module-in-python-so-that-exceptions-that-occur-in)
Answer: You can first compile your code and give it a filename argument:
code = compile('error', 'foo.py', 'exec')
exec(code)

Output:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "foo.py", line 1, in <module>
NameError: name 'error' is not defined

Comment: The only way I could come up with is quite an ugly hack: `code = compile(('\n' * 99) + 'error', 'foo.py', 'exec')`. That would give you the same error but on line 100 :) I tried setting the `co_firstlineno` property of the code  but it's read-only just like `co_filename`.
Comment: Thanks, that did it :-)  Btw. is there some way to specify a line-number offset, for use if the compiled code does not start at line 1 in the source file ?
Comment: Not pretty, but I think it will do the job and is robust. Thanks :-D
Answer: Write the code you're execing to a file, and run it.
Or better still, accept code input from a file in the first place. This is potentially more secure and makes the code more easily auditable. It also makes it easier for the user to change it later, if that feature is desired.
You should avoid using exec for code you don't control - it's extremely dangerous. Unless you're writing  procedurally generated code, there's no reason for using it.
Comment: The code defines a number of functions that can be called later, and allows users to easily extend a main Python program.  The code given to `exec` is no different from the main Python program; just gives a way to extend the program in a easy way, so I don't think this make the use of `exec` "dangerous".
Comment: Thanks for the update, and good point about not using `exec` to let in 3rd party uncontrolled code.
Comment: @EquipDev You're absolutely right. If you're absolutely sure that you're executing code provided by the user, `exec` is safe. The problem is not as much with `exec` as it is in getting code from the user; that's the part that's different from your main python program - the mechanism for obtaining the code. This is also why using files is a better idea.
Comment: Another reason is to read the code from a file, and then preprocess the code; one type of preprocessing might even analyze the code for dangerous behavior, but a more common type of preprocessing would be macro expansion, another would be decompression.


First principles assessment of Overfitting

Question: I am looking at some machine learning algorithms at the moment, namely logistic regression and simple neural networks.
It seems that the only way that people restrict this is to check for bias and variance in the errors and check this way if it is overfit. Or vary $\lambda$ (the regularisation parameter) to adjust overfitting/underfitting.
Are there any methods which use first principles instead of merely observing the effects. I.e. looking at the number of roots that a polynomial can create and knowing that by the input amount of information that it is more probable than not that this model achieved low error by virtue of replicating information than and actually modelling the link.
Comment: What you're describing sounds like a type of "hypothesis testing" at the full model level. That kind of reasoning is in fact used with things like the ANOVA F test, I don't know if there's some general approach that's model independent.  I do think though that the desire to make good predictions is a perfectly reasonable first principle in itself, even if it may not have much theoretical content.
Answer: The question of (over)fitting only applies to a specific dataset. If you use hypothesis-free methods like neural nets, it's because you have no idea of the structure of that dataset. Adopting a principled way of setting the model parameters is only possible if you have prior information (or hypothesis) on the data structure, in which case there are more powerful methods than ANNs. Empirical approaches (training and validation subsets, etc) follow from the choice of an unconstrained fitting method.
Comment: "Adopting a principled way of setting the model parameters is only possible if you have prior information" ... Is that strictly true? In the case of a Bayesian semi-/non-parametric approach the parameterisation of the prior is learned to some degree from the data. Admittedly some algorithmic presumptions are required.


Jquery UI date-picker focusout

Question: Jquery UI date picker loses focus when selecting a date. Are there any alternatives to this?
If not, how do I achieve the standard web bevaviour of user entering data into the input field and not losing focus while doing so.
Answer: I ended up using onselect function of the date picker

Jquery UI date-picker focusout


What is the initial step?

Question: A three-sided fence is to be built next to a straight section of river, which forms the fourth side of a rectangular region, as shown in the diagram below. The enclosed area is to equal  $1800  m^2$  and the fence running parallel to the river must be set back at least  $20  m$ from the river. Determine the minimum perimeter of such an enclosure and the dimensions of the corresponding enclosure.
I am using this for the first part: $1800m^2 = l(w- 20)$
Every time I use this I can't really figure out how to differentiate, which leads me to believe I'm doing something wrong. I know that one of the sides needs to be subtracted by $20$, but I can't understand when it should be subtracted.
Also, if I do find the new width, would that change the entire area?
Comment: The equation you have is the constraint. You must also write down the expression for the perimeter which will be a function of $l$ and $w$. You can use the constraint to solve for one of the variables. You plug that into your perimeter equation to get a function of one variable. Then you can differentiate that to get the minimum perimeter.
Answer: We have $$1800 = l \cdot w$$
where $$l \ge 20$$
We want to minimize $2l+w$.
The Lagrangian is given by $$\mathcal{L}(l)= 2l + 1800/l +\lambda(20-l)$$
Then,
$$\frac{d}{dl}\mathcal{L}(l)= 2 - l^{-2} 1800 -\lambda$$
We conclude that
$$\frac{1}{l}=\sqrt{\frac{2-\lambda}{1800}}$$
Therefore, if $\lambda=0$,
$$\frac{1}{l}=\sqrt{\frac{2}{1800}}$$
then $l=30$, which is the solution.
Candidate solutions: $l=20$ and $w=90$  or $l=30$ and $w=60$.
Solution: $l=30$ and $w=60$.

Alternative problem: We want to minimize $2(l+w)$.
The Lagrangian is given by $$\mathcal{L}(l)= 2(l + 1800/l) +\lambda(20-l)$$
Then,
$$\frac{d}{dl}\mathcal{L}(l)= 2(1 - l^{-2} 1800) -\lambda$$
We conclude that
$$\frac{1}{l}=\sqrt{\frac{1-\lambda/2}{1800}}$$
Therefore, either $\lambda=0$, implying that $l = w = \sqrt{1800}$ or $l=20$ and $w=90$.
Solution: $l=w=\sqrt{1800}$.
Comment: Problems of this sort are often set in a first calculus sequence, before Lagrange multipliers are discussed.  In that context—as you know but the asker might not—the intent is to maximise $2l + 1800/l$ on the domain $l \ge 20$, where it has exactly one critical point, which, say, the second-derivative test verifies is a local, hence global, minimum.
Answer: Let the lenght and breadth of the rectangle $x,y$ respectively. Then the area of the rectangle is:
$$\mathcal A=xy=1800$$
or $y=1800/x$ with $x\ne 0$. Also, it is know the perimeter is the sum of all sides, or
$$p(x)=2x+y=2x+\frac{1800}{x}$$
Differentiating the function $p(x)$ we have:
$$p'(x)=2-\frac{1800}{x^2}$$
Putting this $p'(x)=0$ we can compute the critical points. We get $x=30$ as a critical point. We see that when $x>30$, $p'(x)>0$. Also when $0<x<30$, $p'(x)<0$. By first derivate test we see that $x=30$ is the point of minimum. Thus $y=1800/30=60$. Therefore, the dimensions are $30 \times 60$ and the perimeter is $120$ feets.

What is the initial step?


VAE loss doesn't converge to zero. Does it make sense to sample new instances from trained latent space?

Question: I aim to use a variational autoencoder (VAE) as a generative model. Does this make sense only if the reconstruction loss converges towards zero?
On a project I'm working on, the loss is getting reduced but at some point it won't converge to 0.
<code>Epoch 1 of 1000
100%|██████████| 506/506 [00:07<00:00, 63.36it/s]
Train Loss: 31.2318
Epoch 2 of 1000
100%|██████████| 506/506 [00:07<00:00, 63.57it/s]
Train Loss: 19.9676
Epoch 3 of 1000
100%|██████████| 506/506 [00:08<00:00, 61.88it/s]
Train Loss: 19.0511
Epoch 4 of 1000
100%|██████████| 506/506 [00:08<00:00, 63.07it/s]
Train Loss: 18.5793
Epoch 5 of 1000
100%|██████████| 506/506 [00:08<00:00, 62.91it/s]
Train Loss: 18.1751
</code>
And it won't improve that much.
So the network is learning, maybe just not that much as it should. Despite this, does it still make sense to sample new instances from the trained latent space?
Comment: You might also want to output the parameters of the likelihood distribution $p(x|z)$ with the decoder. What I mean by that is that depending on the type of data it should output parameters of a distribution (similar to the encoder), parameters of a normal distribution for continuous data and parameters for a bernoulli distribution for binary data. Then you can use the negative log likelihood as loss function. This change helps the model to better express uncertainty.
Answer: There's no reason to believe that the loss must converge to 0. That might suggest you're overfitting—the capacity of your model is too high, and it's memorizing training instances.
For the sake of analogy, consider a normal autoencoder whose latent dimension is smaller than the feature space. You can minimize the reconstruction error, but never get it to 0 (assuming that the data don't actually live on a lower-dimensional manifold). The auto encoder is still usable and of value.
Comment: Thank you very much!


Inheriting module/class methods

Question: I have this module with a method:
module MySqlConnection
  def database_connect(application)
    # Code in here
  end
end

I have a second module with a class that uses database_connect:
module ResetPopups
  class PopupsOff
    include MySqlConnection
    def self.reset_popup
      database_connect("#{APP}")
    end
  end
end

When I call:
ResetPopups::PopupsOff.reset_popup

I get an undefined method database_connect. Why does this happen?
Answer: include adds module methods as instance methods, while extend adds them as singleton methods. Since you want to use this in the context of class (singleton context), you need to use extend:
extend MySqlConnection

Comment: I don't know. Maybe it's because my answer had an explanation from the beginning? ;) +1 from me for 'balance'. :)
Comment: how come you have the upvote 7 seconds after posting the answer even though I was first :D
Comment: Thank you for answering, much appreciated
Comment: @MarekLipka, hm, you must be right (but still i've updated the answer earlier then yours appeared) ;) Then +1 from me for (as usual) being so fast with the explanation from the beginning :)
Answer: module ResetPopups
  class PopupsOff
    extend MySqlConnection
    def self.reset_popup
      database_connect("#{APP}")
    end
  end
end

would work
What is hapening here, is that you include MySqlConnection, which makes method defined in it (database_connect) instance methods. But you use this module in the class scope, calling the database_connect on the class.
Comment: Thanks both for your answers (that upvote on Marek's post was not me :-)) I'll accept this as the answer, thanks again for your help

Inheriting module/class methods


Appium unable to take screenshot on xCode 13.3 and iOS 15.4

Question: I woke a few days ago to run an appium UI automated test on iOS simulator which has been running perfectly without any error. I recently upgraded to iOS 15.4 and iOS 13.3 and to my surprise Appium is unable to take screenshots again. I tried checking what the cause could be and found exact similar problem posted here Socket hang up error while taking screenshot in appium (iOS 15.4 beta & xCode 13.3 beta 2). I find this as well on Apple post Xcode 12 Beta 3 Release Notes. Are there any workaround presently for this?
This is the error I'm getting
<code>[HTTP] --> GET /wd/hub/session/ea84cef2-3649-4e76-91b9-23cec159e3a1/element/1B000000-0000-0000-1439-000000000000/screenshot
[HTTP] {}
[debug] [W3C (ea84cef2)] Calling AppiumDriver.getElementScreenshot() with args: ["1B000000-0000-0000-1439-000000000000","ea84cef2-3649-4e76-91b9-23cec159e3a1"]
[debug] [XCUITest] Executing command 'getElementScreenshot'
[debug] [WD Proxy] Matched '/element/1B000000-0000-0000-1439-000000000000/screenshot' to command name 'getElementScreenshot'
[debug] [Protocol Converter] Did not know how to rewrite the original URL '/element/1B000000-0000-0000-1439-000000000000/screenshot' for W3C protocol
[debug] [WD Proxy] Proxying [GET /element/1B000000-0000-0000-1439-000000000000/screenshot] to [GET http://127.0.0.1:8100/session/88FE5109-F180-482B-B948-980F345404CC/element/1B000000-0000-0000-1439-000000000000/screenshot] with no body
[WD Proxy] Got response with status 500: {"value":{"error":"unable to capture screen","message":"Error Domain=com.facebook.WebDriverAgent Code=1 \"Cannot take a screenshot within 20000 ms timeout\" UserInfo={NSLocalizedDescription=Cannot take a screenshot within 20000 ms timeout}","traceback":""},"sessionId":"88FE5109-F180-482B-B948-980F345404CC"}
[debug] [W3C] Matched W3C error code 'unable to capture screen' to UnableToCaptureScreen
[debug] [W3C (ea84cef2)] Encountered internal error running command: UnableToCaptureScreen: Error Domain=com.facebook.WebDriverAgent Code=1 "Cannot take a screenshot within 20000 ms timeout" UserInfo={NSLocalizedDescription=Cannot take a screenshot within 20000 ms timeout}
[debug] [W3C (ea84cef2)]     at errorFromW3CJsonCode (/Users/kadeoye/.appium/appium-xcuitest-driver/node_modules/appium-base-driver/lib/protocol/errors.js:780:25)
[debug] [W3C (ea84cef2)]     at ProxyRequestError.getActualError (/Users/kadeoye/.appium/appium-xcuitest-driver/node_modules/appium-base-driver/lib/protocol/errors.js:663:14)
[debug] [W3C (ea84cef2)]     at JWProxy.command (/Users/kadeoye/.appium/appium-xcuitest-driver/node_modules/appium-base-driver/lib/jsonwp-proxy/proxy.js:272:19)
[debug] [W3C (ea84cef2)]     at runMicrotasks (<anonymous>)
[debug] [W3C (ea84cef2)]     at processTicksAndRejections (node:internal/process/task_queues:96:5)
[debug] [W3C (ea84cef2)]     at XCUITestDriver.proxyCommand (/Users/kadeoye/.appium/appium-xcuitest-driver/node_modules/appium-xcuitest-driver/lib/commands/proxy-helper.js:96:12)
[debug] [W3C (ea84cef2)]     at XCUITestDriver.getElementScreenshot (/Users/kadeoye/.appium/appium-xcuitest-driver/node_modules/appium-xcuitest-driver/lib/commands/screenshots.js:52:16)
[HTTP] <-- GET /wd/hub/session/ea84cef2-3649-4e76-91b9-23cec159e3a1/element/1B000000-0000-0000-1439-000000000000/screenshot 500 20106 ms - 1319
</code>
Answer: Change back to iOS 15.2 I had the same issue and struggled for hours...  tried everything.. It was absolutely the same case as yours. Yesterday it was working and suddenly today it stopped working. So at the end, the only change was that the xcode simulator updated itself to iOS 15.4 from 15.2. That's why somehow appium inspector stopped working and taking screenshots. I guess it will take some time from appium side things to be updated but until then just row back to latest stable iOS simulator version 15.2. How to do that - Xcode -> Preferences -> Components -> select older iOS version Simulator -> download, Check and Install now -> build -> voila :)
Answer: It can be fixed by changing WebDriverAgentLib/Utilities/FBScreenshot.m (257th line):
<code>(nullable id)screenshotRequestWithScreenID:(unsigned int)screenID
</code>
to:
<code>(nullable id)screenshotRequestWithScreenID:(long long)screenID
</code>
Problem is reported and it's solution is also here:
https://github.com/appium/appium/issues/16604