Na POO quando se deve usar return?

Question: Tenho uma duvida relacionada a POO, quando devo usar o return em um método?!
Visto que quando eu passo um objeto para o método e as modificações são feitas nele, eu não preciso de return, exemplo abaixo:
Chamada do método:
this.ordenaArquivo(this.arquivos);

private void ordenaArquivo(List<Video> arquivos ) {
    VideoComparatorUtil comparatorUtil = new VideoComparatorUtil(VideoComparatorUtil.ORDERBY_TAMANHO);

    Collections.sort(arquivos, comparatorUtil);
}

Ou deveria fazer isso:
Chamada do método:
this.arquivos = this.ordenaArquivo(this.arquivo);

private List<Video> ordenaArquivo(List<Video> arquivos ) {
    VideoComparatorUtil comparatorUtil = new VideoComparatorUtil(VideoComparatorUtil.ORDERBY_TAMANHO);

    Collections.sort(arquivos, comparatorUtil);

    return arquivos;
}

Comment: Você pode realizar um teste, passe como parâmetro do seu método uma `String` e dentro do seu método, tente alterar esta `String`. algo como isso: `public void changeStringValue(String value) {  value = "Ohh!!"; }`.
e veja que se tentar imprimir o valor da sua `String` após invocar este método, o valor imprimido será o mesmo de antes de invocar o método.

`String myStr = "initialValue" ; `
` System.out.printLn(myStr); //initialValue`
` changeStringValue(myStr);
` System.out.printLn(myStr); //initialValue`

por este motivo, passe os parâmetros, e retorne o resultado, caso necessário.
Answer: Na verdade o return não chega a ser um conceito específico de orientação a objetos. Faz parte da sintaxe do Java e de muitas outras linguagens e é uma palavra chave usada pra retornar para o código onde o método inicialmente foi chamado.
Um método de tipo qualquer retorna quando encontra o return seguido do seu respectivo tipo;
Um método do tipo void retorna quando encontra o return; ou quando chega ao fim dele.
Mas a sua dúvida pode ser melhor explicada pelos tipos de dados do Java e passagem de argumentos por valor ou referência.
Passagem de argumento por valor
Quando você passa pra um método apenas argumentos de tipos primitivos (int, float, double, long, short, char ou byte), eles são passados por valor. Ou seja, uma cópia daquela variável é feita dentro do escopo do método e mesmo que você a altere, nada vai acontecer com a variável original que você tinha passado como argumento primeiramente.
public static int metodoSomaDois(int argumento) {
    //Uma cópia do seu argumento recebe ele mesmo + 2
    //Sendo assim vc precisa retornar ele caso
    //queira atribuir o seu valor alterado à uma outra variável externa
    argumento += 2;
    return argumento;
}

Exemplo:
 int original = 5;
 metodoSomaDois(original); //Nada vai acontecer já que vc não atribuiu o retorno do método a nenhuma outra variável e a original permanece 5.
 original = metodoSomaDois(original); //Agora a variável original vai receber o valor retornado do método

Passagem de argumento por referência (o seu caso)
Já argumentos de tipos não primitivos (arrays, objetos e etc) são passados por referência. Isso significa que o objeto em si é passado (mais precisamente um ponteiro pra aquele objeto) e não uma cópia. Ou seja, qualquer mudança feita naquele objeto dentro do escopo do método também vai alterar o objeto que foi originalmente passado como argumento.
public static void metodoAlteraValores(int listaPorArgumento[]) {
    //Como esta sendo passado por referência
    //os valores da lista original vão ser alterados também sem a necessidade de atribuir o retorno
    for (int i = 0; i < 3; i++)
        listaPorArgumento[i] = 10;
}

Exemplo:
int lista[] = {5, 5, 5};

    for (int i : lista)
        System.out.print(i + ", "); //Exibe 5, 5, 5,

    metodoAlteraValores(lista); //Altera os valores pra 10 sem precisar de atribuir a nenhuma outra variável

    for (int i : lista)
        System.out.print(i + ", "); //Exibe 10, 10, 10, (o que mostra que a lista original foi alterada)

Conclusão
Isso mostra que o seu primeiro exemplo é o mais correto e o porque.
De forma resumida, o return vai ser utilizado quando você precisar retornar um valor que tenha que ser atribuído a alguma variável, e não será necessário quando for alterar diretamente um objeto que for passado por referência.
Vale lembrar que é possível retornar um objeto de tipo não primitivo, que pode ser atribuído a uma variável do mesmo tipo. Normalmente isso acontece quando você, por exemplo, quer alterar um array sem alterar o original.
Sendo assim, o ideal, para o seu caso, seria criar um objeto do mesmo tipo dentro do método e fazer um clone do original que possa ser alterado e posteriormente retornado.
Comment: Perfeito, não havia parado para pensar que tipo primitivos de variáveis não eram alterados quando passado para um método, ótima resposta, muito obrigado.
Comment: Não concordo com o enquadramento do problema. O problema não se trata apenas de passagem de argumentos por referência vs por valor, mas sim de tipos imutáveis (primitivos ou não) vs tipos mutáveis (não primitivos). Por exemplo, `string` é passado por referência - no entanto, quaisquer "alterações" devem ser retornadas, visto `string` ser um tipo imutável.
Comment: Acredito que a resposta não carece informações. A dúvida era de quando se deve usar o return. Eu respondi e até extrapolei um pouco explicando e exemplificando passagem por referência usando array, que é bem próximo do exemplo que ele usou na pergunta. Poderia explicar diretamente sobre imutabilidade também, mas diante do que já foi escrito, cabe a ele ir atrás de mais informações já que tudo isto esta conectado.
Answer: Em java todo objeto é passado como referência. Logo, se voce quer alterar um objeto em um método, é suficiente passar ele como parâmetro e sem retorno. No seu caso, a primeira opção parece melhor (Lists são objetos).
Se mesmo assim você quiser retornar um objeto, note que ao usar return em um objeto voce não retorna uma cópia dele, retorna apenas a referência para este objeto. Então, return na lista não retorna uma cópia completa da lista, retorna apenas uma referência para sua lista.
Usa-se retorno apenas para tipos primitivos (int, float ...) que em Java são passados por valor;

Na POO quando se deve usar return?


When were the terms "Major" and "Minor" applied to keys?

Question: In 1547, Heinrich Glarean published Dodecachordon in which he posited that in addition to the 4 existing pairs of church modes (plagal and authentic versions of modes with finals on D (Dorian), E (Phrygian), F (Lydian), and G (Mixolydian)), there should also be pairs of of modes on A (Aeolian) and C (Ionian). He even claimed that the Ionian mode was one of the most often used modes (since the B's were often flatted in "Lydian" mode). This brought the number of modes from 8 up to 12, and caused quite a stir among music theorists.
In 1571, Gioseffo Zarlino, in Dimonstrationi harmoniche, affirmed these extra modes, and went so far as to renumber all the existing modes, placing C (Ionian) first. Of course, these modes went on to become what we call major and minor keys, but at this point, they were not called this. Furthermore, the "Ionian"/"Aeoliean" terminology seems to have never been widely adopted (outside of the realm of theorists) until very recently, even though the concepts themselves were.
At some point in the Baroque era, even before tonality had been formalized, pieces were being labeled as being "major" or "minor", and almost never by mode (there is a "Dorian" fugue by Bach, but this stands out as an exception). I believe (but I'm not certain) that by the time Jean-Phillipe Rameau published his Treatise on Harmony in 1722 the terms were already in wide circulation. (Of course, in 1725, Fux's more historically conservative Gradus Ad Parnassum was still referring to the six modes.)
My question is specifically about the origin of this terminology. Obviously, 3rds were already being classified as major or minor before this, but at what point do these terms start to be used to describe keys, rather than merely intervals? Who (if anyone) first proposed this system, or what is the earliest attested usage? Or is this a detail lost to time?
If possible, I'm specifically looking for explicit names, dates, and publications of original sources.
Comment: I'm so tempted to write an answer based on a certain character in "Catch-22" (who had the same first, middle, and last name which matched his rank  ) deciding to go into the subterranean mineral retrieval business.  :-)  But, maybe this will shed some light:  https://www.academia.edu/326349/A_rudimentary_approach_to_the_history_of_the_major_and_minor_keys
Comment: This is a very interesting question that I hope is thoroughly answered. FWIW, I support your assertion about Rameau.  Some earlier composers, such as Vincenzo Galilei, were advocates of what would be come to be known as Equal Temperament. I suspect that the answer may lie in the development of Equal Temperament and the Overtone Series; after all, the notes of a major scale are derived from the overtones of the fundamental, since they occur naturally and thus more often, it would be logical to posit this acoustic phenomenon as being the origin for the term "Major".
Comment: Since "minor" scales ("natural" ones anyway) involve lowering three tones that are not diatonic to the intended fundamental (though invariably creating another inverted major scale,) and do not naturally occur, thus appearing less often, one could posit *that* acoustic phenomenon as being the origin for the term "Minor".  That all said, my comments are speculation and I only offer them as a means for you to continue your research.
Comment: How about Locrian?  I know that it was not part of the modes you are talking about...
Answer: I hope no one minds that I got curious, and did a bit of digging into this on my own. I discovered what appears to be an excellent resource answering this very question. The book is entitled Between Modes and Keys: German Theory, 1592-1802 by Joel Lester (1989). I do not have access to a copy of the book, but I've been able to see several relevant portions online (thank you, Google Books!). Even though it deals primarily with German music theory, it does occasionally touch on the rest of Europe. I'll try to summarize what I've gleaned so far, although I may not not be seeing the whole picture, since I'm not reading through the complete book.
The primary development that necessarily preceded the concept of major and minor keys, was triadic harmony (rather than intervallic harmony). Johannes Lippius (Synopsis musicae novae, 1612) coined the term "triad" to describe the three-part harmonies that had emerged in the late Renaissance, and, being part-theologian, compared the concept to the Trinity. He also recognized all the inversions of intervals (and triads), including the fact that major 3rds inverted to minor 6ths (and vice versa). Any set of consonances could now be reduced to a triad, and placed in root position. He classified the 6 pairs of modes as being constructed around either a major or a minor triad, with an additional interval of a fourth either above or below. This classification didn't take hold right away; indeed, Germany seems to have been especially resistant to abandoning the old concept of modes (this seems to be a major theme of the book). Apparently, as late as Haydn, traditional German musicians were still advocating the use of modes.
In fact, throughout the Baroque, there seems to have been widespread confusion, even among musicians, over the exact definition of a mode. Were modes defined by the octave range in which they sat? Were they defined by their final tone? Or by their "reciting tone"? Or by the mood they evoked? Or by the melodic and harmonic phrases and patterns that they accommodated (especially around cadences)? Or the patterns of tones and semitones they formed? What about transpositions? And what of the chromatic alterations that were becoming popular in theatric music? Are we better off sticking to the older traditional 4 pairs of "time-tested" church modes?
The practical solution, oftentimes, was to avoid the question altogether and just list out a handful of permissible "keys" (as in, on a keyboard) that could be used as the final, along with their corresponding signature (initially either blank, or containing one flat). The key of G, for example, could be used with either no signature, or a single flat. As additional keys were added to these key lists, they were classified, not by the quality of their third, but by whether they included flats, sharps, or neither in their root triads. Thus what we call "G-minor" would have been classed along with what we call "B-flat major" as a "flat key", while our "C major" and "D minor" would be examples of "natural keys", and so on.
Andreas Werckmeister, a church organist and theorist, whose works (and well temperament) were well-known to Bach, had a solid understanding of modes, and describes them as being important to understand (for which he would later be dismissed by proponents of keys). But he also acknowledged that, outside of chorales, only two were in popular use in his time. In Musicae mathematicae, (1687) he gives us this description of the system then in use, along with his own proposed nomenclature (which was not adopted):

Today's music is entirely different... and only some four modes are in
  use: Ionian mixed with Mixolydian, and Dorian mixed with Aeolian...
  [which each differ only in the upper fourth of their octaves].
  Thus no more than two modes can now be established. And that is not so
  unnatural... If we take Lydian, on account of the tritone... there is
  such an unnatural progression in it that even the ancients themselves
  never or hardly ever used it. Who uses Phrygian in today's music?
  Nobody. Who Mixolydian? Hardly any. Therefore... according to today's
  style of composition, we want to maintain only two modes. But because
  these can take their names neither from the Dorians, the Ionians, nor
  from any other nations (because they did not have our present style of
  music), therefore we want to name them according to their nature and
  character, so that they can be differentiated. The first can be named
  the natural mode, because it always maintains the major third in
  the beginning over the fundamental note... the second can be named the
  less natural mode, because the root numbers in its natural progression
  are further removed from perfection, and therefore do not
  establish such a happy harmony as the preceding... We can also name
  one mode perfect, and the other less perfect. Some performers
  name them dur and moll; e.g., C E G is C dur, C E-flat G
  is C moll... We are not happy with these names... nevertheless,
  because these terms are now used so commonly, they will probably
  persist.

Lester claims this may be the first published usage in German of the terms dur [hard] and moll [soft] to refer to major and minor keys, but the process was already said to be widely used by performers. Also mentioned is that Werckmeister originally envisioned the minor as being derived from Dorian rather than Aeolian.
Lester also shows that "By the late seventeenth century, French works routinely differentiated keys solely on the basis of major and minor." One reference refers to the distinction of "major" and "minor" keys as being according to the "French opinion". The first published recognition of all 24 major and minor keys is from a French mathematician named Jacques Ozanam, who in his Dictionaire mathematique (1691) explains:

There are twice as many modes as there are notes in an octave: each of
  these notes gives its name to two modes, of which one proceeds by the
  major third and the other by the minor. Since the octave contains
  twelve notes, there are twenty-four modes.

Note here that each key is called its own mode, rather than transpositions of two basic modes. An earlier French quote, from a 1689 basso continuo manual, refers to two types of modes: a "sharp" type that "reduced to C," and a "flat" type that "reduced to D," (here again is the Ionian/Dorian distinction).
As noted by Robert Fink's answer, in Germany it is not until 1711 and 1713 that Johann Heinichen and Johann Mattheson enumerate a full list of all 24 possible major and minor keys along with their proper key signatures (using Aeolian as the relative minor). Heinichen connects them into a circle of major and minor keys, a formalization of a "well-known" device he learned from his organ teacher. There is also a series of letters between Mattheson and Fux, in which Fux complains that Mattheson's 24 keys are all just transpositions of two modes. Mattheson argues that each key is still distinct, due to differences in its temperament.
It's interesting to note that, as late as 1722, J. S. Bach's title for the Well-Tempered Clavier refers to the 24 keys rather obliquely: "preludes and fugues through all the tones and semitones both as regards the tertia major or Ut Re Mi, and as concerns the tertia minor or Re Mi Fa." (Re Mi Fa could even be seen as indicating that the minor third is still rooted in the Dorian mode).
In conclusion: If it could be said that there was one single thing that changed, which slowly but inevitably pushed music towards a natural distinction of major and minor keys, and made the modes obsolete, it was the recognition of triadic harmony, and the understanding that those triads could be inverted into various positions. Once that was recognized, early in the 17th century, it was only a matter of time before the concept of modal finals was replaced with that of a tonic triad, of which there could only be two types. Much of this process took place intuitively over the course of a century, with theoreticians describing the system after the fact, and traditionalists often regretting the loss of modes in the modern style of music.
Comment: There's absolutely nothing wrong with answering your own question (in fact, I think there's a badge for that...)  I'm really liking where your research is going - is this for a paper or book?
Comment: Neither; mostly just my own curiosity. I've been around Renaissance and Baroque music for so long, and had heard the statement that tonality was still evolving through the Baroque, but had never seen any specific details of how or why. Hopefully, understanding the reasoning behind its origin will also make it easier to explain to others (if not to this level of depth).
Comment: "Re Mi Fa could even be seen as indicating that the minor third is still rooted in the Dorian mode": I suspect rather that Bach is using the Guidonian hexachord (as does Fux), so re-mi-fa doesn't tell you whether it's d-e-f or a-b-c (or g-a-b♭ for that matter).  In this system, as you are probably aware, _mi_ can denote E, A, or B (and, through _musica ficta,_ any raised leading tone).  I always took this as a recognition that the lower fifth of the minor scale is responsible for its identity, since the upper fourth is mutable.
Answer: From the Grove Online article on Mode by the late, noted musicologist Harold Powers:
"[Johan Mattheson's Das neu-eröffnete Orchestre listed] the 24 major and minor keys, [which had been] first set out as a whole in 1711, only two years earlier, in Heinichen's Neu erfundene und gründliche Anweisung … des General-Basses." Powers quotes Mattheson specifically talking about the quality of thirds:  "'There are just the 12 semitones of the chromatic octave, each of which can be differentiated once, through the major or through the minor 3rds; thus the aforementioned 24 arise, and so it remains'." (Mattheson,  1713, p.63).
Comment: Grove Online is behind a paywall, unfortunately. The link would be this: http://www.oxfordmusiconline.com/subscriber/article/grove/music/43718pg3#S43718.3.5
Answer: Along with the German theorists like Lippius cited in other answers, English musicians and theorists from quite an early date also divided the keys or 'tones' into two categories based on the major or minor quality of the third above the final.  At least in the seventeenth century, however, they did not use the terms 'major' and 'minor', but rather 'sharp' and 'flat'.  This terminology is taken over from the terminology for intervals, which were likewise sometimes described as a 'sharp third' or a 'flat third'.  (Of course, the German sources mentioned by other answers do not use 'major' and 'minor' either, but Dur and Moll, which are even older terms taken over from the theory of hexachords).
Christopher Simpson was quite unambiguous about the division of all tonalities into two types in his Compendium of Practical Musick of 1667:

Every Composition in Musick, be it long or short, is (or ought to be) designed to some one Key or Tone, in which the Bass doth alwayes conclude.  This Key is said to be, either Flat, or Sharp: not in respect of its Self; but in relation to the flat or sharp 3d. which is joyned to it.
To distinguish this, you are first to consider its 5th. which consists alwayes of a Lesser and a Greater 3d. [...] If the lesser 3d. be in the lower place next to the Key, then is the Musick said to be set in a flat Key.  But if the Greater 3d. stand next to the Key, [...] then the Key is called sharp. (Part II., §5, p. 43).

Arguably, the division of tonalities by English musicians into only two types, rather than eight or twelve, goes back further, at least to Thomas Campion's A New Way of Making Counterpoint of c. 1610.  Campion's classification is less clearly expressed than Simpson's, but like Simpson's, it emphasises the division of the fifth between the final and fifth degrees of the scale into a major and minor third, and described keys in terms of the quality of the third note of the scale.  In the following excerpt, 'close' refers to a cadence.  Like many other theorists, Campion took the notes on which cadences were made to be a defining feature of the key or mode.  In somewhat convoluted language, he states that keys with a minor ('flat') third should have cadences on the first, third and fifth degrees of the scale, while keys with the major ('sharpe') third should have cadences on the second and fourth notes of the scale in preference to the third:

... looke to your fift above, and the lowest Note of that fift assume for your key, [...] then divide that fift into his two thirds, and so you shall finde out all the closes that belong to that key.
The maine and fundamentall close is in the key it selfe, the second is in the vpper Note of the fift, the third is in the vpper Note of the lowest third, if it be the lesser third, as for example, if the key be in G. with B. flat, you may close in these three places.
(example of cadences in G, D and B♭)
But if the key should be in G. with B. sharpe, then the last close being to be made in the greater or sharpe third is vnproper, & therfore for variety sometime the next key aboue is joyned with it, which is A. and sometimes the fourth key, which is C.

Unlike Simpson, Campion hints that 'minor' or 'flat' keys can be further divided into two subtypes, depending on whether the second note of the scale is naturally a whole tone or a half tone above the final.  The latter case corresponds roughly to what is sometimes called a 'Phrygian' mode; Campion's example of it has the final on A and a B♭ in the signature.

[...] wheresoeuer your key shall stand, either in G. or C. or F. or elsewhere, the same rule of the fift is perpetuall, being diuided into thirds, which can be but two waies, that is, eyther when the upper third is lesse by halfe a Note then the lower, or when the lower third containes the halfe Note, which is Mi Fa, or La Fa.
If the lower third containes the halfe Note it hath it eyther above [...] or else when the halfe Note is vnderneath [...] but whether the halfe Note be uppermost or lowermost, if the lowest third of the fift be the lesser third, that key yeelds familiarly three closes; example of the halfe Note, standing in the uper place was shewed before, now I will set downe the other.
(examples of cadences on A, C and E with a B♭ signature)

However, Campion notes that both types of 'flat' keys have the same proper cadences, on the first, third and fifth degrees of the scale, so the point of distinguishing them may be somewhat theoretical.  There are certainly not many examples of compositions in such 'Phrygian' or mi tonalities from early seventeenth-century England.
Answer: Well, we have an answer about German (with a mention of French) theory, and an answer about English theory, so I figured I'd round it out with what seems to be a good reference for Italian theory, which I just came across today (I haven't had a chance to read any of it yet): Tonal Space in the Music of Antonio Vivaldi
According to the synopsis (emphasis mine):

Tonal Space in the Music of Antonio Vivaldi incorporates an analytical
  study of Vivaldi's style into a more general exploration of harmonic
  and tonal organization in the music of the late Italian Baroque. The
  harmonic and tonal language of Vivaldi and his contemporaries, full of
  curious links between traditional modal thinking and what would later
  be considered common-practice major-minor tonality, directly reflects
  the historical circumstances of the shifting attitude toward the
  conceptualization of tonal space so crucial to Western art music.
  Vivaldi is examined in a completely new context, allowing both his
  prosaic and idiosyncratic sides to emerge clearly. This book
  contributes to a better understanding of Vivaldi's individual style,
  while illuminating wider processes of stylistic development and the
  diffusion of artistic ideas in the 18th century.

Glancing at the table of contents, Part Two (chapters 3-6) is entitled "Key and Mode".
Comment: Does the book indicate whether Vivaldi used the terms "major" and "minor" to identify keys?  If not, it won't help us identify when these labels began to be used.
Answer: I have never tested my theory that the Ionian mode lends itself to pleasing polyphony more readily than the other modes with the exception of the Aeoliean. I have tried rendering a popular hymn tune in all seven modes and the results are striking. Only the Ionian (the original) and Aeoliean modes are acceptable to my ear.  But that may simply be because of my Western musical conditioning. The search goes on.
Comment: Or it may simply be because the hymn was written in a major key and therefore exploits the shape of the major-key intervals to good effect.  That effect would be lost when adapting the melody to some other mode.


How to grab subtitle from screenshot with PHP?

Question: I grab subtitle from movie screenshot.
An example

It will grab

Hey, why don't we all just relax, huh?

It has no relation with subtitle. It is screenshot. Since it is a subtitle we know the font type size etc if this will make it easier to grab.
I know most of you will say PHP OCR library  but since the background is always different, it looks like it won't work.
Comment: `it looks like it won't work.` - have you tried? I mean it probably won't, but at least *try*. And the reason it probably won't work is because pretty much nothing will. Certainly nothing that has pre-built PHP support.
Comment: Doesn't matter that the background is always different, just use GD (or some other image lib) to replace any colour that isn't white (the font colour) with black. Then the background will always be the same (or close to it) and you can use OCR.
Comment: I really don't understand what your question is.
Comment: "Looks like it won't work", but have you tried it (an OCR library)? Subtitles are generally at the bottom of the scene, so you would be able to trim a lot of the picture to start with.
Comment: I meant I tried this http://www.phpclasses.org/package/2874-PHP-Recognize-text-objects-in-graphical-images.html and it didn't work. That class has not updated since 2006. Is there any alternative to that class? I couldn't find.
Comment: @nmagerko to make it easier for you to understand I will keep simple. How to grab "Hey, why don't we all just relax, huh?" text from that JPG with PHP?
Comment: @RichAdams Good point and nice idea, but just replacing everything that isn't white is dangerous, the text is probably not pure #FFFFFF - you would have to replace everything (e.g.) less than #EEEEEE
Comment: @RichAdams do you know any php ocr library/class that works? Because I ended up with there is no php soluiton. The only option seems call an external OCR program with PHP.
Comment: @SNaRe I've never tried any, so I don't know. A quick Google search brings up PhpOCR (http://www.phpkode.com/scripts/item/phpocr/) though, which seems like a decent candidate.
Comment: @RichAdams It is  the only library PHP OCR. I tried it and it doesn't work.
Answer: The background being different shouldn't be a problem, you can just use an image library to remove anything that isn't the text colour.
Here's a quick example that gives a decent idea of what I mean, it replaces any colour lower than #f5f5f5 with #000000,
<?php
$im = imagecreatefromjpeg("img.jpg");

for ($x = imagesx($im); $x--;)
{
    for ($y = imagesy($im); $y--;)
    {
        $rgb = imagecolorat($im, $x, $y);

        if ((($rgb >> 16) & 0xFF) <= 245
            && (($rgb >> 8) & 0xFF) <= 245
            && ($rgb & 0xFF) <= 245)
        {
            $black = imagecolorallocate($im, 0, 0, 0);
            imagesetpixel($im, $x, $y, $black);
        }
    }
}

header("Content-Type: image/jpeg");
imagejpeg($im);

Here's how the result looks:

You can probably chop most of the top part off since you know the subtitles will be at the bottom. Then just run it through an OCR library.
For PHP there's PhpOCR, although this has to be taught first with example letters.
It's probably better to use an external OCR library or command line tool and call it from PHP. For external tools, there's tesseract and ocropus (I believe ocropus is sponsored by Google too).
Comment: Thanks for that. This can be useful for pre-processing. After that I think I should work on a server side solution. PHP is not enough to do this, even though there are some libraries around.


AngularFire2 RealTime DataBase sort by date value

Question: My Service
get ActivityList():any {
    return this.activityList.snapshotChanges().map(changes => {
        return changes.map(c => ({
            key: c.payload.key, ...c.payload.val();
        }));
    });
}

My Component
getActivity() {
    this.activityService.ActivityList.subscribe(activity => {
        this.activity = activity;
    });
}

HTML

    {{item.created|date:'medium'}}

Question
This is how I am currently getting my activity from Firebase RealTime Database. where and how is the best way to modify this to sort by the created value.
Answer: Sort it after subscribe.
getActivity() {
    this.activityService.ActivityList.subscribe(activity => {
        this.activity = activity.sort((a, b) => a.create - b.create );;
    });
}

Comment: working on solving this now `changes.map(...).do is not a function`
Comment: this is not working. Im trying different variations of this.
Comment: just adding my 2 cents, add that sort that sachila wrote in a pipe to have that functionality in other places without adding more code.
Comment: ERROR TypeError: list.sort is not a function  .... also trying the pipe
Comment: grrr, `do` operator should work. Ok i guess u have to sort it inide the subscribe, check the update
Answer: change service to
get ActivityList():any {
    return this.activityList.snapshotChanges().map(changes => {
        return changes.map(c => ({ key: c.payload.key, ...c.payload.val() })).sort((a, b) => b.created - a.created );
    });
}


Distance between center of side of regular polygon inscribed in a circle, and the perimeter of that circle?

Question: Point A : The center of a side of a polygon inscribed in a circle
Point B : The point on the perimeter of that circle that is opposite Point A
I want to calculate the distance between Point A & Point B
I know the number of sides the polygon has and the radius of the circle it's inscribed in.
I believe this is the way to calculate the length of the side of a regular polygon with n sides (Please correct me if I'm wrong as I am not a mathematician and found this online) :
x = nrsin(π/n)

Now is the distance I'm looking for : distance = 2r - x ?
I'm trying to figure out a formula that I could use in a bit of code I'm writing
Comment: Do you mean an inscribed polygon? So that the vertices are on the circle itself? In that case the distance is 0 because the side is touching the circle. If you want to calculate the distance from the center of a side, draw a triangle with vertices at the center of the circle and at the ends of a side and subtract the altitude from the radius.
Comment: Ah yes, sorry for not being clear Matt. I want to calculate the distance between the center of a side of the polygon and the point on the perimeter of the circle right opposite that center. I want to use Math to do that as I will use it a bit of Javascript code I am writing. I will update the OP.
Answer: The length of a side is $2r sin(\frac{\pi}{n})$ by trigonometry.
The distance is $r(1-cos\frac{\pi}{n})$, which is the difference between the radius and the length of the line from the center of the circle to the center of the side.
Comment: That's perfect! Thanks!


$http get by id with AngularJS

Question: I'm using AngularJS 1.6.3
I'm trying to get data by id but my angular-side is not working
Server side :
app.get("/user/:id", function(req,res){
    testDb.findOne({_id : req.params.id}, function(err, doc){
        res.send(doc);
        res.statusCode = 200;
    });
});

AngularJS side :
    var UserCtrl = myApp.controller('UserCtrl', function($scope,$http){
    $scope.user = null

    $scope.getByID = function() {
            $http.get("/user/" + id).then(function(response){
                console.log("get");
                $scope.user = response.data;
            });
        }

getByID();
    });

I've got an error "id is not defined". But I would like to get it from the URL.
Comment: @Tewan `getByID();` ==> `$scope.getByID(3);` (To get user with `id==3`)
Comment: _No console errors, it's like my function isn't called_ Yes - You don't call it anywhere. Show us how you call this function
Comment: any console errors??
Comment: Expected result and the result you're getting? You're just saying it's not working which isn't helpful.
Comment: No console errors, it's like my function isn't called.
Comment: Th results expected is a json which would be getted by this request, there is no results
Comment: Sorry guys, I was looking a wrong file, yes I've got the error "id is not defined"
Comment: _But I would like to get it from the URL._ so use javascript (`$window.location.stuff`) and be sure to pass that into your function argument.
Comment: @AlonEitan Yes but I want that the id should be getted from the URL, like `/users/3` then `id === 3` and then i get the json for this user
Comment: @Tewan In that case - Take a look [at this](https://docs.angularjs.org/api/ngRoute/service/$routeParams)
Comment: Where is **id** defined?  I don't see it declared anywhere.
Answer: Finally I found the solution by using $routeParams.
Controller :
var UserCtrl = myApp.controller('UserCtrl', function($scope,$http,$routeParams){
$scope.user = null;
var id = $routeParams.id;
$scope.getByID = function() {
        $http.get("/user/" + id).then(function(response){
            console.log("get");
            $scope.user = response.data;
        });
    }

   getByID();
});

Answer: pass parameter to the function when you are calling it
  $scope.getByID = function(id) {
            $http.get("/user/" + id).then(function(response){
                console.log("get");
                $scope.user = response.data;
            });
        }

$scope.getByID(10); // pass id

Comment: I don't to pass the parameter in the function when I'm calling it, I want to retrieve the ID in the URL like if my URL is http://localhost:8080/user/5 then my function do a GET request with id = 5.
Answer: You can use $state to get state parameters.
var UserCtrl = myApp.controller('UserCtrl', function($scope,$http,$state){
    $scope.user = null;

    $scope.getByID = function() {
            $http.get("/user/" + $state.params.id).then(function(response){
                console.log("get");
                $scope.user = response.data;
            });
        }

$scope.getByID();
    });

Comment: Question was about getting id value from URL to use inside controller function. getByID is defined inside controller.
Comment: don't know what really the backend service expects "id" to be. integer or it could be string as well. My focus is to point usage of $state to get parameter to use inside controller.
Comment: You're already there (I believe), but the OP doesn't use `[ui-router]`, if you demonstrate the native [$routeParams](https://docs.angularjs.org/api/ngRoute/service/$routeParams) for url params then I'll even upvote. Considering that the OP didn't gave enough details, you're answer is very good
Comment: When I try your solution, I got an error : `Error: [$injector:modulerr] Failed to instantiate module myApp due to:
[$injector:unpr] Unknown provider: $stateProvider
http://errors.angularjs.org/1.6.3/$injector/unpr?p0=%24stateProvider`
Answer:
Install ui-router.
bower install --save angular-ui-router#0.3.1
Link the script in index.html.
<!doctype html>

Add the ui router dependency in app.js.
var myApp = angular.module('helloworld', ['ui.router']);
Define the states in config.

You can define a $state to pass id to a page as state parameter.
routes.js
myApp.config(function($stateProvider){
    $stateProvider
            .state('home', {
                url: '/home/:id',
                templateURL:'home_page.html',
                controller: 'UserCtrl'
                }
            });
});

userCtrl.js
var UserCtrl = myApp.controller('UserCtrl', function($scope,$http,$stateParams){
        $scope.user = null;

        $scope.getByID = function() {
                $http.get("/user/" + $stateParams.id).then(function(response){
                    console.log("get");
                    $scope.user = response.data;
                });
            }

    $scope.getByID();
        });

Finally, redirect to the page with id as below
From JavaScript: $state.go('home', { id: '12345' });
From html: Home
Comment: I've got an error : `Error: [$injector:unpr] Unknown provider: $stateProvider <- $state <- UserCtrl`
Comment: the state should be defined inside the routing file. Not inside the controller
Comment: Did you link the script in index.html and add dependency of ui.router in app.js ?
Answer: I hope this help you.
I suggest you pass your variable using params section like below AngularJS To Node JS
AngularJS Code
    $http({
           method : "GET",
           url : "http://localhost:4800/p",
           params:{"tagId":"5"}
         }).then(function mySucces(response) {
            console.log("success");
            }, function myError(response) {
     });

Node JS
app.get('/p', function (req, res) {
        console.log(req.query.tagId)
        console.log("call");
    });

Comment: So if I have 10 users different, I have to make 10 different GET request in AngularJS ?
Comment: if you want to pass more than one variable you can use post method either in get method you can pass in array like below
`code`
var array = [10,20,30,50];
        $http({
            method : "GET",
            url : "http://localhost:4800/p",
            params:{"tagId":array}
        }).then(function mySucces(response) {
        console.log("success");
        }, function myError(response) {
});
`code`
But that's not a good way because get request not support  longer than 256 characters, you can use post method

$http get by id with AngularJS


Graph API batching with paging?

Question: I'm using the PHP Facebook SDK and graph API to get all the likes of all of a user's friends. Problem is it's taking quite a while to execute.
Currently I'm getting all the user's friends, then individually looping through each friend and collecting all their likes.
To speed things up, I want to batch every 50 "/user_friend_fbid/likes" requests (but also do paging for these as well).
i.e. this:
foreach (facebookUserFriends($fb_id) as $friend) { //custom func returns friends
    facebookUserLikes($friend['id'],$fb_location); //custom func returns all user likes
}

...versus:
$i = 0;
foreach (facebookUserFriends($fb_id) as $friend) {
    $queries[$i]['method'] = 'GET';
    $queries[$i]['relative_url'] = $friend['id'].'/likes';
    if ($i==49) {
       batchProcess($queries); //custom func returns all likes (but doesn't do paging)
       $i = 0;
    }
    $i++;
}

TL;DR how do I perform paging within a batch query?
Answer: That stuff could get ugly really fast ;-)
Use FQL multi-query instead and save both parties some time: https://developers.facebook.com/docs/reference/rest/fql.multiquery/
See here as well:
Facebook New PHP SDK For Graph API - Multi Query
For your case, a single FQL could suffice:
SELECT object_id, user_id FROM like WHERE user_id IN (SELECT uid2 FROM friend WHERE uid1=me())

That finds the likes for my own friends for instance; substitute me() with something else.
Comment: Hmm, that's not a fun language. I've worked out how to retrieve a user's likes and a user's friends, but not all if a friends likes...
Comment: This seems to work, but only returns "MUSICIAN/BAND": SELECT name, type
FROM page
WHERE page_id
IN
(SELECT page_id
FROM page_fan
WHERE uid
IN
(SELECT uid2
FROM friend
WHERE uid1 = me())) - then filtering by type = "local business" returns 4 results which isn't everything. I've read that FQL doesn't return everything.
Comment: There are certain limitations to FQL, but so far I have not encountered those before :) your data set also seems to be particularly large, which might cause some intermediate results to be capped to an upper limit?
Answer: I would take a breadth-first approach. Queue up the first 50 users 1st batch request, and when the batch is returned, save the data, and then create a new batch from the 50 paging urls returned.

Graph API batching with paging?


Dirichlet distribution and its applications in data science

Question: What is the Dirichlet distribution and what are its applications?
Comment: @Akram There are literally thousands of applications and potential applications. If you want more than just a few applications, your question is too broad and will be closed. It's up to you, but if a few applications isn't sufficient for you your question won't be suitable for our site.
Comment: Did you read the wikipedia page? Do you have any specific questions after reading it? https://en.wikipedia.org/wiki/Dirichlet_distribution
Comment: What is that you don't understand? What do you want to combine and why? Please edit to make your question more clear.
Comment: I basically dont understand the applications of the Dirichlet distribution in the context of numerical simulations.
Comment: I hope that is clear
Comment: Sorry, but it is still unclear. Moreover, if your problem is that you don't understand documentation of `numpy.random.dirichlet`, then it's off-topic on this site since we do not provide help on using Python (see http://stats.stackexchange.com/help/on-topic)
Comment: How about that?
Comment: At best people might be able to give a few of the applications
Comment: Hmm is there not enough research into this?
Answer: A Dirichlet distribution is a vector-valued continuous distribution whose components are in (0,1) and which sum to 1.
Consider a situation where $X_1\sim\text{Beta}(\alpha_1,\alpha_2)$ and $X_2=1-X_1$. Then $\mathbf{X}=(X_1,X_2)^\prime$ is the simplest case of a Dirichlet distribution, but more typically $\mathbf X$ will be of dimension $3$ or more.
It generalizes the Beta distribution (which is commonly used to model continuous proportions) to the situation where some whole is made up of multiple proportions of interest (e.g. the proportions of the various components in some mixture, such as the proportions of different soil types in a region, or the proportion of various ingredients in some mixture (such as a shampoo, say), or the proportions of a document on each of several topics. That is, it is a common choice for compositional data.
This distribution has the density
$f(\mathbf{x};\,\mathbf{\alpha})=\frac{x_1^{\alpha_1-1}\,x_2^{\alpha_2-1}\,...\,x_k^{\alpha_k-1}}{\mathbf{B}(\mathbf{\alpha)}}\,,\: 0<x_i<1\,,\sum_i x_i=1\,,\alpha_i>0$
where $\mathbf{B}(\mathbf{\alpha})=\frac{\Gamma(\alpha_1)\Gamma(\alpha_2)...\Gamma(\alpha_k)}{\Gamma(\alpha_1+\alpha_2+...+\alpha_k)}$
Another common use for the Dirichlet is as a prior distribution on the multinomial in Bayesian statistics.


Recursively filter and map a list of properties

Question: I'm using Kotlin reflection to check if attributes that have a certain annotation are null.
Given the following example:
data class DataClass(
    @SomeRandomAnnotation
    val otherAnnotated: String?,
    val inner: InnerClass
)

data class AnotherDataClass(
    @SomeRandomAnnotation
    val annotatedProperty: String?,
    val dataClass: DataClass
) {

    fun checkCreditAnalysisConstrain() {
        print(checkConstrain(this))
    }
}

And the function that checks it:
fun checkConstrain(parentClass: Any): List<String> {
    val filter = parentClass::class.memberProperties.filter {
        if (memberIsDataClass(it)) checkConstrain(getMemberPropertyInstance(parentClass, it))

        hasAnnotation(it) && propertyIsNull(it, parentClass)
    }
    return filter.map { formatResult(parentClass, it) }
}

The idea is that the function is going to iterate through the attributes of my classes checking if they have the annotation and checking if the value is null.
If the property is a data class, the code evaluates the properties of the childs, recursively.
After that, I map the results, transforming the KProperty's into a simple String that is human readable, containing the class name and the attribute name.
The problem is that the above code does not work as expected. The properties returned are only the properties from the first-level class.
If, instead of doing a filter, I just run a forEach and print the result, I get the expected attributes. So I'm pretty sure it's related to the recurring inside a filter.
Do you see any way of doing this in a more functional way? I'm just concerned I won't need a "temp" list and add values to the list and reset it afterwards.
Answer: Your function recursively calls itself, but does nothing with the returned list of that recursive call. That's why you only get results for the top-level class.
Also, in my opinion, you shouldn't rely on side effects happening from your filter call. It probably works, but the function's documentation does not provide a guarantee that it will be called exactly once per item in the collection. So there should be a separate for-loop to do the recursive calls, and the result should be added onto existing results.
fun checkConstrain(parent: Any): List<String> {
    val memberProperties = parent::class.memberProperties
    var result = memberProperties
        .filter { hasAnnotation(it) && propertyIsNull(it, parent) }
        .map { formatResult(parent, it) }
    memberProperties.filter { memberIsDataClass(it) }
        .mapNotNull { getMemberPropertyInstance(parent, it) }
        .forEach { result += checkConstrain(it) }
    return result
}

You didn't provide code for several of the functions you used. This is what I used for them:
val KProperty<*>.returnTypeClass get() = this.returnType.classifier as? KClass<*>
fun <T> memberIsDataClass(member: KProperty<T>) = member.returnTypeClass?.isData == true
fun <T> getMemberPropertyInstance(parent: Any, property: KProperty<T>) = property.getter.call(parent)
fun <T> hasAnnotation(property: KProperty<T>) = property.annotations.firstOrNull { it.annotationClass == SomeRandomAnnotation::class } != null
fun <T> propertyIsNull(property: KProperty<T>, parent: Any) = getMemberPropertyInstance(parent, property) == null
fun formatResult(parent: Any, property: KProperty<*>) = "$parent's property(${property.name}) is annotated with SomeRandomAnnotation and is null."


How does $\frac{xy}{A}=\frac{1}{bcK}+\frac{x+y}{bc}$ become $\frac{A}{xy} = bcK - \frac{A(x+y)K}{xy}$?

Question: As part of a derivation for a formula I was given the following:
$$\frac{xy}{A} = \frac{1}{bcK} + \frac{x+y}{bc} \quad\Rightarrow\quad \frac{A}{xy} = bcK - \frac{A(x+y)K}{xy}$$
Where $b$, $c$, and $K$ are all constants (I've replaced most chemistry symbols with something more readable). The idea here is that by varying $x$ or $y$, and measuring $A$, you are able to determine $K$ (equilibrium constant) from the slope.
I was told the rearrangement involved some less user friendly maths, so I made a few attempts with little success. How is this rearrangement done? And what is the "less user friendly maths" used in this situation?
Comment: As for what makes this "less user friendly maths" ... It's hard to say. The steps are elementary enough. Maybe the person telling you this is observing that the left-hand sides of the two equations alone *might* seem to be suggesting that "all you have to do" is reciprocate, whereas the actual procedure isn't quite so simple (or "user friendly") as *that*.
Comment: Think that's where I went wrong to begin with. Seems fairly user friendly now that I've seen it. Thanks for the help @Aman
Answer: \begin{align}
\frac{xy}{A} & =\frac{1}{bcK} + \frac{x+y}{bc}\\
 & = \frac{1+(x+y)K}{bcK} \\
\implies bcK &=\left(1+(x+y)K\right)\left(\frac{A}{xy}\right)\\
&=\frac{A}{xy}+{A(x+y)K\over xy}\\
\implies \frac{A}{xy} &= bcK - \frac{A(x+y)K}{xy}\end{align}


Como quebrar a linha?

Question: Nome = input("Digite o nome do cliente: ")
DiaVencimento = input("Digite o dia de vencimento: ")
MêsVencimento = input("Digite o mês de vencimento: ")
ValorFatura = input("Digite o valor da fatura: ")

print("Olá,", Nome,
"A sua fatura com vencimento em ", DiaVencimento, " de ", MêsVencimento, "no valor de R$", ValorFatura, "está fechada.")

Tem como quebrar a linha logo após a variável "Nome"?
Answer: Basta colocar o caractere de quebra de linha onde deseja a quebra.
Esse caractere é digitado escapando-se a letra "n" com uma barra invertida - a famosa sequência "\n" -  quando o parser do Python encontra essa sequência dentro de uma string ela é automaticamente convertida para o caractere de quebra de linha usado em sistemas Unix, que é universal (o "print" depois converte para a sequência correta em cada sistema operacional):
print("Olá,", Nome,
"\n A sua fatura com vencimento em ", DiaVencimento, " de ", MêsVencimento, "no valor de R$", ValorFatura, "está fechada.")

Também não é legal ficar abrindo e fechando aspas, e mais as vírgulas toda hora - Python tem diversas possibilidades de formatação de string que permitem que você crie seu texto de saída de forma bem mais legível. Uma delas é o método ".format" de strings:
print("Olá {nome}\n. A sua fatura com vencimento em {vencimento} de {mesvencimento} no valor de R${valor:0.02f} está fechada".format(nome=nome, vencimento=DiaVencimento,  mesvencimento=MesVencimento, valor=float(ValorFatura)))

E na versão 3.6 em diante você pode até usar strings com o prefixo f" " que permitem a formatação direta a partir das variáveis, sem precisar chamar o método format. Ou seja, fica só assim:
print(f"Olá, {Nome}\n A sua fatura com vencimento em {DiaVencimento} de {MêsVencimento} no valor de R$ {ValorFatura} está fechada.")

Comment: EM Python 3 pode sim  - eu pessoalmente não recomendaria, mas pode.
Comment: Python permite variáveis com nomes acentuadas `MêsVencimento`? Eu jurada que isso não era permitido.
Answer: Use o escape \n
print("Olá,", Nome, "\n A sua fatura com vencimento em ", DiaVencimento, " de ", MêsVencimento, "no valor de R$", ValorFatura, "está fechada.")

Como quebrar a linha?


Fundamental theorem of calculus and pullback bundles

Question: Let $X$ be a manifold and $\pi:E\rightarrow X$ a vector bundle
over $X$ equipped with a metric $\left\langle \cdot,\cdot\right\rangle $.
Let $f:[0,1]\rightarrow M$ be a smooth map, and consider the pullback
bundle $f^{*}E\rightarrow[0,1]$. This is the vector bundle whose
fiber over $t\in[0,1]$ is
$$
(f^{*}E)_{t}=\left\{ (t,v)\,:\, v\in E_{f(t)}\right\} .
$$
Let $\phi:f^{*}E\rightarrow E$ denote the map $\phi(t,v)=v$.
Let $\nabla$ denote a connection on $E$, and let $D:=f^{*}\nabla$
denote the induced connection on $f^{*}E$.
$D$ is defined as follows:
suppose $F\in\Gamma(f^{*}E)$ is a section of $f^{*}E$, so that $\phi(F(t))\in E_{f(t)}$
for all $t\in[0,1]$. Fix $s\in[0,1]$, and let $v$ denote any vector
field on $X$ with $v(f(s))=\phi(F(s))$.
Then by definition
$$
(D_{\partial_{t}}F)(s)=\left(s,(\nabla_{\dot{f}(s)}v)(f(s))\right)\mbox{ as elements of }(f^{*}E)_{s},
$$
the points being that the right-hand side of the above expression is independent of the choice of $v$.
Assume now that $f(0)=f(1)$. Then if $F\in\Gamma(f^{*}E)$ then $\phi(F(1))$
and $\phi(F(0))$ both lie in the same vector space $E_{f(0)}$. My question
is: does the following generalization of the fundamental theorem of
calculus always hold?
$$
|\phi(F(1))-\phi(F(0))| \le \int_{0}^{1}|\phi(D_{\partial_{t}}F)(t)|dt.
$$
Comment: $\phi(F(1))$ and $\phi(F(0))$ lie in the same vector space, but $\phi(DF(t))$ for $t\in(0,1)$ do not. So how do you integrate over $\phi(DF(t))$?
Comment: good point, now it makes more sense
Comment: presumably $f:[0,1]\to X$? (You wrote $\to M$).
Comment: This is still not right. Now you introduced $|\cdot|$ applied to vectors of $E_x$. But plain vector bundles do not come with a norm on their fibers; some additional structure is needed.
Comment: @Florian: the vector bundle is equipped with a metric. (First line of the question; at least that's what I hope the OP means.)
Comment: @Willie: Oh, OK, I didn't see this. But I still don't see a compatibility condition between the connection and the metric, so the statement is obviously false. Never mind; you already explained that it's even false for Riemannian manifolds.
Answer: No. A simple counter example comes when $E$ is not orientable: consider the Möbius strip as a one dimensional bundle over $S^1$. We can give a metric on it and consider the induced Levi-Civita connection.
If you start with the vector $v$ over $0$, when you parallel transport $v$ around the circle you get $-v$. The norm of the derivative is 0, but the total difference is $2|v|$.

In the orientable case it is not better. Just take $E$ to be the tangent bundle $TX$ and treat it as a Riemannian manifold. Then parallel transport around a closed loop (for which by definition your RHS expression vanishes) does not necessarily bring a vector back to itself: you will in general pick up a defect related to the area of the loop and the enclosed curvature.
Comment: From the analysis point of view, you should think of this failure as the following: in a local trivialisation, the covariant derivative is $\nabla v = dv + \omega\wedge v$, where $\omega$ is the connection one form. You have then that in the trivialisation, using the usual fundamental theorem of calculus $v(1) - v(0) = \int_0^1 \dot{\gamma}\cdot dv~ds$. To conclude your inequality you necessarily need strong assumptions on the 0th order term $\omega\wedge v$.
Answer: As Willie says, it's not true. It is true if $E$ is a flat trivial vector bundle over $X$. In general however $f$ and $D$ determine a map $\mathrm{Hol}(f,D): E_{f(0)} \rightarrow E_{f(0)}$ called the holonomy map, and if $F$ is parallel then the RHS vanishes but the LHS is $|\mathrm{Hol}(f,D)(F(0))-F(0)|$ which is not necessarily zero.


What is the difference between Incoming webhook, Outgoing webhook and O365 webhook

Question: Can anybody explain at a very basic level what is the difference between Incoming webhook, Outgoing webhook, and O365 webhook
Comment: It's documented [here](https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/what-are-webhooks-and-connectors).
Comment: In short, (1) Webhooks is a lightweight HTTP pattern for connecting Web APIs & services with a publish/subscribe model. It's widely used in Microsoft Graph API world. (2) Outgoing webhooks allow your users to send text messages from a channel to your web services. Say, users can use @mention to your outgoing webhook & send a message to your service. (3) Incoming webhooks are the simplest type of connector used in your Microsoft Teams. For any channel in team  you can choose to expose an HTTPS endpoint that will accept JSON & insert messages into that channel. Hope this clarifies.
Comment: Let me move this to answer. Consider upvoting it and accepting the answer; so it can be useful to other community members as well.
Answer:
Webhooks is a lightweight HTTP pattern for connecting Web APIs & services with a publish/subscribe model. It's widely used in Microsoft Graph API world.
Outgoing webhooks allow your users to send text messages from a
channel to your web services. Say, users can use @mention to your
outgoing webhook & send a message to your service.
Incoming
webhooks are the simplest type of connector used in your Microsoft
Teams. For any channel in team you can choose to expose an HTTPS
endpoint that will accept JSON & insert messages into that channel.
It's documented here.
Answer: The answer above is pretty accurate - webhooks are a lightweight API call - specifically known as an HTTP push request. Incoming webhooks are useful for triggering actions within your existing software application, database, etc. Outgoing webhooks can signal specified events to external applications, databases, etc. O365 provides opportunities to generate webhooks within several applications - more complex API calls are available via native development in the Azure programming interface.


What kind model or brand guitar do I have what kind is this

Question: I have an Acoustic 6 string that has plastic tuning keys on it also the top of the neck goes into a point by the keys, not flat.
The tag on the inside states the name Austin and after that Lonestar in the middle. It says Houston Texas bottom left-hand Corner, the tag also states on the right-hand bottom corner "made in Mexico".
Tell me about this guitar, why can I not find it on the internet, what kind of guitar is this?
Comment: Sorry but you have made this very confusing by not structuring your post in sentences.  A bit of punctuation would make a huge difference here.
Answer: The Lonestar line of Guitars and Mandolins were not made for very many years. They were distributed by LPD Music, a wholesale music company.  I believe they were manufactured in Paracho Mexico. The mandolins had deep bodies and solid cedar tops. I never sold the guitars, so I can't tell you much about them, but they were likely solid cedar also.
You won't find them on the internet because the brand didn't last very long.
If I can find an old LPD catalogue I'll update with the product description.
EDIT: Here's link to the Internet Archive of the Product site:
http://web.archive.org/web/20030201114253/http://www.lonestarguitars.com/


Install error in rhel server

Question: I have a rhel machine with no internet or rhel subscrription. I loaded a rhel 6 dvd and trying to install some package from that dvd. When I am trying to install gcc I get the following error.
<code>Error: Package: glibc-2.12-1.149.el6.i686 (rhel6-Server)
           Requires: glibc-common = 2.12-1.149.el6
           Installed: glibc-common-2.12-1.192.el6.x86_64 (@rhel-6-server-rpms)
               glibc-common = 2.12-1.192.el6
           Available: glibc-common-2.12-1.149.el6.x86_64 (rhel6-Server)
               glibc-common = 2.12-1.149.el6
</code>
What does that error mean? I have both 32 bit and 64 bit glibc installed on my machine
<code>[root@ip-10-0-0-34 rhel]# yum list installed | grep glibc-common
glibc-common.x86_64                2.12-1.192.el6            @rhel-6-server-rpms
</code>
Answer: Most likely you installed and/or updated the server from a package source that is newer then the DVD you now try to install from.
Try to burn a newer DVD. 6.8 is the current version, but I've no idea if they include glibc 2.12-1.192 or an earlier release. If that's not working because you updated the server to an even newer state, you'll have to either connect it to the network or manually import the correct package versions of everything you need.

Install error in rhel server


IIS7 + ASP.NET Impersonation + Windows Auth = 401 Unauthorized

Question: I've got an asp.net app that relies on Request.LogonUserIdentity.Name to be populated with the username of the person logged onto the client machine. In IIS7 on the webserver, I've disabled Anonymous Authentication and enabled ASP.NET Impersonation & Windows Authentication. (I'm logging onto the webserver with a service account, not my own.) When I try to browse to the site from my desktop, I get prompted for my network credentials which fail - 401 Unauthorized....  I'm using .Net 3.5 sp Whatever. The server is running IIS 7.5.
Application Pool:

Managed Pipeline Mode: Classic
Load User Profile: false
Identity: ApplicationPoolIdentity

Web Application:

.NET Auth Rules: Allow All Users
Enabled auth types: ASP.NET Impersonation, Windows

File-system Folder permissions:

Creator Owner: Special Permissions
Machine\IUsr: Read & Execute, List folder contents, Read
Machine\System: Full Control
My Domain Account: Full Control
Machine\Administrators: Full Control
Machine\Users: Read & Execute, List folder contents, Read
Machine\IIS_IUSRS: Read & Execute, List folder contents, Read
Trusted Installer: Full Control

I've tried adding Machine\Everyone and Domain\Domain Users with Read and also with Full Control and I'm still being blocked.
Comment: can you look at the servers security event log or IIS log and see what user account is in the logon event / log record ?
Comment: When I try to hit the site and enter my domain credentials, my domain account is recorded in the logon/logoff events. Is it that I essentially need to grant the entire network logon rights to the machine?
Comment: when you said the user account is in the security log, was the status success or failure ?
Comment: "An account was successfully logged on." The values under the "Subject" header are blank or null; logon type = 3; values under "New Logon" header are my information.
Comment: this means you have logon rights to the machine, but the web server turns you down. so i`m guessing that the user permissions for iis folders are amiss. theres a good kb [here](http://support.microsoft.com/kb/907273) that deals with exactly this problem, i hope it helps.
Comment: Unfortunately, that link appears to only contain information for IIS6. I still looked it over and attempted to re-apply permissions to the folder under inetpub\wwwroot. Still getting the 401.
Comment: does your app go get data from a database on another machine (not the web server machine)?
Comment: Yes, mssql 2008, but that's via a sql login. It also pulls data from MOSS 2007, but the error would be different (seen plenty of those).
Answer: This is most likely from the loopbackcheck when testing locally on the server.  I bet it works if you test it from another server.
Turn off the loopback check using method 2 from this page: http://support.microsoft.com/kb/896861. A reboot isn't required for your change.
As for permissions, with impersonation enabled it will need the authenticated user, plus the app pool user will be needed some some things.  So, the key permissions to use are SYSTEM, Administrators, "IIS APPPOOL\{apppoolname}" and a group for the possible users that will authenticate.
Answer: In IIS 7.5 when you turn on Windows authentication, there is also an option for providers. By default, Negotiate is 1st preference and then NTLM. I've seen issues where negotiate fails because of other setup related issues and then presents user with credential challenge. I've been able to work around this by making NTLM the first provider.
You can also view the site traffic with fiddler to see what's happening when you get challenged for credentials.


How to align and compare two elements (sequence) in a list using python

Question: here is my question:
I've got a file which looks like this:

103L   Sequence:   MNIFEMLRIDEGLRLKIYKDTEGYYTIGIGHLLTKSPSLNSLDAAKSELDKAIGRNTNGVITKDEAEKLFNQDVDAAVRGILRNAKLKPVYDSLDAVRRAALINMVFQMGETGVAGFTNSLRMLQQKRWDEAAVNLAKSRWYNQTPNRAKRVITTFRTGTWDAYKNL   Disorder:   ----------------------------------XXXXXX-----------------------------------------------------------------------------------------------------------------------------XX

It contains name, which in this case is 103L; protein sequence, which has "Sequence:" label; disorder region, which is after "Disorder:". the "-" represent that this position is ordered, and "X" represent that this particular position is disordered. For example, that last two "XX" under disorder represent that the last two position of the protein sequence is disordered, which is "NL".
After I use split method, it looks like this:
['>103L', 'Sequence:', 'MNIFEMLRIDEGLRLKIYKDTEGYYTIGIGHLLTKSPSLNSLDAAKSELDKAIGRNTNGVITKDEAEKLFNQDVDAAVRGILRNAKLKPVYDSLDAVRRAALINMVFQMGETGVAGFTNSLRMLQQKRWDEAAVNLAKSRWYNQTPNRAKRVITTFRTGTWDAYKNL', 'Disorder:', '----------------------------------XXXXXX-----------------------------------------------------------------------------------------------------------------------------XX']
I want to use python to find the disorder sequence and its position. So the final file should look somewhat like this:
Name Sequence: 'real sequence'
Disorder: position(Posi) residue-name(R)
Take 103L as an example:

103L Sequence: MNIFEMLRIDEGLRLKIYKDTEGYYTIGIGHLLTKSPSLNSLDAAKSELDKAIGRNTNGVITKDEAEKLFNQDVDAAVRGILRNAKLKPVYDSLDAVRRAALINMVFQMGETGVAGFTNSLRMLQQKRWDEAAVNLAKSRWYNQTPNRAKRVITTFRTGTWDAYKNL
  Disorder: Posi R
            34   K
            35   S
            36   p
            37   S
            38   L
            39   N
            65   N
            66   L

I am new in python, really hope someone can help me, thank you so much!!!
Answer: suppose we have the results of the split command in a variable
split_list = ['>103L', 'Sequence:', 'MNIFEMLRIDEGLRLKIYKDTEGYYTIGIGHLLTKSPSLNSLDAAKSELDKAIGRNTNGVITKDEAEKLFNQDVDAAVRGILRNAKLKPVYDSLDAVRRAALINMVFQMGETGVAGFTNSLRMLQQKRWDEAAVNLAKSRWYNQTPNRAKRVITTFRTGTWDAYKNL', 'Disorder:', '----------------------------------XXXXXX-----------------------------------------------------------------------------------------------------------------------------XX']

lets work with just the important pieces, items 2 and 4,
res_name = split_list[2]  # ( i.e. 'MNIFEML...' )
disorder = split_list[4]  # ( i.e. '-----...XXX')

You can associate the elements of the two arrays like so.
sets = []
for i,c in enumerate( disorder ):
  if c == 'X':
    sets.append( (i, res_name[i]) )

The enumerate command in Python iterates through a list like object and returns an index and an item (i,c) for each member of disorder.  At the end of this operation, sets will contain tuples of what we're after, the index numbers where 'X' occurs in disorder and the corresponding residues from res_name.
sets = [(34,'K'), (35,'S') ... ]

If you want to use another nice Python feature you can construct sets in one line using whats called a list comprehension ,
sets = [ (i,res_name[i]) for i,c in enumerate(disorder) if c=='X' ]

This is a quick way to build a list and will be more efficient than the loop although the difference shouldn't matter for on the order of 100 items as you've shown in your example.  The only thing left is to write this new data to file.  We can create a string in the format that you want by making another list and joining the pieces with a space between them.  For each tuple in list we want the string version of the index and the residue name (which is already a string).  This can be done list so,
txt = ' '.join( [str(t[0]) + ' ' + t[1] for t in sets] )

the variable txt will now be equal to
>>> txt
'34 K 35 S 36 P 37 S 38 L 39 N 165 N 166 L'

To write out to a file with the format you specified you can do the following,
f = open( 'test.out', 'w' )
f.write( ' '.join(split_list[0:2]) + '\n' )
f.write( split_list[2] + ' Disorder: Posi R ' + txt )
f.close()

the first write command puts '>103L Sequence:' on the first line and adds a new line character.  The second outputs the original residue sequence and the txt variable we created above.
Answer: You can break this up into three distinct parts:

parse the input;
construct the new disorder string;
output the new file.

(1) and (3) are pretty simple, so I'll focus on (2). The main thing you need to do is iterate through your "disorder string" where you can access the character at each position, as well as the position itself. One way to do this is to use enumerate:
for i, x in enumerate(S)

which gives you a generator for each position (stored in i) and character (stored in x) in string S. Once you have that, all you need to do is record the position and the character in seq whenever the disorder string has an "X". In Python, this could look like:
if (x == 'X'):
    new_disorder.append( "{} {}".format(i, seq[i]) )

where we are formatting the result as a string, e.g. "34 R".
Here's a complete example:
# Parse the file which was already split into split_list
split_list = ['>103L', 'Sequence:', 'MNIFEMLRIDEGLRLKIYKDTEGYYTIGIGHLLTKSPSLNSLDAAKSELDKAIGRNTNGVITKDEAEKLFNQDVDAAVRGILRNAKLKPVYDSLDAVRRAALINMVFQMGETGVAGFTNSLRMLQQKRWDEAAVNLAKSRWYNQTPNRAKRVITTFRTGTWDAYKNL', 'Disorder:', '----------------------------------XXXXXX-----------------------------------------------------------------------------------------------------------------------------XX']
header   = split_list[0] + " " + split_list[1]
seq      = split_list[2]
disorder = split_list[4]

# Create the new disorder string
new_disorder = ["Disorder: Posi R"]
for i, x in enumerate(disorder):
    if x == "X":
        # Appends of the form: "AminoAcid Position"
        new_disorder.append( "{} {}".format(i, seq[i]) )

new_disorder = " ".join(new_disorder)

# Output the modified file
open("seq2.txt", "w").write( "\n".join([header, seq, new_disorder]))

Note that I get slightly different output than the example you gave:
103L Sequence:
MNIFEMLRIDEGLRLKIYKDTEGYYTIGIGHLLTKSPSLNSLDAAKSELDKAIGRNTNGVITKDEAEKLFNQDVDAAVRGILRNAKLKPVYDSLDAVRRAALINMVFQMGETGVAGFTNSLRMLQQKRWDEAAVNLAKSRWYNQTPNRAKRVITTFRTGTWDAYKNL
Disorder: Posi R 34 K 35 S 36 P 37 S 38 L 39 N 165 N 166 L

Comment: Thank you so much! I really appreciate your help. But may I ask one more question? I run your example in python. and it gives me this: Traceback (most recent call last):
 File"/Users/Jasonlin/PycharmProjects/Parsing_PDB/PDB/MDML_example.py", line 5, in
    seq = lines[1].rstrip()
IndexError: list index out of range. \n So I assume that the seq. txt file that you use are a text file generated by the example I gave you right? Sorry to bother you again. Thank you so much!
Comment: @user3817527: is your input all stored on one line? I was assuming that you had input across multiple lines, separated by the newline character `'\n'`.
Comment: I just copied the example into the txt file @mdml
Comment: @user3817527: I'm not sure I understand how your input is working, but if you can get the input into a `list` named `split_list` as in your example my code should work.
Comment: I still got a different error. it says:   File "/Users/Jasonlin/PycharmProjects/Parsing_PDB/PDB/MDML_example.py", line 20, in
    open("/Users/Jasonlin/Documents/PDB/seq2.txt", "w").write( "\n".join([header, seq, new_disorder]))
TypeError: sequence item 0: expected string, list found.
Comment: And this is my code (I basically copied yours but I do parse the line into a list named split_list)                                  # Parse the file which was already split into split_list
lines = open("seq.txt")
for list in lines:
    split_list = list.split()
header = split_list[0:2]
seq = split_list[2]
disorder = split_list[4]
Comment: # Create the new disorder string
new_disorder = ["Disorder: Posi R"]
for i, x in enumerate(disorder):
    if x == "X":
        # Appends of the form: "AminoAcid Position"
        new_disorder.append("{} {}".format(i, seq[i]))

new_disorder = " ".join(new_disorder)

# Output the modified file
open("seq2.txt", "w").write( "\n".join([header, seq, new_disorder]))
Comment: @user3817527: you need to join the lists here: `header = "".join(split_list[0:2])`
Comment: @user3817527: glad to be of help!
Comment: Actually I have another question. What if I have multiple lists just like the example I showed you? I used your code on the file which contains multiple protein sequence and their corresponding disordered regions. They are all formatted correctly. There is no error but only the last sequence and its disordered region showed up. What should I do?
Comment: @user3817527: sounds feasible, maybe you can post it as a different question? I'd be happy to look at it. Also, if my answer solved your original problem, please [accept it](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) by clicking the green check box.


JS: Switch case seemingly goes to default

Question: I have a very simple method that receives a number and returns a text based on the range.
This is it:
getBoardLocation(num) {
    switch (num) {
        case (6 >= num >= 1):
            return 'bl';
        case (12 >= num >= 7):
            return 'br';
        case (18 >= num >= 13):
            return 'tl'
        case (24 >= num >= 19):
            return 'tr';
        default:
            break;
    }
}

For some reason, despite being sure via breakpoints that the parameter being passed is indeed a number, and indeed in the range of one of the cases, it just goes to the default case, as seen in devtools, like here:

I feel like I missed something incredibly stupid, but I can't figure out what.
Comment: what do you mean?
Answer: there are many things wrong with your switch
try this

const isBetween = (n, start, stop) => n >= start && n <= stop

function getBoardLocation (num) {
    switch (true) {
        case isBetween(num, 1, 6):
            return 'bl';
        case isBetween(num, 7, 12):
            return 'br';
        case isBetween(num, 13, 18):
            return 'tl'
        case isBetween(num, 19, 24):
            return 'tr';
        default:
           throw new Error(num + 'is not valid')
    }
}
[1, 9, 14, 21].forEach(n => console.log(n, getBoardLocation(n)))

another approach could be this using some sort of a configuration object

const config = [
 {min: 1, max: 6, value: 'bl'},
 {min: 7, max: 12, value: 'br'},
 {min: 13, max: 18, value: 'tl'},
 {min: 19, max: 24, value: 'tr'}
]

 function getBoardLocation (num) {
    const res =  config.find(({min, max}) => num >= min && num <= max)?.value
    if(!res){
      throw new Error(num + 'is not valid')
    }
    return res
 }

[1, 9, 14, 21].forEach(n => console.log(n, getBoardLocation(n)))
Comment: And to really make the code more logical, just get rid of the `switch / case`, and put the more logical `if else`..
Answer: You'll be disappointed to learn that JS switch statements don't work the way you think.
The value provided in the case statment must exactly match the value provided in the switch statement for that specific case to match.
In your case, true/false doesn't ever match the provided number, so you fall through to the default case.
Answer: from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch:

The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered. The default clause of a switch statement will be jumped to if no case matches the expression's value.

which means the expression (num) is evaluated to 1 in your example,
but the expressions in the cases are evaluated to either true/false, and 1 !== true


Fetching and rendering custom-library generated blocks in twig

Question: I am using the following code in my theme to fetch 3 blocks (each containing 4 fields) generated via the custom block library interface i:e all 3  block are of the HomePage-Block type:
<code>function legislation_research_theme_preprocess_page(&$variables, $hook) {
    for($i = 1; $i <= 3; $i++) {
        $block_entity = Drupal\block_content\Entity\BlockContent::load($i);// BLOCK_ID
        $block_view[$i] = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity);
    }

    if ($block_view) {
        $variables['page']['my_block'] = $block_view;
    }
}
</code>
In my page--front.html.twig, my blocks output via:
<code>    {{ page.my_block }}
</code>
However, the output is of the individual fields from each of the blocks rather than 3 divs containing 4 fields of content from each block. That's making it impossible to to style:

Can anyone advice how I might be able to output each block but contained in individual parent divs?
Comment: A block content entity doesn't have a template on its own. You need to wrap it in a block plugin template, see https://drupal.stackexchange.com/questions/236854/how-do-i-place-a-block-in-a-region-programatically
Answer: I render my custom library blocks like this:
<code>{{drupal_entity('block', 'block_id')}}
</code>
So you have to search your block at your library and use this block's machine name where i say block_id.
Hope it helps.
Comment: Thank you for you response. I just tried it and Twig does not recognise the drupal_entity function and so it fails with an Unknown "drupal_entity" function error message.

Is there something extra you are doing to make that function active in twig?
Comment: I'm sorry, but i also found that in the documentation. https://drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak
Comment: I see! But that would work only if the Twig Tweak module is installed. I'm assuming you do?
Comment: Yes, i always install this module. I am not so advanced so i thought that was part of the best practice to follow when you install drupal. Something like a starter pack. So my bad.


Is there a practical example on how to define the Region of Practical Equivalence (ROPE) in Bayesian estimation?

Question: I've been reading up on Bayesian estimation and see the Region of Practical Equivalence (ROPE) as a potentially very useful concept. It seems to be analogous to the rejection region in classical hypothesis testing.
Is there a practical example(s) (preferably in R) that walks you on how we select the ROPE for a particular user case?
Answer: Explained here.
http://doingbayesiandataanalysis.blogspot.com.au/2013/08/how-much-of-bayesian-posterior.html
Each particular case/example/domain of interest has its own ROPE. Selecting a ROPE does not depend on a particular analysis example but instead is based on the consequences of the data you are dealing with and what you consider the ROPE should be.


Adding Additional login security

Question: Considering login security for user logins, I would like an additional option such as a PIN option for all aspects of user login. This seems quite common now across a number of portals out there such as personal banking, social security/gov. tax sites and I would like possibly to offer this as an option to those who do not want to use Facebook, Twitter etc logins which I use on my projects. I appreciate it could simply be an additional field in the system config, but I would be keen to hear any comments on such features, or possibily a popular D7 module which most people use which for me as a Drupal 'plumber' can just drop in for easy of setup, or a generalistic 'how-to'.
Thanks in advance.
Comment: Would this be one pin across the entire site or a pin per user? And would the pin be the same for the same user (until they changed it) or would it be a "one time use" pin?
Comment: Preferably the usage would be to have a PIN per user account and not 'one time' but always required. Whilst I would use Captchas for initial registration, I'm keen to impliment additional user login security for user accounts whereby for users to login to their account, they not only have to enter the standard name (email,p/w) but an additional say 4 number PIN. Of course, I'm not sure how this would be overcome if the user was using an open ID or one of the popular social network 'allow' access such as those found in ala FB/Twitter. It's just an idea, I'm curious of the 'plumbing' involved.
Comment: I'll research this idea a bit and try to provide some responses soon.
Answer: Is there an existing "pin" login module?
I'm not aware of any module that does this itself. There are some pin-related modules, but most of them are related to using 2-factor authentication authentication.
Is a pin field actually useful to improve security?
My sense is that adding a pin would not be worth it.
First, pins are easily guessed: this article on commonly used pins shows how only 20 pins would break over 26% of accounts!
Second, if you were to just require the pin to be on the end of the password that actually makes it harder to break than making it a separate field because they would both need to be cracked at the same time rather than serially. That is in addition to the problem above of pins not being well distributed among the 10^4 potential combinations.
Third, you would have to build, audit, and then maintain this additional code for managing per user pins. That's a new database table, some form fields, and at least a few hundred lines of code that can be buggy that overall adds very little extra security.
Alternate improvements to login security
So, I have some other suggestions on how to improve login security in general:

Security Review offers brute force detection.
You could use one of the 2-factor authentication modules. My favorite way to do that is the tfa module which is the module deployed on drupal.org.
You could use a module to improve true password strength (vs. password policies that usually promote nonsense).
Comment: Thank you Greggles, your answer is satisfying. I suppose then it would be good practice to advise others to follow what other good portals do, ensure users use a good combination of characters and not simply name/number combi (ie ben1920). 10 characters for example, bxexnx1x9x. Anyway, you get my drift. My own annoyance is the 'drop down' 4 letter select (post login) some UK banks use!! Thanks again.
Comment: I'm not familiar with the dropdown thing you mention. If it is a select list of numbers for entering a pin then that could be focused on preventing a keylogging attack (which happen, but are pretty rare). One thing I'd like to see in Drupal is a "choose my login photo from a group of 20 photos" kind of feature. Those help prevent phishing AND protect against keylogger issues.
Comment: Having come back to this issue, I then decided that the module: https://www.drupal.org/project/security_questions was easier to implement as it also allows users to set their own questions (single or multiple) and given that users can set 'bizarre' questions, it may mean the answer can be of any strange answer related to it's owner. Hope that helps to future readers.

Adding Additional login security


is there a way to remove elements on a list through indexes entered on a text box

Question: I am trying to enter the command "remove" followed by indexes so that specific strings on a "to-do" list can be removed, is there any way I can do this without confusing the compiler and mistaking integers for strings. (I get the TypeError: string indices must be integers error as half of the command is a string, while the other is a number)
p.s. - id assume to use the .split tag so that I can pass arguments, however, I already have a function that parses commands.
todo_list = []

def parse_command(cmd):
    arg = cmd.split()
    if arg[0] == 'add':
        add_item(arg[1])
    elif arg[0] == 'remove':
        remove_item(arg[1])
    elif arg[0] == 'move':
        move_item(arg[1], arg[2])
    elif arg[0] == 'list':
        list_items()
    else:
        print("not a valid command")

def add_item(item):
    for i in range(0, 1):
        tasks = item
        todo_list.append(tasks)
    print("Your to-do list so far: ", todo_list)

def remove_item(idx):
    for idx in todo_list:
        if cmd == idx[cmd]:
            todo_list.pop(int(cmd))

def move_item(idx1, idx2):
    return("This function moves! ")

def list_items():
    for x in range(len(todo_list)):
        return todo_list[x]

while(True):

    cmd = input("Please input command: ")
    parse_command(cmd)

#input: Please input command: add hello
       #Your to-do list so far:  ['hello']
       #Please input command: add stack_overflow!
       #Your to-do list so far:  ['hello', 'stack_overflow!']
       #Please input command: remove 1

#after inputting "remove 1" it spits this message out:

TypeError                                 Traceback (most recent call last)
<ipython-input-78-9b3707886f99> in <module>
     37
     38     cmd = input("Please input command: ")
---> 39     parse_command(cmd)
     40
     41

<ipython-input-78-9b3707886f99> in parse_command(cmd)
      6         add_item(arg[1])
      7     elif arg[0] == 'remove':
----> 8         remove_item(arg[1])
      9     elif arg[0] == 'move':
     10         move_item(arg[1], arg[2])

<ipython-input-78-9b3707886f99> in remove_item(idx)
     23 def remove_item(idx):
     24     for idx in todo_list:
---> 25         if cmd == idx[cmd]:
     26             todo_list.pop(idx)
     27

TypeError: string indices must be integers```

Comment: Welcome to SO, please see [mre] it would help if you could provide sample input and the expected output.
Comment: I don't understand your question's body, but judging from the title the answer is `list.pop(int(input()))`.
Comment: updated the post so that it involves all the code for better understanding, sorry!
Comment: The compiler is not confused and is not making a mistake. `input()` takes a string so if you want to use part of that string as a number you have to convert it
Answer: This is how you can delete item from list by the idx index value:
def remove_item(idx):
    print("idx {} cmd {}".format(idx, cmd)) # cmd = remove 1

    #remove by index
    todo_list.pop(int(idx))

The reason you get Type Error is because of following line:
if cmd == idx[cmd]: which is a bit unclear to me.
However, the above function works fine


What playing techniques are sensitive to "jamming fingers"

Question: A Korg Krome 61/73 review mentions that you can jam fingers between two keys because they are flat. I've had an opportunity to play some cheap keyboards with flat keys and this didn't happen to me.
For considering this issue while buying a new synth, I would like to know: which playing techniques are vulnerable to this happening? And is it truly a problem at all (i.e., can it really happen when you play the keyboard or is it just another negative remark in the overall negative review)?
Answer: This is probably most likely to occur if you are stretching your hand, playing notes for apart, then a part of your finger could get stuck under a key, which wouldn't be good fun while playing a piece.
However, if you have good piano technique and keep your hands over the keyboard, rather than beyond the end of it, this shouldn't really happen.


Language switching does not work when browser language is configuired in drupal 8.3.7

Question: Language switching fails after enabling browser on  Detection and selection

/admin/config/regional/language/detection

Exisiting :
On switching language from the browser the url changes but the content remains the same
E.g, Default language browser is Germen.
mywebsite.com mywebsite.com/about etc shows German content.
While swiched to English url changes to mywebsite.com/en mywebsite.com/en/about etc
It shows Germen content instead of English.
Expected
On browser configured with Germen as default language, the site url should be mywebsite.com/de.
When I swich to the English website, it should show English content
Please find the configuration.
Comment: Post a screenshot of your negotiation settings. Browser negotiation must be *after* URL detection. And you should have a prefix for all languages. Basically the first option there that returns something wins. And you should combine with the redirect.module, which will then redirect example.com to example.com/en if it detects english or /de.
Comment: Sorry for thge delay in reply. I  have implemented it with .htaccess.Could you please explain how to combine it with redirect module.
Comment: Just enable the module and make sure that the Enforce clean and canonical URLs option is enabled
Answer: It is very obvious why this is happening. Language selection process the language detection systems from top to bottom. (Top has highest priority.) Your configuration means that the browser will always be selected first and that url and user settings are ignored.
If you move browser below user (drag with the arrows icon), the processing order will be:

url
user (if url resolved no language)
browser (if user had no language configured)
Comment: Modified configuration in the given order.But issues still exists.
Answer: I have fixed the  issue with htaccess.Please refer this code,it may be helpful for similar issues.
<code>  ## On frontpage redirect to /de if the browser language start with de
  RewriteCond %{HTTP:Accept-Language} ^de.*$ [NC]
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} !(^q\=) [NC]
  RewriteRule ^(.*)$ /de [L,R=302]

  ## On frontpage redirect to /en if the browser language start with en
  RewriteCond %{HTTP:Accept-Language} ^en [NC]
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} !(^q\=) [NC]
  RewriteRule ^(.*)$ /en [L,R=302]

  ## To make all other requests (that is, URLs not starting with /en/ or /de/) redirect to a default language (say en)
  RewriteCond %{HTTP:Accept-Language} () [NC]
  RewriteCond %{REQUEST_URI} ^/$ [NC]
  RewriteCond %{QUERY_STRING} !(^q\=) [NC]
  RewriteRule ^(.*)$ /en [L,R=302]
</code>


What is fesm2015 and how it relates to esm2015?

Question: I know that esm2015 refers to ecmascript modules described by the ecmascript 2015 specification (modules section)
In some libraries under node_modules/ I see, next to the directory esm2015/, another one  called fesm2015/.

What is fesm2015?
Does it extend esm2015?
Is there any specification describing it?
Comment: Per e.g. https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/preview it's *flattened* (i.e. to a single file) ES module (i.e. using import/export syntax).
Answer: It's part of the Angular Package Format.

FESM - short for Flattened ES Modules and consists of a file format
created by flattening all ES Modules accessible from an entry point
into a single ES Module.

The specification appears to be in this google doc:
https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs
More info:

We strongly recommend that you optimize the build artifacts before
publishing your build artifacts to npm, by flattening the ES Modules.
This significantly reduces the build time of Angular applications as
well as download and parse time of the final application bundle.
Please check out the excellent post "The cost of small modules" by
Nolan Lawson.
Angular compiler has support for generating index ES module files that
can then be used to flattened module using tools like Rollup,
resulting in a file format we call Flattened ES Module or FESM.
FESM is a file format created by flattening all ES Modules accessible
from an entry point into a single ES Module. It's formed by following
all imports from a package and copying that code into a single file
while preserving all public ES exports and removing all private
imports.
The shortened name "FESM" (pronounced "phesom") can have a number
after it such as "FESM5" or "FESM2015". The number refers to the
language level of the JavaScript inside the module. So a FESM5 file
would be ESM+ES5 (import/export statements and ES5 source code).
To generate a flattened ES Module index file, use the following
configuration options in your tsconfig.json file:

{   "compilerOptions": {
     ...
     "module": "es2015",
     "target": "es2015",
     ...   },   "angularCompilerOptions": {
     ...
     "flatModuleOutFile": "my-ui-lib.js",
     "flatModuleId": "my-ui-lib"   } }

Once the index file (e.g. my-ui-lib.js) is generated by ngc, bundlers
and optimizers like Rollup can be used to produce the flattened ESM
file.


codeigniter foreach multiple entries with same ID, sum elements and displey as one

Question: I use foreach to make table with data from "sale" row json_decode($row['sale']), that now show each entry separately, what I wanted to do is to show each entry with same id [product_id] as one and to sum [num], sum [product_pcs], sum [price_per_pcs] of all entries with same id and show it one row.
json_decode($row['sale']):
Array ( [0] => stdClass Object ( [stock_id] => 501 [product_id] => 7 [product_pcs] => 1120 [price_per_pcs] => 1.17 [num] => 1) [1] => stdClass Object ( [stock_id] => 500 [product_id] => 7 [product_pcs] => 1120 [price_per_pcs] => 1.17 [num] => 1 ) [2] => stdClass Object ( [stock_id] => 497 [product_id] => 3 [product_pcs] => 600 [price_per_pcs] => 1,1 [num] => 1 ) [3] => stdClass Object ( [stock_id] => 496 [product_id] => 3 [product_pcs] => 600 [price_per_pcs] => 1,1 [num] => 1 ) [4] => stdClass Object ( [stock_id] => 526 [product_id] => 25 [product_pcs] => 1120 [price_per_pcs] => 1.22 [num] => 1 ) [5] => stdClass Object ( [stock_id] => 525 [product_id] => 7 [product_pcs] => 1120 [price_per_pcs] => 1.17 [num] => 1 ) )

I display the received data on this way:

                            No
                            Product ID
                            Price Per Piece
                            Product pcs
                            Total products
                    <?php
                        $count      =   1;
                        $sale   = json_decode($row['sale']);
                        foreach ($sale as $product):
                    ?>

                            <?php echo $count++;?>.
                            <?php echo $product->product_id; ?>
                            <?php echo $product->price_per_pcs;?>
                            <?php echo $product->product_pcs; ?>
                            <?php echo $product->num; ?>

                    <?php endforeach;?>

With the above I get a table that looks like this:

And I want to look like this:

I would be very grateful.
Comment: The best way would be to change the SQL-query source... could you share that?
Answer: The best way would be to alter the original SQL-query, but since that information is lacking at the moment, you could create a new array with the sums you need with something like:

        No
        Product ID
        Price Per Piece
        Product pcs
        Total products

    <?php
    $sale = json_decode($row['sale']);

    $sum = array(); // INITIATE NEW ARRAY WITH SUMS

    //  SUM UP VALUES IN A NEW ARRAY...
    foreach ($sale as $product){
        // CHECK IF ITEM IS SET TO PREVENT "Undefined offset" ERRORS...
        if (!isset($sum[$product->product_id])) {
            // INITIATE ARRAYS.. THE PRODUCT ID IS USED AS ARRAY KEY
            $sum[$product->product_id]['price_per_pcs'] = $product->price_per_pcs;
            $sum[$product->product_id]['product_pcs'] = $product->product_pcs;
            $sum[$product->product_id]['product_num'] = $product->num;
        } else { // ARRAYS ALREADY SET.. USE ASSIGNMENT OPERATORS TO SUM UP THE VALUES
            $sum[$product->product_id]['price_per_pcs'] += $product->price_per_pcs;
            $sum[$product->product_id]['product_pcs'] += $product->product_pcs;
            $sum[$product->product_id]['product_num'] += $product->num;
        }
    }

    // LOOP THROUGH SUMS ARRAY...
    $count = 1;
    foreach ($sum as $key=>$val){
    ?>

        <?php echo $count++;?>.
        <?php echo $key; ?>
        <?php echo $val['price_per_pcs'];?>
        <?php echo $val['product_pcs']; ?>
        <?php echo $val['product_num']; ?>

<?php } ;?>

Let me know if this works for you.. or if i can assist you with any other solution.
Comment: I apologize for waiting. Thank you very much for your response. With this code message appears: Undefined offset on line `$sum[$product->product_id]['price_per_pcs'] += $product->price_per_pcs;`. I tried to resolve but without success.
Comment: Thank you very much once again! Error occurs when there is nothing to be calculated. I just added this: `foreach ($sale as $product){
  if ( ! isset($sum[$product->product_id])) {
   $sum[$product->product_id]['price_per_pcs'] = $product->price_per_pcs;
   ...
}
else {
   $sum[$product->product_id]['price_per_pcs'] += $product->price_per_pcs ;...}
}` I apologize once again due to untimely responses. I owe you a beer!
Comment: Glad that it worked out for you. Thanks for the feedback about the undefined offset error... I have updated the answer to also use `ìsset()`