How does one analyze a song that moves primarily between two non-diatonic chords?

Question: The score for 'The Simple Life' by Jerry Martin indicates three flats, which would typically mean either Eb major or C minor. However, almost the entire song just moves back and forth between Bb major and Ab major chords, ending very clearly on Bb major. The overall tonality, therefore, suggests we're in Bb major, but then the Ab major chord doesn't make sense, since there's no Ab in the key of Bb major.
I know about the Pythagorean scales and Messiaenean modes, but this song doesn't seem to fit either model. So what is the key, and how is that determined? How does one deal with a song that primarily moves back and forth between two chords that are not diatonic to each other?

Here is the first page of the score, showing the key signature and the back-and-forth movement between Bb and Ab major chords.

Here is a recording of the piece.
Comment: Personally, I'd be up for re-opening this question. The close prompt states that "Questions should be substantial and refer to a well-defined work or subsection, including a concrete reference (sheet music, etc.)." This question does all of those things, I think; the only issue is where the question is "substantial" (whatever that means) or not.
Comment: Basically, songs and melodies are not 'in scales', so this question is invalid.
Comment: There are a number of posts on this site discussing the issue of notes that don't fit the key. A couple that might be helpful: [How come songs in a certain key play notes not in that key](https://music.stackexchange.com/q/22792/70803) and [Can a song contain pitches outside of its intended key?](https://music.stackexchange.com/q/65136/70803)
Comment: Does this answer your question? [Can a song contain pitches outside of its intended key?](https://music.stackexchange.com/questions/65136/can-a-song-contain-pitches-outside-of-its-intended-key)
Comment: I've substantially rewritten your question, because I think it touches on an important point that was lost as originally written. However, if the change doesn't reflect your intentions, it can be rolled back either by you or, if you let me know, by me.
Comment: The last chord of a song does not determine the key. It's almost certainly not in Bb. I'm wondering why you don't think it's in Eb
Comment: @ToddWilcox I've rewritten the phrase that attributed the key purely to the final chord.
Comment: Difficult one, this. What is a key sig? Is it there to tell what 'changed' notes are to be used? Or is it there to give clues as to what the key actually is? While it *could* sound like home is Bb, that Ab sound defeats it. Modal is evoked, thus putting it into Bb Mixolydian. Which has a parent key of Eb - 3 flats.
Comment: @ToddWilcox - the last chord doesn't *necessarily* determine the key. Although in the vast majority of pieces it actually does. Whether we've been programmed to expect a piece to arrive 'home', or whether it's what's considered 'natural' is a question for another day. But playing an Eb chord somewhere in this piece, and stopping at that - would that sound finished? If yes, maybe it's in key Eb. If no, maybe not...   A long Bb to end sounds o.k., thus my feeling of Bb Mixolydian. Something to do with a lack of leading note?
Answer: The usual question I ask when someone asks "What key is this in?" is "Why do you care? What do you want to do with that information?"  In some repertoires, like a lot of "classical" music, it's very clear what constitutes "being in a key."  But even there, there can be significant ambiguity.  (I discussed some of the issues about interpreting an ambiguous key in an answer here.)
The piece in this question doesn't follow the standard harmony of "classical" music, though.  It has a different harmonic vocabulary.  Trying to shoehorn it into some other classification system according to some arbitrary ranking or rules is an exercise often more about the priorities of the particular analyst than about how the music actually works.
To spare you from the rest of my thoughts (if you don't want to read the extended discussion below), if you forced me to classify this piece according to standard diatonic modes, I guess I'd say B♭ Mixolydian, with some chromaticism (particularly the repeated extended use of the D♭ harmony).  That accurately reflects the predominant scale and the fact that B♭ seems to be a local "center" that the piece keeps coming back to.
But what does it mean to be "in B♭ Mixolydian" other than the fact that there's an A♭ instead of an A♮?  Is that a useful classification?  It doesn't necessarily tell us a lot about how the harmony of this piece works.  As I discussed in the linked answer above, a piece of music is often like a "world" that you enter into.  As you listen to the piece, you learn the "language" of that world, including the harmonic language.
A piece in B♭ major in the stereotypical classical sense will harmonic progressions that you could think of in a flowchart.  Most of the flow keeps going back to B♭.  Specifically, a lot of harmony will go through F major (or F7) back to B♭ major.  You'll see a lot of things like B♭-E♭-F-B♭ progressions, known as I-IV-V-I.  Or you might substitute C minor in and see something like I-ii-V-I.  And you'll also see cycles like I-IV-I and a possibly other things.
That's absolutely not the harmonic flowchart of this piece.  As noted in the question, the most common harmonic cycle in this piece is I-♭VII-I, or B♭-A♭-B♭.  There's no real use of the dominant F major that I heard listening through once.
What else do we have?  Mostly a bunch of E♭ major chords and also quite a bit of D♭ major.  These are also two major chords a whole step apart, like B♭ and A♭.
There is a kind of harmonic backdrop for a piece like this.  It's a cycle of fifths going toward the subdominant side of the circle of fifths (B♭-E♭-A♭-D♭).  Typically classical harmony in major keys tends to be rather dominant-side "heavy," with V and V/V appearing a lot.  There are often even longer cycles of roots of descending fifths, like iii-vi-ii-V-I.
But other musical styles (e.g., some gospel influenced music) tends to go the other direction, with IV and IV/IV, and in this case even IV/IV/IV (which is one way of interpreting D♭).
I personally wouldn't interpret D♭ really that way, but instead think of the "flowchart" metaphor again.  There's a lot of motion between E♭ and D♭ when they occur.  There's a lot of motion between B♭ and A♭.  Basically, in a similar fashion to how V/V relates to V in a typical major key, there's an E♭ subsidiary or secondary "tonic-like" area around E♭ in this piece, perhaps.  (Again, the E♭-D♭ relationship is like the B♭-A♭ relationship.)
So, you can think of a flowchart that has I and ♭VII, and then there's another part of the diagram that has IV and ♭III, which can also be viewed as having a common relationship like I and ♭VII.  These chords constitute most of the harmonic vocabulary of the piece, and you can draw various arrows showing the most common pathways among these chords.  For example, sometimes you'll get a direct motion from D♭ to B♭, like in a IV-♭III-I motion (mm. 8-9).  Rather than a I-IV-V-I cycle that would appear in a major key piece, this piece appears to use I-♭III-IV-I (as in mm. 5-6).  Progressions like this recur later in the piece.  They are part of the harmonic "world" of this piece.
Does this fit into a particular "mode" (e.g., Mixolydian)?  Not stereotypically, but that's what the piece does.  To answer the title question of "how does one analyze a song...", this is the place I'd start, by describing the general content and typical motions of harmony in this piece, particularly the emphasis on IV and the I-♭VII progressions.  And you create the flowchart and go from there.
In the end, is it in "B♭ major" or "B♭ Mixolydian" or some other more arcane term for a scale?  Not in the most typical sense of those terms, at least in terms of what they imply about harmonic usage.  But it certainly uses a type of Mixolydian-like harmony that emphasizes ♭VII in a way I've seen in other pieces.  I don't know a specific name for it, but describing the types of motions of harmony here is more interesting (and more like "analysis") than simply trying to put a scale label on it.
EDIT: I just realized that this question has been reworded by edits and originally asked "what key" the piece was in rather than how to "analyze" it.  I think I still tried to answer the "what key?" question here, but the bit about analysis may have gone further afield than the original question wanted.  Still, to me, the question we should be asking is how to describe the musical features (like harmony, melody, etc.) of a piece, rather than worrying about how to stamp a label on it.  So I'll leave my answer as-is.
Answer: Because the song starts, ends, and continually revisits Bb major, I would analyze it as being in Bb major.
The Ab major chord is borrowed from Bb minor. Borrowed chords are not (necessarily) considered to change the key, and here it clearly is just serving to move toward and away from Bb, reinforcing it rather than subverting it.
The chordal analysis, overall would be <code>||: I - bVII :|| I ||</code> in the key of Bb major.
The key signature is a matter of convenience. Because Ab is used so often, whomever wrote the score decided to include Ab in the key signature rather than using the Bb major key signature and then adding flats to every A in the piece.
It is tempting, because Ab is so consistently used in place of A natural, to consider the piece as being in Bb mixolydian, which shares its key signature with Eb major. However, I don't feel that analysis reflects the overall sound of the piece, which I hear as major, not modal. Bb Mixolydian reflects the literal notes played, but not the overall sound created.

A similar question involving a song that moves back and forth between two chords not diatonic to each other, but which results in a different answer, is What's the most useful way to think about a song that progresses from C to D and back again?
Comment: You like the chromatic medient explanation for the Dbs more than the bVII of Eb major analysis? I think the key signature combined with the accidentals points more to Eb, but as with a lot of modern music, it's hard to be sure and it also doesn't matter as much, really
Comment: @ToddWilcox The Dbs on the first page are the exception in the piece; I didn't attempt to analyze them. Listening to it, nearly the entire piece is just a back-and-forth between Ab and Bb. The tonality is clearly Bb major, at least to my ear.
Comment: To me it's the accidents which confirm things but I also agree when they are temporary it means less. Listening to it, my ears hear it "hovering" over the Eb tonic that might be more implied than anything else. But the fact that we can hear it differently but still understand the musical message is why I feel like it doesn't matter what key one considers it to be in. Keys are kinda over for me. Lots of modern music doesn't fit nicely into any key and there's nothing wrong with that
Comment: @ToddWilcox I think your comment reflects the richness of musical interpretation, whether listener, performer, or analyst. If you can develop your comments into a "competing" answer / alternative analysis, I think the site would be well served.
Comment: I'm not certain I understand what is meant by "I hear as major, not modal."  What precisely does "modal" music sound like (to you), and why is this not it?  To me, one of the strongest features that distinguishes major from many other modes is the use of a leading tone (in this case A resolving to B-flat), which this piece lacks.
Comment: @Athanasius I think it's the absence of, for example, the minor V chord and the fact that the VII chord always returns to I — that is, it always takes the roll of a dominant chord rather than some other function. In a modal piece, I would expect more emphasis on the b7 as a characteristic tone rather than just a gentler version of the leading tone.


Como fazer aplicação angular funcionar apenas em um navegador específico?

Question: Gostaria de fazer minha aplicação angular funcionar em um determinado navegador, e bloquear qualquer outra versão.
Ex: Funcionar apenas no Google Chrome 75. E se o usuário tentar acessar em um Firefox, Edge, ou Chrome em qualquer versão posterior ou inferior, ele envia um mensagem ao usuário que esta tentando usar esta aplicação.
Comment: qual versão do Angular?
Comment: Seria a versão 8.0
Answer: Você pode usar a propriedade: "navigator.userAgent" para exibir a versão do browser. Existem outras propriedades também. Execute o código abaixo em um navegador para visualizar todas elas:
var txt = "";
txt += "
Browser CodeName: " + navigator.appCodeName + "
";
txt += "
Browser Name: " + navigator.appName + "
";
txt += "
Browser Version: " + navigator.appVersion + "
";
txt += "
Cookies Enabled: " + navigator.cookieEnabled + "
";
txt += "
Browser Language: " + navigator.language + "
";
txt += "
Browser Online: " + navigator.onLine + "
";
txt += "
Platform: " + navigator.platform + "
";
txt += "
User-agent header: " + navigator.userAgent + "
";
alert(txt);

Comment: Não basta `console.log(navigator.appVersion.includes("Chrome/75"));` ? Talvez não funcione para todos os casos mas certamente apanhará a maioria.
Comment: Esse funcionou... mas eu teria que usar um algoritmo para pegar o valor de dentro da string, certo? A string seria esta: "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"


How to decide to create a multilingual site or to create different site for each language?

Question: This is the first time I want to create a multilingual website. The site is Turkish now and I want to add English as second language (for both interface and content).
The main site (the Turkish one) has about 15 content types and each content type has 10-20 fields (text, entity reference, date, image etc). Also each content type has its own node.tpl.php and I made lots of customization to display node types. In short, the site is a bit complex.
I made some research about creating multilingual site (in Drupal of course) but I couldn't decide yet to use Drupal's multilingual features or to clone the Turkish site and create another site for English with some (language) modifications.
Creating two separate site is easier for me but using Drupal's multilingual features seems the "correct" way but more painful.
How to decide to create a multilingual site or to create different site for each language?
(More details: - Almost all of the contents in the Turkish site will have its corresponding content in the English site. - There is a team of non technical editors.)
Comment: Sitting on this for a bit, but this is very close to being either a "too broad" or "primarily opinion" based questions.
Comment: @mpdonadio, this question is not opinion-based, it's an **"experience-based"** question. I think it shouldn't be closed.
Comment: @herci I sat on the fence for a bit on this, but still think it is opinion-based or too broad (the exact close reason doesn't have to be precise).  We currently have one answer that is "I think" and just a bunch of links, another "personal view" with little substance,  one short answer, and another that is an "another thing to consider".  The fact that this question is attracting forum-type answers is an indication that it isn't a good fit for a Q&A site.
Comment: We (the mods) talked about this question. It doesn't fit into the Stack Overflow engine of asking questions that has a correct answer. Still we feel that the question has merit and in time the answers provided could as well. So we converted this into a wiki.
Comment: Creating a different site per language means and different (ip) address per site, correct? And even if you create that second site for the other language, won't you to use the drupal's mulitlingual features to translate nodes, terms, menu items and so on? Managing, maintaining and deploying two different sites is way more open to mistakes rather than doing so for one site considering that the same features/code will be used for both sites
Comment: Even adding _experience-based_ in the question would not stop users from giving what are opinions. I agree with @mpdonadio: The question is opinion-based and too broad.
Answer: In my personal view, I will consider if the new language site will be mostly identical to the existing one or not.
It means that if most of the pages / contents in the Turkish site will have its corresponding page / content in the English site, then I will build multilingual site, otherwise, I would like to set up a separate one.
Comment: Thanks for your answer. Yes, most of the contents in the Turkish site will have its corresponding content in the English site.
Answer:
Using Drupal's multilingual features seems the "correct" way but more painful.

Indeed, more painful, but I think it is what you should go for. Because in the long run you'll achieve the best possible solution for also addressing your requirement "Almost all of the contents in the Turkish site will have its corresponding content in the English site".
If you do go for such a multi language implementation, you'll run into some typical issues (questions) for which many contributed modules will actually help you out (the most painful part is to know which module is available to solve which issue). To get you started (in getting used to the pains?), here are some challenges (in a random order), which may help to establish evaluation criteria to decide:

Do you only need node translations, or rather Entity Translation?
Managing translations, which is covered by either Translation Overview or Translation Management.
Path translations, typically covered by either Pathauto i18n or i18n_path (submodule of i18n).
Block translations, typically covered by i18n_block (submodule of i18n).
Translation of Views, which is where the i18n-fun really starts ...

Think about how you would address those challenges if you'd be using multiple sites ... I'm not sure it's possible ... So i18n (and other modules related to it) is the way to go.
PS: Multi language in D8 has become easier ... a bit.
Comment: Hey @herci merci for the feedback. Lucky you that you have time for trying both ways. I'd be interested in "ever" hearing what you ended up as a final decission. Also, 2 more translation related tips .... (1) you may want to add "Translation Management" to your things to check and (2) you'll have to decide between (the rather new) "entity translation" (since D7) and "node translation" (rather old, since at least D6), both of them have pros/cons. PS: let me know if you want me to expand my answer a bit about those 2 tips ...
Comment: You simply state that the best solution is X and making an "advertisement" of other posts you made. You aren't actually answering the question (How to decide ...)
Comment: Thanks a lot for the detailed answer. I haven't decided yet but I'm trying both two ways now. Actually, because there is a team of non technical editors, two separate site might be easier. The Drupal "translate" interface is not easy for non technical users. Thanks again :)
Comment: Thanks @Pierre, I'm still trying the both ways and will tell if I need more help :)
Answer: I'd take into consideration who will maintain the content of the page. I've done some multilanguage sites already and i have to admit, that not every content editor will follow the sometimes hilarious ways of managing multilingual content in drupal. I'd say the work of maintaining two complex single sites can easily equal the effort that has to go into making a site truely multilingual.
Comment: Hehe, you did understand me quite right, according to your smiley. It really depends. If I had to decide it AND if I'm the only one maintaining the sites I'd go for two different single sites (maybe even a multisite installation). If there is a team of non technical editors I'd tend to a multilingual site (even if that means a higher effort to educate the editors).
Comment: Thanks for the answer. Does the last sentence of your anwer _(I'd say the work of maintaining two complex single sites can easily equal the effort that has to go into making a site truely multilingual.)_ mean go with two complex single site or vice verse? :)
Comment: How do you handle the `` headers with separate sites?
Comment: That's an interesting question indeed. Until now there was no need for international seo, but this will be an issue sometime in the future. Thanks for pointing this out...
Answer: I have bit of experience working with Drupal multilingual sites.
Another thing to consider if you are using 'entity reference' and referencing nodes to other nodes. This will be bit complex to non technical users.
As the referencing child nodes has to have the same language as the parent node.
as an example: if you have a main/parent product in "Turkish" and you have referenced products(nodes) as "related products", Those has be translated to Turkish as well. you cannot link a  node in "English" to another node in "Turkish".
since it's only for one language that's fine. assuming that you can give a training session to them.
Other than that you'll be good to go with "internationalization"
it will give a translate tab in the node/edit when you activate it.
you will just need to create translations for those.
for blocks you need to activate the block languages module
then you'll be able to translate the blocks too.
Menu translation will be done by activating the "Menu translation(i18n_menu)" www.drupal.org/node/1113982 module.
views translation can be done by activating the "Views translation (i18nviews)" www.drupal.org/node/2326037 can be filtered using "current users language" in filters in the view.
There won't be any need to change the template files. It will use the same template that is in currently use.
Hope this helped too.
Cheers!
Answer: The main thing to consider when asking to solve multi lingual issue by creating multiple instances of the same site (same code base but different database) or using Drupal's multi lingual system is:

Is it important that content is linked, so you can find same article in different languages?
Is the editorial team split into regional teams, where one or more can't be trusted?

Why select Multi Lingual (ML) solution
The main thing you gain by setting up Drupal to be ML, is that all content is available in a single site. You can provide information about which languages the content is translated into and links to see the translated content. You only need a single login. Solving the ML issue is only something you need to solve once. Create a new language site will always take a certain amount of time depending on complex your Drupal site is.
Why select separate installation solution
On the other hand creating separate sites allow you manage the content better. I have a few times, tried being asked to limit the access of certain users, so they only could make changes on the local site. For big companies where branding and control can be important, solving this issue can be quite troublesome. Implementing custom access control on nodes based on language is doable, but once the site start using modules like panels, it's not really possible to manage user control.
Having the content on separate sites instantly solve these issues.
Conclusion
Overall most people will benefit from using ML solution. With entity translation handling ML in Drupal 7 isn't that bad. There are many blog posts and experiences all over the internet that can help you in most situations. I've seen separate site route work well in some situations. Usually site that doesn't have a lot of content, like e-commerce sites are viable for this.
Note that no matter which solution you end up choosing, there will be pains you have to overcome. What you need to do, is pick the solution where these pains are manageable and acceptable for stakeholders.


Adding a column to a DataGrid after the ItemSource is set / adding a field to every row of a DataGrid after the ItemSource is set

Question: So...
I have a Class with the following properties:
 public class TblCity
    {
        public int id { get; set; }

        public string Name { get; set; }

        public int CountryId { get; set; }
    }

I also have a DataGrid whose ItemsSource is set to a generic list of
the same class ( List<TblCity> )
All works good and all, the DataGrid automatically generates the columns according to the public properties in the Class,
This is where my brain gives up:
I want to add a CheckBox to every row of the datagrid.
ambitious isn't it?
What I can't afford: Adding a CheckBox as a property the Classes
Or creating a copy Class that Derives from the original, and has an extra CheckBox
(There are many of them. too many.)
What I have Tried: this abomination:
class DataGridModel<T> : T
    {
        public CheckBox checkBox { get; set; }
    }

Which as you might know, Does not work.
Sorry if this is a dumb question to unreachable levels of idiocy. I'm still learning.
Thanks in advance.
Answer: have you tried adding a boolean field to the class? After that, from where you want to change that field with your checkbox, just write some code to change the boolean field with the checkbox. This seems reasonable?
Comment: Unfortunately, as I said above, I can't really meddle with the class itself. The Classes are DataModels, changing them would make serializing and deserializing pretty difficult. Thanks for your answer though!


Is there a word for when key signatures change every few bars, similar to how time signatures can change every few bars -> "multi-metric"?

Question: Changing key signatures/keys but NOT SIMULTANEOUSLY
Comment: Contemporary practice for music that changes key constantly is not to write a key signature at all and just use accidentals everywhere.
Comment: For rhythm, the term would be [mixed meter](https://www.scales-chords.com/scalefinder.php); ["polymetric"](https://music.stackexchange.com/questions/10488/polymeter-vs-polyrhythm) means that multiple different time signatures are occurring simultaneously.
Comment: What piece of music does this?
Comment: Can you clarify? Are you asking for a term meaning that the key signature changes, but the actual key at the time does not? And I suggest removing "multi-metric", which seems to confuse the question further.
Comment: Sorry about that. I mean when a piece might change its key signature every few bars, similar to how the time signature may change every few bars. For rhythm, I believe this would be called multi-metric/poly-metric
Comment: I stand corrected: [multimetric](https://en.wiktionary.org/wiki/multimetric)
Comment: Agree with @PiedPiper -- as a performer, I find it much easier to work with accidentals unless the key change is going to persist for at least a couple desks.
Answer: There's no specific term for the fact of changing key signatures frequently (but see ViviRukisha's answer), but in light of the term multi-metric I see no reason not to coin the term multi-tonal or multi-modulatory. The latter might be better to avoid confusion with polytonal.
Comment: +1 for multi-tonal, and I would mention that it is not necessary to have key signatures written explicitly in order for a piece to be multi-tonal. Many jazz standards (extreme example: Giant Steps) are multi-tonal, but they don't bother specifying all the different key signatures: you have the chords and the melody and all the accidentals, and the different tonal centers and modulations are easily inferred from that.
Comment: Yes, something like multi-modulatory seems good
Answer: No there isn't, and I counsel against inventing one!  The distinction between 'multi', 'poly' or any other prefix you could come up with won't be immediately clear, and there will be confusion between your intended meaning and SIMULTANEOUSLY multiple keys.
If you want to describe this, do it in plain English.  Something like 'This passage has frequent changes of key signature'.
Answer: Yes. This is often referred to as  Modulation. However, it is not mandatory for a change in key signature when it comes to modulation. This can be achieved by the use of accidentals as well.


Using puppet to distribute Apache SSL certificates

Question: Is it a bad idea to distribute Apache SSL certificates via puppet? Is it insecure to do it this way? Is there a better way to distribute SSL certs to lots of servers?
Answer: I've seen this done before. It's only as insecure as your network/destination servers make it. Only you know that. Are you transmitting these over a secure network? If so, you SHOULD be fine. But we can't possibly guarantee that. Why not write a simple ssh script to distribute them? That's what I would recommend. Or write a script to download the cert from a central server and distribute the script via puppet. Just an idea.
EDIT: Since there is some confusion. I'm NOT saying Puppet/SSH are anymore secure. But if you're worried about unauthorized access, ensure everything is secure. This is most easily done with a custom SSH script YOU distribute.
Comment: Why would SSH be any more secure?  Puppet uses SSL for the transport, and RSA keys to authenticate a puppet client.  Puppet should be as secure as SSH.  Puppet IS a tool to download the cert from a central server.  That is exactly its function.   If you already have puppet in place, building another system to do the same thing doesn't seem like a good idea.
Comment: @Publiccert Puppet agent/master communication uses client certificate authentication; it won't feed manifest or file data to unauthenticated clients unless it's been configured to do so.
Comment: The puppet master isn't hosted on the same ISP/datacenter, so transmission is over the internet, but puppet does use SSL. I just don't know how hard it would be someone to request the certs from my puppet master without me knowing.
Comment: @Zoredache I think you misinterpreted what I said.
Comment: Are there any authorization rules applied to the stored SSL certificates, or can ANY client with a valid client certificate fetch ANY stored SSL certificate or other key/password?
Answer: This is too old but I'm going to answer anyway.
You can encrypt private keys using eyaml and let puppet do the install. This way you are sure that key data is encrypted even on hiera and it is safely delivered to the node while agent is run.


How do you train a model on a dataset that's unlabeled but we know the percentage of every class?

Question: Say we have a data set that's pictures of apples and oranges, but we don't know which is which. However the data is organized in such a way, that for some groups of images we know how many of them are apples and how many are oranges. For example the dataset could consist of 1000 groups of images, each group contains 100 images and a label that's basically the percentage of the images in this group that are apples but not which ones are they.
Is it possible to train a model to classify this data? If so what's the technique called? How error tolerant is it (if the group labels are only an estimate and not precise)? Is there any recommended literature on this topic?
Answer: This is sometimes called learning from label proportions in machine learning, falling into the realm of weakly supervised classification.
A machine learning paper that establishes one variant of the problem, along with some algorithms and some theoretical guarantees, is

Quadrianto, Smola, Caetano, and Le. Estimating Labels from Label Proportions. JMLR 2009.

There's been a decent amount of work on it since; check out papers citing that one.
A closely related problem, with a long history in statistics and political science, is ecological inference. This sometimes refers to inferring about subgroups, rather than individuals: given labels on how the total population of counties voted, how did different demographic groups vote? But it's also sometimes used to refer to individuals.


How would I go about creating the summation formula

Question:
Consider the following program segment, where i, j , k, n, and counter are integer variables and the value of n (a positive integer) is set prior to this segment.

counter := 0
for i := 1 to n do
for j := 1 to i do
for k : = 1 to j do
counter := counter + 1

We shall determine, in two different ways, the number of times the statement

counter := counter + 1

is executed. (This is also the value of counter after execution of the program segment.) From the result in Example 1.39, we know that the statement is executed $$\binom{n+3-1}{3}=\binom{n+2}{3}$$ times. For a fixed value of i, the for loops involving j and k result in $$\binom{i+1}{2}$$ executions of the counter increment statement. Consequently, $$\binom{n+2}{3}= \sum_{i=1}^n \binom{i+1}{2}$$ Use this result to obtain a summation formula for
$$1^2 + 2^2 + 3^2 + .. + n^2 =  \sum_{i=1}^n i^2$$

I'm trying to figure it out, but I just don't know how to get to the answer.
Comment: I dont understood absolutely nothing... Maybe this is not a mathematical question, morelike a programming one.
Comment: See also [Faulhaber/Bernoulli](https://en.wikipedia.org/wiki/Faulhaber%27s_formula)
Answer: It is clearly
$$\sum_{i=1}^n\sum_{j=1}^i\sum_{k=1}^j 1=\sum_{i=1}^n\sum_{j=1}^i j=\sum_{i=1}^n\frac{i(i+1)}{2}\\=\frac{1}{2}\left(\sum_{i=1}^n i^2 +\sum_{i=1}^n i\right)=\frac{1}{2}\left(\frac{n(n+1)(2n+1)}{6} +\frac{n(n+1)}{2}\right)$$
Comment: Thanks for the answer! There is only one step that I don't get. How did you do this step:

$$\sum_{i=1}^n\binom{i+1}{2} = \sum_{i=1}^n\frac{i(i+1)}{2}\\$$
Comment: I'm not sure about your notation $\sum_{i=1}^n\binom{i+1}{2}$, but I got $\frac{i(i+1)}{2}$ from $\sum_{j=1}^i j$. This is essentially $1+2+\cdots i$.
Comment: @user35774 note that the binomial coefficient $\binom{i+1}{2}$ equals $\frac{(i+1)!}{(i + 1 - 2)!2!} = \frac{(i-1)!\cdot i \cdot (i+1)}{(i -1)!2!} = \frac{i(i+1)}{2}$.


How to access my site as http://www.blah.com and http://blah.com

Question: I own a domain on GoDaddy, let's say blah.com. And i point an A record @ to my server IP, let's say 18.104.22.168.
The GoDaddy panel already have a CNAME record www wich points to @.
I suppose that under this configuration, i could acces blah.com as http://blah.com and http://www.blah.com.
However, only http://www.blah.com works ok, because http://blah.com shows me a GoDaddy page.
What aim doing wrong?.
Answer: Are they also hosting your server? You have to properly configure your web server to handle each request accordingly. You got the DNS part correct. Now configure your webserver.
Comment: No they don't. I will try configuring the apache Virtual Host section.


Java - método para verificar se uma String contém determinado caractere

Question: Estou com um problema neste método. Ao que me parece, sempre que o tento usar com alguma String, obtenho false para o valor de a, mesmo que a String contenha esses três caracteres. Alguém me pode dizer o que há de errado aqui?
 public static boolean VerSeTemLetras (String qqString){
    boolean a;
    int tem_a;
    int tem_b;
    int tem_c;

    if (qqString.contains("a")) {
        tem_a = 1;
    } else {
        tem_a = 0;
    }
    if (qqString.contains("b")) {
        tem_b = 1;
    } else {
        tem_b = 0;
    }
    if (qqString.contains("c")) {
        tem_c = 1;
    } else {
        tem_c = 0;
    }

    a = ((tem_a + tem_b + tem_c) > 2 );

    return a;
}

Comment: O propósito é saber se a `String` tem `a`, `b` ***e*** `c` ou é para saber se contém `a`, `b` ***ou*** `c`?
Comment: Da para melhorar bastante seu código, o que você quer saber exatamente?
Answer: Acho que isso é melhor
public static boolean VerSeTemLetras (String qqString){
    return qqString.contains("a") && qqString.contains("b") && qqString.contains("c");
}

Answer: public static boolean verSeTemAeBeC(String qqString) {
    return qqString.contains("a") && qqString.contains("b") && qqString.contains("c");
}

public static boolean verSeTemAouBouC(String qqString) {
    return qqString.contains("a") || qqString.contains("b") || qqString.contains("c");
}


Complex integral with residuals

Question: questions for complex integrals

For $R>0$ let $\Gamma_R$ be the circle {$z\in \mathbb{C} : \lvert z \rvert =R $} equipped with counterclockwise direction. Figure out for which $R>0$, the function $f(z)=\frac{1}{\sin^2(z)}$ is continuous on $\Gamma_R$ and evaluate $$\int\limits_{\Gamma_R}\frac{dz}{\sin^2(z)}$$
for every such $R$ (the answer may depend on $R$)
Evaluate $\int\limits_{0}^{\infty}\frac{\cos{x}}{1+x^6}dx$

I have no idea where to start from for any of the questions above, any help to get me started is greatly appreciated.
Comment: Welcome to MSE! You'll receive a better response here if you (1) write your question on the site using MathJax: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference, and (2) show your own thoughts/work on the question.
Comment: Start at the beginning.  Where is the function $1/\sin^2 z$ continuous?  For which $R$ does that contour consist only of such points of continuity?
Comment: i tried using Euler's formula and derived that for $sin(z)=\frac{e^{iz}-e^-{iz}}{2i}$ is that how i should start the question?
Answer: Function $\sin{z}$ has zeros at $k\cdot \pi, k \in \mathbb{Z}$ and same applies to $\sin^2{z}$. As a result, function $\frac{1}{\sin^2{z}}$ has singularities at $k\cdot \pi, k \in \mathbb{Z}$. These singularities are poles of order $2$ since (using this fact)
$$\lim\limits_{z\rightarrow k\pi}\frac{(z-k\pi)^2}{\sin^2{z}}=\lim\limits_{z-k\pi\rightarrow 0}\frac{(z-k\pi)^2}{\sin^2{(z-k\pi)}}=\frac{1}{\lim\limits_{z-k\pi\rightarrow 0}\frac{\sin^2{(z-k\pi)}}{(z-k\pi)^2}}=1$$
and
$$\lim\limits_{z\rightarrow k\pi}\frac{(z-k\pi)^3}{\sin^2{z}}=0$$
Any $\Gamma_R$ where $R=k\pi, k\in\mathbb{N}\setminus\{0\}$ is of the form $\Gamma_R=\left\{k\pi e^{it}\mid 0\leq t < 2\pi\right\}$ and will contain $k\pi$ and $-k\pi$ where $\frac{1}{\sin^2{z}}$ is not continuous. In all the other cases ($R\ne k\pi, k\in\mathbb{N}\setminus\{0\}$), $\frac{1}{\sin^2{z}}$  is continuous on $\Gamma_R$. To calculate the integral on such a contour, residue theorem can be applied
$$\int\limits_{\Gamma_R}\frac{1}{\sin^2{z}}dz=2\pi i\sum\limits_{|k|<\frac{R}{\pi}\\ k\in \mathbb{Z}} \text{Res}\left(\frac{1}{\sin^2{z}}, k\pi\right)$$
We already know that the pole order at $k\pi$ is $2$, so calculating the residues shouldn't be a problem
$$\text{Res}\left(\frac{1}{\sin^2{z}},k\pi\right)=\lim\limits_{z\rightarrow k\pi}\left(\frac{(z-k\pi)^2}{\sin^2{z}}\right)'=\\
\lim\limits_{z\rightarrow k\pi}\left(\frac{2(z-k\pi)\sin^2{z}-2(z-k\pi)^2\sin{z}\cos{z}}{\sin^4{z}}\right)=\\
\lim\limits_{z\rightarrow k\pi}\left(\frac{2(z-k\pi)\left(\sin{z}-(z-k\pi)\cos{z}\right)}{\sin^3{z}}\right)\overset{\text{L'Hospital}}{=}\\
\lim\limits_{z\rightarrow k\pi}\left(\frac{2((z-k\pi)^2 \sin{z}-(z-k\pi) \cos{z} + \sin{z})}{3\sin^2{z}\cos{z}}\right)\overset{\text{L'Hospital}}{=}\\
\lim\limits_{z\rightarrow k\pi}\left(\frac{2(z-k\pi)\left((z-k\pi)\cos{z}+ 3\sin{z}\right) }{-\frac{3}{4}\left(\sin{z}-3\sin{3z}\right)}\right)\overset{\text{L'Hospital}}{=}\\
\lim\limits_{z\rightarrow k\pi}\left(\frac{ -2\left(\left(z^2-2 k\pi z-3+(k\pi)^2\right)\sin{z}-5(z-k\pi)\cos{z}\right) }{-\frac{3}{4}\left(\cos{z}-9\cos{3z}\right)}\right)=\\
\frac{0}{6\cdot (-1)^k}=0$$
As a result $$\int\limits_{\Gamma_R}\frac{1}{\sin^2{z}}dz=0$$

For the second one, function $\frac{\cos{x}}{1+x^6}$ is even, as a result
$$\int\limits_{0}^{\infty}\frac{\cos{x}}{1+x^6}dx= \lim\limits_{R\rightarrow\infty} \int\limits_{0}^{R}\frac{\cos{x}}{1+x^6}dx=\frac{1}{2} \lim\limits_{R\rightarrow\infty} \int\limits_{-R}^{R}\frac{\cos{x}}{1+x^6}dx=...$$
Now $\frac{\sin{x}}{1+x^6}$ is odd and as a result $\int\limits_{-R}^{R}\frac{\sin{x}}{1+x^6}dx=0$, thus
$$...=\frac{1}{2} \lim\limits_{R\rightarrow\infty} \int\limits_{-R}^{R}\frac{\cos{x}+i\sin{x}}{1+x^6}dx=\frac{1}{2} \lim\limits_{R\rightarrow\infty} \int\limits_{-R}^{R}\frac{e^{ix}}{1+x^6}dx=...$$
Now we will look at this contour

$$...=\frac{1}{2} \lim\limits_{R\rightarrow\infty} \left(\int\limits_{C_R}\frac{e^{iz}}{1+z^6}dz - \int\limits_{\Gamma_R}\frac{e^{iz}}{1+z^6}dz \right)=\\
\frac{1}{2} \lim\limits_{R\rightarrow\infty} \left(\int\limits_{C_R}\frac{e^{iz}}{(z-i)(z+i)\left(z-\frac{\sqrt{3}}{2}-\frac{i}{2}\right)\left(z+\frac{\sqrt{3}}{2}+\frac{i}{2}\right)\left(z-\frac{\sqrt{3}}{2}+\frac{i}{2}\right)\left(z+\frac{\sqrt{3}}{2}-\frac{i}{2}\right)}dz \\
- \int\limits_{\Gamma_R}\frac{e^{iz}}{1+z^6}dz \right)=
\frac{1}{2} \lim\limits_{R\rightarrow\infty} \left(\text{Res}\left(\frac{e^{iz}}{1+z^6},i\right)+
\text{Res}\left(\frac{e^{iz}}{1+z^6},\frac{\sqrt{3}}{2}+\frac{i}{2}\right)+\\
\text{Res}\left(\frac{e^{iz}}{1+z^6},-\frac{\sqrt{3}}{2}+\frac{i}{2}\right)
- \int\limits_{\Gamma_R}\frac{e^{iz}}{1+z^6}dz \right)=\\
\frac{1}{2}\left(\text{Res}\left(\frac{e^{iz}}{1+z^6},i\right)+
\text{Res}\left(\frac{e^{iz}}{1+z^6},\frac{\sqrt{3}}{2}+\frac{i}{2}\right)+
\text{Res}\left(\frac{e^{iz}}{1+z^6},-\frac{\sqrt{3}}{2}+\frac{i}{2}\right)\right)$$
It remains to show that
$$\lim\limits_{R\rightarrow\infty} \int\limits_{\Gamma_R}\frac{e^{iz}}{1+z^6}dz =0$$
which is
$$\left|\int\limits_{\Gamma_R}\frac{e^{iz}}{1+z^6}dz\right| \leq \text{length}(\Gamma_R) \max\limits_{z \in \Gamma_R}\left|\frac{e^{iz}}{1+z^6}\right|=\pi R \max\limits_{z \in \Gamma_R}\frac{|e^{iz}|}{\left|1+z^6\right|}\leq \pi R \max\limits_{z \in \Gamma_R}\frac{|e^{i(x+iy)}|}{\left||z^6|-|1|\right|}\leq\\
\pi R \frac{e^{-y}}{\left|R^6-1\right|}\leq \frac{\pi R}{R^6-1} \rightarrow 0, R \rightarrow \infty$$
I will leave you to finish the calculations of residues.

Complex integral with residuals


How to use if statement in Accessor/Mutator in Laravel 9?

Question: On Laravel version 9, I'm trying to use Accessor with an if condition inside; to put it simply, I need to use the Accessor for my application's postImage attribute, only if the path of the image does not start with the 'http://' or 'https://' terms, (so that the image sources coming from another website would be displayed correctly with no manipulation in their paths) but nowhere can I find the right way of doing it in terms of the new syntax of Laravel 9 Accessor (and Mutator).
The postImage attribute Accessor in my Post model (I know it's wrong but I'm trying to find the right way of doing it and that's the point):
protected function postImage():Attribute {
    return Attribute::make(
        get: fn ($value) =>
        if (strpos($value, 'https://') !== FALSE || strpos($value, 'http://') !== FALSE) {
        return $value;
        }
        return asset('storage/' . $value);
    );
}

Can you please help me with the new suitable approach to what I'm trying to do?
Answer: Use the other function format (with return)
protected function postImage():Attribute {
    return Attribute::make(
        get: function ($value) {
            if (strpos($value, 'https://') !== FALSE || strpos($value, 'http://') !== FALSE) {
                return $value;
            }
            return asset('storage/' . $value);
        }
    );
}

Or use the new format correctly (with value, no return)
protected function postImage():Attribute {
    return Attribute::make(
        get: fn ($value) => (strpos($value, 'https://') !== FALSE || strpos($value, 'http://') !== FALSE) ? $value : asset('storage/' . $value),
    );
}

Comment: the second one worked perfectly to me, thanks! `[+1]`


Using Pedal For Two Part Writing

Question: I am working on a piece for solo jazz piano that includes the following two part writing for the right hand.

It is possible for me to play the sequence beginning on beat 3 without pedaling by holding the lower voice with fingers 1 and 2 while the melody is played with fingers 5-4-3-4. However, does the arranger expect one to sustain the lower voice with pedal to free up the hand to play the melody more smoothly?
There are no pedal markings in this piece, but the book it's included in does include some pedal markings for arpeggiated sections in other pieces.
Generally speaking, is it appropriate to use the pedal (instead of the fingers alone) to sustain a voice in two part writing if you feel it allows you to better phrase the melody? This pattern of a half note voice simultaneously occurring with four sequential eighth notes is fairly common (but often less cumbersome than the example I provided) in the book I'm working through.
Comment: In general? Yes. During a descending chromatic melody? Not really, no. That's probably the *least* appropriate context for technical (as opposed to sound-enhancing) pedalling.
Comment: Thank you all for your input. It seems that I just need more practice playing the chromatic line while sustaining the C# and F with the fingers alone.
Comment: Even more generally, is any decision to sustain a note/chord solely with the pedal (where the fingers leave contact with keys immediately after the initial attack) considered to have successfully captured whatever duration is notated for the note/chord?
Comment: Some concrete advice: I would finger that passage as 5-4-3-3, or even 4-5-4-5.  More general advice: nobody really cares if you have "successfully captured whatever duration is notated," it only matters whether it sounds good.
Answer: This is quite playable legato with no pedal.  Playing it over, I found myself just using a dab of pedal half way through the bar, to faciliatate the change of hand position.  But it's just laziness really.  It would be perfectly playable on organ, with no possibility of sustain.
Answer: Yes, you can use pedal per your own judgment if the composer wasn't explicit about it. I would avoid pedal if it would cause the melodic line to get muddy, e.g. sustaining the chromatic line in your example would cause quite a sonic mess. On the other hand, Some  pianos have a separate pedal that only sustains held notes or lower notes, so it could work for this passage.
Comment: I submit that you can use the pedal per your own judgment even if the composer *was* explicit about it. :) However, it's also important to look at composers' pedal markings because they can contain beautiful ideas that you would otherwise miss.
Answer: I'll speak even more generally to your question. It is appropriate to do anything you want if you feel that it allows you to better phrase the melody.
I sight read this bit, cycling from the end to the beginning a few times, to see how I used the pedal. Tempo makes a big difference in the pedaling choices you have available; for example, if you play it slowly, you can pump the pedal on each 8th note if you want to.
Personally, playing at about 120 to the quarter note, I like a bit of pedal on the two stressed beats, although I don't have much trouble holding out the half notes while playing the upper voice. The only place I use the pedal to connect notes is between the D and C#, taking both notes with the thumb. Also, I finger the upper voice 3,235434.
Keep in mind that you can use the pedal to create a better legato if that's what you want, but more importantly, it colors your music differently. If you think of the pedal only as a way to connect notes, then you need to give some thought to how the coloristic aspects of the pedal affect phrasing.
Answer: I agree with BobRodes that whatever allows the best phrasing is the right approach.
My personal approach would be to finger the passage as 1 & 2 on the C# & F, 3/4/5 on the eighth notes.  Obviously the challenge to mastering this is to make the eighth notes as smooth as possible.
Once I got comfortable playing this without the pedal I'd throw the pedal in without changing the fingering) to see if it adds anything to the phrase. If you keep the same fingering the only significant change the pedal adds is to smear the eighth notes.  You'll have to decide if this spoils the affect of the passage and the harmony.  Good luck!

Using Pedal For Two Part Writing


tell datatable to use custom button for file export

Question: I have a working html/js datatable example jsfiddle that has two working buttons for exporting data; excel and csv. I declare my datatable like so:
<code>$('#example').DataTable( {
    dom: 'Bfrtip',
    columns: [
        { data: 'name' },
        { data: 'surname' },
        { data: 'position' },
        { data: 'office' },
        { data: 'salary' }
    ],
    buttons: [
                  {
                      extend: 'excelHtml5',
                      text: 'excel',
                      exportOptions: {  modifier: {  page: 'current' }  }
                  },
                  {
                      extend: 'csvHtml5',
                      text: 'csv',
                      exportOptions: {  modifier: {  page: 'current' }  }
                  }
              ]
} );
</code>
Which cases the two default buttons to appear. In my html I have two custom button elements I want to connect to my datatable:
<code><button id='excelExport'>click this to export excel</button><button id='csvExport'>click this to export csv</button>
</code>

So that when I click my 'excelExport' button, it triggers the datatable export excel. I'm trying to get both custom buttons working so I can place them in more specific places with different styling, instead of using the table's default export buttons.
How can I extend my datatable export excel function to work with my custom button with id=excelExport ?
I've done something similar in the past with using a custom search bar for my table's search. To do so I had to extend the search function like so:
<code> //set datatable to use custom search box
$('#bottomTableSearch').on('keyup change', function () {
    myBrandGapsTable.search(this.value).draw();
});
</code>
Is there someway I can do the same for my id=excelExport button? Like:
<code>//set datatable to use custom excel export button
$('#excelExport ').on('click', function () {
    myBrandGapsTable.export(excel); //???? pseudocode, trying to get this concept working
});
</code>
Jsfiddle with my example is here:
https://jsfiddle.net/martinradio/c0wezht7/12/
Answer: You can just trigger click events of the datatables buttons like this:
<code> $("#excelExport").on("click", function() {
    $(".buttons-excel").trigger("click");
 });
 $("#csvExport").on("click", function() {
    $(".buttons-csv").trigger("click");
 });
</code>
Comment: thanks for the tip, but what is the buttons aren't visible or not rendered and what about print?
Comment: You could extend the class with `sr-only`, e.g. `buttons: [{extend: 'csvHtml5', className: 'sr-only'}]` in your datatable.


How to fix packaging error in Aide (mobile IDE)?

Question: I am creating android application using Aide (mobile ide).
My project has no errors but when I run the app, during building APK it displays an error dialog with message :
'Packaging error: com.blankj.utilcode.util.ReflectUtil sSReflectException: java.lang.refle ct.InvocationTargetException
'.
This has happened when I added these two libraries in my project:
Dexter library : to handle runtime permission in android
KingsMentor library : to scan barcode or QR code
Please help me how do I fix it?
Comment: Please add more details: error codes, error messages, etc.
Comment: @p-syche I have edited you can check.
Answer: Now I know where the actual bug is.
If the same happens to you then kindly note that it is due to the 3rd party library that you are using in your project.
So the solution is to remove that library from your project and try another one , moreover try to code from scratch for that task if possible instead of using such libraries.
It happens because those libraries use another library or libraries.
Hope it helps you.
Happy coding :)


How to programatically add WCF data service(ODATA) reference in silverlight

Question: I have a Oata i.e., WCF data service running.Is it possible for silverlight client to programatically add the reference of that service with only the URL of the service?
Currently I add the service reference by right clicking the project,Add service reference,Discover and then add the service reference.How can I do it programatically?
Answer: It's not possible for several reasons, couple of them here:

Add Service Reference in Visual Studio generates code (the client side classes for the entities and other types exposed by the service). Silverlight doesn't have the necessary libraries to handle this task reasonably easy (lot of code would have to be rewritten/ported to silverlight for this).
In order for your code to actually use it, you would need to compile the generated code. There's no way to do this in SL, since it doesn't contain any compilers.
It's not very practicle to actual use, since your code using this would have to be able to deal with types it doesn't know up-front (the types generated by the code above). So you would have to use lot of reflection or other similar tricks.

If you want to write a client application which can access arbitrary OData service I would suggest you look at Microsoft.Data.OData.dll. It's part of the recent CTP: http://blogs.msdn.com/b/astoriateam/archive/2011/10/13/announcing-wcf-data-services-oct-2011-ctp-for-net-4-and-silverlight-4.aspx
And it implements readers and writers for OData format (something like XmlReader/XmlWriter, but for OData). In particular it doesn't require the knowledge of the service up-front, it can read any OData response.
Answer: You should do the following:
<code>BasicHttpBinding binding = new BasicHttpBinding();
var endpoint = new EndpointAddress("<Yours Endpoint Address>");
var factory = new ChannelFactory<IYourServiceContract>(basicHttpBinding, endpointAddress);
</code>
Hope this will help.
Comment: But this is for normal WCF service if i am not wrong.Is it the same way for WCF data service also?


Web iframe videos start automatically

Question: I have a website http://emuonline.emu.edu.tr/
In this site, there is no flag and TR top right side. When I click the link it goes to Turkish site but when the page loads, all videos play automatically. I do not want to play them automatically.
Answer: Remove the autoplay attribute from the video tag.
<video controls="" autoplay="" name="media"><source src="http://emuonline.emu.edu.tr/videos/Emu_Egitim_Videosu_Moodle.mp4" type="video/mp4"></video>

Comment: There is no autoplay and i do not use video tags. These videos are in the iframes.
Answer: You need to remove the autoplay attribute
<video src="example.mp4" controls="controls" autoplay="autoplay">

Comment: There is no autoplay and i do not use video tags. These videos are in the iframes.
Comment: You can try this -

Otherwise it is not possible.

Web iframe videos start automatically


Probability for sum of events greater than 1

Question: When two events, A and B, are mutually exclusive, the probability that A or B will occur is the sum of the probability of each event.
The same thing we could say about sum of A, B and C.
In several articles I found another definition of the sum:
When two events, A and B, are mutually exclusive, the probability that A or B or A and B will occur is the sum of the probability of each event.
First question: Is second definition correct?
For second question let imagine the following example:
Probability of getting tail of the coin is 1/2. Person throws coin 3 times.

Event A: get tail at first throw, P(A) = 1/2
Event B: get tail at second throw, P(B) = 1/2
Event C: get tail at third throw, P(C) = 1/2

Then probability of getting tail at first or second or third throw is:
P(A + B + C) = 1/2 + 1/2 + 1/2 = 3/2, but 3/2 > 1
But as we know probability P of event is always 0 <= P <= 1
Second question: Where am I wrong?
Comment: Check out the [inclusion-exclusion principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle#In_probability)
Comment: Addition of probabilities is only correct if at most one event can happen. This is not the case here.
Comment: @Peter Could you also said which of the sum definitions is correct?
Comment: For two events , you have $$P(A\cup B)=P(A)+P(B)-P(A\cap B)$$ To get the formula for three events just use $P(A\cup B\cup C)=P((A\cup B)\cup C)$
Comment: In your case, it is much easier to calculate the probability that no throw is tails (it is $\frac{1}{8}$). So, the desired probability is $1-\frac{1}{8}=\frac{7}{8}$.
Comment: @Peter Thank you, but I'm talking about sum definition. In words: when two events, A and B, are mutually exclusive, the probability that A or B or **A and B** will occur is the sum of the probability of each event. Is bold part is correct?
Comment: @NoNameYp Yes, this is the correct definition of "or".
Answer: First question:  Yes, the definition is correct. If $A$ and $B$ are mutually exclusive, then: $$P(A \cap B)=0$$ and: $$P(A \cup B) = P(A) + P(B)$$ and so indeed we have that: $$P(A \cup B \cup (A \cap B))=P(A) + P(B)$$
Second question: Your events are not mutually exclusive, and so you cannot add up the probabilities: you can only use $$P(A \cup B) = P(A) + P(B)$$ when $A$ and $B$ are mutually exclusive. And your events are not mutually exclusive because any two of them can happen in the same scenario. In fact, they can all three happen: you throw a tail for all three tosses.
Comment: Thank you for your explanation! Then What formula should I use to calculate probability of getting at least one tail from my original question?
Comment: @NoNameYp Getting at least one tail is the same as not getting $0$ tails. So, calculate the probability of getting $0$ tails, and subtract that from $1$.  Since $A$, $B$, and $C$ are *independent* (that is, geting a tail on the first toss does not effect the probability of getting a tail on the second or third toss, etc.), you have that $P(A \cap B \cap C) = P(A) \cdot P(B) \cdot P(C)$
Comment: One more question: When two events, A and B, are independent, the probability that A or B  will occur is P(A+B) = ??
Comment: @NoNameYp It is *always* true that $P(A \cup B) = P(A) + P(B)-P(A\cap B)$, so when $A$ and $B$ are independent, we have $P(A \cup B) = P(A) + P(B)-P(A)\cdot P(B)$
Comment: I'm really sorry, I meant word "dependent". So the right question will be: When two events, A and B, are dependent, the probability that A or B will occur is P(A+B) = ??
Comment: @NoNameYp Then we have $P(A \cup B) = P(A) + P(B) -P(A \cap B)$ ... for that is *always* true, whether $A$ and $B$ are dependent or independent, and whether they are mutually exclusive or not.
Comment: The very last question: according to all your answers I suppose that independent and not mutually exclusive events are the same thing. Is it true?
Comment: @NoNameYp Well, if events are mutually exclusive they are dependent ... unless both have a probability of $0$. So, if independent, then not mutually exclusive. But, not being mutually exclusive does not mean independent. Indeed, any event is not mutually exclusive with itself, but certainly not independent from itself. So no, they are not the same thing.


Is there a way to tell a browser to not cache a particular custom page?

Question: A custom module I'm building has a page callback that creates and Inbox listing. When a user clicks an item in the inbox, another page callback displays the message, and it updates the database to record that it's been read.
The problem is that when the user presses Back, they get back to their local cache of the inbox which suggests it has not been read. If they reload, it's OK.
Is there a way (in hook_menu?) to flag that a page should not be cached/expires immediately?
Answer: If I understand your expectation correctly, it's less of a Drupal and more of a browser thing. When the user presses the Back button, if you don't want the browser to show a copy of the web page that it might already have, the Cache-Control header in your initial response must have no-store. Drupal by default, doesn't have this. You can confirm this by checking the definition of this function.
Simply overwriting the Cache-Control header seems to fix this on Opera 16, Firefox 23 and Chrome 30. However, on Safari 6, it doesn't. Turns out that it might be a known issue. So, we might have to turn to a Javascript hack for that.
In summary, including the snippet below in your page callback should do the trick for you. I have assumed Drupal 7.
// Add no-store in Cache-Control.
drupal_add_http_header(
  'Cache-Control',
  'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
  FALSE
);
// Hack for Safari
drupal_add_js('jQuery(window).unload(function(){});', array('type' => 'inline'));

This seems to work on a fresh Drupal 7.22 install for an authenticated user. If the page in question has been asked to be stored in the Drupal cache or if you are using a contributed module that also messes with the response headers, this might not work as is for you.
Useful References

https://stackoverflow.com/questions/866822/why-both-no-cache-and-no-store-should-be-used-in-http-response
http://madhatted.com/2013/6/16/you-do-not-understand-browser-history
https://developer.mozilla.org/en-US/docs/HTTP_Caching_FAQ
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
https://drupal.org/node/197786#comment-1055633
Comment: WOW! Thank you for providing such an amazing answer! And it works (always a bonus). Apols that it's officially not a drupal thing, hope it will be still useful to others as a question.
Comment: I have a similar issue but more in general for any page. Where should I put the above code to make pages not cached by the browser?
Answer: To avoid particular page being cached, you may try either of the following:

Add the following in page callback function of hook_menu:

drupal_page_is_cacheable(FALSE);

drupal_page_is_cacheable(): Determines the cache ability of the current page. Set it to FALSE if you want to disable caching for that page.
Use the cacheexclude module: This module provides a simple way to exclude certain pages from being cached. Sometimes you want all pages to be cached for anonymous users except for one or two pages that have dynamic or random or rotating content. If those pages are cached, the dynamic parts cease to be dynamic. This module allows an administrator to selectively exclude certain paths from being cached so that dynamic content is actually dynamic.

If you want to disable the cache for particular page than you try the cacheexclude module that provides the UI for adding pages that doesn't need to be cached.
Comment: I get `Notice: Use of undefined constant CACHE_DISABLED - assumed 'CACHE_DISABLED' `
Comment: Well, no error, but it doesn't fix the problem. I fear some horrible JS polling fix...
Comment: @artfulrobot Final update, Can you give this a try, I have check the above on my system and it seems to be working fine. Don't forget to clear the cache :)
Comment: Thanks Ankit for your perseverance! Still not quite working: I don't think *Drupal* is caching this page (I can always hit reload and get new results), but what I want is for Drupal to tell the browser that the page has expired so that when the user hits Back they don't get a stale page. Sorry, perhaps this is not possible? (which would explain the 2 anon 'close' requests! - wish people would be clear why they vote to close/vote down stuff...)
Comment: Both these methods can be used to skip the Drupal cache exclusively for one or more pages. The way I see it, the question has nothing to do with the Drupal cache. Hence, this might not be useful probably in this scenario.
Answer: Try changing the following global variable on the page load:
$GLOBALS['conf']['cache'] = FALSE;

but the problem is that you cannot use this in hook_boot(), because it's already too late to disable the caching. But there is a patch for it, see: Allow hook_boot() to disable page cache. Unless you'll add it into your settings file.
See also: Dynamic Cache and CacheExclude modules.


A WYSIWYG editor for only bold italic and list

Question: I was wondering if anyone had any advice on a cross browser WYSIWYG editor for producing only lsits, bold and italic. I don't want to use markdown because my users are not very computer friendly, and I also don't need them to have many controls.
My experience of WYSIWYG editors is that they are huge sledgehammers and I only want to crack open a small nut.
Any input would be much appreciated.
Comment: I guess that every WYSIWYG editor can be configured to produce only bold, italic and list. Question is - which can also filter input (pasting, d&d).
Comment: you can customize `Wysiwyg` editors to your requirements
Answer: UPDATE 11/11/2015:
The Wysihtml editor mentioned below now lives here: https://github.com/Voog/wysihtml
And since I mentioned Basecamp, they have a new rich text editor (written for Basecamp 3): https://github.com/basecamp/trix
Trix targets modern browsers (IE11+), so if you need older IE support, Wysihtml may still be a better choice.

OLD 7/11/2013:
This seems to be a reasonably modern one: https://github.com/xing/wysihtml5
I believe it's used on Basecamp.
Supported in IE8+, FF 3.5+, Safari 4+, Safari on iOS 5+, Opera 11+ and Chrome.
Simple Demo
Advanced Demo
Answer: Check out this line-control.You can also find the demo in github
Answer: Froala editor http://editor.froala.com is a very good choice. You can customize what buttons to use.
Works on all major browsers and on mobile too.
Answer: the simpliest editor ive found : http://nicedit.com/demos.php
Answer: TinyMCE can do this but you have to configure it.
go to http://www.tinymce.com/tryit/3_x/custom_toolbar_button.php and click the "View Source" tab
change this line:
theme_advanced_buttons1 : "mybutton,bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink",

into:
theme_advanced_buttons1 : "bold,italic,bullist,numlist",

Answer: TinyMCE allows to configure which options are available to format text. It's open source under LGPL
toolbar: "bold italic |"


What is the origin of the term 'on the hill' in pool?

Question: In pool it is often said by the commentators that a player/team is "on the hill", or if the match goes to the last rack: a "hill-hill game".
Where were these terms first coined, and by whom?

The term on the hill is used when a player/team is one rack away from winning their match, for example the commentator might say:

... and Joe Public wins the rack to put him on the hill in this race-to-5 match.

The term hill-hill is used when both players/teams are one rack away from winning the match, for example:

... and Team Europe win this rack to square up the scores, and take us to hill-hill.
Comment: The only definition of *on the hill* in combination with an author and date is Wikipedia, but there's no reliable source if it was the first mention of that term.
Answer: It comes from when two armies are in battle, the army that reaches the high ground (ie 'the hill') is likely about to win the battle. (see also 'The Grand Old Duke Of York' nursery rhyme)


What is dynamic method dispatch and how does it relate to inheritance?

Question: What is meant by dynamic dispatch in Java, and why do we need it in the context of inheritance?
Answer:
What is meant by dynamic dispatch in Java […]?

Think of "dispatch" as "determining which method to call".
The "dynamic" part simply says that it is determined at runtime. That is, which method is to be called is determined at runtime.

why do we need it in the context of inheritance

Without inheritance / polymorphism we wouldn't need this. The type of an expression would be decidable at compile time, and which method that would have been called at runtime would be known when compiling the program.
With inheritance / polymorphism we don't know the concrete runtime type of an expression, thus which method to be called must be "dynamically" determined during runtime.
Without dynamic dispatch, virtual methods wouldn't make sense, which is central for abstraction and encapsulation.
Recommended reading: Wikipedia article on Dynamic Dispatch
Comment: It's quite simple: If you weren't allowed to do `List l = new ArrayList<>();` but _had_ to do `ArrayList l = new ArrayList<>();` you wouldn't need dynamic dispatch, because the type of `l` would necessarily be `ArrayList` in runtime (that is it couldn't be any other `List`). This would make dynamic dispatch meaningless since the compiler could just hard wire a call to `l.add(...)` to the `ArrayList.add` method (as opposed to wiring it to `List.add` and dispatch it to `ArrayList.add` or `LinkedList.add` dynamically).
Comment: Single dispatch: You base your choice of method on a single input, for example the object type. Multiple dispatch: You base your choice on multiple input, for example the object type, and the argument types. In Java you can call different methods depending on which type of arguments you provide, (method overloading) but this mechanism works entirely in compile time. So for multiple dispatch, imagine this was decided in runtime: `Object o = "hello"; m(o);` and `Object o = new Integer(5); m(o);` could call different methods.
Comment: Can you please share some example to explain this point `With inheritance / polymorphism we don't know the concrete runtime type of an expression, thus which method to be called must be "dynamically" determined during runtime.`
Comment: got it now. And as I know there are 2 forms of Dynamic dispatch. `single` and `double/multiple` dispatch.  Could you please share some light on those too. Preferably with an small example.
Comment: Ah, in java the two method calls will invoke the same method `m`, since both `o`s are `Object` types. If it supported `multiple dispatch` it should call two different methods. Thank you very much for clearing that piece.  But anyway Java is not supporting multiple dispatch. Any idea why.
Comment: Can't say for sure, but possible explanations are: Efficiency. Simplicity. Same semantics as virtual methods in C++.
Comment: Great ! Thank you for explaining so much. But I have few other questions regarding `Dynamic Dispatch` hope you don't mind (I have few others also it's better to ask a SO question later). Is it different from `Late Binding` ? Coz one other answer in this page state that `...dynamic dispatch (also called late binding) is ...` . Basically are `dispatching` and `Binding` the same ?
Comment: Reading [this](https://lukasatkinson.de/2016/dynamic-vs-static-dispatch/) it seems to me as if late binding is more or less the same thing as dynamic dispatch.
Comment: Hmm Anyway I asked a question.  If you have please look into this and provide some thoughts :) Thanks for the support.
Answer: Other Answers discus the theory, this is an example to show why dynamic dispatch (also called late binding) is needed.
Assume you have an Class 'Rectangle`.
public class Rectangle{
  public void draw() {
     System.out.println("___\n| |\n---");
     //does it look nice?
  }
}

And you have a subclass with rounded corners
public class RoundedRectangle extends Rectangle {
  @Override
  public void draw() {
     System.out.println("assume it is a rectangle with rounded corners");
  }
}

Now assume you have a method getting with an Parameter of Type Rectangle, which is used in the method to invoke the draw method
public class Demo() {
...
  public demonstration(Rectangle rect) {
    rect.draw();
  }
...
}

It the argument of this method is of class Rectangle then it will draw
___
| |
---

But when the argument is of type RoundedRectangle, then we expect:
assume it is a rectangle with rounded corners

And this is where late binding is needed for: When the code compiles, it is not clear which method needs to be invoked by
rect.draw();
I could be Rectangle.draw(), RoundedRectangle.draw(), or the draw method of any other yet not implemented subclass of Rectangle.
Summary (from the view of an developer):
So late binding means: invoke the method of given signature (Method name, and argument list) for an instance where is only known that it is of an specific class or subclass - but it is not known which class it is exactly. And when a method is overriden, then ivoke the overriding method.
So there is no Polymorphism vs. Late Binding -- It is you need Late Binding when you have Polymorphism. In Java and in C++ (and i belive, in every other Object Oriented language too)
Comment: @Ralph This answer is great !!!  Could you please share some light on the `single dispatch` and `double/multiple dispatch` with examples.
Answer:
What is dynamic method dispatch in case of java

Same as it is in any other language. Despatching dynamically to a method chosen on the basis of the type of the object the method is invoked on.

and why do we need that in case of inheritance(what is the need of DMD)

That's the only time you do need it. If you don't have inheritance there is nothing to be dynamic about.

Which one is better Polymorphism in C++ or DMD in java.

The question is meaningless, as they aren't different. DMD is a mechanism for implementing one aspect of polymorphism.


Problema de unicode textarea no IE8 e MVC2

Question: Eu estou com problema em um campo textarea.
Eu tenho um campo textarea o cliente digita neste campo insere ç ã àèìáéí, no textarea perfeito, no js também esta ok, mas quando resgato no controller o campo do textarea, todos caracteres especial ficam com ?
Isso só acontece com IE8 , Chrome e firefox está ok.
alguém sabe como resolver isto?
Answer: Verifique o "character set" tanto do servidor quanto da página que está sendo gerada. Eles devem ser o mesmo, por exemplo, utf8. Se não forem iguais você terá problemas.
Na sua página, por exemplo, você deve ter uma linha como esta:
<code><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</code>
Ou se estiver usando windows, o teclado, ao abrir o IE pode estar setado para usar outro padrão.


(Flask) SqlAlchemy after_insert event listener with rollback inside causes TransactionClosed error

Question: I have two tables A and B.
I need to create some rows in table B (with ForeignKey reference), after I create a new row in table A. But if I get exception in event listener I need to make rollback for executed code inside listener. How can I do it?
For example:

class A(db.Model):
    __tablename__ = 'a'

    id = Column(BigInteger, primary_key=True)
    ...

class B(db.Model):
    __tablename__ = 'b'

    id = Column(BigInteger, primary_key=True)
    a_id = Column(BigInteger, ForeignKey('a.id'), nullable=False, index=True)
    ...

@event.listens_for(A, 'after_insert')
def after_insert_listener(mapper, connection, target):
    transaction = connection.begin()
    try:
        ...
        connection.execute(B.__table__.insert(), a_id=target.id, ...)
        transaction.commit()
        ...
    except Exception as e:
        # need rollback here if i got exception inside my code
        transaction.rollback()

Next, in my code i have somethin similar:

a = A(some_field='foo')
db.session.add(a)
db.session.commit()

This code leads me to ResourceClosedError: This Connection is closed (this was when I closed conn inside listener) or InvalidRequestError: This transaction is inactive
Please, help me what I do wrong? I think with this code I'll get nested transaction, but as I understand only one transaction performs from session.commit() to the end of listener.
Some info about after_insert listener:
http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.MapperEvents.after_insert
if it can make a difference, I use Flask-SqlAlchemy extension.
Answer: Unless the exampe code you gave in the after_insert_listener is bad, you are going the wrong way about it: instead using a listener to insert B instances, just let sqlalchemy handle this for you by defining a relationship between A and B:
class A(db.Model):
    __tablename__ = 'a'
    id = Column(BigInteger, primary_key=True)
    ...
    b_s = relationship("b", backref="a") # @note: new code

...
a = A(some_field='foo')
b1 = B(some_b_field='some value')
a.b_s.append(b1)
db.session.add(a)
#db.session.add(b1) # @note: no need for this, as b1 will be added
                    # automatically due to relationship with "a" added above
db.session.commit() # @note: this will insert A and then all Bs
                    # related to it with correct `a_id`

Comment: The relationship is not working for me, because I simplify my example, and in listener I do much more work in loop with FKs (one-to-many). And I can't do linking as in your example at creation time, because I don't know some fields values (None on those time), they are filling later in background celery task.


Not all the buttons are displayed

Question: I installed CKEditor plugin ver. 1.16. In configuration page for editor appearance I selected "Full":

But when I open "Add content" page I see the different picture:

When I changed the appearance from "Full" to "Advanced", the appearance doesn't change. But when I switched to "Basic" appearance, it worked.
What's the issue here? Why not all the buttons are displayed?
Answer: On 'Add content' page, please check which 'Text format' you have selected in drop-down below the CKEditor.
Make sure that you have selected the Full HTML or Filtered HTML according to your field settings.
Comment: I did it from the beginning - "Full HTML" was selected.

Not all the buttons are displayed


Android OneBusAway - How do I change colors?

Question: I'm not an android develop at all but I've been tasked with updating colors and styles for OneBusAway.  Nothing fancy is required.  Examples are changing the header area for green to purple or something like make the default grey background color a darker grey color. I figure that I should be able to open the code, change some hex colors, build and be done.
This should all be really simple but I cannot find where the actual colors get set.
For example, take a look at the code below:
<LinearLayout
            android:id="@+id/stop_info"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@drawable/ab_stacked_solid_busbot"
            android:visibility="gone">

I want to change the background color.  So, I search for ab_stacked_solid_busbot which leads me to the following:
public static final int ab_stacked_solid_busbot=0x7f020002;

This does not at all look like a style to me. However, it could potentially be a hex or RBA value but can't get it to match the existing app colors.
In styles.xml, I can find the following:

This still seems like there is a pointer to a style class somewhere with an atual color attached to it.
Can anyone point me in the direction of where I can make these simple color changes.
Answer: I believe that line you found is from the generated R.java file. That is an internal id used by the OS to find the drawable image. Take a look in your drawable folders and you should find an image or xml named ab_stacked_solid_busbot. You will need to modify the xml or in your image editor of choice based on the type.
Comment: it may not be an actual image it could be xml drawable... but yes dcharm has it right
Comment: I updated my question with some xml from Styles.xml. Does this indicate that the background is using drawable sml?
Comment: What is in your drawable folders? That is what you need to zero in on and modify.
Comment: There isn't much in the drawable folder.  A handful of images and maybe 10 or 12 xml files.  None of them seems to correspond to what I'm looking for.  Wouldn't a global search but enough to look everywhere?   Am I really just looking for an image?
Comment: There is a file somewhere in one of your drawable folders with the name `ab_stacked_solid_busbot`. It can either be an xml or .png. Make sure you look in all of the `drawable-xxx` folders.
Comment: I looked inside the drawable-mdp folder and it looks like my answers may be found in there.  Stay tuned....
Answer: hex color bro.... here
http://www.colorspire.com/rgb-color-wheel/
find the color you want here.... and it will tell you the hex(six digit code)
you can set the background directly to the color like so...
android:background="#000000"

if your knoow the hex or rgb of the color you want u can use the above site to convert from one to the other, otherwise play with it til the color matches and youll have your code
Comment: I can't do it that way.  I need to change the global styles. change once, works everywhere.Do you know how I can change the styles for ab_stacked_solid_busbot?
Comment: 0x7f020002 is the image id... did u pull that from r.java? check your drawables folder and see if you find ab_stacked_solid_busbot in there.... either  in xml, or png. then replace that
Comment: There isn't an image of that name in the drawable folder.  The app is riddled with similar items.
Comment: show me the class that says   public static final int ab_stacked_solid_busbot=0x7f020002;


html5 file api, storing user selected directory in sessionStorage?

Question: I'd like to make an application where a user can select a directory on their own computer, and I can refer to the images in that directory across page refreshes/etc.   For example, the user selects a directory, or just multiple image files, and then every time the page is refreshed, display a random image from the selected directory.   I don't want the images to get uploaded to my server, rather allow users to customize the experience by selecting which images get displayed on a session-by-session basis.   I know it sounds like a very obscure scenario, but there is at least one circle of people I know of who will really appreciate this functionality.
Is there some way to achieve this with the HTML5 file api?
I'm currently using:
<code>$imagesDir = 'random/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
</code>
to serve a random image from a directory on my server at each page refresh.   I'd like the user to be able to replace this directory with a directory they select on their own computer.
Answer: Grabbing them from an average (user selected) directory on the user's computer is not possible (see this answer for more in-depth info).
Basically you can not serialize/store the user-selected directory, neither do you have a directory-indexing method (for local files), so the user would still have to select each and every file (they want to share to your web-app) separately. Likewise, you can not store references to those files (beyond sessions).
You could however have them (the users) select files (images) from their computer and 'upload' them into the browser's local storage area (that is technically still on the user's computer).
Comment: I think you have put me on the right track with this.   For anyone else reading this question, I also found [this answer](https://stackoverflow.com/questions/19183180/how-to-save-an-image-to-localstorage-and-display-it-on-the-next-page) that seems like it should help.   I just need to work out how to apply it to multiple images and randomize it!
Comment: You are welcome! That's a great follow-up link you have provided. That is the way to go!


Responsive image styles

Question: In /admin/config/media/responsive-image-style. I created a responsive image style. The breakpoints group is bartik so now I have 3 breakpoints. Wide, Narrow and Mobile. I want to use a new image style I created called small, its 80x80 scaled pixels. I set all 3 breakpoints to use small. But in Mobile I want the image to stretch a little maybe have it go from 120 wide to 80 wide. Is this possible? Does that make sense? If I select multiple image style under small this field appears Enter the value for the sizes attribute, for example: (min-width:700px) 700px, 100vw. What does this mean and where can I find some format examples?
Answer: Responsive Image Style:
Here you can tell WHEN and WHAT STYLE to apply
Image style:
Here you can tell WHAT OPERATION should take place on the original image.
Create a new image style with scale & crop (or whatever fits you) first,
and then set this image style to the right Responsive Image Style interval (in your case the smallest)
Answer:
Is this possible?

Sure

Does that make sense?

That depends on your design, not our opinions. ;)
You should create an image style for all variations of an image you can have. So if your default 'small' style is 80x80 and you want to use 120x80 as well, you should create a new image style 'small_mobile'.
The purpose of the sizes attribute is explained in this change record:

The sizes attribute tells the browser how much space this type of
  image will take up in the browser at various breakpoints. The image
  styles you select gives the browser multiple options to select an
  image source that is appropriately sized for the amount of space
  available at a particular breakpoint and screen resolution.

It is also explained in Drupal's built-in help system:

Sizes field
Once the sizes option is selected, you can let the browser know the
  size of this image in relation to the site layout, using the Sizes
  field. For a hero image that always fills the entire screen, you could
  simply enter 100vw, which means 100% of the viewport width. For an
  image that fills 90% of the screen for small viewports, but only fills
  40% of the screen when the viewport is larger than 40em (typically
  640px), you could enter "(min-width: 40em) 40vw, 90vw" in the Sizes
  field. The last item in the comma-separated list is the smallest
  viewport size: other items in the comma-separated list should have a
  media condition paired with an image width. Media conditions are
  similar to a media query, often a min-width paired with a viewport
  width using em or px units: e.g. (min-width: 640px) or (min-width:
  40em). This is paired with the image width at that viewport size using
  px, em or vw units. The vw unit is viewport width and is used instead
  of a percentage because the percentage always refers to the width of
  the entire viewport.
Image styles for sizes
Below the Sizes field you can choose multiple image styles so the
  browser can choose the best image file size to fill the space defined
  in the Sizes field. Typically you will want to use image styles that
  resize your image to have options that range from the smallest px
  width possible for the space the image will appear in to the largest
  px width possible, with a variety of widths in between. You may want
  to provide image styles with widths that are 1.5x to 2x the space
  available in the layout to account for high resolution screens. Image
  styles can be defined on the Image styles page that is provided by the
  Image module.

Finally, if you always want to use 120x80 on mobiles, you can select a single image style.
Comment: No problem, I hope the update explains it even better.

Responsive image styles


Iterating through rows and filtering data in R

Question: I am working with the following data (see picture)
I am trying to predict future Y axis values from the X values. As you can tell from the picture and as I discovered, the prediction is going to be horrible based on the data alone.
I am now trying to go row by row through the data and classify each point as significant or nonsignificant and see if I can find anything interesting in the classification. I want my algorithm something like this:

Take absolute value of every element in both Y axis and X axis data columns

Iterate through Y axis column and find the top 5% largest values

Iterate through again marking those top 5% or maybe 1% (Will fiddle with this) with a flag

Plot only the top 5% and see if the linear model (or some model) has a better R^2

Perform some sort of classification analysis against the two flags, significant and non significant (I really need help and suggestions with this step)

The two things I need are a pointer on are

How to step element by element through data, making modifications along the way
What kind of classification analysis exists that might be helpful, goal being to predict which classification future sampled elements will fall into.
Answer: You don't step element by element through data in R. Well, you can, but you need to be a very patient person.
The R way would be to calculate the quantile you want and subset the data.
Example:
<code>set.seed(42)
DF <- data.frame(x=runif(1e3),y=rlnorm(1e3))
plot(y~x,data=DF)

#95 % quantile
q95 <- quantile(DF$y,0.95)

#plot data subset
plot(y~x,data=DF[DF$y>q95,])

#fit linear model to data subset
fit <- lm(y~x,data=DF[DF$y>q95,])
abline(fit)
</code>
Can't help you with the statistical issue ...
Comment: Hey this helped a lot. I really needed some help with the basic subset commands.


Sum up values from different worksheets

Question: I'm building the budget template in Excel. In the Summary sheet, I want to sum columns from different worksheets by the corresponding cell.
enter image description here
In my way, I get all sheet names (by VBA code, it will automatically update when creating new worksheets), then use TEXTJOIN to have all reference cells I want in a text. It looks like this: Sheet1!$B$2,Sheet2!$B$2,Sheet3!$B$2,Sheet4!$B$2,Sheet5!$B$2,Sheet6!$B$2,Sheet7!$B$2
I guess we can have some way to put that text in SUM function in Excel to sum up all reference cells value, but I haven't found how to do that yet.
If anyone can have a look and give me a solution, it's much appreciated.
Thank you as always
Answer: As I understood the question you can do like this in reference cell:
<code>  =SUM(Sheet1:Sheet7!C2)
  =SUM(Sheet1:Sheet7!C3)
  =SUM(Sheet1:Sheet7!C3)
  =SUM(Sheet1:Sheet7!C5)
  =SUM(Sheet1:Sheet7!C6)
     --------
</code>
Comment: Thank you so much @gretal. Your formulas are worked if Sheet1 is sitting in the 1st position, and Sheet7 is sitting in the last position (All other sheets have to be put between Sheet1 and Sheet7).
Also, in the case I need to add more sheets, I have to manually adjust, right?
Comment: welcome, yeah you can adjust.
Comment: Is there anyway to get "Sheet1:Sheet7" by INDIRECT function or some things else.
Comment: this is the way i often use.
Comment: Ok. Thank you @gretal.

Sum up values from different worksheets


Finagle client handle onConnected event

Question: I'm trying to build async client for some tcp service. Service requires handshake. When initial connection is established I can make handshake, but if connection fails and finagle reconnects i have no way to make handshake again. Is there a way to catch connected event?
Thank You!
Answer: You can override the method prepareConnFactory in your codec.
Basically each time finagle establishes a connection it will execute this method before putting the connection into the queue.
We use this feature in the ThriftClientFramedCodec to verify that the server is compatible with our custom thrift protocol.

Finagle client handle onConnected event


Is it true to say that methods are correlated?

Question: I'm comparing a set of methods. Each method generates a list of observations, then I compute the correlation between the observations of the methods. Is it correct to say that I'm checking the correlation between the methods? if so, why is it correct?
Or is it more correct to say that what I'm doing is checking the correlation of the results of the methods?!
Answer: If you are using method to describe a transformation that makes the observations correlated then I would say yes. It is OK, but confusing to say that. I would go with checking the correlation of the results.


How to target specific sites with Drush when using Multisites?

Question: I have a Drupal Multisite set up. It contains two sites, but the core Drupal install has no site.
With Drush, I can use @sites to target all sites. For example:

drush @sites -y cc all - Updates all multi-sites
drush @sites -y en jqmulti - Install Jquery in all Multi-Sites

However, because I have no site installed in the core folder, I always get an error message  stating that the core site is missing. Is there any to use Drush to only update the sub-multisites and skip the core one?
I know I can run Drush from the sites directory of the sub-sites, but that isn't very convenient when I want to target all sites.
The reason I am using Multisites is because both sites share themes and user-logins.
Answer: When you say "core site", do you mean the site in sites/default?  Is it an option to just delete the settings.php file at sites/default/settings.php?
If you'd like to manage your aliases in an alias file, create a file ~/.drush/mysite.aliases.drushrc.php:
$root = '/path/to/root';

$aliases['site1'] = array(
  'root' => $root,
  'uri' => 'site1.com',
);

$aliases['site2'] = array(
  'root' => $root,
  'uri' => 'site2.com',
);

See this link for an example.
Then, to refer to one site:
drush @site1 status

or -

drush @mysite.site1 status
To refer to all sites:
drush @mysite status
Maybe you want to get more fancy than this, though.  If you have more aliases in your alias file (e.g. for 'dev' and 'live' sites, you can make your own lists:
$aliases['dev'] = array(
  'site-list' => array('site1', 'site2'),
);

Then:
drush @mysite.dev status
If you want, you may also store your alias file in /path/to/root/drush or /path/to/root/sites/all/drush, but if you do this, Drush won't be able to find your alias file unless you specify --root on the commandline, or change your working directory to be somewhere inside of /path/to/root.
Answer: You need to setup a new Drush alias file for running the command on the remote site.
Typically you name the file as <project_name>.drushrc.php.
You then need to place this file in the .drush directory in the home directory of your logged in user.
See this link for a sample Drush alias file.
After setting up the file, do a drush cc drush to clear the Drush cache and let it allow picking up the new alias files (Note: This might not be required on some environments)
UPDATE: If you are hosting your remote site on Acquia or Pantheon, you get to download the alias file directly.
To download the alias file for

Acquia, go to https://accounts.acquia.com/account/<login_id>/security?site=insight and you download the alias from the link:

For Pantheon go to https://dashboard.pantheon.io/users/<user_id>#sites/list and download the alias file
Comment: Do I create a Drush directory in my Drupal site? Do I specify each of multis-ties in the Alias file? thanks for your help!
Comment: @big_smile You don't have to create a Drush directory for your site. The directory should be present in the `home` directory of the current unix user. You could setup multisite in a single alias file.
Comment: @big_smile If you are hosting your site on Acquia or Pantheon you get to use the alias file they provide directly! Just copy it to the `.drush` directory, and you are good to go