What instruments can a four-year-old with left-side paralysis begin to learn/hope to ever learn?

Question: My four-year-old sister has tragically suffered left side paralysis from a brain injury. Because she's so young, her brain is remarkably plastic, and a lot of functionality has returned. She can walk, she can talk, and cognitively, she's fine. Her smile has even become more symmetrical.
We don't know to what degree her motor skills will return, but in her left hand/arm, progress is really slow. We know she will always have some left-side weakness, but just not how much.
I really want her to be musical. What fairly complex instruments will she be able to learn in the future, assuming she never fully recovers the use of her left arm/hand? Are there any simple instruments we can start her on now so she can have fun and experience music?
Also, as a bit of a fun tangent, are there any examples of musicians that became paralysed to some capacity and continued to play?
Comment: She is human; the instrument is a tool for humans to be expressive. People don't fit the instruments; it's the other way around. My answer is that she should play whatever she wants to play - whatever it is, there is a way to make it work. It would indeed be a sad thing to teach a 4-year old that she's limited by her disability.
Comment: No, that's not cruel at all; that's how the organ is traditionally played. However, it would be cruel to teach them that they're less-than because of it. It would be *my* jumping-off point: "The organ is traditionally played this way, so for you, we're going to have to figure something out". Problems are not barriers, they are opportunities for solutions. It's quite easy, with today's technology to find videos of successful, disabled musicians. This is a link to Evelyn Glennie, a remarkable percussionist who happens to be deaf: https://www.youtube.com/watch?v=IU3V6zNER4g
Comment: @jjmusicnotes Fair point. But just to play devil's advocate, if I were to lose both of my arms and legs in a car accident, and then decide that I really want to be a concert organist, would it be cruel to inform me that you need hands and feet to play the organ traditionally? (I can, of course, argue against this myself, I'm just developing your thesis.)
Comment: @jjmusicmotes Thank you. I think all of that meets the criteria of a great answer. You should post it as such.
Comment: I've re-posted my comment as an answer, per your suggestion. I've also edited it slightly so that it reads more like an answer.
Answer: All of the above.  And if none work out, there's always the voice.  I wouldn't say that a great singer is less musical, and less musically valuable, than any instrumentalist.
Comment: Great work here! So easy to overlook the voice sometimes.
Answer: TRDR: Singing, from personal experience.
Since birth, my right side has been paralyzed, though not as badly as your sister. I have had singing lessons for years, and I still find them very enjoyable. I have never felt like I was hindered at singing.
Another reason to choose singing is that the technical part is easy, especially at the beginning. A beginning singer sings a melody badly, but a beginning piano player plays one tone... and then another. Every child learns the very basics of singing, when they learn to talk, but the basics of an instrument need to be learned from scratch.
Also, she will probably get a lot of physical therapy throughout her childhood. Physical therapy can be fun, but also very frustrating. During therapy, I frequently thought things like: "Why do I need to practice this, I will never heal anyway", or "Why can't I just use my good arm" Knowing that your physical skills will never be that high isn't motivating, and singing might be easier to practice.
One final bit of advice if you want to get her a musical teacher, get her a teacher who is concerned with fun and advancing at you own pace, not one who cares much about results. Her whole childhood, she will see that she is not as far as other children, that she needs to work harder for a worse result. She will have to learn to set her own goals, and to not be overly concerned about others advancing faster. A teacher who doesn't help with this will be terrible for her, and might kill her interest in music and her self-confidence.
Comment: In a nutshell, she needs to understand that the only competition is against herself. It's not competing against others, only bettering herself. If only we could all take on that mantle...
Comment: This is such an incredibly valuable answer. Thank you for your unique insight into the mind of my sister!
Answer: In the long run, brass instruments require only one hand, for the most part. There are also several manufacturers who make one-handed versions of woodwind instruments, though these are quite expensive. But it's very hard for a four-year-old to start on these instruments.
I would recommend piano. It has been shown to be an effective means of physical therapy for stroke survivors. As a personal anecdote, there was a kid who had the lesson slot right before mine for years (so I heard him practicing quite a lot), and I actually didn't know at first that he had a severe impairment in his left hand.
Comment: I like the piano idea, although repertoire will be limited if you're restricted to one hand. You need both hands to play most pieces of classical music (i.e. what a lot of piano lessons, including the ones I took from 3 piano teachers, solely provide), even easy ones such as Clementi sonatas and Bach minuets. However, you can make decent arrangements of a lot of non-classical songs for one hand only.
Comment: @Dekkadeci I guess there are ways to simplify piano pieces as well to enable her playing the classics
Answer: Just speculative idea....
Music instruments are slowly becoming electronic, and  some sound very good.   And there are numerous newer type of electronic instruments that are perfectly suitable for and designed for one hand play.   See for example Roli blocks.

Answer: I'm not sure about one-sided paralysis specifically, but there are a number of famous musicians who had disabilities which involved partial or total loss of a hand (or two). Those that spring to mind are:

Paul Wittgenstein lost his right arm in the First World War and continued to perform piano concerts, commissioning works for left-handed piano from major composers of the day.
Django Reinhardt was partially paralyzed (and badly burned) in a caravan fire, and permanently lost the use of two fingers. He was a pretty mean guitarist.
Felix Klieser has no hands and plays French Horn wonderfully.
Tony Iommi of Black Sabbath lost the fingertips of his left hand in an industrial accident and used home-made prosthetic fingertips to play bass guitar.
Rick Allen, drummer for Def Leppard, lost an arm in a car accident in 1985 at the height of the band's fame, and continues to play with them to this day.

Some instruments (cornet, bugle, trumpet) can be used one-handed as-is, many others with modification. Another Way To Play lists different instrument adaptaions that are available. A good place to start might be the recorder. There are one-handed models available from several manufacturers. They're not cheap though!
For advice on your sister's specific problems, ask her doctors. Medical professionals who know her will be able to give much better advice than some random person on the internet! It might be worth contacting a music therapist, you may even be able to find someone with experience of similar cases. Depending on her level of abilility with the weaker hand, it may be be that going for a one-handed instrument straight off could be counter-productive, in that it might be possible to find an instrument that would help to strengthen the weaker hand.
So you should be able to find an instrument she can physically play even if she doesn't recover much function in the left hand, but as with any child it's important that it's her that wants to play it and not you. If you sing with her, and play lots of music for/with her then she will develop her musicality and be able to make up her own mind about which instrument (if any) she wants to learn. Four is pretty young to be learning an instrument anyway: for now toy instruments like xylophones, drums, slide whistles and so on can get her started with musical play just like any other four year-old.
Comment: PS and there's always the [nose flute](https://www.youtube.com/watch?v=8FV6sFnsITc)
Comment: That's a very good point about strengthening the weaker hand. And, of course, my top priority is for her to have control over what she does. For now, the glockenspiel or drums or whatever are fully acceptable and may even help with her recovery! (She had in the past expressed interest in playing the guitar, so she more than likely would have started with that, or uke, or whatever interested her. It's just good to know we have options!)
Comment: Wasn't Django's accident a caravan fire?
Comment: @Tim oops - you're quite right. Will edit.
Answer: So far I've thought of:

Piano/keyboards/synth (perhaps with foot pedals added)
harmonica
percussion
electric guitar with a sustainiac like device instead of strumming
potentially any brass instrument with a harness or something to hold it
Comment: She had in the past expressed interest in guitar. That is an interesting idea indeed.
Comment: Chromatic harmonicas have the button *on * the right, so she'd play it the normal way, since her left side is paralysed.   Theremin could be another.
Comment: @GeneralNuisance - guitar can be played with it resting on her lap, tapping and pulling off the strings with r.h. fingers. Several players use one like this. Obviously it'd have to have the neck facing to the right - maybe strung left-handed?
Comment: @Tim Good point. It's been way too long since I played harmonica I guess. Edited.
Answer: I would have added this as a comment as it doesn't fully answer the question but here is an amazing example of what you can do with Bare Conductive paint, a capacitive touch board, and a little bit of programming. I assume that, as you mentioned she was going to be a cellist, she was going to be a classical musician. In that case, you could paint on (modify) an existing instrument and write a program that modifies the notes played so it would better suit her needs.
Answer: French horn could be a suitable instrument, given that it doesn't actually require pressing the keys to make the notes.
Comment: Most French horns found in orchestras nowadays have valves, playable using r.h., although the l.h. is used to provide better tuning for certain notes. Perhaps  bugle is better?
Comment: Quick correction: French Horns have the valves played by the **left** hand, with the right hand stuffed up the bell for intonation and sound effect purposes. Pretty much all the other valved brass instruments have the valves on the right hand, with the left either just holding the instrument or operating a tuning trigger. (Some low brass instruments have extra valves operated by the left hand.)
Answer: She is human; the instrument is a tool for humans to be expressive. People don't fit the instruments; it's the other way around. My answer is that she should play whatever she wants to play - whatever it is, there is a way to make it work. It would indeed be a sad thing to teach a 4-year old that she's limited by her disability.
For example, organs are traditionally played with both arms and feet. Telling them that you traditionally need arms and feet to play it isn't, in of itself a sad, cruel thing. However, it would be cruel to teach them that they're less-than a person because of it, that they might as well not even try.
A different approach would be to use it as a jumping-off point: "The organ is traditionally played this way, so for you, we're going to have to figure something out". Problems are not barriers, they are opportunities for solutions.
It's quite easy, with today's technology to find videos of successful, disabled musicians. This is a link to a talk by Evelyn Glennie, a remarkable percussionist who also happens to be deaf.
Answer: A computer can be a musical instrument and there are so many options available for music controllers that you can in effect build your own custom musical instrument.
As well as basic music keyboards and percussion pads there are foot operated controllers, devices that respond to breath pressure, body posture,  head movements etc.
Maybe you could team up with someone, possibly a student on a technology course, and work together on a project develop musical control concepts for disabled people. There are probably a lot of existing assistive technologies that could be adapted for musical applications.
One thing that comes to mind is to get involved in the maker movement and involve your local HackSpace. I'm sure there will be someone in the community who would love to get involved in such a project.
Answer: I like the piano idea offered earlier. Piano music comes in many levels of complexity regarding what the left hand has to do.
A left-handed guitar would also offer a lot of options for how to use the left hand, ranging from strumming to complex fingering.
You can also make notes with the right hand on a left-handed guitar by hammering or pulling off.
A serious problem with both of these instruments, however, is they are generally built for adult-sized hands, not four-year-old hands.
That may be more of a limiting factor at this point than any partial paralysis is.
But at the age of four, I'd say the critical thing is to play music.
My recollection from being taught via the Orff method at a young age (thought not nearly as young as your sister) was that it involved a lot of percussion instruments (drums, wood blocks, xylophones) that can be played with very small hands.
And if your sister's left hand is not yet able to hold a stick and hit the bars of a xylophone where she wants to when she wants to, she can still play a tune with her right hand and can even hold two sticks in that hand to play some harmonies.
Answer: I would suggest Trumpet, as the instrument is small enough/light enough to be held in one hand, and the valves and hand positioning favors the right hand. Of course, this isn't the only option, but immediately that's what comes up in thoughts.
EDIT: Recently the idea of a "left-handed" cello came to mind. It sounds counter-intuitive, but a left-handed cello requires the right hand to do fingering (the bridge, strings, and sound post reverse sides). If the left side is unable to grip and draw a bow, a bow-grip brace can be made for the right foot, and the cello can be bowed with the right foot.
Comment: The question was what instrument would she be able to continue playing assuming a continued left-side paralysis. If for the first few learning years she can be assisted in holding the trumpet up, it's not implausible
Comment: Not implausible, true. Maybe small trumpets could be used. I wouldn't really fancy anyone holding my trumpet while I played, and maybe her fingers are too small at the moment to press valves, not to mention embouchures with a standard mouthpiece. just some thoughts, rather than criticisms.
Comment: Hardly small/light enough for a four-year-old!
Comment: It's been said before, but the player doesn't fit the instrument, the instrument fits the player ;) I'm sure a fractional-size instrument is to be found somewhere. Strings certainly have them, but that's beside the point given the construction is different.
Answer: I agree with some of the previous posts, but here's my list anyway:
First, the instruments she can fully play:
1) Chromatic Harmonica
2) Blues Harmonica
3) Trumpet
4) French Horn (palm of right hand over the rotors, nothing inside the bell)
5) Trombone, Euphonium, Tuba
6) Pan Flutes
7) Auto Harp -probably-
8) Theremin -maybe-
9) Hurdy-Gurdy (reversing hands) if she gets to operate the crank someday
Now, instruments that she can also play to some decent extent:
1) Piano and Synths -melody leads and so-
2) Harp
3) Hammered Dulcimer
4) Marimba, Vibraphone, Xylophone, Glockenspiel, etc.
5) Guitar and Bass (Stringed for left-Handed and using Hammer_On/Pull_Off/Tap techniques)
5) Most Percussion
Hope this helps!
Answer: Trumpet.
There was a  UNISA concert by a man who had only one arm, if you only have the use of one side of your body it could maybe work. (Im no trumpet player though)


Language cookie module not working in Safari?

Question: I use language_cookie module to safe the users preferred language with a cookie. E.g. The default site language is English. But i am from Holland so i want always the Dutch version of the site: http://landberg.at/nl. But the cookie is not working on Safari MAC?
In Configuration » Regional and language » Languages i have:

URL (enabled)
Cookie (enabled)
User (enabled)

How can i make it work also for Safari?
(i use this module instead of IP redirect because with IP redirect you can not switch the language after you are redirected..? So the only solution in my opinion is to do it with a cookie. Or does somebody has another idea about this?).
Answer: I think you should further verify/tune your configuration at Configuration -> Languages -> detection and selection: the order you mentioned (= 'URL, Cookie, User') seems a bit strange to me. I.e. it'd be interesting to see what results you get by specifying "Cookie" BEFORE "URL" in your case.
Because with your current order, "Cookie" will only be used to select your preferred language if from the "URL" it's impossible to decide about which language should be shown. Though "User" is probably fine to leave it as the last one.


Unable to find package 'Swashbuckle.AspNetCore.SwaggerUI.6.2.3'

Question: I'm using swagger, but I have this problem according to the documentation. The nuget package has not been downloaded successfully. What should I do?
This is the error message:

Severity Code Description Project File Line Suppression State Error
The feed'nuget.org [https://api.nuget.org/v3/index.json]' lists
package'Swashbuckle.AspNetCore.SwaggerUI.6.2.3' but multiple attempts
to download the nupkg have failed. The feed is either invalid or
required packages were removed while the current operation was in
progress. Verify the package exists on the feed and try again. Unable
to find package'Swashbuckle.AspNetCore.SwaggerUI.6.2.3'.

Update:
I try to use the command:Install-Package Swashbuckle.AspNetCore -Version 6.2.3
Error:
Comment: Have you installed .net 6 or visual studio 2022? You created a asp.net core 3.1 project? Because you didn't mention your code environment, just provided the error message, so I thought about the environment first, as the command is installing version 6.2.3. By the way, I test the command in my asp.net core 3.1 mvc project with vs2019, but I already installed 2022 version. And the command worked.
Comment: Did you try to execute the `Install-Package Swashbuckle.AspNetCore -Version 6.2.3` command in the Package Manager Console?
Answer: Maybe a problem on your internet connection? Package seems exist (https://www.nuget.org/packages/Swashbuckle.AspNetCore.SwaggerUI/6.2.3).
Comment: I can download normally now, it seems to be caused by the network, thank you!


Use non-static variable with chrome.storage.local.set / get

Question: Is it possible to use a non static variable with chrome.storage.local.get. Right now, I can not recover anything.
here's what I do:
myVar = 'test';
var obj = {};
obj[myVar] = Output;
storage.set(obj);

and to recover, I do:
var key = example + 'js';
storage.get(key, function (result) {
console.log (result.key)
});

Thank you in advance for your help!
Comment: I don't understand your problem here.
Comment: I save a variable that I want to recover any time. But the name of my variable carries the project name in which the user work. As can be several projects, I want to retrieve information related to the project. And I do not know in advance the project name that the user will give his project. So when I get done, I get the name of the project via a button and that's how I chrome.storage.local call to retrieve the information.

ex: there is a projected A, B, C. I want to be filled, when click the B, retrieve information that I had saved earlier. But I can not.

Is that clearer?
Comment: No, not much clearer. Do you want to retrieve the list of keys / all of the data in the storage not knowing the key?
Comment: This is exactly the idea. Recover the key that I do not know the name. If I could retrieve them, would be great. Is this possible?

Thank you very much in advance! I'm sorry, my English is not so good :)
Answer: You can pass null as the query to retrieve the whole storage:
chrome.storage.local.get(null, function(data) {
  // data contains everything in storage
});

Comment: For more practical advice: if you're going to store several keys with names you don't know, store along an object containing all those keys. It will be easier.
Comment: Or use a query-able storage like web sql or indexed db. Will have much better performance if you are storing a lot of pairs (say over 1000)
Comment: and to retrieve the values I console.log (data), right?
Comment: Define "retrieve". You can use them as you wish.
Comment: See the data storage... But I think I understood the idea :) Thanks so much for all


JavaScript Table content Add and Delete

Question: I'm working on a table content with JS. What I can update with a button or clear data from the table.

Phone Number: phoneNumber.value
Bay Number: bayNumber.Value (it's not added yet, but will work same)

The First column in the table is always the same (Phone Number and Bay Number), but the second column should change what is in the input after I press the save button (it works fine) Just if I press the delete, it deletes the all table.
I think the problem is how I created the table, but don't know how should I fix it.
//FORM//
var form = document.createElement('div');
form.style.width = "500px";
form.style.height = "500px";
form.style.margin = "auto";
form.style.textAlign = "center";
form.style.paddingTop = "20px";
form.style.background = "grey";
form.classList.add("printVisible");
document.body.appendChild(form);

var phoneNumber = document.createElement("INPUT");
phoneNumber.setAttribute("type", "text");
phoneNumber.value = "07";
phoneNumber.classList.add("hiddenPrint");
form.appendChild(phoneNumber);

var bayNumber = document.createElement("INPUT");
bayNumber.setAttribute("type", "text");
bayNumber.value = "Bay Number";
bayNumber.classList.add("hiddenPrint");
form.appendChild(bayNumber);

var buttonSave = document.createElement("BUTTON");
buttonSave.addEventListener("click", saveDatas);
var buttonSaveT = document.createTextNode("Save");
buttonSave.appendChild(buttonSaveT);
form.appendChild(buttonSave);

var buttonClear = document.createElement("BUTTON");
buttonClear.addEventListener("click", clearDatas);
var buttonClearT = document.createTextNode("Clear");
buttonClear.appendChild(buttonClearT);
form.appendChild(buttonClear);

var phoneNumberT = document.createElement("P");
form.appendChild(phoneNumberT);
var bayNumberT = document.createElement("P");
form.appendChild(bayNumberT);

//SAVE BUTTON//

function saveDatas() {
   tablePhoneNumberTx.textContent = phoneNumber.value;
   bayNumberT.textContent = bayNumber.value;
}

//CLEAR BUTTON//

function clearDatas() {
   tablePhoneNumberTx.textContent = "";
   bayNumberT.textContent = "";
}

//TABLE//

    let body = document.body;
    let tbl = document.createElement("table");
    tbl.style.textAlign = "center";
    tbl.style.margin = "auto";

    let tablePhoneNumberTx = tbl.insertRow();
    let tablePhoneNumber = tablePhoneNumberTx.insertCell();
    tablePhoneNumber.appendChild(document.createTextNode(`Phone Number`));
    tablePhoneNumberTx.appendChild(document.createTextNode(phoneNumber.value));
    tablePhoneNumber.style.border = "1px solid black";
    tablePhoneNumber.style.width = "250px";
    tablePhoneNumberTx.style.border = "1px solid black";
    tablePhoneNumberTx.style.background = "250px";

    form.appendChild(tbl);

P.S. Its a TamperMonkey Script so, must be everything in JS
Comment: even if everything must be written only in javascript, it does not prohibit you to factorize your code.
Comment: I'm not programmer, just doing for fun. Could you explain me what wrong with this code? :)
Comment: too much code here, like some sort of forest hiding your problem. read the recommendations of this site to properly ask a question, and for which your interlocutors will want to answer without having to clear everything. There are nearly 3 million JS questions here, about 1 every 3 minutes
Answer: some sort of code factorization you could use, but since you wrote "only JS" I wonder why you are referencing CSS classes?

const newEl = ( tag, styling={}, attrbs={} ) =>
  {
  let elm = document.createElement(tag)
  for(let key in styling) elm.style[key]  = styling[key]
  for(let key in attrbs)  elm[key]        = attrbs[key]
  return elm
  };

let myDiv = document.body
  .appendChild
    ( newEl('div'
      , {width:'200px', margin:'auto'}
      , {className:'toto', textContent:'hello world'}
    ) );

console.log( myDiv )
Comment: @DaniMisi this is just a `named function` in [Arrow function expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
Comment: Because this is how I can do styling. The first part of your code I don't really unterstand

JavaScript Table content Add and Delete


How does the concept of functional harmony help me pick the next chord while composing?

Question: I'm trying to understand the concept of functional harmony as it pertains to composing chord progressions, in order to compose my own progressions.
I've read a few articles and watched some videos, I think I get the basic idea that some chord classes lead to and from other chord classes (T, P, D).  This image sums up what I understand so far quite succinctly.  I got it from here.
Fundamentally though, I don't understand whether this concept is saying "Do this", or "Have you noticed how music tends to do this?"
Because if the latter, then the concept of functional harmony is a great ice breaker when trying to pick someone up at a bar, obviously, but not very useful for actually writing music.
If it's the former, and it's narrowing my list of "what should the next chord be" candidates while writing, that's great, but then I have to wonder why almost none of my favorite progressions fall in line with that graphic, as I understand it.
For instance, Creep, by Radiohead: G-B-C-Cm.  The article tells me that I can move right as far as I like, so no problem going from the tonic to the III.  Then no problem going from III to IV, we're still moving right.  But then... we just go from IV to iv?  Huh?  I thought we were in G Major?
What about Jimi Hendrix's Little Wing?  Em-G-Am-Em-Bm-Am-G-F(wtf?)-C-D.  Why can we move from dominant to pre-dominant in the first place?  That basically means we can move from any of our three chord types to any of the others, except for pre-dominant to tonic.  But we do that in this progression anyway when we go from Am to Em.  And then we go Am to G, and it doesn't say we can do that anywhere.  Then we go to F?  The worst possible chord we could pick, and it turns out to be the best, most sweetly harmonious sounding part of the progression?  It's not a passing chord, he lays on the F chord for a bar, and plays F major pentatonic licks over it.
How does chord function explain any of that?
More importantly to me, how would thinking about chord function have helped me write those chord progressions?
Answer: Trying to answer simply. All music theory tries to explain what has happened - to be helpful to future musicians. Like most laws, when a certain thing happens time and time again, and can be proved, its theory changes to a law. (Boyles law, Charles law et al). Music has no such laws, as it's still in (and probably will be for ever!) in the theory stage.
The movement of one harmony to another to another has been studied, and there are certain patterns that crop up time and time again. If it ain't broke...But that never means that other, possibly more interesting sequences, aren't going to work. In fact, they're usually the ones that stand out, as in your examples.
Working formulaically produces music that's not bad, but relying on functional harmony 'rules' means you're treading in furrows that have already been ploughed deeply. Ruts if you like. It's often been said that one cannot break the rules properly until one knows the rules properly, and that's what's important here. Know the 'rules' of functional harmony, then go beyond. The other old adage is that if it sounds good, it probably is. Doesn't come truer than that. So, in composing, functional harmony is a good start point - and will be used a lot - but there's no reason to use it as a crutch. Break out from the mould, after all, that's what a lot of the more notable composers have done.
Answer:

that basically means we can move from any of our three chord types to any of the others.

Yes, you can combine any chords together. Jimmy Hendrix and Palestrina (or any other Rock - or Renaissance musicians e.g. didn't compose typical functional music. You can make statistics and discover yourself that functional harmony has been developed through hundreds of years while there was always other chord or non chord music without functional harmony.
2.

Fundamentally though, I don't understand whether this concept is
saying "Do this", or "Have you noticed how music tends to do this?"

There are rules that the leading tones should be resolved half step wise up (or down):
the tritonus BF in a V7 chord (GBDF) "wants to" (or should - but must not) resolved B up to C, F down to E). If you go through the circle of fifths you will always find this voicing! (Look up the voice leading of the chord progression e.g. C->E7-A7-D7-G7-C ... you will find that the tritone of the 3rd and the b7 leading down in semi tones to the 7th and 3rd of the next chord. This is one important fact of the functional harmony (the 5th fall sequence).
3.

the concept of functional harmony is a great ice breaker when trying to pick someone up at a bar, obviously, but not very useful for actually writing music.

Now there are other rules like the substitution by relative chords: They contain common tones like e.g. iii EGB is related with the dominant GBD (GB) and the tonic CEG (EG). In a club you are looking for an icebreaker of commonness and relations as any subject like "coming from", "being fan of", "political party" and other connections. In music we have the parallel chords, the relative chords, the mediant chords, which are related and can be easily connected. Understanding these terms and functions you can explain almost any progression of yours above. So to understand the concept of functional harmony you have to look up all these 3 chord relations and the tritonus substitution.
And if there is no connection or explanation remind section 1.
Answer: In both the examples you shared, the key of using those chords (Cm in the key of G Major and F in the key of G Major) is modal exchange.
The chords don't belong to G Major (Ionian mode) but they both belong to G Minor (Aeolian mode). So it results as a short modulation to G minor, spicing up the progression.
Another nice chord you may find in the context of a G coming from the same scale is Eb major, like in the song Gravity by John Mayer.
Answer: The flow chart you linked looks like a copy of...

...which is from Kostka/Payne, Tonal Harmony. But with some German theory sprinkled in. Combining the American and German theory might get a little confusing.
The basic idea of American functional harmony is: pre-dominant (ii, IV, etc.) moves to dominant (V, viio) moves to tonic (I). You could also generalize it as root movements by descending fifth with two caveats: I IV V I is a harmonic sequence of two descending fifths motions [I IV][V I] and V, vii0, and viio7 can all be viewed as portions of a larger dominant chord.

...I don't understand whether this concept is saying "Do this", or "Have you noticed how music tends to do this?"

I think most theorists will say it is a matter of "have you noticed...", and it's specifically about European music from around 1650-1850.

...I have to wonder why almost none of my favorite progressions fall in line with that graphic

It's a generalization for European music, 1650-1850-ish. It's origin is in the Christian Church and aristocratic court music. It's often called the Common Practice period. At that time composition was fairly strict, but that changed over time. Elements of the style crossed borders too. You can follow a line from the European hymn to America to the spiritual to the blues to rock. It's a long line. Some elements of the old European strict style persisted, other were abandoned.

...Radiohead ...Jimi Hendrix ...Why can we move from dominant to pre-dominant in the first place?

The IV, I, and V chords are the primary diatonic triads. Those chords used in any order will give a clear sense of tonality. But, if we are strict about functional harmony, V IV is backwards, a retrogression. Rock/pop music isn't strictly functional. It's as simple as that. You can move from dominant to pre-dominant, because the music isn't strictly function, and that doesn't necessarily undermine a clear sense of tonality.

...But then... we just go from IV to iv? Huh? I thought we were in G Major?

That's called a borrowed chord or mode mixture.
A single flow chart or cheatsheet won't cover everything about tonal/functional harmony. If you try to rely on just that chart, you will keep having questions. Get a textbook like Kostka or Walter Piston. Bach's Chorales are probably the most comprehensive and densely packed resource to see it all in action.

...How does the concept of functional harmony help me pick the next chord while composing?

It gives you a basic idea of norms. Essentially the charts tell you chord roots commonly move by descending fifths and also by descending thirds. That certainly narrows the scope of choices. But, both the Kostka chart and the one you linked indicate the I chord can go to any other chord. That's not much of a guide.
I think the problem with both charts is they don't convey the importance of voice leading and cadences in Common Practice. Charts like this certainly aren't how musicians learned harmony at that time. They are not wrong, but in terms of making choices to compose a lot of information is missing.


Insert piece of .doc .docx file to another by using the Apache POI HWPF or XWPF

Question: Can somebody help me to integrate some MS Word document to another.
I can open, edit and save, but only with one MS Word document.
My simple code only creates, edits and saves .docx:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

public class SimpleDocument {

public  void SimpleDocument() throws Exception {
    XWPFDocument doc = new XWPFDocument();

    XWPFParagraph p1 = doc.createParagraph();
    p1.setAlignment(ParagraphAlignment.CENTER);
    p1.setAlignment(ParagraphAlignment.LEFT);//setVerticalAlignment(TextAlignment.TOP);

    XWPFRun r1 = p1.createRun();
    r1.setBold(true);
    r1.setText("The quick brown fox");
    r1.setFontFamily("Courier");
    r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);

    XWPFParagraph p2 = doc.createParagraph();
    p2.setAlignment(ParagraphAlignment.RIGHT);

    XWPFRun r2 = p2.createRun();
    r2.setText("jumped over the lazy dog");

    FileOutputStream out = new FileOutputStream("C:/simple.docx");
    doc.write(out);
    out.close();

}
}

How to combine two pieces of formatted text (RANGE, PARAGRAPH) ?
Comment: Are you saying you want to take text from one document and place it into another?
Comment: I want to take text from two documents and place it into one. I dont know how to combine formatted text in code.
Comment: What sort of 'formatting' are you on about?  Is it just plain text from two different documents or is their something special about it?
Comment: Formatting, like: text color, text font, text size, alignment, tables, headers, footers, images, etc.
Comment: I am trying to merge two pieces of formatted text without making it parsing
Comment: The only way I know of doing that would be to get the text from the documents and reformat it upon entering it into the new one,  I am unaware of any way of keeping the formatting when extracting text.  The other option is to pick the document with the least formatting,  extract that and reformat it into the other doc, then save that as a new one.
Comment: Have to take the input text without formatting(extract the text ), and continue to work with it.thanks for joining
Answer: try the following code:
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;

public class test {
    public static void main(String[] args) throws Exception {
        // POI apparently can't create a document from scratch,
        // so we need an existing empty dummy document
        HWPFDocument doc = new HWPFDocument(new FileInputStream("D:\\src.doc"));
        Range range = doc.getRange();
        CharacterRun run = range
                .insertAfter("Text After copied file contents!");
        run.setBold(true);
        OutputStream out = new FileOutputStream("D:\\result.doc");
        doc.write(out);
        out.flush();
        out.close();

    }
}


Distributive law over submodules

Question: I'm currently working my way through Matsumura's "Commutative Ring Theory", but I'm stuck on what I feel should be an easy proof of the following theorem:

Theorem Let $R$ be a commutative ring with identity, with $\mathbb{M}$ an $R$-module and $N\subseteq\mathbb{M}$. Then for all $r,r'\in R$, $$rN-r'N=(r-r')N\iff N\ \text{is a submodule of}\ \mathbb{M}.$$

This is not directly in the book, but I've reduced an implicit theorem in there to this simpler one. (he claims that $N:N'$ is an ideal iff $N$ and $N'$ are submodules on p.6; this is part of showing that claim to be valid).
It is clear that $(r-r')N\subseteq rN-r'N$ regardless of the structure of $N$, since $$x\in(r-r')N\implies\exists n\in N\big[x=(r-r')n\big]$$ $$\therefore x=(r-r')n=rn-r'n\in rN-r'N.$$
The reverse inclusion is not so clear to me, since $$y\in rN-r'N\implies\exists n,n'\in N\big[y=rn-r'n'\big],$$ but I cannot see how to decompose $rn-r'n'$ into something with a coefficient of $r-r'$. (usually adding in an appropriate preimage of $0$ under multiplication and addition works, but it doesn't seem to here)
Comment: Where did you find this claim? I looked at p. 6 in my edition of the book and couldn't find this claim, even in an implicit form.
Answer: What does $N_1-N_2$ even mean for submodules? The naive thing would be that it means $\{a−b∣a∈N_1,b∈N_2\}$. But if that's the case here, this is obviously wrong, say, in the case $r=r′$. I think your "implicit theorem" might be a tad off...
Suppose $x,y\in (N:N')$.
Then $xN'\subseteq N$ and $yN'\subseteq N$.
If $N$ is an additive group, $-xN'\subseteq -N=N$. So $-x\in (N:N')$
Also if $N$ is an additive group,  $(x+y)N'\subseteq xN'+yN'\subseteq N$. So $x+y\in (N:N')$
At this point we've established that $(N:N')$ is an additive subgroup of $R$.
If $N'$ is a submodule of $N$, then $xrN'=xN'r\subseteq xN'\subseteq N$. So $xr\in (N:N')$.
I don't see why you'd need the lemma you suggested (even if we defined subtraction between submodules.)
Comment: The theorem in the book is indeed independent of the lemma suggested, thank you. Subtraction is defined as you suggest, but apparently the lemma is false -- I am only a month into commutative algebra, so I thought perhaps there was a trick I was missing.

Distributive law over submodules


Setter concatenates value twice separated by comma

Question: I'm trying to pass a value ferm a jsp back to the bean. I create an action url with several parameters and they are all set correctly but the company name is set to "companyName, companyName" instead of just "companyName"
This is my url
var url="<liferay-portlet:actionURL><liferay-portlet:param name='struts.portlet.action' value='/reg/submitStep1'/><liferay-portlet:param name='isSimplified' value='true'/></liferay-portlet:actionURL>&customerNo=" + custNo + "&companyName=" + companyName;
I get the company name variable from the text field using jquery. The text input's id is companyName
var companyName = $('#companyName').val();

When I print it out using console.log(companyName); the value is fine, not concatenated twice.
In the setter, however, the value of the String is set to "companyName, companyName". All otherparameters (isSimplified, customerNo) are fine. Any idea why this is happening?
Comment: It seems you are passing companyName as url parameter and form parameter as well.
Comment: Is it set to litteraly companyName (`companyName ,companyName`) or to the value? (e.g. `Apple, Apple`)?
Comment: It's set to the the value
Comment: May we see the whole class then (the parts, that modify your fields)?
Comment: `public void setCompanyName(String companyName) {
  this.companyName = companyName;
 }`
It's just a simple setter, the value of the fields is not modified
Comment: @Pankaj Kathiriya you are right. Add your comment as an answer and I'll accept it
Answer: You are passing companyName as url parameter and form parameter as well, hence you are getting both parameters on server side.
Keep only one parameter either as url parameter or as form parameter.
Answer: I am migrating my health domain application from struts 1.x to struts 2 and its a very big and mature application.
so finally i created below working code to overcome concatenates value twice separated by comma in case if duplicate parameter is passed.
    I created below generic method in my Util class to overcome
    this issue for all models thoughout my whole application,
    Call this method from your Action class validate method
    Note : it will give priorty to url parameter rather than form parameter, which was my requirement.
 Here is my  customized method:
public static void refineModel(HttpServletRequest request , Object modelObject) {
                           Enumeration enumeration = request.getParameterNames();
                           while (enumeration.hasMoreElements()) {
                               String parameterName = (String) enumeration.nextElement();
                               String parameterValue = request.getParameter(parameterName);
                               try {
                                   if (modelObject.getClass().getDeclaredField(parameterName) != null &&
                String.class.isAssignableFrom(modelObject.getClass().getDeclaredField(parameterName).getType())) {
                                           Field field = modelObject.getClass().getDeclaredField(parameterName);
                                           field.setAccessible(true); // to access private variables also
                                           field.set(modelObject, parameterValue );
                                   }
                               } catch (Exception e) {
                                   //not required
                               }
                           }
                       }

Answer: To overcome from this problem , finally i created interceptor and called it just after the model interceptor in stack
public String intercept(ActionInvocation invocation) throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        ValueStack stack = invocation.getStack();
        StringBuffer sb = new StringBuffer();
        Iterator<Object> iterator = stack.getRoot().iterator();
        try {
            while (iterator.hasNext()) {
                Object actionObject = iterator.next();
                try {
                    if (ActionSupport.class.isAssignableFrom(actionObject.getClass())) {
                        if (invocation.getAction().getClass().getMethod("getModel", null) != null) {
                            Method modelMethod = invocation.getAction().getClass().getMethod("getModel", null);
                            Object modelObject = modelMethod.invoke(actionObject, null);
                            sb.append("\n*********RefineModelInterceptor**************");
                            sb.append("\n********** " + modelObject.getClass().getName());

                            Enumeration enumeration = request.getParameterNames();
                            while (enumeration.hasMoreElements()) {
                                String parameterName = (String) enumeration.nextElement();
                                String parameterValue = request.getParameter(parameterName);
                                try {
                                    if (parameterName.matches("^(.*)\\[\\'(.*)\\'\\]$")) {
                                        String mapName = parameterName.substring(0, parameterName.indexOf("["));
                                        String mapIndex = parameterName.substring((parameterName.indexOf("'") + 1), parameterName.lastIndexOf("'"));

                                        if (modelObject.getClass().getDeclaredField(mapName) != null) {
                                            Field field = modelObject.getClass().getDeclaredField(mapName);
                                            field.setAccessible(true); // to access private variables also
                                            if (HashMap.class.isAssignableFrom(modelObject.getClass().getDeclaredField(mapName).getType())) {
                                                HashMap<String, String> tempHashMap = (HashMap) field.get(modelObject);
                                                String hashMapValue = tempHashMap.get(mapIndex);
                                                sb.append("\n"+parameterName+" **earlier** " + hashMapValue);
                                                sb.append("\n"+parameterName+" ****now**** " + parameterValue);
                                                tempHashMap.put(mapIndex, parameterValue);
                                                field.set(modelObject, tempHashMap);
                                            } else if (TreeMap.class.isAssignableFrom(modelObject.getClass().getDeclaredField(mapName).getType())) {
                                                TreeMap<String, String> tempHashMap = (TreeMap) field.get(modelObject);
                                                String treeMapValue = tempHashMap.get(mapIndex);
                                                sb.append("\n"+parameterName+" **earlier** " + treeMapValue);
                                                sb.append("\n"+parameterName+" ****now**** " + parameterValue);
                                                tempHashMap.put(mapIndex, parameterValue);
                                                field.set(modelObject, tempHashMap);
                                            }

                                        }
                                    } else if (modelObject.getClass().getDeclaredField(parameterName) != null && String.class.isAssignableFrom(modelObject.getClass().getDeclaredField(parameterName).getType())) {
                                        Field field = modelObject.getClass().getDeclaredField(parameterName);
                                        field.setAccessible(true); // to access private variables also
                                        sb.append("\n"+parameterName+" **earlier** " + field.get(modelObject));

                                        boolean notFoundSetterMethod=true;
                                        /* below code is to invoke the setter method so that if any functionality return in setter method could be sustained
                                            if failed in finding setter method than directly set value on the field
                                        */
                                        try {
                                               Method method = modelObject.getClass().getMethod("set" + org.apache.commons.lang3.StringUtils.capitalize(field.getName()), String.class);
                                               notFoundSetterMethod=false;
                                               method.invoke(modelObject, parameterValue);
                                               sb.append("\n"+parameterName+" ****now**** " + field.get(modelObject));
                                                 } catch (Exception ex) {
                                                     notFoundSetterMethod=true;
                                                    //not required
                                                 }
                                        if(notFoundSetterMethod){
                                            field.set(modelObject, parameterValue);
                                            sb.append("\n"+parameterName+" ****now**** " + field.get(modelObject));
                                        }
                                    }
                                } catch (Exception e) {
                                    //not required
                                }

                            }
                        }
                        //break; .. should we really break since got the action object ?
                    }
                } catch (Exception e) {
                    //not required
                }
            }
        } catch (Exception e) {
            //not required
        }
        sb.append("\n**************************************\n");
        logger.debug(sb.toString());
        return invocation.invoke();
    }

below is my stack:
<interceptor-stack name="myCustomizedDefaultStack">
                <interceptor-ref name="exception"/>
                <interceptor-ref name="alias"/>
                <interceptor-ref name="servletConfig"/>
                <interceptor-ref name="prepare"/>
                <interceptor-ref name="chain"/>
                <interceptor-ref name="scopedModelDriven"/>
                <interceptor-ref name="modelDriven"/>
                <interceptor-ref name="fileUpload"/>
                <interceptor-ref name="checkbox"/>
                <interceptor-ref name="datetime"/>
                <interceptor-ref name="multiselect"/>
                <interceptor-ref name="staticParams"/>
                <interceptor-ref name="actionMappingParams"/>
                <interceptor-ref name="params"/>
                <interceptor-ref name="conversionError"/>
                <interceptor-ref name="refineModelInterceptor"/>
                <interceptor-ref name="validation"/>
                <interceptor-ref name="workflow"/>
                <interceptor-ref name="debugging"/>
            </interceptor-stack>


Determine max, min of width, height device media query css3 by yourself?

Question: Assum that I have a device has size 1024X768, I want to use media query css 3 to hide or show (example) some elements. How I know what size is max-width, min-width, ... etc? Thanks for watching :)
Comment: I think this is just possible with javascript. the jQuery way would be: $( window ).height(); https://api.jquery.com/height/ and $( window ).width();  https://api.jquery.com/width/
Comment: Well I'm not real sure what you want!? min- and max-, with and height are css rules you can use them on every element. Could you please update your question and be more clear what you want? Maybe provide a fiddle with the problem and explain the expected result..
Comment: I know that. Example, with screen 1024x768, what size is min-width, max-width, min-height, max-height?
Answer: Can you please elaborate your question a little bit more. What do you actually want? You want to find out the min width and height of the device or you know these values and you just want to apply media queries to hide/show elements?
follow:- http://css-tricks.com/snippets/css/media-queries-for-standard-devices/ and try to go through the comments also may be this can help you out.
and http://nmsdvid.com/snippets/ for deciding device widths.


How to remove the last part of the current url using jstl

Question: I was wondering if you can remove the last part of the url using JSTL.
My current link is
http://localhost:8080/program/year/eventid/resources

I want to remove the /resources (/resources is dynamic is will change depending on the page I am visiting example /home or /logistics) part and use the url again to go back to the home page
what I used to get the current URL is
<c:set var="currenturl" value="${pageContext.request.requestURL}" />

I cannot really find an answer to this question with only the use of JSTL, so no javascript or JAVA. That would be my last option.
So can anybody help me with this?
Answer: Maybe you could have a look at the JSTL function fn:replace() (tuto, doc).
Answer: You could, if you really want to:
<c:set var="splitUrl" value="${fn:split(pageContext.request.requestURL, '/')}" />
<c:forEach items="${splitUrl}" var="part" varStatus="status">
  <c:if test="${not status.last}">
    <c:set var="trimmedUrl"
           value="${trimmedUrl}${status.first ? '' : '/'}${part}"/>
  </c:if>
</c:forEach>

But the better way would be creating a custom tag or function to do the work. Benefits:

Reusable
Better readable JSP


Swift: JSONDecoder won't decode when struct has default array initialization

Question: I'm decoding a simple structure and ran into unexpected behavior.
struct Contacts: Codable {
  struct Recipient: Codable {
    let name: String
  }

  let recipients: [Recipient]
}

do {
    let jsonData = SOME STING WITH VALID JSON
    let contacts = try JSONDecoder().decode(Contacts.self, from: jsonData)
}
catch {
}

This decodes just fine. If I do this simple change to the structure, it no longer decodes.
struct Contacts: Codable {
  struct Recipient: Codable {
    let name: String
  }

  let recipients: [Recipient] = []
}

Now JSONDecoder won't decode the exact same string. Why does the default initialization of the array cause the decoder to stop working?
Comment: Maybe because it is declared `let`and can't be changed once it is initialized?
Comment: A `let` property can only be set once so if you're giving it a default value then the initializer generated by `Codable` can't set it again.  If you change it to `var` it will decode.  It will still fail to decode if the recipients key isn't present in the json though which is what I'm assuming you were trying to prevent
Comment: Added a custom decoder init and do `decodeIfPresent([Recipient].self forKey: .recipient) ?? []` to default initialize it..
Comment: Why do you want to do that? Let the decoder initialize the stuff unless you implement a custom `init(from decoder` with custom behavior. If instances of the struct are created without the decoder add an `init` method providing a default value.
Comment: Yep, 'let' was the issue--brain freeze on my part.
Answer: Change your code to read:
struct Contacts: Codable {
  struct Recipient: Codable {
    let name: String
  }

  var recipients: [Recipient] = []
}

The issue (as described in the comments above) is that your initial declaration of the variable is immutable (meaning it cannot be changed after it is initialized).  So, if you declare the initial value for a let as [] then you cannot subsequently change it.  By changing let to var you are declaring the variable as mutable (meaning it can be changed) which allows you to both supply an initial value as well as change the value later.
Answer: Your let here isn't a "default initialization." It's defining recipients as a constant with a specific, compile-time, value. If you want a default value, then you can create a initializer for that if you like:
struct Contacts: Codable {
  struct Recipient: Codable {
    let name: String
  }

  let recipients: [Recipient]

  init(recipients: [Recipient] = []) { self.recipients = recipients }
}

Generally speaking on this kind of very simple data type, I'd make recipients a var instead (see John Ayers's answer for example). It's much more flexible, while maintaining all the advantages of a value type. But in cases where you want a let constant with a default (rather than a single value), you need an init.


AWS queries regarding subnetting and routing

Question: I have some queries regarding AWS setup please clarify.
I have created a VPC with CIDR 172.16.0.0/16 which is a private range of IP's. In my route table, I routed all the traffic from this range. Below are my queries.

How IGW connects to the internet(As CIDR range is private)?
What is the IP range of EC2 instance in this scenario? Is it 172.16.x.x?
Is it possible to assign a public IP to an EC2 instance which is not in CIDR range?
How an Elastic IP impacts here?

Any help on these questions would be highly appreciated.
Thanks in advance.
Answer: The IP stack in the kernel of a running instance is only aware of the instance's private IP address.
The IGW is a 1:1 NAT device with a static map, which translates the instance's private IP to the instance's assigned public IP, if it has one, for traffic to/from the Internet.  Configuration of the IGW is fully automatic. The IGW is not a physical device in a physical place.  It's a logical entity whose functions are performed by the network infrastructure itself.
Instances without a public IP cannot be situated on a subnet whose default route is the IGW (called a "public subnet" because it is intended for use by instances with public IPs).  Instead, they must be placed on a subnet whose default route points to a NAT Gateway or a NAT Instance (a "private subnet," intended for use by instances with only private IPs), so that their traffic can ultimately use the public IP address of that NAT device for outbound Internet access.
It is not possible to have an EC2 instance with a private IP address that is outside the CIDR range for the subnet where the instance is placed.  If you change the IP address on the Ethernet interface of an instance, itself, the instance simply becomes inaccessible.
When an EC2 instance has a public IP, either because it was launched with one requested or launched on a subnet configured to assign them automatically, that address comes from a public pool and will go away when the instance is stopped or terminated and cannot be reclaimed.  An EIP works the same way, during operations, except that it is allocated to your account until you release it, so it does no change if it is attached to an instance that is subsequently stopped.  You are not billed for any EIP that is the first EIP attached to a running instance.  Additional EIPs on the same machine, EIPs attached to a stopped instance, or EIPs attached to nothing, are subject to a charge.
Answer: When you say "I have routed all the traffic in this range" where have you routed it? That's a bit ambiguous. You can't route traffic in a VPC, you route traffic in / between subnets, the internet, and a few other places I'll skip over.

An internet gateway (IGW) connects to the internet in a way AWS don't describe. It Just Works.
You can't create an instance in a VPC unless you've created a subnet. If you create a single /16 subnet (which is really large, 65K hosts) then yes it's 172.16.x.x. If you create a subnet 172.16.0.0/24 then the IP will be 172.16.0.x.
The VPC CIDR range is just for private IPs. AWS assigns a second IP either as a public IP or elastic IP. In general any server, AWS or not, can have many IPs.
Question is ambiguous. See #3.

My general suggestion to you is to do a course such as AWS Architect Associate at Linux Academy or Cloud Guru to learn the basics of AWS VPCs before you try to use them commercially. Server Fault is a place for professionals with good IT knowledge to ask questions, rather than a place for beginners to ask question. SuperUser.com may be more suitable for these types of questions.


how to update the order total in checkout page?

Question: I'm calculating discount amount base on total order amount. how can I show the discount amount like something what coupon module has done? (see the picture)

what is the correct way to update the total order amount? I mean how should I subtract the discount amount from the order total so if any products has been removed or added it always works correctly??
Comment: do u still need solution for your problem or found answer?
Comment: yes my problem is solved, I used the first answer which has been suggested by @Molot
Answer: You need to use hook_form_alter().
First, for integrity purposes, write a validator that will ensure all amounts are correct, and if not - update them & show form to user again.
Second - use AJAX. Drupal allows only for one callback, so your new one will have to take care of calling the original one in the first place, and you may have some problems if you will need to replace more than one form element, but it can be done.
Comment: tanx for the solution Molot, I didn't need to update more than one element and everythings works fine
Comment: I'm glad it worked. If I could humbly ask you to mark my answer as accepted, so other will see there is working solution?


How to customize activityController Swift

Question: I am trying to customize UIActivityViewController but i really confused how to customize.
Code:
let image =  UIImage(named: (self.userProfileModel!.userdata?.image)!) ?? #imageLiteral(resourceName: "app_logo_v6-2")
let text = "Discription: \(String(describing:
self.userProfileModel!.userdata?.descriptionValue)) \n UserName: \(String(describing: self.userProfileModel!.userdata?.name))"
let shareAll = [text, image] as [Any]
let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
activityViewController.completionWithItemsHandler = { (activity, success, items, error) in
if success == true
  {
SVProgressHUD.showSuccess(withStatus: "SUCCESS")
    }
 }
UIApplication.visibleNavigationController.present(activityViewController, animated: true, completion: nil)
return

Output:

Here is what I am trying to do:
Share profile Information
UserName: Sham Dhiman
Description: Hello everyone how you
UserImage: Image
Application Name: ABCD

Can someone please explain to me how to solve this , i've tried to solve this issue but no results yet.
Any help would be greatly appreciated.
Thanks in advance.
Answer: let shareAll = ["Discription: \(String(describing:self.userProfileModel!.userdata?.descriptionValue)) ", " UserName: \(String(describing: self.userProfileModel!.userdata?.name))", image ?? ""]


Find $\lim\limits_{x \rightarrow \infty} \sqrt{x} (e^{-\frac{1}{x}}-1)$

Question:
Find $$\lim\limits_{x \rightarrow \infty} \sqrt{x} (e^{-\frac{1}{x}}-1)$$

$$\lim\limits_{x \rightarrow \infty} \sqrt{x} (e^{-\frac{1}{x}}-1)
= \lim\limits_{x \rightarrow \infty}  \frac{e^{-\frac{1}{x}}-1}{x^{-0.5}}
= \lim\limits_{x \rightarrow \infty}  \frac{[e^{-x^{-1}}-1]'}{[x^{-0.5}]'}
= \lim\limits_{x \rightarrow \infty}  \frac{x^{-2}e^{-x^{-1}}}{-0.5x^{-1.5}}
= 2 \cdot \lim\limits_{x \rightarrow \infty} \frac{1}{e^{x^-1}x^{0.5}}
$$
So as $x \rightarrow \infty$, $\frac{1}{e^{x^-1}x^{0.5}} \rightarrow \frac{1}{1 \cdot \infty} \rightarrow 0$
Is this correct ? any input is much appreciated
Comment: Why students apply de l'Hopital when there is no need for it? $$\lim_{x\to +\infty}\sqrt{x}(e^{-1/x}-1) = \lim_{z\to 0^+}\frac{e^{-z}-1}{\sqrt{z}} = 0 $$ since $\lim_{z\to 0}\frac{e^z-1}{z}=1$.
Comment: @gegu The point is that here, you basically can recognize somewhere a derivative (at $0$), by definition. Using de L'Hopital then boils down to computing *two* derivatives (including the one you are looking for) to find *one* derivative.
Comment: @JackD'Aurizio.They likely use l'Hopital when it's not needed because they  first  see its use in  some "mysterious" examples , and so they expect that it's the Rosetta stone for limits.
Comment: Average students are result-oriented. When I teach linear systems with the Gaussian reduction procedure, then I teach Cramer determinant's rule, after they use the last one even to solve $x+y=5;\;x-y= 3$. They need to be $sure$... :)
Answer: Yes your way is correct,but you can do it simply as  $$\lim _{ x\rightarrow \infty  } \sqrt { x } \left( e^{ -\frac { 1 }{ x }  }-1 \right) =\lim _{ x\rightarrow \infty  } \sqrt { x } \frac { \left( e^{ -\frac { 1 }{ x }  }-1 \right)  }{ -\frac { 1 }{ x }  } \left( -\frac { 1 }{ x }  \right) =\lim _{ x\rightarrow \infty  }{ -\frac { \sqrt { x }  }{ x }  } =0$$
Comment: @gegu Not all indeterminate expressions require L'Hospital's.$$\frac{\sqrt x}x=\frac1{\sqrt x}\to0$$Indeed, you should always check if you can solve the problem algebraically before attempting to use L'H.  (unless the assignment explicitly tells you to do so)
Comment: thx for the interesting input, but isnt the limit of the last expression you wrote yielding an indeterminate form (trying to understand)
Comment: @gegu That is the point where you  can understand it by applying L'Hopital's rule. The result then is simply obvious.
Answer: Note the fundamental limit formula $$\lim_{t\to 0}\frac{a^{t}-1}{t}=\log a$$ and put $x=1/t,a=1/e$ to get $$\lim_{x\to \infty} x(e^{-1/x}-1)=-1$$ and then dividing by $\sqrt{x} $ we can see that the desired limit is $0$.
Answer: I always prefer Taylor expansion to L'Hospital rule, as it is clearer and more generalized. For this one, write:
\begin{align}
\sqrt{x}(e^{-1/x} - 1) & = \sqrt{x}\left(1 - \frac{1}{x} + o\left(\frac{1}{x}\right) - 1\right) = -\frac{1}{\sqrt{x}} + o\left(\frac{1}
{\sqrt{x}}\right) \\
& \to 0 \quad \text{as } x \to \infty.
\end{align}
It might be safe to say that all univariate limit problems/exercises can be handled neatly by applying Taylor's theorem with the Maclaurin remainder.


Cyclic vectors in irreducible GNS representation of pure states

Question: I have a confusion regarding the unit cyclic vectors in the GNS construction of pure states. It seems every corresponding GNS representation $(\mathcal{H}_f, \varphi_f)$ of a pure state $f$ of a unital C*-algebra $\mathcal{A}$, should have its unique unit cyclic vector $x_f \in \mathcal{H}_f$. However, I also see a claim (forgot where) that for every non-zero unit vector $x\in \mathcal{H}_f\setminus \{0\}$, such that $\|x\|=1$, we always have, for $a\in\mathcal{A}$,
$$f(a)=\left\langle \varphi_f(a)x,x\right\rangle.$$
So for example, if $f(a)>0$ for every pure state $f$, we can conclude that $\varphi_f(a)$ is always a self-adjoint positive definite operator. Then, deduce that $a$ is positive in $\mathcal{A}$.
But is this correct? Shouldn't this equality only hold for the unique $x_f$ obtained from the GNS construction? Am I missing something? Is this a special property for pure states?
Answer:
I also see a claim

You don't say where, so I cannot comment on that.
For any $b\in A$ such that $f(b^*b)=1$ you have that $\hat b=\phi_f(b)x_f$ is a unit vector, and
$$
\langle \phi_f(a)\hat b,\hat b\rangle=\langle\phi_f(a)\phi_f(b)x_f,\phi_f(b)x_f\rangle=\langle\phi_f(b^*ab)x_f,x_f\rangle=f(b^*ab).
$$
So the assertion is not true as stated.
Now, if $f(a)≥0$ for all pure states then $a$ is positive. This follows from the fact that the state space is the weak$^*$ closure of the convex hull of the pure states. Then $f(a)≥0$ for all states and so $a≥0$.
Comment: But that has nothing to do with GNS. If  $a$ is positive, then $a=b^*b$. For any representation $\phi$ and any $h$, $$\langle\phi(a)h,h\rangle=\langle\phi(b)^*\phi(b)h,h \rangle=\|\phi(b)h \|^2\geq0.$$
Comment: Indeed. $ \ \ $
Comment: I guess I should ask it this way: if $(H, \varphi)$ is the direct sum of irreducible GNS representations $(H_f, \varphi_f)$, where $f$ runs through pure states, then how to conclude that the linear functional $\tau_h: a \mapsto \langle \varphi(a) h, h \rangle$ is a positive operator? I know each $\tau_{h_f}$ is positive for $h_f$ the corresponding unit cyclic vector.
Comment: Or if we are talking about the universal representation. The cofusion is this: for each corresponding GNS representation, I can see why the functional is positive. But for the direct sum, we can't use the GNS construction and directly concluse it is. Maybe I misunderstood something in the GNS construction?
Comment: Thank you. So this is true for all $*$-homomorphisms
Comment: Can you please elaborate the last paragraph in your answer? Specifically, the part where you claim "if there is a state $\tilde{g}(a)=0$, then there exists a pure state $f(a)=0$? I don't get why the canonical evaluation map being weak*-continuous guarantees that.
Comment: Also, for a faithful representation $\pi: \mathcal{A}\to \mathcal{B}(\mathcal{H})$, if $\pi(a)$ is positive definite in $\mathcal{B}(\mathcal{H})$, why can we directly conclude $a$ is positive in $\mathcal{A}$? What if $\pi$ can also map some non-positive elements to positive definite operators?
Comment: If $f(a)>0$ for all pure states, the set of pure states (compact when $\mathcal A$ is unital) is mapped to a compact subset $C$ of $(0, \|a\|]$. Take $c=\min C$. As for the representation, a faithful representation is injective, and $\mathcal A\simeq\pi(\mathcal A)$.
Comment: May I ask why the set of all pure states is weak-* compact? Is it mentioned in Murphy (1990)?

For the faithful representation, my confusion is, just because it's injective, doesn't mean other elements can't be mapped to positive operators, right? Sorry if the question is silly...
Comment: I'm thinking I was wrong, and that it isn't necessarily closed; I'll check. As for the representation, an isomorphism of C$^*$-algebras preserves positivity.
Comment: Can you understand this answer?? https://math.stackexchange.com/a/1635924/416552
Comment: No. In any case, it's wrong, as the set of pure states is known to be non-closed is some (most?) cases. See [this](https://mathoverflow.net/a/102310/3698). I'm deleting that part of my answer, if I come up with something I'll answer your other question.


F-Invariant matrix has a block triangular matrix

Question:
Suppose $F : V \to V$ is linear. A subspace $W$ of $V$ is said to be invariant under $F$ if $F(W) \subseteq W$. Suppose $W$ is invariant under $F$ and $\mbox{dim}(W)=r$. Show that $F$ has a block triangular matrix representation $$M = \begin{pmatrix} A & B \\ 0 & C \end{pmatrix}$$
  where A is an $r \times r$ submatrix.
Answer: Builds an orthonormal basis $\{w_i\}$ for $W$, and complete it to an orthonormal basis $\{w_1, \ldots, w_r, v_1, \ldots\}$ for all of $V$.
What do you know about the action of $M$ on a generic vector in $W$ expressed in this basis? What can you conclude about $M$'s representation in this basis?
Comment: Do you mean the invariant transformation beyond r is determined by v? Is that why you complete the basis for V? Could you explain more in detail? I don't quite understand the idea of this problem.


How to show a field in a view taken as input in a different content type?

Question: I made a form Company Information, which contains standard fields like Name, Address, Rating etc.
Now I am taking Rating from a different content type "Company Reviews", under Rating Field.
What I want to display various fields from Company Information and Company Reviews in a single view. I tried using the machine name in twig but somehow the view is showing values from Company Information but not from Company Reviews.
Does this sound familiar? I am sure it can be done but I am missing out something. Any help or even a direction is much appreciated, thanks.

[ UPDATE 1]
So, I was researching this for a while and just after posting the question I stumbled upon "Entity Reference", but it seems that this is not available for drupal 8
can we do this in drupal 8 somehow
https://www.ostraining.com/blog/drupal/entity-reference-views/

[ UPDATE 2]
The entity reference was suppose to show up in Add Relation under Advance Tab

And I am getting a few fields,  but not the ones I want.
neither the view is showing following entity relation

instead, I am having this on my dashboard,

so I went ahead and added Review content filter anyway, as a result, the Listing View started showing the reviews as companies, which was not the desired result, using review title as company title.

Do I require a module or should something have be-be done at content types Company Profile and Review?
[ UPDATE 3 ] The Answer is correct, Here is how did it, if anyone is interested.
It was rather simple,
Suppose you have Content-Type A, and Content-Type B, and a result View C
In Content Type A, you add a field, that is actually a Reference to Content-Type B, let's call it ref-AB. Similarly, Add add a field, that is actually a Reference to Content-Type A, say ref_BA.
Now fields of A & B Content-Type are related, and you can show them in the view.
To Show them in a view, you need to add "reference to the content" as a relation in view ( Go to view> your-view > advance > add relation). Suppose, you added ref_BA to your view, then all fields of content type B, will be available in your view.
In your view, add the field you want to show, making relation to ref_BA.
Answer: Entity Reference is now included in Drupal 8 core.
To use it, simply add a field "Reference-Content" and you may use your Company Reviews content type. Then, following the tutorial from your link, you should be able to add any field from Company Reviews in a view showing content of type Company Information.
Comment: I want to use the said field in a View,
Comment: That's what I understood, yes. So now with your entity reference field, you may add a relationship based on this field in your View. Then, you add a field (let's simply say the title) and you choose the relationship previously built. Finally, you will display the title of the content referenced (here the Company Reviews). This works for any field or property.
Comment: Is there any tutorial for this ?
Comment: the one you mentioned is clear (OSTraining)
Comment: but my drupal setup is not showing "Entity Reference: Referenced Entity".


Swagger on Scala, type uuid and long are undefined

Question: I'm trying to implement swagger on my routes with akka-http 10.0.0 and swagger-akka-http 0.8.2. It works well but query parameter with type : UUID and Long are considered as undefined.
Should I use format?
How to use it?
Here is one of my route :
  @GET @Path("/{publisher_id}/{app_id}")
    @ApiOperation(
        value = "get a app Installation stat for an app ID",
        notes = "Returns a session based on ID",
        httpMethod = "GET"
    )
    @ApiImplicitParams(Array(
        new ApiImplicitParam(name = "app_id", value = "ID of app that needs to be fetched, format com.totot.plop ", required = true, dataType = "string", paramType = "path"),
        new ApiImplicitParam(name = "publisher_id", value = "publisher id : publisher_id ", required = true, dataType = "UUID?",  paramType = "path"),
        new ApiImplicitParam(name = "date_start", value = "Timestamp start date ", required = true, dataType = "LONG???" , paramType = "query"),
        new ApiImplicitParam(name = "date_end", value = "Timestamp end date", required = true, dataType = "LONG???", paramType = "query"),
        new ApiImplicitParam(name = "access_token", value = "session token of the user ", required = true, dataType = "UUID????", paramType = "query")
    ))
    @ApiResponses(Array(
        new ApiResponse(code = 404, message = "App not found"),
        new ApiResponse(code = 400, message = "Invalid ID supplied"),
        new ApiResponse(code = 401, message = "access token invalid")
    ))

Comment: I don't see UUID or LONG listed here http://swagger.io/specification/#data-types-12
Answer: First of all, you can specify a class as it said in the document:

The dataType can be either a primitive or a class name.

https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#apiimplicitparam-apiimplicitparams
By class name, it means you have to include the full class name which is "java.util.UUID", or {UUID.class} as mentioned in the document.
Answer: For Long, use @ApiImplicitParam(... dataType="long" ...). The swagger json that gets generated for the parameter:
{
   "name" : "name",
   "in" : "query",
   "description" : "param desc",
   "required" : true/false,
   "type" : "int",
   "format" : "int64"
}

https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X has such an example param.
For params of type java.util.UUID, there is no special processing in swagger.io code for UUIDs that I know of. So I would recommend dataType="string". As a general pointer, @ApiImplicitParam dataType is documented as:
/**
 * The data type of the parameter.
 *

 * This can be the class name or a primitive.
 */

The primitive values seem to be the java primitive type names, eg int, long, etc. string is also supported.


AngularJS - complex filter base on categories

Question: All I can find about AngularJS filters is simple examples about simple filters (mostly on a single field's value).
What I'm after though is somewhat more complex. Imagine you have an array of the following JSON objects:
{
    "Categoria": "Informática",
    "Title": "Consultor DBA Oracle",
    "professionalarea": {
        "idAreaProfissional": 1,
        "description": "IT"
    },
    "Horario": "Estágio Profissional"
}, {
    "Categoria": "Finanças",
    "Title": "Gestor de Projeto",
    "professionalarea": {
        "idAreaProfissional": 1,
        "description": "IT"
    },
    "Horario": "Full-time"
}

My goal is to create a frontend interface that allows me to cumulatively apply various kinds of filters to those JSON objects.
I have one example I was following:
jsfiddle
Answer: For filters there are many options:
string: The string is used for matching against the contents of the array. All strings or objects with string properties in array that match this string will be returned. This also applies to nested object properties. The predicate can be negated by prefixing the string with !.
Example (search is a simple search string, search in all fields):
ng-repeat="player in filteredPlayers | filter:search"

Object: A pattern object can be used to filter specific properties on objects contained by array. For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1". A special property name ($ by default) can be used (e.g. as in {$: "text"}) to accept a match against any property of the object or its nested object properties. That's equivalent to the simple substring match with a string as described above. The special property name can be overwritten, using the anyPropertyKey parameter. The predicate can be negated by prefixing the string with !. For example {name: "!M"} predicate will return an array of items which have property name not containing "M".
Example (filtering 2 specific fields with specific values)
ng-repeat="player in filteredPlayers | filter:{Categoria: cat,Title: tit}"

Note that a named property will match properties on the same level only, while the special $ property will match properties on the same level or deeper. E.g. an array item like {name: {first: 'John', last: 'Doe'}} will not be matched by {name: 'John'}, but will be matched by {$: 'John'}.
function(value, index, array): A predicate function can be used to write arbitrary filters. The function is called for each element of the array, with the element, its index, and the entire array itself as arguments.
The final result is an array of those elements that the predicate returned true for.
Example (filtering with a custom function selection() )
ng-repeat="player in filteredPlayers | filter:selection"

In your app script (custom function, filter only items with some optional values):
$scope.selection=function(value, index, array){
  if ( value.Horario == 'Full time' || value.Horario == 'Estágio Profissional'){
    return true;
  }
  return false;
}

Comment: i need the if return me the value in my json automatic but i will try change my code because as i have doesnt' work
Comment: In my example jsfidlle works well but when i try put professionalarea.description doesn't work
Comment: can you create a jsfiddle with that case to check what could be wrong?
Comment: in my post i have one jsfiddle


SQL Like query excluding space characeters

Question: Below is a basic idea of how my table looks.
id -  Name
1  -  C A D Systems
2  -  A & B Company
3  -  A M A T Systems
4  -  HHH Systems
5  -  A A Systems

I am looking for a query to handle this functionality:

If I search "CAD", I should be able to get C A D Systems back.
If I search "A&B", I should be able to get A & B Company.
If I search "H H H Systems", I should be able to get HHH Systems.

Is there a way to search and ignore space characters?
Comment: Replaced `psql` tag with `postgresql`. `psql` is the command line client. The DBMS is named PostgreSQL
Answer: You can use replace() to remove spaces and then do the comparison:
where replace(name, ' ', '') like '%CAD%'


How to fix error 1064 while trying to add foreign key

Question: I am trying to set up a DataBase for a library and after I created the table and trying to create foreign keys I get this error (1064) and I relly dont know what to do. I am using MySQL 8
I searched and I couldnt find anything similar. All I found was problem with reserved words , something I dont think is the problem in this case.
ALTER TABLE `project`.`book`
ADD INDEX `pubName_fk_idx` (`pubName` ASC) VISIBLE;
;
ALTER TABLE `project`.`book`
ADD CONSTRAINT `pubName_fk`
  FOREIGN KEY (`pubName`)
  REFERENCES `project`.`publisher` (`pubName`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

Error message:

Operation failed: There was an error while applying the SQL script to
  the database. Executing:

ALTER TABLE `project`.`book`
ADD INDEX `pubName_fk_idx` (`pubName` ASC) VISIBLE;
;
ALTER TABLE `project`.`book`
ADD CONSTRAINT `pubName_fk`
  FOREIGN KEY (`pubName`)
  REFERENCES `project`.`publisher` (`pubName`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2
  SQL Statement:

ALTER TABLE `project`.`book`
ADD INDEX `pubName_fk_idx` (`pubName` ASC) VISIBLE

Comment: Been a while since I played with MySQL, but could it be that wayward extra `;`?
Comment: No I already tried , the only thing I found working was removing the INDEX code line but I dont think  its the right thing to do.
Comment: CREATE INDEX instead of ADD INDEX perhaps?
Comment: No, still the same error
Comment: What version of mysql are you using?
Answer: If you are using MariaDB or MySQL under 8.0, they have not inplemented the VISIBLE or INVISIBLE index, so you need to change your query:
ALTER TABLE `project`.`book`
ADD INDEX `pubName_fk_idx` (`pubName` ASC)

Comment: It worked! Thank you very much you kind sir! Have a nice day!


How important is consonance/dissonance in suspensions?

Question:
It's difficult for me to really hear any (harmonic) consonance or dissonance value when two notes are heard at the same time, but do NOT begin at the same time. As a listener, I find myself more drawn to the melodic interval than the harmonic interval of a suspension or any other moment where two notes are heard at the same time, but do NOT start at the same time.
When two notes begin at the same, the harmonic interval is obvious, but not so much if you offset them. If I really try to listen closely, I can hear the harmonic interval,  but I think it would be irresponsible for me to assume the average listener is going to examine my music as much as I do especially if they have no musical training.
For context, I'm asking this question as I'm learning fourth species counterpoint. I understand you need to consider consonance/dissonance when using suspensions, but it's difficult for me to place any value on that beyond just following the rules of fourth species.  Thoughts???
Answer: I'm going to go out on a limb here and assume you're playing on or listening to only a piano or perhaps a harpsichord.  These instruments are characterized by a sharp attack that can overwhelm the sustained pitch in the listener's mind.
Here's a piece that turned me on to suspensions when I was in high school: Den Tod niemand zwingen kunnt, the second verse of Bach's Cantata BWV 4, Christ lag in Todes Banden (usually seen as "Todesbanden" but if I recall correctly the source has it as two words).
There are a couple of extended suspensions here, which you may find of interest, but the classic sequence of suspensions in the final hallelujah serves to illustrate the point.  That starts at 8:30.  To be perfectly clear, the point is that each time the soprano voice descends (and the alto voice holds its pitch), the dissonance is very apparent in the musical texture.  The "crunchy" texture dissipates when the alto voice descends to the consonant interval, and this repeats a few times in sequence.
If you're composing at the keyboard, try a pipe organ or, if you can't manage that, a synthesizer with a sustained tone and a gentle attack.


How to install Oracle WebLogic Server ( JAR file ) in Mac OS?

Question: I understand perhaps it's not the right question to ask here, but, I really can't install Oracle WebLogic Server 12c (12.1.3) in Mac OS ( Yosemite ). I get the following error message :
The Java JAR file "oepe-12.1.3-kepler-installer-macosx-cocoa-x86_64.jar" could not be launched. Click the console for possible error messages.
I get the following information's about Java environment ( java -version) from the terminal:
java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)
Solution
I get the solution for this problem. Just need to go in the folder containing the JAR file using terminal and run it from there:
java -jar oepe-12.1.3-kepler-installer-macosx-cocoa-x86_64.jar
It will take you through the installation procedure.
Comment: Anyone has experience with installing WebLogic in Mac OS please let me know.
Answer: Open a terminal and run
<code>java -jar fmw_220.127.116.11.0_wls.jar
</code>
You should see this window open and then is just configuring your options:
Comment: Thanks, if you run the JAR file from the terminal, this is working.
Comment: If you consider solving your issue you might marked as solved (only if you consider, so other can benefit in case they look for an answer)
Comment: How to marked as solved ? I'm now going through using the WebLogic sever in Spring tool. I will write a small note about the entire process soon.
Comment: If you consider it was the correct answer just tick the response as answered


Is there any way to check, in PHP, that whether any email is active or not?

Question: Is there any way to check (through PHP) that whether any given email address is active (means is it currently being used & opened by anyone) or not (means it is blocked or no one uses/opens it, it's inactive)?

Regards & Thanks in advance.
Comment: Are you talking about an E-Mail server you host yourself or something like Google Mail?
Comment: Short answer no, email is so transient that it is very difficult to confirm whether or not an email is exists.
Comment: @Lukas Knuth I am talking about external servers like Google, Yahoo or Hotmail etc
Answer:
Is there any way to check (through PHP) that whether any given email address is active (means is it currently being used & opened by anyone) or not (means it is blocked or no one uses/opens it, it's inactive)?

No.
The only way to be sure is to send an E-Mail to the address, not get a bounce message, and get some kind of reply back (like an answer, or the user clicking a unique link in the E-Mail, or an image with a unique URL being opened [this is frowned upon though, and blocked by many E-Mail clients], or a read receipt). None of these methods is foolproof, though, so you can never tell for 100% sure.
Answer: I think you are asking if the email user enters is valid or not!! if this is the case then you should use nslookup for unix-based operating system with help of exec.. here is a small function for that: (i am checking if the domain is correct or not)
function myCheckDNSRR($email)
{
      list($userName, $hostName) = split("@", $email);
$recType = '';
if(!empty($hostName)) {
   if( $recType == '' ) $recType = "MX";

   exec("nslookup -type=$recType $hostName", $result);
   // check each line to find the one that starts with the host
   // name. If it exists then the function succeeded.

   foreach ($result as $line) {
     if(eregi("^$hostName",$line)) {
       return true;
     }
   }
   // otherwise there was no mail handler for the domain
   return false;
}
return false;

}
Comment: PHP has an own function checkdnsrr ;)
Answer: You can but have to use an API to an external service
There are a few email validation api's out there, data8 got one. http://www.data-8.co.uk/integr8/services/email_validation.aspx
Here is a sample
function IsValid($email, $level)
{
  $params = array(
    "username" => "your-username",
    "password" => "your-password",
    "email" => $email,
    "level" => $level,
    "options" => $options
  );
  $client = new SoapClient("http://webservices.data-8.co.uk/EmailValidation.asmx?WSDL");
  $result = $client->IsValid($params);
  if ($result->IsValidResult->Status->Success == 0)
  {
    echo "Error: " . $result->IsValidResult->Status->ErrorMessage;
  }
  else
  {
    // TODO: Process method results here.
    // Results can be extracted from the following fields:
    // $result->IsValidResult->Result
    //   Contains a status code indicating if the email address could be validated.
  }
}

Comment: Mmmmm, kind of, but this checks only whether the *domain* of the E-Mail address is live and active, and maybe the general existence of the E-Mail address on that server. It does not tell you whether a *specific* E-Mail address on that domain is in use, whether a user has access to it, etc.
Comment: It verifies the stated e-mail but like you say it's never 100% way to be sure, "Valid; According to the selected level of validation, the email address appears to be valid. This is not an absolute guarantee that emails sent to this address will be delivered and read."
Comment: Yes, my task is that to check that whether a user has access to it or not?
Comment: So you want to check if you can log in to an email account or not?
Comment: No actually I am trying to develop Mailing-List software, so I want to send emails to only those emails which are active and in use.
Comment: Is that Web Service API free or payed?
Comment: The one I posted is payed , but there should be several few. I choose this one cause of it's clear example.


Quebrar a linha após uma determinada palavra com PHP

Question: Colegas,
Estou fazendo uma busca interna em um site existente, porém em um dos resultados, está trazendo da seguinte forma:
 página 1 página 2 página 3

Como eu faria para que após a palavra  houvesse uma quebra de linha com PHP?
Comment: usa `str_replace("", "", $tua_variavel);`
Comment: Nos mostre o que você já tentou e quais erros está enfrentando. Uma dica é a utilização da função explode();
Comment: `após a palavra ""` deveria ter uma palavra entre as aspas?  Ou quer dar um quebra de linha em um ponto vazio mesmo? Existem diversas maneiras, depende um pouco de como vem o resultado etc...
Comment: Não reparei... ajustei agora. Seria depois da palavra
Comment: Já tentei o explode(). porém ele me retorna sempre a primeira linha. Vale lembrar que nem todos os resultados trazem dessa forma...
Comment: quebrar em todos os `` ou somente em alguns especificos
Comment: Quebrar em todos, pois nesse resultado específico , está trazendo um ao lado do outro.
Comment: Funcionou Thiago. Obrigado!
Answer: Acredito que isso resolve pra você
$text = 'página 1 página 2 página 3';
$newtext = str_replace('', '
', $text);

Ou se preferir pode quebrar nos
$newtext = str_replace(' ', '
', $text);

problema é que pode afetar outras areas que tenham isso e voce nao queira uma quebra de linha
Comment: Perfeito... Funcionou! Obrigado!


Proving by Cauchy's definition $\lim_{x\to -1} x^2+3x-5=-7$

Question:
Prove by Cauchy's definition $\displaystyle\lim_{x\to -1} x^2+3x-5=-7$

From definition: $|x+1|<\delta\Rightarrow |x^2+3x+2|<\epsilon \iff |x+1||x+2|<\epsilon$.
Now I'm not really sure how to continue, is it correct that because $|x+1||x+2|<\epsilon$ then $\delta(\delta+1)<\epsilon$? But that doesn't help to find $\delta$...
Comment: No, it is not correct that $|x+1||x+2|<\epsilon$ implies $\delta(\delta+1)<\epsilon$. However, $\delta(\delta+1)<\epsilon$ implies $|x+1||x+2|<\epsilon$, which seems to be what you really want.
Answer: Hint 1: Let's suppose that $\delta < 1$.  Then, $|x+1| < 1$, so $0 < x < 2$.  This means that $|x+2| < 4$, so $|x+1||x+2| < 4|x+1|$.  Can you add an additional restriction on $\delta$ so $4|x+1| < \epsilon$?
Hint 2: Alternatively, take $\delta < 1$ again.  Then $\delta(\delta+1) < 2\delta$.  What additional restriction can you put on $\delta$ so $2\delta < \epsilon$?
Comment: Are the restrictions: 1. $\delta=\min\{1,\epsilon/4\}$ or 2. $\delta=\min\{1,\epsilon/2\}$ ?
Comment: Yup, that's correct!
Answer: For every $\epsilon > 0$ we need to find $\delta > 0$, such that for all $|x +1| < \delta$, $|x^2 + 3x - 5 + 7| = |x^2 + 3x +2| = |x+1||x+2| < \epsilon$. Doing some calculation we get this inequality $$|x+1||x+2| < \delta |x + 2| \leq \delta|x+1| + \delta.1 < \delta^2 + \delta $$
So if we find $\delta > 0$, such that : $\delta^2 + \delta < \epsilon$, we are done. You can easily see that $\delta = \frac{\epsilon}{2}$ works fine.
Answer: Let $\delta=\min\{1,\frac{\epsilon}3\}$. (Note that I chose the $1$ arbitrarily.) If $|x-(-1)|=|x+1|<\delta$, then $$|(x^2+3x-5)-(-7)|=|x^2+3x+2|=|x+2||x+1|<3 \delta=3\cdot\frac{\epsilon}3=\epsilon.$$
Comment: Why is it smaller then $3\delta$?
Comment: As stated, $|x+1|<\delta$. If $\delta=1$ (from the $\delta=\min\{1,\frac{\epsilon}3\}$), then we have $|x+1|<1$, or $-1<x+1<1$. Add $1$ on both sides, and you will get $0<x+2<3$, and so $|x+2|<3$. Put these both together, and you get $|x+2||x+1|<3\delta$.


Prove inequality in complex numbers in an unit circle

Question: Given $|\omega| < 1$, $\omega \neq 0$ and $|z| < 1$. Prove inequality:
$$\frac{|\frac{|\omega|}{\omega}z+1|}{|1-z \bar \omega|} \le \frac{2}{1-|z|}$$
It is simple but i have problems with it. Thanks :)
Comment: The denominator of the first fraction could be complex.
Comment: Is the left hand side necessarily real?
Comment: Sorry, that was misprint
Comment: Assume $w \neq 0$?  Clear away some clutter by replacing $u = \frac{|w|}{w} z$, so that $z\overline{w} = u |w|$.
Answer: Hint:
Triangle inequality ($|x+y|\leq |x|+|y|$)  and triangle inequality ($|x-y|\geq |x|-|y|$).
Answer: Triangle inequality 1:
$$
| \frac{|\omega|}{\omega}z+1|\leq |z|+1 < 2.
$$
Triangle inequality 2:
$$
|1-z\bar{\omega}| \geq 1 -|z||\bar{\omega}|\geq 1-|z|.
$$
Answer: Let $w=R(\cos \beta+i\sin\beta),z=r(\cos \alpha+i\sin\alpha)$
So,  $$\frac{|\frac{|\omega|}{\omega}z+1|}{|1-z \bar \omega|}=\sqrt{\frac{r^2+1+2r\cos(\alpha-\beta)}{R^2r^2+1-2Rr\cos(\alpha-\beta)}}\le \sqrt{\frac{(r+1)^2}{(1-rR)^2}}$$ as $-1\le\cos(\alpha-\beta)\le 1, r^2+1+2r\cos(\alpha-\beta)\le (r+1)^2$ and $R^2r^2+1-2Rr\cos(\alpha-\beta)\ge (1-Rr)^2$
$$\frac{|\frac{|\omega|}{\omega}z+1|}{|1-z \bar \omega|}\le\frac{r+1}{1-Rr}\le \frac2{1-R}$$ as $r<1$
Comment: Being explicit with sines and cosines makes things overly complicated. I advise using the reverse triangle inequality $|u-v| \geq ||u| - |v||$ in the complex numbers to get upper bounds on ratios. For this problem, $||\omega|/\omega| = 1$, so numerator has abs. value at most $|z| + 1 < 2$ by the usual triangle inequality, and for denominator, from $|z\overline{\omega}| = |z||\omega| < 1$ we get $|1 - z\overline{\omega}| \geq |1 - |z\overline{\omega}|| = 1 - |z\overline{\omega}| > 1 - |z|$. Thus the left side is less than $2/(1 - |z|)$.
Comment: Thanks, your solution is good too:)
Comment: @Makarios, I've actually proved what the other answers assume
Comment: See my answer at http://math.stackexchange.com/questions/275547/bag-of-tricks-in-advanced-calculus-real-analysis-complex-analysis/275616#275616 for a place where the reverse triangle inequality $|u-v| \geq ||u|-|v||$ has an important role in complex analysis.


On a VM, do logical vs physical disks still matter?

Question: My brother is using a hosting provider which is providing his company with a VM with Windows Server 2008 R2.
They unfortunately have to run the whole stack on one server, so my brother at least asked for separate drives for OS, IIS, DB, Logs, etc.
They provided him with 5 logical drives all on the same "physical" disk 0 (e.g. showing to the OS as a physical disk -- one VMDK).
Assuming that there's a reasonable churn across these various logical disks, would adding them as separate "physical" disks (VMDKs I suppose) make sense? It seems like there would still be a performance gain there but I'm unsure how best to go about proving it and haven't found any literature (yet) on the subject.
Answer:
would adding them as separate "physical" disks (VMDKs I suppose) make
  sense?

Yes, you don't have to prove it, it's common sense, it just costs money is all. Of course that 'single physical disk' could well be a VMDK on a datastore based on a LUN that's wide-striped across hundreds of disks - the only way to know is to ask EXACTLY what they're providing and EXACTLY how - then you'll be able to make an informed decision.
Comment: Thanks for responding! I'm interested in the language to explain it. The issue is my brother's host is telling him they won't put it on separate disks because it "makes no difference in a VM". So I guess I'm wondering, would using separate VMDKs always guarantee some better performance, or no?
Comment: Taken at face value their assumption that 'makes no difference in a VM' is utter shit but this could well be a terminology issue - which is why I'd suggest you get them to spell it out in great detail - come back to us if you'd like to discuss these details, until then there's not enough to go on sorry.
Comment: I don't think creating separate VMDK's makes any difference if on the same PHYSICAL disk.  The physical disk has an IOP limit.  Once that limit is reached it doesn't matter how many VMDK's you create.  Like @Chopper3 said, it could be striped across hundreds of disks so the the IOP capacity could be astronomical.  VMs don't act like traditional servers where you would have the OS, IIS, DB partitions on separate drives for speed.  VMs can use 1 datastore that's across 100 drives or just 1 drive (think RAID) with multiple VM's in that 1 datastore.
Comment: I have one datastore that has 4 separate servers on them.  One of those servers has 4 virtual disks (VMDKs) because I wanted to "partition out" the space.  Has nothing to do with speed.  That 1 datastore has 6 PHYSICAL drives in the SAN using a RAID10 configuration.  Adding 5 more, separate VMDKs to that VM will not make it any faster.