Can one be too old to learn an instrument?

Question: I own a guitar. I've owned it since I was about 13, but never really got into it because I was a spiteful teen who wanted to play the drums, and went out of my way to play the drums instead (to the dismay of my parents who acquired the guitar for me).
Now, as a 22 year old, I occasionally find myself entertaining the thought of picking it up and learning it. I really would someday like to learn music theory; I have created digital compositions for awhile, but struggle with keyboard and string derived instruments due to not knowing even basic music theory.
It takes me a very long time to derive melodies as a result, and I am hoping that learning a string instrument would help me develop the skills to be a better composer.
I mentioned this to one of my colleagues in the music industry, and while he was supportive, he warned me that I may have trouble seeing as I have never really picked up the guitar and that this is an older age to begin learning it.
This really discouraged me. If this is true, what limitations can I expect in the way of learning? I already have a lot of trouble playing due to the size of my hands, and hearing this is making me wonder if I should consider a different instrument entirely.
To be clear, I am asking about both the fundamental theory and the physical technique, as I have no formal education in other.
Comment: Seriously, you are 22 and you think your are too old to learn something? What will you feel when you are 30, 40, 50, 50 ,... . Sorry to say so, but what a misplaced arrogance.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/85610/discussion-on-question-by-nostalgk-can-one-be-too-old-to-learn-an-instrument).
Comment: I added proof that it's possible with a video link in my answer. It's how I sound on violin after 17 months of practice in my 40s https://music.stackexchange.com/a/76071/51575
Comment: @Oбжорoв Yep. Absurd.
Answer: Even if one can ever be too old to learn an instrument (I don't think so), then this is definitely not the case already at 22.
You may not be able to make as fast progress as if you had learned it at 13, but ultimately it's up to how much effort you put in. Practive five minutes every week, and it'll probably not go anywhere. But practice half an hour every day, and you'll be able to make decent progress. Will you ever become a virtuoso? Probably not. But that's not the point, I guess. A nice thing about guitar and piano is that one can achieve quite musically useful results without needing to be technically terribly skilled. Definitely enough to be helpful for composition.
Comment: Just as one anecdotal data point, I'm 56 and started learning the flute last fall.
Comment: @Dedwards I'll leave it to somebody else to spin that comment into a joke about bassists...
Comment: "Will you ever become a virtuoso?" Well I imagine the majority of players won't become a virtuoso, regardless of when they start. If you want to be good at an instrument, you're free to put in the effort, and if you end up becoming a virtuoso, great! But becoming a virtuoso is not that useful to consider before starting an instrument.
Comment: Thank you. It does seem like there's a prevailing culture of "start young or never try" with music, so it's always seemed very daunting to me to try to get into. The drums were easier for me to learn, that's why they appealed to me.
Comment: I started playing Bass guitar at 31 and two years later can play a huge number of songs that come along after only about an hour or two of practice. Plenty of rifts and licks I can get right away.
Comment: @colonelsanders being able to shred some fast solos is in my book not sufficient to deserve the label "virtuoso". Becoming a true virtuoso does require some serious dedication. I don't know if it's still possible to get there after starting only at 21, but I certainly doubt that someone who had a guitar for 9 years and never seems to have felt much urge to put in _any_ dedication will suddenly muster enough of it.
Comment: _"Will you ever become a virtuoso? Probably not."_ is unnecessarily discouraging. A few years' practice with an emphasis on technique is sufficient for many shred tunes. You won't be playing any Shawn Lane, but you'll be _way_ beyond "good enough to compose".
Answer: Certainly children learn more quickly than adults, particularly when it comes to languages, and to skills.  (That is, "proficiency, facility, or dexterity that is acquired or developed through training or experience.")
As a former US Figure Skating Basic Skills instructor, I observed this effect time and again when teaching school-age children as compared with teaching adults.  (It's a skill that requires both physical learning and mental understanding, and practice, similar to musicianship.)
And it is well-documented that as we progress through our 30's, 40's, 50's, and upward, our learning rate decreases.  (why-learning-is-harder-as-we-get-older)
However, there is absolutely no reason to avoid learning a new instrument in your 20's.  In my own personal experience, I started learning "pop" organ at age 11, and studied viola from ages 15 through 18.  Then -- having taken no musical lessons of any kind for 30 years -- I started studying piano at age 48, and found it enjoyable and not terribly difficult.
<code>Side Note: Although piano and organ are both keyboard instruments, the left hand
accompaniment is entirely different, as is the expression.  The organ has bass pedals,
which the piano doesn't.  The organ has one or more expression pedals or "swell shoes,"
which the piano doesn't.  The piano's loudness and timbre are sensitive to touch, which
doesn't happen on the organ.  They are different instruments.
</code>
In both my experience teaching skills to others (figure skating and a couple of other skills), and in my experience as a music student, learning as an adult is
different than learning as a child, but not necessarily worse:

As a child, you may have more time available to practice, though this is not a hard-and-fast rule.

As an adult, you are likely to be more focused and more motivated in your practice and your study.  You are better able to understand the need for boring things such as drills, and better able to master your own feelings and attitudes.  Adults "buckle down" better than children do.

As a child, you do learn more quickly.

As an adult, you may tend to value what you're learning more, and may retain it better.

As a child, you approach things with fewer preconceived notions, and are likelier to accept things at face value.  (I saw this all the time teaching children to skate, particularly when teaching the beginnings of jumping skills.)

As an adult, you are more capable of analysis: both of what the teacher is saying and of what you yourself are doing.  Some examples:

Teaching adults proper skating posture was far easier than teaching children.  I could draw word pictures involving imaginary lines through parts of the body, and the adults could translate that into actions and posture.  I had to physically bend the children into the shapes I wanted -- repeatedly -- before they could successfully reproduce the instructions.  Then they would revert and have to be taught again, whereas adults only required a simple verbal reminder.

Learning aspects of musical theory was far easier for me as an adult than as a child.  As a child, I understood that an E-flat was the same as a D-sharp, so "who cares what you call it."  As an adult, I could see why the key of the composition affected the names (or identities) of the notes.

As an adult musical student, I'm able to analyze my own playing and state "___ is the right way to finger this, but my pinky finger on my right hand will always be weak due to a childhood injury, so I'm deliberately [incorrectly] doubling it up with my right ring finger so I'm able to strike a high note with particular force when needed."

As an adult, you are better capable of evaluating whether a particular teacher/instructor is the "right" one for you.

As an adult, you have much better proprioception than you did as child or even as a teen.  For example, you should be able to learn the distances between frets (and strings) without looking, and learn it more quickly.  As an adult, you've also done most of your growing, and your fingers are capable of being stronger than they were as a teen.  If you are like me, you are also better able to ignore pain while developing calluses for playing.

The size of your hands may be another matter entirely.  You may need to consider getting a 3/4 or 2/4 guitar, or switching to something smaller, such as the mandolin.
Not everyone is suited for every instrument.  For example, I tried playing saxophone in 6th and 7th grades.  I had trouble controlling my breathing, and I never could really learn the fingering well enough: there's no real pattern to it (it's dictated by physics).  So, while I love listening to the sax, it's not the instrument for me.
I hope these observations serve to encourage you to continue your musical education.  Learn any instrument you want, at any age you want!
Comment: @RandyZeitman - did you read the entire article?  Or just the first part and skimmed the rest?  The article mentions studies that show for certain kinds of learning, young adults in their late teens to late 20's are fastest.  But the applicable part here is when it talks about task training (such as memorizing tapping patterns), and that *consolidation* of skills happens differently in children than in teens or adults.  By the way, I *DO* agree with you on the point that persistence matters far more than efficiency!  And I did mention language in my very first sentence.
Comment: The link you have about "learning faster" is about LANGUAGE. "Adults "buckle down" better than children do." ... and that matters far more because persistence matters far more than efficiency. I am 100x better learner now.
Answer: First, 22 isn't old to start music, even 82 isn't. Because skill and your propensity for music is partly inherent. You could have musical abilities that other people don't. For example, people that are more sensitive/emotional tend to be more musically inclined than people that aren't. So it's not all about when you learn, or even the theory that you learn, part of being good at music is also very much inherent to your personality without even picking up an instrument.
Second, it's not like you ever stop learning music. You can learn music for decades over many hours a day. So learning music is not something that takes a year or two, or even a decade. It's something that you develop throughout life. And the more you develop and practice, the better you get. If you're looking to start at 22, that's great. It's not too late. The only question is, will you continue..
Comment: *"People that are more sensitive/emotional tend to be more musically inclined than people that aren't"* Source?
Comment: I really like this comment. So much of music is not a skill that is acquired, but is rather a state of wisdom achieved. What notes NOT to play. How to be economical. How to listen. How to practice! And what I think is the big one, how to have something to say. Any art needs to be done with intent, and it can take years of personal growth to get to the point where you have something to say and the comfort level to say it - with music.
Comment: life experience
Comment: @user45266 there are hundreds of scientific links on this too https://www.google.com/search?q=musicians+more+emotional+science
Comment: @user45266 also check this out "It also appears that a high proportion of people with depressive illnesses are drawn to working in the arts" https://www.theguardian.com/music/musicblog/2010/dec/17/musicians-depression
Comment: @foreyez - maybe that explains some of the guys I work with...
Comment: Not what I was hoping for, but fair enough.
Comment: This is a rather whimsical answer that doesn't account for the reality of the brain's plasticity at age 82.
Answer: Unless one only has a couple of years to live due to a terminal disease, one is never too old.
It's true that in the early years up to maybe early twenties, children are (hopefully) more sponge-like, however, there are decades left for most of us. The biggest problem is that while kids learn more quickly (due to having nowhere near as much on their plate at the time) we oldies still have the propensity, but must manage time far better. And money - kids get their lessons paid for, and often aren't even aware of it - whilst we have other avenues that our money disappears down.
Bottom line is - just get on with it. You may find theory helps - you may not. It depends how you're wired. Playing an instrument (at any age) needs some sort of commitment, and if understanding what goes on is part of that, so be it. But until you commit, nothing will happen, let's face it. Fundamental theory, and basic technique are still abundantly available to you, whatever your age. And early twenties? Don't even bother asking! Stop wasting your time. Get going!
Comment: A teacher will shave off so much time and effort - and since it aspires that you're still a student, make this part of your studies.
Comment: Unfortunately, between working a full-time job and studying full time at a poly-technic university that does not offer musical education, my hands are tied on including it in my studies on a formal educative basis due to time constraints. However, I do have time on my own for practice and could possibly fit in a lesson every week or so with a private instructor.
Comment: @nostalgk - being an 'elder' isn't a given age; it's living under the constraints you just mentioned.
Comment: @nostalgk You also can look for an instructor who gives you lessons on base of appointments. I found such an instructor and make my appointments as it fits in my other time constraints. So I have lessons only every three or four weeks. And it works...!
Answer:
Can one be too old to learn an instrument?

First of all, if you are 22 years old, you aren't old :-)
Categorically speaking you can never be a child prodigy. Of course I mean that as a little joke, but the serious point is you're never too old.
But now you have to ask yourself what your goals and and get serious about striving to meet them!
As far as the guitar given to you by your generous parents is concerned: why not learn how to play it? The beginning is always hard, but it isn't that hard to learn the basic open chords to play rhythm guitar accompaniment to a huge number of songs in many styles. You could develop that basic proficiency and be enriched as a musician. Or, it you have the urge, take it further. Learning a new instrument doesn't necessarily require mastery. In fact, I think many people would say they learn about their main instrument and all music generally by learning the basics of other instruments even though they don't master them.
About learning an instrument to help you learn music theory. Typically piano is the instrument for studying theory. Music students are often required to take some piano proficiency classes. The goal isn't to become a pianist, but to get enough skill to play chord and scales from a score to assess it, or play examples from harmony textbooks, etc. A cheap electronic keyboard is all you need to support that kind of theory study.
Another aid to learning theory is singing out loud, or singing along with your keyboard or guitar. It's not so commonly recommended, but I think it helps develop good hearing. I'm a terrible singer, but from time to time I add singing to my practice to develop my ear.
Comment: Thank you for your thoughts. I will add that I can play the guitar well enough to play tabs and remember the sequences, but nothing really beyond that. I think it would behoove me most to start from the "beginning" and learn chords, like you say. I will look into getting a cheap electronic keyboard; one that would serve as a MIDI controller would be a boon to my digital music creation.
Answer: UPDATE:
I'm 40 now, and I picked up violin - which is known to be one of the harder instruments - around 17 months ago. Listen to the result: https://i.imgur.com/SGng4mH.mp4
Do note that I had played guitar, bass, fretless bass, banjo and mandolin before attempting the violin, and this certainly made the learning easier. But still, yes, it's indeed possible to learn even a pretty tricky instrument at the age of 40.
But do also note that I have not been practicing like crazy. It was pretty intense in the beginning. Maybe 20-30 minutes per day for the first six months or so. After that, I practice more rarely, but it probably averages to at least ten minutes a day. Unfortunately, I only practice songs and playing together with others nowadays. I never practice bowing separately, which is exactly what I would need to advance further.
Old answer:
EVERYTHING gets harder to learn as you get older. This includes learning an instrument.
Whether you're to old to learn something depends on your definition of "learn". For exemple: Is it possible to learn a new language when you are 40 years old so good that you can fool a native speaker? I would say that this is impossible except for maybe a handful people in the world.
If you instead ask if it is possible to learn a new language when you are 40 so that you can communicate reasonably well with people, then the answer is yes. Most people would be able to do that.
So it all depends on your goals. It is most likely to late to become a world known star on your instrument of choice. You could probably become a (mediocre) professional, but it would require a lot of work. If your goal is to be good enough to get occasional gigs at your local pub, or just earn a place in a garage band, then it's definitely feasible.
I'm 37 now, and I started learning trumpet quite recently. Sure I wish I started earlier, but I am learning, and I can contribute with it. Most of the music theory I know I have learned the past five years.
So if you want to do it, then just do it. It's definitely not to late to have fun with an instrument.
Answer: I am starting to learn how to play guitar, and I am 58 years old. Will I ever become a skilled musician? No, but that is not my goal.
Do it! Do it now. Because if you don't you will later and you will regret not starting it at 22.
Answer: I find the two vital ingredients to learning to play an instrument of any sort are honest interest and whether or not you are really driven.  I've known a few people  who have lived most of their lives wishing they could play guitar, piano, percussion, etc. Finally as they reached retirement age, their responsibilities changed and they were able to pursue those interests. I know of a 79 year old man enrolled in a community college guitar class, and it's studying guitar that is addressing a pretty serious regret that he's had for a long time now.
 My point is that if your interest and drive are real, you'll most likely regret a decision to not pursue that interest. Fear of not being able to learn would certainly end in regret.
Answer: Wow, ripe old age of 22.  That is very young so you are not too old by any standard.  In my experience anyone can learn music at any age.  Some keys are attitude and commitment.  As adults sometimes our daily responsibilities get in the way of making steady progress.  To make progress on any instrument requires a regular practice schedule.  Every teacher will tell their students, 1/2 hour a day is better than 3.5 hours the day before your lesson.  And almost every student does 3.5 hours once a week (at least for a while).  My point is that if your current life situation does not afford you the ability to commit a small time every day you will not see progress and you may get discouraged and disappointed.  In my opinion this is one of the root causes of people thinking (incorrectly) that they are too old to learn.  It's just an example of life getting in the way.
Your friends comments may be coming from the point of view of a working musician.  Like sports it is usually recommended that one start very young to ensure they are prepared for success in their teens.  For example, to get into a good music program in college you need to audition and compete for seats, etc.  You will not likely get into Julliard at 17 is you started at 16.  But to say that you are too old to start is a gross misconception on your friends part (no offense).  I have students who are retired (in their 60s) and they make great progress.  But this speaks to my point about life getting in the way.  Sometimes people excel at new things when they are older because they have the time and resources to devote to it.
To your comment about music theory you can learn that regardless of what instrument you play, vocalists learn it to and they don't need guitar or keyboard skills to learn.  So keep those two separated.
Don't put yourself in a box before you try.  If you really want to learn guitar I'd say get a good teacher and take some lessons, see how it progresses for a while.
Answer: I only started to play any instrument at all around your age. (Actually, I had two months of French horn in a high school music class at 14 that I was forced to take but I didn't care for the instrument and dropped the course as soon as I could so I'm not counting that.) By the time I was your age (or maybe I was 21), I was increasingly intrigued by music and asked my friend's brother, James, who was a guitar teacher, if I was too old to learn. He assured me I was not. I wanted to learn guitar but having seen some great guitar players like Steve Howe, I was sure I'd NEVER be able to do a fraction of what he could do so I decided to do something "simpler" and got James to help me buy a bass and give me some lessons on it. He gave me lessons for a few months (free!). About the same time, I moved into a university housing co-op and found that there were some musicians in the place. They liked to jam on weekends and they didn't have a bass player so I was encouraged to join them, even though I knew almost nothing. But they were at least somewhat drunk most of the time and they really didn't mind me there, trying to add to the sound. :-) And that's how I discovered the great joy of playing with other people, even before I could do almost anything by myself! Before too long, I'd acquired a practice amp which was enough for the jamming and my individual practice (what little there was). Before long, I bought a cheap guitar to go with my cheap bass and started to play a little guitar. I won't bore you with the whole story of my musical misadventures; suffice it to say I had a great deal of fun, even if I never developed any great skill. I also learned the basics of theory through a self-study book that James gave me; it was the first two grades (out of five) of the conservatory material taught here in Canada. I also had a lot of fun trying to write music and record it on the four-track recorder I bought.
As for physical technique, I initially thought anyone who had two working hands could play guitar but I learned that there are exceptions. I girl I knew in residence said she wanted to play guitar and even had a guitar but said she couldn't play it because her hands were too small. I found this a little improbable but asked James and he said it was possible. As luck would have it, he came to visit me at the residence on one occasion and I asked if he could possibly evaluate the girl in question, Charlene. We went to see her and he quickly determined that she was right: her hands WERE too small to comfortably play the guitar. As I recall, he simply tried to get her to play a few of the standard chords, while showing her how to form them. I seem to recall that a standard G chord at the third fret was more than she could handle. And that was all for Charlene and the guitar as far as I know. (I regret now that no one thought of having her try a smaller instrument like mandolin; she might have done really well with that.) You should probably have an experienced player test you in a similar way to make sure you don't have a similar obstacle to playing.
I also went to mention a woman named Nancy that I worked with on my first full-time job. She was a married woman with two young teenagers. She really wanted to get her kids to start instruments but they were reluctant. She didn't want to be the kind of mom that twisted their arms to play; she wanted them to WANT to play. She asked if they'd be interested if she took up an instrument too? They decided that if their mom wanted to do it, it wasn't a chore being forced on them and that it might be fun so they agreed if all three of them took up an instrument. Her daughter decided to start on piano, I don't remember what her son started on, and Nancy herself started on organ. It was her first instrument and she must have been close to 40, if not older. The best part of the story is the ending: Nancy LOVED playing music and was absolutely delighted that she had finally done something she always wanted to do.
Bottom line: I would strongly encourage you to start on guitar or any other instrument that interests you. It IS possible to start that "late" on both an instrument and on music theory and to still have a great time. You may be too late to be the next Eddie Van Halen wowing audiences around the world but I wouldn't even rule that out. There may be some late starter somewhere that is a top ranked professional for all I know. But you have every chance of having a great time, even if you never set the world on fire with your playing. I see no reason you can't become a good composer too.
Sorry for the long-winded answer. ;-)
Answer: Go for it! There are trade-offs when it comes to learning an instrument when you're older vs when you are younger. When you're older you have more persistence to keep trying to get that riff right. If you go to school or work you'll have to kinda schedule your practice, which might end up being more beneficial.
I think the best part though, is that your perspective has changed since you were a kid.
I started playing guitar when i was 11. i was forced to take piano lessons around the same time, but it they kinda sucked and all the music i listened to had guitar in it, not piano. but when i got into my early twenties, i had access to a piano where i lived, and i just loved slugging down some beer or whiskey and learning some Phillip Glass or whatever.
you're not too old. give it a try, you've got nothing to lose.
Answer: Another answer began with ...

Unless one only has a couple of years to live due to a terminal disease, one is never too old.

... but I'd like to correct that i.e. to say that one might learn in less than a year.
I'm in my late 50s and I started to learn guitar less than a year ago -- folk-style guitar, e.g. strumming the "open" chords and singing.
My guitar skills are now that I can play a song like (most recently) Mad World almost instantly, i.e. assuming that ...

I know the song (i.e. I've heard it previously and like it)
The chords are easy (e.g. no barre chords) and my fingers know that chord already
The rhythm or strumming pattern is easy (I might play but find it difficult to sing on top of playing, when the rhythm of the melody I'm meant to sing is unlike the rhythm of the guitar -- perhaps what's called "syncopation")

... I already know the chords for that song (i.e. Em, G, D, and A) well, and so I can just play them. I can learn to fit the chords to the song after only several minutes of practice.
There are a lot of songs like this -- easy three- or four- or five-chord songs -- see e.g. PartyMarty EasyGuitarTunes (though, when I want to see how to play a song, I've found/used many other sources too).
So, "mission accomplished" to some extent. I can sing and play well enough to accompany my own singing at amateur folk club evening (previously I could only sing, unfortunate since the commercial music I have liked e.g. starting with The Beatles tends to be accompanied).
I've still a way to go, of course ...

Learning to play barre chords -- I can play some now but the trick is to play them fast enough for them to be usable in a song -- e.g. a chord like Bm or F, which are needed for some songs (I can now nearly play Tomorrow Wendy well enough to perform it -- it has a Bm in it, i.e. the chord progression is D, A, Bm, G).
Learning to play finger-style -- e.g. I nearly know how to play Dust In the Wind now, i.e. I can actually play it but not yet perfectly -- apparently that song was written as a finger-style exercise.
Picking -- I'm strumming with my fingers. I can strum various patterns, strum fairly rhythmically, but I'm not good at using a pick and can't very accurately  hit specific strings when strumming.
Playing by moving up and down the neck (I'm not sure what that's called, but I mean not using open chords at all).
Playing with other people (playing solo is easier, or with a teacher who will keep pace with you rather than your keeping pace with them).

... an infinitely long way, especially compared to any professional, but "mission accomplished" too.
I had a guitar teacher for several months -- not a professional teacher, a kind neighbour who has played an an amateur since he was young -- with once-a-week lessons.
He told me to practice every day, even if only for 5 minutes (also I have a steel string acoustic, which hurt my fingers until they acclimatised to it) -- that 5 minutes of practice every day is much better than half an hour once a week. The key is to develop the new habit, of practice, of playing.

You can learn quickly (e.g. the difference between knowing how to play a chord and not knowing, or knowing what chords to fit a song and not knowing).
Then improvement might come slowly, because to play (e.g. to make chord shapes with your left hand) fast enough, it's not sufficient for the brain to know how, the fingers themselves need to be able to do it.
At that stage, I found I didn't seem improvement in my playing from one day to the next (i.e. I was often no better than the day before), but (with daily practice) I did see progress from week to week -- so don't get discouraged, it's quite an interesting learning practice.

Sometimes I practice longer than 5 minutes, but I think it's the daily habit that will make progress inevitable.
I'm not actually taking lessons any more, perhaps I've learned enough that I can learn more (e.g. from YouTube), and practice more, unaided.
He also told me to practice songs I like -- i.e. songs that I'd want to learn, to practice -- to find songs I like that I can practice. I think the first one he gave me was Hide Your Love Away (playing the C chord instead of F) -- but, yeah, what you like.
Anyway, it's not too late. Being intellectual and all too (i.e. some kind of technician, which I define as "someone who reads the manual") I've learned a bit of music theory (e.g. why the various chords are named as they are -- "major", "minor", "sus4", "add9", "C/E") but I think that's optional, there are people who just play by ear instead (and you can learn chords and finger-picking using tabs or charts and from watching other people play and explain). I think I read (I don't know if it's true) that The Beatles were unable to write music, so the songs they were able to practice were only whatever songs they were able to remember from one day to the next (maybe part of the reason why their songs were memorable and initially not too complicated)!
It takes me a very long time to derive melodies as a result, and I am hoping that learning a string instrument would help me develop the skills to be a better composer.
I'm no musician but, though I like to play and practice, I'm not sure that learning guitar is the most efficient (i.e. the least time+effort) way to learn theory and to compose a melody -- e.g. because a lot of the practice is physical -- habitual finger/chord shapes, fine-motor and gross-motor skills.
If your primary interest is composing melodies (N.B. that I don't know) you might be better with videos about theory (I like the 12tone videos), with something like a keyboard, and/or perhaps software such as MuseScore or similar.
Answer: As for music theory, learn the guitar first.  There is a decent amount of music theory you naturally pick up as a guitarist (chords, chord progressions, major, minor, dimished, augmented etc.) because that's part of playing a guitar (alternate fingerings, soloing, alternate picking and strumming techniques, and so forth).  If you later are interested in picking up the rest of the music theory, it is going to be much easier once you already understand the parts of music theory used in guitar playing.  You won't be able to easily play some of it on a guitar, but you can always get a computer program to play it for you.
Answer: There is no such thing as "too old" only "didn't try" or "didn't keep trying."  The problem with most humans is they confuse trying with age and resign themselves with the easy way out.
You could be the next Jimmy Page, Kurt Cobain, Fred Frith or Chuck Berry but only one thing is absolutely guaranteed - if you don't try, you will never ever know and neither will anyone else.


How can I check which nodes have the highest value in a certain field?

Question: My content type 'Article' has an integer field called 'Ranking'. How can I check which nodes have the three highest values after saving a new node or comment? I'd like to use the result in a rule, so I'm looking for some kind of "The node has ranking 1/2/3" condition.
Any ideas how I can achieve this?
Comment: I'm thinking maybe try to filter the results via view and then use rules integration with views to get what you want, but it was the first thing coming into mind, maybe it's not that simple anyway
Comment: https://drupal.org/node/1113158
Comment: you can get idea here http://miss-hana.com/calculate-field-values-using-computed-field-in-drupal-7/ check this module too https://drupal.org/project/computed_field_tools
Answer: If within your Computed Field you've selected Store value in the database, you can easily use Views to sort results based upon this field.
So, for example, in broad strokes, you could create a View that filtered on whatever you needed, most probably published and node type; then for sort, you would select this field and select descending; in paging, you'd select a specific number, eg, 3; and in fields, you'd select whatever you wanted to display.
If you wanted to have a block of the top three nodes, in the fields I could see you selecting the title and so forth, but if you are wanting to see if a specific node was in the top three, I'd just put the node nid in there.
So, if that's the case, when this View is run, it will return three nids.
If you look into views_get_view_result() you can quite easily access that output, eg:
$result=views_get_view_result('top_three'); // or whatever the name of the view is

will populate $result with something along these lines:
Array
(
    [0] => stdClass Object
        (
            [nid] => 2340
            [node_created] => 1390349535
        )

    [1] => stdClass Object
        (
            [nid] => 1176
            [node_created] => 1390086303
        )

    [2] => stdClass Object
        (
            [nid] => 1133
            [node_created] => 1390086313
        )

)

So, now you just have to look in there to see if your current nid is in there and if so, act accordingly.
Now, of course, the other question is where to put all of this?  I'd suggest looking into hook_node_update() but be aware of the performance considerations of doing all of this each time a node is updated.  Caching is certainly your friend here.
Comment: you could do this with custom php, eg, upon saving content, do whatever to get the node nid of the node that needs the gold badge, then load that node and set whatever you need in that node object and then save it; and etc on the silver and bronze.
Comment: Thanks, that sounds very promising! I created the top_three view you suggested: it displays the nids of the 3 articles with the highest value in the integer field 'Ranking'. Now, I'd like to create a new rule with an event like 'After saving new content' or 'A node has been flagged' that switches a 'Trophy' image field of the highest rated node (situated at the top in top_three) to some picture. I was wondering how I can get the condition right. Should I add an 'Execute custom PHP code' condition? What should the code look like? I'd create 2 similar rules for the 2nd & 3rd best rated content.


Calculating VAT

Question: I have a customer who is disputing a (UK 20%) VAT total, but not sure how they are calculating this. This is their comment:
"The RRP is £225. Then minus the 10% discount which is £202.50. £202.50/1.2 = £168.75"
So they are saying 20% VAT of £202.50 leaves £168.75
I thought you simply take 20% from £202.50 which would be £40.50 leaves £162
So which is correct & why!
Comment: VAT is $20$ per cent of the price without VAT, not of the RRP (this might sound confusing but once you play around with the numbers, you will understand it). If the price without VAT is $x$, then the final price (RRP) is $1.2x$. Therefore, you have to divide by $1.2$. I think the customer is right here.
Answer: If you take a number and you first add the 20% and then take the 20% you don't obtain the original number. In fact $100 + 20\% = 120$ and $120 - 20\% = 96$.
So, since VAT is "adding $20\%$" the inverse is not "subtract $20\%$".
Since "adding $20\%$" is equivalent to multiply by $1.2$ then dividing by the same quantity is correct.
If you want to subtract a percentage then the right percentage is
$$ 100 \cdot \left( 1- \frac{1}{1.2} \right) = 100 \cdot 1.\bar 6 = 16.\bar 6 \% \approx 16.67\% $$
Comment: perfect answer & thanks!
Answer: I calculate VAT in these ways of two different (most common) contexts:
<code>X = Cost.
Y = VAT Calculation Basis.
</code>
1) Expanding a number by Y:
<code>  X * Y / 100 == costsVAT (Add it to the cost to get sum).
  X * Y %     == costsVAT (Add it to the cost to get sum).
  X * 1.Y     == ES (End Sum).
</code>
2) Decerment VAT from a number:
<code>  X * Y / 100 == Only VAT (decerment it from the charging sum to get end sum).
  X * Y %     == Only VAT (decerment it from the charging sum to get end sum).
  X / 1.Y     == cost decermented by costsVAT
</code>

Calculating VAT


Is the value of probability invariant of function of a random variable

Question: Consider two random variables following a common distribution F. Is $P(X_{1} > X_{2}) = P(f(X_{1})>f(X_{2}))$ for any function f?
Comment: If $f $ was a constant function then the right hand side would be zero.
Comment: Take f(x) = -x for an obvious counterexample.
Comment: You need to make assumptions about f in order for this to be true. Assuming that f is strictly monotonic and increasing should do it
Answer: Let $X_1, X_2$ be two independent random variables each with pmf
$$ P_{X}(x)=
\begin{cases}
\frac{1}{2} & x =1 \\
\frac{1}{2} & x =-1 \\
\end{cases} $$
Then $\mathsf P(X_1>X_2)=0.25$ but $\mathsf P\big(X_1^2>X_2^2\big)=0$
Answer: No.  That equation does not hold in general.  Although that equation does not hold in general, it does hold for monotonically increasing functions.  If $f$ is monotone increasing (e.g., exponential or logarithmic functions) then you have the event equivalence:
$$\{ X > Y \} \quad \quad \iff \quad \quad \{ f(X) > f(Y) \}.$$
In this case the underlying events are equivalent and so the probability equation you give holds regardless of the distribution of $X_1$ and $X_2$.  Note also that there are some special combinations of a distribution $F$ and a function $f$ for which your probability equation holds, but it will not hold as a general property unless $f$ is a monotonically increasing function.
Comment: Might want to add the qualifier "strictly" to "monotonic". "monotonic" is often used to refer to functions with $x > y \rightarrow f(x) \ge f(y)$ rather than $x > y \rightarrow f(x) > f(y)$
Comment: Wikipedia says "[A function is called monotonically increasing (also increasing or non-decreasing), if for all x and y such that  $x\leq y$  one has$f(x) \leq f(y)$](https://en.wikipedia.org/wiki/Monotonic_function)"
Comment: Maybe.  But for non-strict version I would usually say "monotone non-decreasing" rather than "monotone increasing".  I would generally take "increasing" to imply strictness, unless the contrary is stipulated.  Rather than change it, I think I'll just leave these comments here for the OP to see.
Comment: That's all very well, but I've seen the alternative terminology elsewhere, and it makes more sense.  By the terminology you have linked to, the constant function $f(x)=c$ is an "increasing" function, yet it never increases.  It is also a "decreasing" function, yet it never decreases.  Curious terminology, no?
Answer: A simple counterexample for any $X_i$ with $P(X_i > 0) = 1$ is the function $f(x) = x^{-1}$. It reverses inequalities, hence $P(f(X_1) > f(X_2)) = P(X_1 < X_2)$, which is in general different from $P(X_1 > X_2)$.


SQL Server - Timed Out Exception

Question: We are facing the SQL Timed out issue and I found that the Error event ID is either Event 5586 or 3355 (Unable to connect / Network Issue), also could see few other DB related error event ids (3351 & 3760 - Permission issues) reported at different times.
what could be the reason? any help would be appreciated..
Comment: Can you post the query? It may helps to solve the problem.
Answer: Can you elaborate a little? When is this happening? Can you reproduce the behavior or is it sporadic?
It appears SharePoint is involved. Is it possible there is high demand for a large file?
Answer: You should check for blocking/locking that might be preventing your query from completing. Also, if you have lots of computed/calculated columns (or just LOTS of data), your query make take a long time to compute.
Finally, if you can't find something blocking your result or optimize your query, it's possible to increase the timeout duration (set it to "0" for no timeout). Do this in Enterprise Manager under the server or database settings.
Answer: Troubleshooting Kerberos Errors. It never fails.
Answer: Are some of your webapps running under either the Local Service or Network Service account? If so, if your databases are not on the same machine (i.e. SharePoint is on machine A and SQL on machine B), authentication will fail for some tasks (i.e. timerjob related actions etc.) but not all. For instance it seems content databases are still accessible (weird, i know, but i've seen it happen....).

SQL Server - Timed Out Exception


How to avoid destructuring mutation from Apollo useMutation hook?

Question: I am wrapping the useMutation hook from react-apollo so that I can send to Sentry the errors every time I use a mutation:
import { useMutation } from '@apollo/react-hooks'
import { DocumentNode } from 'graphql'
import { MutationHookOptions } from 'react-apollo'

type UseMutationWithSentryErrorsProps = {
  refetch: MutationHookOptions<any, Record<string, any>>
  from: string
  mutation: DocumentNode
}

export const useMutationWithSentryErrors = ({
  refetch,
  from,
  mutation
}: UseMutationWithSentryErrorsProps) => {
  const response = useMutation(mutation, refetch)

  const [_apolloMutation, { error: mutationError }] = response
  if (mutationError) {
    captureException(mutationError, {
      info: 'There was an error fetching data.',
      from
    })
  }

  return response
}

How I call the mutation is:
  const [updateSpeakerMutation] = useMutationWithSentryErrors({
    refetch,
    from: 'SomeProvider',
    mutation: UPDATE
  })

The problem is with this line:
  const [_apolloMutation, { error: mutationError }] = response

I get a variable is not read error. I can't access the response error without accessing the mutation, but I am not using the mutation in this wrapper function, but in the places where I truly use it. I tried the classic _ syntax but still same error.
Answer: You can just do this:
const [, { error: mutationError }] = response

Note the comma
Comment: I opted to use it as an extra check `if (apolloMutation && mutationError) {etc.`


How to use Hierarchial Select Module for select field's of webform module?

Question: Answer is to use Hierarchial select module for dynamic options list based on the previous select box value
How do I use Hierarchial select module in my webform module for select fields?
Answer: Seems like webform doesn't support Hierarchical Select module...
You can use Webform Conditional module to create dependent fields...
Project page says

This modules enhances the existing Conditional Rules of the Webform
  Module. It adds the ability to make components dependent on select
  components(i.e. listboxes, radio buttons, and checkboxes) that appear
  on the same page.
Comment: Webform conditional module does not do what I want. http://drupal.stackexchange.com/questions/17975/dynamic-options-list-based-on-the-previous-select-box-value


Send json to jade

Question: I am sending a big json file from server to jade, but the " are replaced with: " therefor the json is unreadable/unparsable and I get this error:
Uncaught SyntaxError: Unexpected token &

I send the data like this from node:
res.render(view, {world:{name:"SomeName",width:50},otherdata:{...}});

and then get it in jade like this:
doStuff(JSON.parse(#{data}));

and here it is unreadable data which looks like:
{world:{name:"SomeName",width:50...

can I somehow disable the conversion of the quotes?
Comment: More details ! this question is bad..
Comment: @NetaMeta added in some more info
Comment: Why do you need to JSON.parse if the data is already an object?
Answer: Server side within your rout you will do the following consider the object user
var user = {username:"myname"};
res.locals.user = user ;

response will be :
res.render('view');

jade view will have the variable available :
if user
    script(type='text/javascript').
        var user = !{JSON.stringify(user)};

Try adding app.use(bodyParser.json()); if you still have the issue
hope that helps
Answer: No experience with jade but from the language reference (http://jade-lang.com/reference/interpolation/) i guess
doStuff(JSON.parse(!{data}))

might work

Send json to jade


Connecting Android tablet to Web Service

Question: I am trying to connect my tablet to a Web Service that I have in my WAMP Server. I have tried doing everything I've read and had no luck connecting it. The web service reads data from SQL Server and shows it in the application. For now, that is all it needs to do. I have a code that I followed from a tutorial so that I could do the ASync Task, but it still doesn't help. Here is the code:
package com.example.secondtestsqlserver;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    String pid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectAll()
        .penaltyLog()
        .penaltyDialog()
        .build());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void clickSend(View view) {
        new TestWS().execute();
    }
    class TestWS extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading product details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... params) {

            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    // Check for success tag
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("pid", pid));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json = jsonParser.makeHttpRequest(
                                "http://184.108.40.206:80/webservice.php", "GET", params);

                        // check your log for json response
                        Log.d("Single Record Details", json.toString());

                        // json success tag
                        success = json.getInt("success");
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json.getJSONArray("master"); // JSON Array

                            // get first product object from JSON Array
                            JSONObject product = productObj.getJSONObject(0);

                            // product with this pid found
                            // Edit Text
                            EditText txtName = (EditText) findViewById(R.id.txtName);
                            EditText txtPrice = (EditText) findViewById(R.id.txtTest);

                            // display product data in EditText
                            txtName.setText(product.getString("test"));
                            txtPrice.setText(product.getString("name"));
//                            Log.e("Checking", product.getString("test"));
//                            Log.e("Checking", product.getString("name"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }
}

This is the JSONParser Class
package com.example.secondtestsqlserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            Log.e("Unsupported Encoding", Log.getStackTraceString(e));
        } catch (ClientProtocolException e) {
            Log.e("Client Protocol", Log.getStackTraceString(e));
        } catch (IOException e) {
            Log.e("IO Exception", Log.getStackTraceString(e));
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
            System.out.println(e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
            Log.e("JSON Parser", json);
        }

        // return JSON String
        return jObj;

    }
}

And this is the PHP Web Service
<?php
    $serverName = "localhost\SQLExpress";
    $connectionOptions = array("Database"=>"Android");
    $conn = sqlsrv_connect($serverName, $connectionOptions);

/*  if ($conn)
    {
        echo "Connection established.
";
    }
    else
    {
        echo "Connection could not be established.
";
        die(print_r(sqlsrv_errors(), true));
    }*/

    $query = "SELECT * FROM AndroidTest;";

    $result = sqlsrv_query($conn, $query, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
    $master = array();
    if (sqlsrv_num_rows($result)) {
        $master["record"] = array();
        while ($posts = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
            $record = array();
            $record["test"] = $posts["test"];
            $record["name"] = $posts["name"];

            array_push($master["record"], $record);
        }
        $master["success"] = 1;
    }
    else {
        $master["success"] = 0;
        $master["message"] = "No products found";
    }
    header('Content-trype: application/json');
    echo json_encode($master);
    sqlsrv_close($conn);
?>

I do know for a fact that the PHP is right, since it is giving me the data I want, but the application doesn't work in my tablet, nor does it work in the emulator. Also, note that on the MainActivity class, I use the StrictMode.setThreadPolicy(). This is because I read that when I get the onNetworkMainThreadException, this usually fixes the problem even though it is unsafe. I was planning to change it, of course, after I find out why I can't connect. The error is this one:
12-21 09:03:45.049: E/IO Exception(25431): org.apache.http.conn.HttpHostConnectException: Connection to http://126.96.36.199:80 refused
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-21 09:03:45.049: E/IO Exception(25431):  at com.example.secondtestsqlserver.JSONParser.makeHttpRequest(JSONParser.java:62)
12-21 09:03:45.049: E/IO Exception(25431):  at com.example.secondtestsqlserver.MainActivity$TestWS$1.run(MainActivity.java:75)
12-21 09:03:45.049: E/IO Exception(25431):  at android.os.Handler.handleCallback(Handler.java:615)
12-21 09:03:45.049: E/IO Exception(25431):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-21 09:03:45.049: E/IO Exception(25431):  at android.os.Looper.loop(Looper.java:137)
12-21 09:03:45.049: E/IO Exception(25431):  at android.app.ActivityThread.main(ActivityThread.java:4745)
12-21 09:03:45.049: E/IO Exception(25431):  at java.lang.reflect.Method.invokeNative(Native Method)
12-21 09:03:45.049: E/IO Exception(25431):  at java.lang.reflect.Method.invoke(Method.java:511)
12-21 09:03:45.049: E/IO Exception(25431):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-21 09:03:45.049: E/IO Exception(25431):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-21 09:03:45.049: E/IO Exception(25431):  at dalvik.system.NativeStart.main(Native Method)
12-21 09:03:45.049: E/IO Exception(25431): Caused by: java.net.ConnectException: failed to connect to /188.8.131.52 (port 80): connect failed: ENETUNREACH (Network is unreachable)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.IoBridge.connect(IoBridge.java:114)
12-21 09:03:45.049: E/IO Exception(25431):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-21 09:03:45.049: E/IO Exception(25431):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-21 09:03:45.049: E/IO Exception(25431):  at java.net.Socket.connect(Socket.java:842)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-21 09:03:45.049: E/IO Exception(25431):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-21 09:03:45.049: E/IO Exception(25431):  ... 17 more
12-21 09:03:45.049: E/IO Exception(25431): Caused by: libcore.io.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.Posix.connect(Native Method)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-21 09:03:45.049: E/IO Exception(25431):  at libcore.io.IoBridge.connect(IoBridge.java:112)
12-21 09:03:45.049: E/IO Exception(25431):  ... 22 more
12-21 09:03:45.049: E/Buffer Error(25431): Error converting result java.lang.NullPointerException
12-21 09:03:45.049: E/JSON Parser(25431): Error parsing data org.json.JSONException: End of input at character 0 of
12-21 09:03:45.049: E/AndroidRuntime(25431): FATAL EXCEPTION: main
12-21 09:03:45.049: E/AndroidRuntime(25431): java.lang.NullPointerException
12-21 09:03:45.049: E/AndroidRuntime(25431):    at com.example.secondtestsqlserver.MainActivity$TestWS$1.run(MainActivity.java:79)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at android.os.Handler.handleCallback(Handler.java:615)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at android.os.Looper.loop(Looper.java:137)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at android.app.ActivityThread.main(ActivityThread.java:4745)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at java.lang.reflect.Method.invokeNative(Native Method)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at java.lang.reflect.Method.invoke(Method.java:511)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-21 09:03:45.049: E/AndroidRuntime(25431):    at dalvik.system.NativeStart.main(Native Method)

I would not be asking if I hadn't already tried everything I found in here and everything I found on the internet. I need to make this work soon, so please any help you can give me will be greatly appreciated.
Answer: This seems to be the root cause:
failed to connect to /18.104.22.168 (port 80): connect failed: ENETUNREACH (Network is unreachable)

So make sure, your service is running there and can be reached from your tablet. (Maybe try to fetch a HTML page from the server to make sure you have connectivity)
Comment: Well, that is the computer's IP Address. I have my laptop and my tablet connected to a LAN I made in a cellphone (no internet), and I am trying to access the computer's local host through there. I have no idea if I'm doing this right, I'm new at this and I'm trying to learn how it works.
Comment: The IP address does not look like its on a LAN. I do not really understand how you have setup your network. Do you have a firewall running on the server?
Comment: I am doing local tests, you probably noticed since I am using SQL Express. My cellphone acts as a router. Both my tablet and my laptop are connected to my cellphone via wireless. Somehow, I need my tablet to find the path to my Web Service (which is located in my WAMP Server local host) which is obviously in my laptop. These are my work conditions right now, as this is something I'm doing at work. I don't know if what I want to do is possible though.
Comment: Ok, it was a very stupid mistake on my part. I was using the IP Address of the Local Network and not the Wireless Network IP. I have access now but it is still not accessing the WAMP Server, as if it was turned off.


RESTful: When to nest JSON?

Question: Say I am building an API with a call that returns a collection of cities, each of which has a relationship to a state. A state has many cities, but a city has only one state.
I can imagine flattening the relationship and obscuring the underlying structure of the data like this,
<code>{ cities : [
    { id: 1,
      name: "Los Angeles",
      state: "CA" }
]}
</code>
Or I can imagine structuring the JSON such that the relationship between cities and states is apparent,
<code>{ cities : [
    { id: 1,
      name: "Los Angeles",
      state: { id: 1,
               name: "CA" }
]}
</code>
The consumer of the API, as of now, only ever needs to know the name of the state. He does not need to know its ID or a way to get more information about the state. What are the pros and cons in structuring the JSON in either way?
Comment: My opinion is to keep API's as simple as possible. That means return content, or variables to request new content.
Answer: In my opinion you should not add useless information to you api, but as @kgb said if your api is prone to be expanded you should design it that way. You asked about the relationship between the cities and states, and in my opinion this relationship is already defined in both of them.
So if you are 100% sure your api will not expand the state functionality, you should go with option 1. If there is only a slight chance, i propose you do this:
<code>{ cities : [{
      id: 1,
      name: "Los Angeles",
      state: { name: "CA" }
  }]
}
</code>
Answer: That depends on the other consumers. Do you have any? Are you planning to?
An API is a machine interface, it is equally easy for the consumer's developer to use both structures. If the "state" entity is not a compound entity(no usable properties except name), it might me a good idea to show just the name, not a structure with the id.
If there is a possibility that state id might be useful in future, or a possibility that a new property is going to be added to state entity, then you should use the second approach from the start. Changing API in any way breaks the software already written, so changing it will make you support two different versions. Change between approaches 1 and 2 is not backward-compatible.
I would go with approach 2. It is not much more complex than 1 and leaves a possibility to extend state entity.
There is also a third approach. But it is noticeably more complex(and more extendable). Return state id only and create a method for state entity retrieval.

RESTful: When to nest JSON?


The Weierstrass map between a torus and an elliptic curve is biholomorphic

Question: Let $\Lambda$ be a lattice in $\mathbb C$. We can build by this lattice the Weierstrass $\wp$-function in the following manner:
$$
\wp(z) = \frac{1}{z^2}+\sum\limits_{l\notin\Lambda\setminus\{0\}}\left(  \frac{1}{(z-l)^2} - \frac{1}{l^2}\right)
$$
It can be shown that this function satisfies the following differential equation:
$$
\wp'(z)^2 = 4\wp(z)^3 - 60G_4\wp(z) - 140 G_6
$$
This function gives us a map frop $\mathbb C/\Lambda$ to the elliptic curve $y^2 = 4x^3 - 60G_4 x - 140G_6$ in such a way:
$$
z \mapsto [\wp(z):\wp'(z):1]
$$
My question is: why this map is biholomorphic?
Comment: @Chill2Macht see my answer
Comment: Is it biholomorphic? I can see how it would be holomorphic, I just didn't know that the Weierstrass function was invertible -- doesn't it have poles of order two at every $l \in \Lambda$?
Answer: For a fixed $\tau \in \mathbb{C} -\mathbb{R}$

Define the curve $$E(\mathbb{C}) = \{ (x,y) \in \mathbb{C}^2, y^2 = 4 x^3 - g_2(\tau)x - g_3(\tau)\}$$
with a complex topology inherited from $\mathbb{C}^2$.
Define the lattice $\Lambda = \mathbb{Z}+\tau \mathbb{Z}$ and look at $(\mathbb C- \Lambda) / \Lambda$ which is a complex torus minus one point. With the complex topology inherited from $\mathbb{C}$ it is naturally a non-compact Riemann surface.
Define the map
$$\varphi : (\mathbb C- \Lambda) / \Lambda \to E(\mathbb{C}), \qquad \varphi(z) = (\wp_\tau(z),\wp_\tau'(z))$$
$\varphi$ is well-defined and bijective because $\wp(z)$ takes all the complex values twice (if not then $\frac{1}{\wp(z)-a}$ would be a bounded entire function) and $(\wp_\tau(-z),\wp_\tau'(-z))=(\wp_\tau(z),-\wp_\tau'(z))$.
$\varphi$ is also holomorphic as a map $(\mathbb C- \Lambda) / \Lambda \to \mathbb{C}^2$.
Thus $\varphi$ is a bijective holomorphic map $(\mathbb C- \Lambda) / \Lambda \to E(\mathbb{C})$ which means it is biholomorphic and $E(\mathbb{C})$ is now a non-compact Riemann surface.
Finally $\mathbb C / \Lambda $ is a compact Riemann surface (and an abelian group) by adding the point $z=0$ to $(\mathbb C- \Lambda) / \Lambda$.
Thus $E(\mathbb{C})$ becomes a compact Riemann surface when adding one point : the image of $z=0$ by $\varphi$, that we call $O$, whose $\epsilon$- neighborhood is $\{O\} \cup \{(x,y) \in E(\mathbb{C}), |x| > \frac{1}\epsilon\}$ (the definition of 'holomorphic at $O$' follows from this thanks to the Riemann's theorem on removable singularities)
Which is the same as defining $E(\mathbb{C})$ as the projective curve
$$E(\mathbb{C})_{proj} = \{ (x:y:w) \in P_2(\mathbb{C}),  y^2w = 4 x^3 -g_2(\tau)xw^2 - g_3(\tau)w^3\}$$
and $$\varphi(z) = (\wp_\tau(z):\wp_\tau'(z):1), \qquad\varphi(0) = (0:1:0)$$ is a biholomorphic map $\mathbb{C}/\Lambda \to E(\mathbb{C})_{proj}$


Why is Gaussian distribution on high dimensional space like a soap bubble

Question: In this famous post "Gaussian Distributions are Soap Bubbles" it is claimed that the distribution of the points looks like a soap bubble (where it is less dense in the center and more dense at the edge) instead of a bold of mold where it is more dense in the center. I would expect that it is more dense in the center like it is in two or three dimensional.
From the post, I could not figure out why this is the case. It uses three figures which I could not figure out what they are telling.

Can someone clarify this figures and the main question why it is looking like a soap bubble in high dimensions?
Comment: This is not special to Gaussian distributions: it applies to every distribution of finite variance.  The squared radius is the sum of iid variables and the Central Limit Theorem takes care of the rest.  What is special about Gaussian distributions is that the soap is distributed uniformly in the angular directions.
Comment: The *mode* is always at the center (irrespective the dimension), but in high dimensions it is very little probability close to the mode, the mass of probability is further out. I will try to add a more detailed answer!
Comment: @Dilip Two properties are in play here: the concentration of probability close to a single radius and uniform angular distribution.  "Looks like a soap bubble" arguably means both, but the phrase "less dense in the center and more dense at the edge" only means the former.  As far as independence goes, I understand this question to concern the distribution of $n$ iid random variables thought of as a point in $\mathbb{R}^n,$ whence their squares are independent, too.
Comment: There is no edge to a Gaussian distribution... I personally think that this is a terrible analogy, not only for that reason.
Comment: @kjetilbhalvorsen 's comment reminded me of a similar remark (albeit in the context of MCMC sampling) made by [Michael Betancourt](https://twitter.com/betanalpha) in [this presentation](https://www.youtube.com/watch?v=pHsuIaPbNbY&t=695s).
Comment: This is just the curse of dimensionality, isn't it?
Comment: @whuber "The squared radius is the sum of iid variables...." If I recall correctly, _both_ spherical symmetry of the pdf and independence of the random variables occurs only in the Gaussian case? If so, the random variables being squared are identically distributed, but _not_ independent (what I call NIBNID in my answer) in all cases _except_ when the random variables are Gaussian.
Answer: I can't answer about what the OP's famous post claims, but let us consider the simpler case of uniform distributions on the unit disc: $(X,Y)$ is uniformly distributed on the unit disc (that is, $f(X,Y)(x,y) = \frac 1\pi$ for $x^2+y^2 < 1$.  What is the probability that $(X,Y)$ is closer to the unit circle, that is, closer to the boundary of the unit disc than it is to the origin (center of the circle)? Well, only those points that lie inside the circle of radius $\frac 12$ are at distance $< \frac 12$ from the origin, and so all points outside this smaller circle are at distance $> \frac 12$ from the origin. It is an easy computation to arrive at
$$P\left(\frac 12 < \sqrt{X^2+Y^2} < 1\right) = 1- P\left(0\leq \sqrt{X^2+Y^2} < \frac 12\right) = 1 - \frac 1\pi \cdot \pi\left(\frac 12\right)^2 = \frac 34.$$
A similar calculation for a uniform distribution on the interior of a unit sphere in 3 dimensions (the pdf has value $\frac{3}{4\pi}$ on the interior) gives
\begin{align}
P\left(\frac 12 < \sqrt{X^2+Y^2+Z^2} < 1\right) &= 1- P\left(0\leq \sqrt{X^2+Y^2+Z^2} < \frac 12\right)\\
&= 1 - \frac{3}{4\pi} \cdot \frac{4\pi}{3}\left(\frac 12\right)^3\\
&= \frac 78.
\end{align}
Generalizing to $n > 3$ dimensions and remembering that the volume of an $n$-dimeensional hypersphere or radius $r$ is proportional to $r^n$, we get by very similar calculations that
$$P\left(\frac 12 < \sqrt{\sum_{i=1}^n X_i^2} < 1\right) = \frac{2^n-1}{2^n},$$
that is, most of the probability mass_ lies closer to the surface of the sphere than to the origin.  As a final comment, note that the $X_i$ are NIBNID random variables which acronym stands for Not Independent But Nonetheless Identically Distributed.
Turning to IID standard Gaussian random variables, the joint density is not uniformly distributed but has a very pronounced peak at the origin. But, there is so little volume near the center of a hypersphere as compared to closer to the surface that when we integrate the density over the volume of a hypersphere of small radius $r$ to find $P\left(\sqrt{\sum_{i=1}^n X_i^2} < r\right)$, most of this probability mass is obtained from the small contributions from the periphery (there are so many of them) and very little from the few but larger contributions from the core; that is, most of the probability mass lies closer to the skin of the orange than to the center. But things change as $r$ increases. Since $\sum_{i=1}^n X_i^2$ is a $\chi^2$ random variable with $n$ degrees of freedom (with mean $n$ and variance $2n$), which for large $n$ can be approximated as a Gaussian random variable with the same mean and variance) most of its probability was lies in the range $\left[n-\sqrt{18n},n-\sqrt{18n}\right] = [\mu-3\sigma,\mu+3\sigma]$. Put another way,
the quantity $P\left({\sum_{i=1}^n X_i^2} < r^2\right)$ is close to $0$ for small $r$ (the nearly empty space inside the soap bubble), and then (regarded as a function of $r$) increases very rapidly with $r$ in the close vicinity of $r=\sqrt n$ (this is the thin skin of the bubble where most of the mass is) to almost $1$, and then very slowly to its asymptotic value of $1$ (the nearly empty space outside the bubble).  In short, the soap bubble analogy is very apt for Gaussian distributions; almost all the probability mass of the joint pdf of $n$ standard Gaussian random variables does indeed lie in a very thin shell of radius $\approx \sqrt n$ and there is very little probability mass that is not in the shell -- both the interior and the exterior of the shell is mostly empty as is the case with soap bubbles.
Comment: Very sweet answer (+1)! By the way, the volume of an n-dimensional sphere, of radius r, is
$$  \pi ^{n/2}r^n / \Gamma [(n/2)+1]  $$.
Answer: The post you link to concerns the use of the normal distribution in high-dimensional problems.  So, suppose you are working in a space $\mathbb{R}^m$ where the dimension $m$ is large.  Let $\boldsymbol{I}$ be the $m$-dimensional identity matrix and consider a normal random vector:
$$\mathbf{X} \equiv (X_1,...,X_m) \sim \text{N}(\mathbf{0}, \sigma^2 \boldsymbol{I}).$$
A well-known property of this distribution is that a centered and normed normal random vector is uniformly distributed on the unit sphere.  That is, if we let $\mathcal{S}_r^m \equiv \{ \mathbf{x} \in \mathbb{R}^m | \sum x_i^2 = r^2 \}$ denote the $m$-dimensional sphere with radius $r$, then we have:
$$\frac{\mathbf{X}}{||\mathbf{X}||} \sim \text{U}(\mathcal{S}_1^m).$$
It is also well-known that the distribution of the scaled-norm of the random vector is:
$$\frac{||\mathbf{X}||}{\sigma \sqrt{m}} \sim \frac{\chi_m}{\sqrt{m}}.$$
Taking $m \rightarrow \infty$, the right-hand-side convergences in probability to one.  Thus, for large $m$ we have:
$$\mathbf{X} \overset{\text{Approx}}{\sim} \text{U}(\mathcal{S}_{\sigma \sqrt{m}}^m)$$
This shows that when $m$ becomes large, the points from this normal random vector are approximately distributed on the surface of a unit sphere with radius $\sigma \sqrt{m}$.  This is what the linked post is referring to when it notes that "...in high dimensions, Gaussian distributions are practically indistinguishable from uniform distributions on the unit sphere".
Answer: I don't think it is true that "a Gaussian distribution in higher dimensions looks like a soap bubble". But first let's see why, in accordance with some of the very detailed responses above, one might be led to think so.
In Cartesian coordinates in $D$ dimensions, after standardization, the probability density looks like
$$ p(\vec{X}) ~d\vec{X} \sim V^{-D/2} \exp(-\frac{||\vec{X}||}{2V}) ~d\vec{X}$$
where $V$ is the 1D variance of each variable.
We can rewrite this in spherical coordinates, and use spherical symmetry to integrate over the D-1 dimensional spheres. I'll leave out the factor corresponding to the volume of the D-1 sphere (not the ball which is the "interior" of the sphere). The radial distribution is
$$ p(r)dr \sim V^{-\frac{D}2} r^{D-1} \exp(-\frac{r^2}{2V})~dr = V^{-\frac{D}2} r^{D-2} \exp(-\frac{r^2}{2V}) ~ \frac12 dr^2, ~r > 0 $$
Introducing $z = \frac{r^2}2$, the distribution is:
$$p(z)dz \sim V^{-\frac{D}2} z^{\frac{D}2-1} \exp(-\frac{z}{V})~dz$$
which is just a Gamma Distribution (in $z$).
Now you can look up https://en.wikipedia.org/wiki/Gamma_distribution or calculate the mean radius (modulo some irrelevant factors and $\pm 1$):
$$<r> \sim D \sqrt{V}$$
and the variance of the radius $<(r-<r>)^2>$:
$$var(r) \sim DV$$
which means the standard deviation of $r$
$$SD(r) \sim\sqrt{DV}$$.
The relative SD:
$$ \frac{SD(r)}{<r>} \sim \frac1{\sqrt{D}}$$
which, as the number of dimensions $D$ increases, tends to 0.
So we think that looks like a bubble. But, the question is, as a distribution, does the radial distribution $\rightarrow \delta(r-r_0)$ in the limit $D\rightarrow\infty$?
Now let's go back to that D-dimensional distribution in Cartesian coordinates. It is peaked at the origin and falls off as your distance from the origin increases. It looks nothing like a bubble. If you had a mass density distributed like this you would not encounter any bubble that you have to pierce nor any "thickening" at $r_0$, in fact the density would continue to increase as you travelled towards the center. It is only when we integrate over the shells of fixed radius and collapse them to a single radial point do we get the relative standard deviation tending to 0 with increased dimensionality.
So, no, it is not true that "a Gaussian distribution in higher dimensions looks like a soap bubble".
Comment: Re " let's go back to that D-dimensional distribution in Cartesian coordinates:" exactly what are you referring to?  If you mean the distribution with density $p,$ then you are flatly contradicting the result of your preceding (correct) analysis.
Comment: Well, if we take it very literally, sure, it doesn't look much like a soap bubble, as the density is actually quite low, but the surface area of the shell is enormous. But the reason for the analogy is pretty clear: a projection down to 3D where shells have the same density by radius produces the soap bubble. Ultimately it's only "wrong" because there is simply no visualizable analogy for extremely high dimensional space.
Comment: @ClimberT8 The human visual system handles 3 dimensions of space and 1 dimension of time at a specific scale and resolution. Our abstract reasoning capacity may handle the concept well enough, but it's pretty hard to believe there is anything "visual" about a billion points, let alone a billion dimensions.

And to clarify, soap bubbles are a specific macroscopic, 3D physical object, like a snowflake, a chair, or a human body. "Higher-dimensional soap bubble" implies a mathematical definition for "soap bubble" which is independent of dimension, which is basically just assuming the premise.
Comment: @whuber I forgot the ||...||^2 in the first equation for the distribution - the Gaussian distribution exp(-(x_1^2 + x_2^2+...)). Since in C artesian coordinates the volume element is 1, both the "function" and the density have the same plot and are peaked at the center. No bubble, "No more than a bubble" by Jamel Brinkley. But if you write this in spherical coordinates and integrate over the D-1 angles (what the next commenter calls "projection"), only then do you get the apparent densification in the radial coordinate.
Comment: @rationalis Sure, you are more than welcome to hold on to your preconception, but it is purely an artifact of projection. So you might as well ask **"Why cubes are like hexagons?"**. And because _you_ can't imagine or know of visualizations in higher dimensions please don't claim that they "simply" doesn't exist.
Comment: @ClimberT8 There are many possible visualizations of higher dimensional space. None of them, however, are perfectly accurate. Perhaps a savant might be able to visualize a thousand dimensions, but I think it's pretty clear no human could visualize a billion dimensions.
Comment: @ClimberT8 At any rate, analogies are basically always flawed. They're useful for identifying specific characteristics of interest. There's no such thing as a "1000-dimensional soap bubble." Soap bubbles are 3D. To see the "point" of the analogy, you have to ask what characteristic is identified between the two objects of comparison. Your interpretation of what it means for a high-dimensional distribution to be "like a soap bubble" is no more or less valid than anybody else's.
Comment: @rationalis There are many possible projections of higher dimensional objects. The question of "accuracy" only arises when there is agreement on what dimensions or features you do want your projection or "visualization" to faithfully capture and which ones are irrelevant. If an object is subject to enough symmetries, e.g. spheres, cubes, Calabi-Yau manifolds etc, I don't see why you would object to visualizing billion dimensional objects.
Comment: @rationalis Mostly agreed about analogies. I don't know what you mean by "soap bubbles are 3D", certainly the structures can exist in higher dimensions and there are many attempts in discrete Quantum Gravity that have lower dimensional intersections of higher dimensional manifolds or even topological n-spheres propagating in some higher dimensional space.
Comment: @rationalis I was going to suggest "Flatterland", but on second thought, it isn't about math at all, I agree with you it is about English, we disagree about what a "bubble" means. To me, one thing it means is that you encounter a radical change in density over a very short traversal distance and that the collection of such points forms a closed manifold. "Why ...?" questions are dangerous unless "Is it true that...?" has been answered affirmatively. The mathy stuff answers "Why the radial projection of a Gaussian asymptotes to a delta distribution?", nothing about bubbles.
Answer: I really think that the vision of an empty bubble is misleading.
(tl-dr: Instead of an empty bubble I think is better to say that it resembles to a star with n-vertices where $n\rightarrow\infty$, or some kind of a non empty fractal structure with the length of its border going to $\infty$). But still more dense in the center.
The higher the dimension is, there are more points close to the border of a n-sphere than to its center (easy to see moving from 2D to 3D), but for a multivariate normal distribution: $$P\left( \left\{ \text{n-sphere center in} \left(0,...,0\right) \text{ and } r=\delta \right\}\right ) > P\left( \left\{ \text{n-sphere center in} \left(\delta,...,0\right) \text{ and } r=\delta \right\}\right )$$
Always, for any dimension, for any $\delta$, the probability is higher the closer to the center (for similar areas of course). So: is still more dense in the center, but is has less center (center is never 0 because remember $dimension \rightarrow \infty$ and not $dimension=\infty$).
Yes... if you pick a point at random is more likely to be in the border than in the center, but not because the probability in the center is "empty as a bubble", but just becasue there are more points close to the border.
This already happens in 2D: in a 2D-Sphere of radius=1 "there are" $\pi/4$ points at distance ½ of the center, while there are $3/4*\pi$ points at distance less than ½ of the border.  And actually with a bivariate normal distribution the probability of picking a point next to the border is higher than picking one in the center
(see code below).
Another way to visualize it is comparing a 2D sphere vrs a 2D star, as the star has "More border" the probability of picking a point next the border in a star is higher, but the start is not "empty".
Instead of an empty bubble It will be better to say: it resembles to a star with n-vertices where $n\rightarrow\infty$, or some kind of a non empty fractal structure with the length of its border going to $\infty$. But still more dense in the center.
PD:
Using r
<code>library(shotGroups)

#using 2d multivariate normal distribution

#probability of choosing a point inside the cercle with radius delta=0.5
inner_cercle_prob <- pmvnEll(r=0.5, sigma=diag(2), mu=c(0,0), e=diag(2), x0=c(0,0))

#probabiliyt of choosing a point inside the cercle of radius=1
full_cercle_prob <- pmvnEll(r=1, sigma=diag(2), mu=c(0,0), e=diag(2), x0=c(0,0))

#probability of choosin a point inside the cercle but closer to the border
corona_prob=full_cercle_prob-inner_cercle_prob

#probability of choosin a point outside the cercle
outside_cercle_prob=1-full_cercle_prob

outside_cercle_prob
[1] 0.6065307
corona_prob
[1] 0.2759662
inner_cercle_prob
[1] 0.1175031

#but for cercles with same radius, the one closer to the center as higher prob.
pmvnEll(r=0.5, sigma=diag(2), mu=c(0,0), e=diag(2), x0=c(0,0))
[1] 0.1175031
pmvnEll(r=0.5, sigma=diag(2), mu=c(0,0), e=diag(2), x0=c(0.5,0))
[1] 0.1044914
</code>
Comment: These descriptions of a "star" are clearly incorrect, because multivariate Normals are elliptical distributions.  In particular, the standard multivariate Normal distribution is perfectly spherically symmetric: no direction is distinguished.  That's the very *opposite* of a star.
Answer: This is an old post with some great responses but I'd like to give a different perspective.
Assume we take a sample $x$ from $\mathcal{N}(\vec0, \mathcal{I})$ in $D$ dimensions. If the high-dimensional Gaussian is hollow, then that would mean at least one coordinate of our sample $x$ deviates from the mean. By the CDF of the normal distribution, the chance of $x$'s first coordinate being within one standard deviation is about $~68.2\%$. Now what is the chance that both the first and second coordinates are within one standard deviation? They are independent, so it's $0.682^2$. By extension, the probability that a sample in $D$-dimensional space is within one standard deviation along every axis is $0.68^D$. Naturally, this goes to 0 very quickly.
Comment: This is an interesting perspective, but it seems to carry a basic flaw.  You can do the same calculation for *any* set of intervals, rather than the 1 sd interval around 0.  If you make these intervals all of length 2 sds, the chance that the sample will lie within their Cartesian product can never exceed $(0.682)^D.$  In this sense you seem to have shown that the density is *greatest* at $0:$ namely, $0=(0,0,\ldots,0)$ remains the mode of the distribution.  Indeed, this is obvious when you inspect any formula for the density.  Thus, your remarks only deepen the apparent paradox.
Comment: Hmm, I think I am either missing your point or I disagree. I am saying that each coordinate has a chance of being either within or outside one standard deviation (1 std. dev. is arbitrary of course). Thus, we end up with a binomial distribution of sorts. The odds that all of your coordinates are within one standard deviation is '$D$ choose 0', where $D$ is the dimensionality of the space. So we are most likely to see points at distance $\frac{D}{2} || \sigma ||$, or whatever the most likely element is under the binomial distribution.
Answer: Let random vector ${ X \sim N(0, I _n) }$. Its density is $f(x)= \frac{1}{(\sqrt{2\pi}) ^n} e ^{- \frac{\lVert x \rVert ^2}{2} } .$
So $$ \mathbb{P}( \lVert X \rVert \in [r,~ r + d r])  \approx C e ^{-r ^2 /2} r ^{n-1} ~d r  .$$
Here $ e ^{-r ^2 /2} $ is density upto multiplicative constant, and $r ^{n-1} dr $ (i.e. derivative of $V _n (r) = r ^{n} V _n (1) $ times $d r $) is volume of shell upto multiplicative constant.
Hence $$ \mathbb{P}(\lVert X \rVert \in [r, ~r + \Delta r])  = C \int _{r} ^{r + \Delta r} e ^{-u ^2/2} u ^{n-1} du,$$ where ${ C \int _{0} ^{\infty} e ^{-u ^2 /2} u ^{n-1} du = 1 }.$
We want $ r ,~ \Delta r $ so that $$ \mathbb{P}(\lVert X \rVert \in [r, ~r + \Delta r]) \approx 1 $$ i.e. $$\int _{r} ^{r + \Delta r} e ^{-u ^2/2} u ^{n-1} du  \approx \int _{0}^{\infty} e ^{-u ^2 /2} u ^{n-1} du .$$
The function $e ^{-u ^2 /2} u ^{n-1} $ attains maximum at point where derivative $$ e ^{-u ^2 /2} (-u) u ^{n-1} + e ^{-u ^2/2} ((n-1) u ^{n-2})  = e ^{- u ^2 /2} u ^{n-2} (-u^2 + (n-1)) $$ is $0 .$ That is, maximum is attained at $ u = \sqrt{n-1} .$
So if at all most of the probability mass concentrates around a thin shell, it is around a shell of radius $r \approx \sqrt{n} .$ (The actual estimates showing Gaussian annulus theorem can be found for eg in Kannan, Hopcroft, Blum's "Foundations of data science").
Comment: On using $\LaTeX, $ you don't need to use `{}` to write the expressions.


What happens If Olympic torch goes out accidentally?

Question: What happens if the Olympic torch goes out accidentally?
Answer:
What happens If Olympic torch gets off accidentally?

In the same Wikipedia article you reference under the section "Reigniting the flame"...
The Olympic torch is re-lit, or another torch is lit, from one of the multiple backup sources of the flame that is accompanying the relay.


cannot fetch proper id from DB in android

Question: I fetch a row from DB as a cursor. And then want to get id of it like this:
String selectQuery = "SELECT * FROM " + TABLE_PEERS + " WHERE " + KEY_NAME + "= '" + peer.name +"'";
Cursor c = db.rawQuery(selectQuery, null);

Log.d("count", c.getCount()+""); // display: count: 1 in LogCat
long peer_id = c.getLong(c.getColumnIndexOrThrow(KEY_SENDER_ID)); // error occurs in this line;

It always display an error:

Problems receiving packet: Index -1 requested, with a size of 1

and when I change:
long peer_id = c.getLong(c.getColumnIndexOrThrow(KEY_SENDER_ID));
to
long peer_id = c.getColumnIndexOrThrow(KEY_SENDER_ID);
 Log.cat("****": peer_id+"");
LogCat would display ****:0. However it suppose to display 1.
Can any one explain what causes the difference and where is wrong in my code? Thanks in advance.
Comment: I think you need to move the cursor once before you get access to the first item: c.moveToNext()
Comment: is KEY_SENDER_ID the id column that you are looking for?
Answer: c.getColumnIndexOrThrow(KEY_SENDER_ID); returns the index of the column KEY_SENDER_ID in your TABLE_PEERS.
c.getLong(c.getColumnIndexOrThrow(KEY_SENDER_ID)) returns the value at Index of the column KEY_SENDER_ID in TABLE_PEERS.
What you are doing wrong:
You should call cursor.moveToFirst before fetching any data from it.
Code Snippet:

    String selectQuery = "SELECT * FROM " + TABLE_PEERS + " WHERE " + KEY_NAME + "= '" + peer.name +"'";
    Cursor c = db.rawQuery(selectQuery, null);
    if (c != null) {
       if (c.getCount > 0) {
         c.moveToFirst();
         Log.d("count", c.getCount()+""); // display: count: 1 in LogCat
         long peer_id = c.getLong(c.getColumnIndexOrThrow(KEY_SENDER_ID));
       }
    cursor.close();
    }

Let me know if it helps
Answer: String selectQuery = "SELECT * FROM " + TABLE_PEERS + " WHERE " + KEY_NAME + "= '" + peer.name +"'";
        Cursor c = db.rawQuery(selectQuery, null);
        if (c.moveToFirst()) {
            long peer_id = c.getLong(c.getColumnIndexOrThrow(KEY_SENDER_ID));
            Log.d("peer_id", peer_id + "");
        }
        cursor.close();

You have to use at first moveToFirst() method.


Goodness of fit likelihood ratio test with zero values

Question: I have a vector of observed frequencies that have zero values in some cells and a vector of expected frequencies generated by a model. I would like to do a likelihood ratio test rather than a chi squared test  because I have different nested models and would like to use $2 \ln\cal{L}$ difference to evaluate the models.
My question is how to deal with the zero cells? Is it sensible to remove the contribution from the 0 cell like in the R-code below? Or should I combine cells or do a continuity correction?
Example:
observed <- c(142,34,18,15,12,136,6,7,2,3,2,1,1,0,2)
expected <- c(141.99,53.33,32.59,23.66,18.78,15.77,13.75,12.33,11.3,10.54,
               9.98,9.57,9.29,9.1,9.02)

2 * (sum(observed * log(observed/expected), na.rm=TRUE))

[1] 455.8816

Comment: Note $x\log{x}$ tends to zero as $x$ does.
Answer: There's no need to combine cells or try some continuity correction, you can compute the likelihood - and hence the statistic - quite readily.
$G = 2\sum_{i} {O_{i} \cdot \ln\left(\frac{O_i}{E_i}\right)}$
Since $\lim_{x\to 0}x \ln x=0\,$, each cell with a 0 count contributes $0 \log (0/E_i)=0$  to the sum in the formula for $G$.
So you can just skip the zero cells, or equivalently you can replace their contribution with 0.
See also Wikipedia here, where it says of this test:

the sum is taken over all non-empty cells.

Consequently (as long as the NAs correspond to the empty cells) the R code that just omits the NAs is correct.

On the other hand, you can very often compare nested models via chi-squared, since the chi-square will generally partition into components that allow for testing the change - you just get another chi-square test.


Filesystem block size confusion

Question: I know that block size is, generally speaking, the minimal operation unit of a filesystem, but I was confused by fio, the I/O performance benchmark tool, which has a bs parameter to set the "block size".
If block size is for a filesystem, why fio can set one for a benchmark? Are they the same "block size"?
If I find the performance is optimal with 1M "fio block size", since fio can do this, can I force all processes operating on this filesystem to use 1M block size to achieve best performance? What about remote filesystems mounted with fuse, can I set the block size at mount-time?
Answer: There are quite many details here, I'll try to summarize the main points here.
The filesystem block size is the minimum allocation unit that can be reserved at one time. So, if a filesystem has a block size of 4096, a file that is one byte in size, still takes 4096 bytes on the hard disk.
This is due to the fact that the filesystem has to know which part of the hard disk belongs to which file. If the block size was smaller, then the allocation table would be larger. If the block size was larger, then even more space would be wasted with small files.
There are also other strategies for allocating space to files, depending on the filesystem used. But this is the basic strategy that is most often used.
However, on the application level, the bs parameter is the block size of an individual write/read operation fio uses when performing the benchmark. Larger write / read operation sizes can provide better performance, because several filesystem level block writes can be combined.
You cannot force applications to use any specific block size. They write / read exactly the amount of data they want to at any time. The sizes of individual write / read operations vary from a few bytes up to megabytes, all depending on the application.
fio is an exception here, because it is a benchmark tool.
Remote filesystems operate on top of the remote server's filesystem, and therefore the actual filesystem on the remote server specifies the block size used on the hard disk.
The protocol used when accessing the remote server's filesystem also has some "block sizes", most often defined by TCP segment size, which is determined from MTU. MTU is most often 1500 bytes in the Internet. In some local environments MTU can be 9000 bytes. This needs support from all parts of the network (switches, routers and NICs) to work properly.

Filesystem block size confusion


Disable field date and checkbox

Question: I'm trying to disable input fields of type date and checkbox in hook_form_alter with above code:
<code>$key = 'field_name';

$form[$key]['widget'][0]['value']['#attributes']['disabled'] = true;
$form[$key]['widget']['#attributes']['disabled'] = true;
$form[$key]['widget'][0]['#attributes']['disabled'] = true;
$form[$key]['widget'][0]['target_id']['#attributes']['disabled'] = true;
$form[$key]['widget'][0]['#attributes']['disabled'] = true;
$form[$key]['#disabled'] = 'disabled';
$form[$key]['widget']['#attributes']['readonly'] = 'readonly';
</code>
Disabled all fields (type text or entity reference) but not work for checkbox and date fields.
Any ideas for solve this?
Answer: This is how to disable the field:
<code>$form[$key]['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
</code>

Disable field date and checkbox