Display chord chart (just symbols) like lyrics for music files (mp3 etc)?

Question: Summary:
Is there a way to display chord symbols in music players (software apps) ? Like .srt files for movie subtitles or .lrc for music lyrics, isn't there a format or alternative for chords ?
Details & Usage:
Lyrics / subtitles support is now common in media players (.srt and .lrc file formats). Knowing this, for a pop song I know well, I could make my own lyrics file with say just Chord Symbols and the first few lyrics of verses + chorus and notes so I can play along / sing / rehearse with the song playing.
But is there a better (ideally standard + well supported) way to do this, to display both the lyrics and chords ?  Even better, an existing format / resource to get these for free / less work ?  A lot of players already have a download lyrics function built-in, so it's almost seamless.
So, does it exist already, or I'm day-dreaming ?
This is more of a question of memory helping tools rather than finding the chords & structure (which are easy once you know the key and song a bit).
Related Info:

Found a mention of something similar on Wikipedia: Chord charts in computer files, but sadly it's missing the source.
This question mentions MuseScore, I'll try to look at that.
Comment: The question is off-topic because it's asking for a software recommendation. See [What topics can I ask about here?](https://music.stackexchange.com/help/on-topic). Also, I suggest https://music.stackexchange.com/conduct: "Avoid sarcasm and be careful with jokes — tone is hard to decipher online." (It's best not to anger the gods: "Updated to attempt to please the evil "off-topic" police / gods.")
Comment: I think your edits helped. No guarantees, because the question is an uneasy fit overall for the site, but at least IMO it meets the "good enough" standard. BTW, the Wikipedia page you found is just about using ASCII files to display chord/lyrics charts. It's not the kind of file format standard you're looking for.
Comment: I still feel that this question is too much of an edge case, so I'll let the community decide if it should be reopened. In the meantime, have you considered other computer, software, or audio engineering Stack Exchange communities?
Comment: @deryb  Music practice and theory is our main topic, but we do have a scope we follow. Both external resources requests and software recommendations are off-topic here and the question seems to have a bit of both I.E. "Even better, an existing format / resource to get these for free / less work ?". The edits I do not feel like have resolved them yet. I will also point out while the other linked question leans into software recs a bit, the core question is terminology of a notation which is very much on topic.
Comment: It's not clear to me just what this has to do with either music practice or music theory
Comment: @BrianTowers What OP describes would give a convenient way to combine backing tracks and chord sheets into one digital object.  It could be very useful for practice or livestreamed performances.
Comment: @BrianTowers I just added more details. Please read the whole question, I did provide enough background info I think. But feel free to suggest anything missing to make it clearer.
Comment: @Tim Of course it's not that hard (for someone well-trained with a good ear, like I mentioned), but it's time consuming, and it's a memory helper. Say I just want to play & sing along a few lesser known songs, have fun & not waste time, this is a definite must, no ?
Comment: @Tim sorry, but why are you trying to convince me to find things by ear?  I just said I have a good ear, matter of fact I have a great one, I used to find guitar solos by ear when I was learning as a teenager. If don't want to help with my original question, please stop.
Comment: Why only chord symbols, why not melody too so you could sing it correctly without rehearsing or play along like instrumental karaoke? IMO there aren't even decent tools and storage/exchange formats for writing chord charts or chords+lyrics charts, let alone having these synchronized to audio. The best thing I know is RTF or maybe Word documents or plain TXT. And pen+paper is even better. Anything with a more music-oriented data/object model gets awkward or just Wrong. C Am F G. I wrote that in 1.5 seconds. This message editor beats every notation application out there, and I have them all.
Comment: @piiperiReinstateMonica I'm sorry if I offended you. My question was marked off topic, I don't understand why. Can anyone help please ?  This question is important to me and I'd like to improve my music practice as much as possible.
Comment: Ok, thanks for the details. But nowhere am I asking for a specific software application. Rather, I'm asking for a software WAY, which is meant to find out if there is any common file format, extension or existing technology to display chords and lyrics. I don't want to get too geekish, of course I could avoid the word "software" altogether if that's what it takes to avoid the "off-topic police". Please help me rephrase my question if possible, to help find if anything's out there to help my quest.
Comment: @Aaron Thanks, I did rephrase my question a bit, to avoid the "please recommend software ..." types of question. And right, sarcasm is rarely a good idea in text online, point noted. Feel free to suggest further edits.
Comment: @Richard I thought since Music was the main topic here, and there's probably lots of other music geeks out there. It's sad to consider my question was immediately closed, [another one quite similar](https://music.stackexchange.com/questions/58411/what-is-the-name-for-this-kind-of-chord-chart?rq=1) hasn't. No one can talk of software or computer tools here to help a fellow musician ? I feel discouraged. I'll add just a bit more background, hoping it might get more sympathy.
Comment: There's a site called Chordify which augments audio/video media (which has a timeline) with time-stamped chord charts (which can be at least partly auto-generated, I supposed), basically synchronizing/aligning two pieces of time-stamped media, and they have an editor for chord symbols + measure structure. The chord chart is media too. Is that what you want, but just a bit different, or completely different? Are the differences functional or non-functional? Non-functional meaning, has to be in my own control, no proprietary stuff, work offline on the desktop, etc.
Answer: I hope I read the original question correctly.  If not, my answer will make no sense and I apologize.  It seems to ask how simple lead sheets can include chords (graphics? or must names?)
Not having specialized programs to display lead sheets, I make my own standard.
I ripped lyrics to favorite songs from the internet and imported them into Notepad.  (Other word processors would also work but Notepad and Wordpad come free with Windows.  Any text processor would do as well.)
I then inserted chord names (enclosed in brackets to distinguish them from the lyrics) into the text.
Presto!  Sheets of lyrics and chords (and playing advice) I can page through as I play and sing.
for example:
{G} Lyric lyric lyric lyric lyric {Am}  lyric lyric lyric {C}  lyric lyric lyric
{D}  lyric lyric lyric {C}  lyric lyric lyric lyric lyric {slow the rhythm}  lyric lyric
No specialized software needed and extremely small file size.
Comment: Thanks!  That's what I imagined as well. I'm just wondering if there isn't a standard (file format / document type) to have both lyrics and chords separate so for example, I could make the font size real big for chords and perhaps to avoid displacing lyrics too much.


Código de alguns branchs sumiram após merge

Question: Estou com uma situação bem esquisita (provavelmente vacilo né...) aqui no meu repositório.
Tenho um branch de DEV e vários outros de features e bugs.
A cada branch de feature ou bug, fazemos o merge com branch DEV.
Trabalhamos em 2 Devs neste projeto, eu, sempre antes de fazer o merge, faço um pull no branch de Dev. Ai depois faço os merges. O outro dev, aparentemente fez um git fecth antes de fazer o merge, não faço ideia se isso implicou em algo, mas alguns dos branches que eu já havia feito merge em DEV simplesmente não consta o código no branch de DEV.
Rodei o comando git log -all, que se entendi bem, mostra os branchs que fazem parte do branch selecionado no momento, então, com o branch de DEV selecionado, ao rodar este comando, constam os branchs cujos códigos estão ausente.
Preciso entender o que fizemos de errado...
Eu tenho o "código perdido" nos respectivos branchs (local e remoto), então selecionei um dos branchs e ao tentar fazer o merge novamente, dá uma mensagem dizendo que está atualizado (Already up to date.)
Alguém pode ajudar?
Comment: Servidor privado, GitHub ou similares?
Comment: Local é local, remoto é remoto, no remoto vc pode ter branchs que não existem no remoto e vice-versa, não tem muito o q ajudarmos, talvez vc olhando de trás pra frente o log até ver o ponto que o tal branch sumido deixou de "existir" ou ser "logado".
Comment: bitbucket privado @JonathandeToni
Comment: talvez tenha me expressado mal @GuilhermeNascimento, não foi o branch que sumiu, quis dizer que o código de alguns branches não constam no branche de DEV, que é o qual "recebe" os merges.

queria muito entender como fizemos essa cagada..., mas tão importante quanto, é saber como faço para refazer estes merges, pois tenho os branches com os códigos que preciso, mas ao tentar fazer o merge com Dev, diz que já está atualizado.
Comment: Da uma olhada no Bitbucket, vê se as branchs ainda estão lá, se estiver, problema é somente local. Ai cai no comentário do @GuilhermeNascimento
Comment: @JonathandeToni, os branches de features e bugs adicionados constam local e remoto. sabe o que posso fazer conseguir fazer o merge novamente?
Comment: Ainda sim recomendo o método do @GuilhermeNascimento de rever o log de trás para frente, assim você consegue achar o momento certo de onde a cagada foi feita
Comment: Quati_Maldito Se não constam no branch então vc não os commitou, se não fez o commit então não existem lá e nem nunca existiram e não tem como pegar algo q vc não salvou (cc @JonathandeToni)
Comment: @GuilhermeNascimento, cara, valeu pela ajuda, mas isso tá bem louco para alguém que não manja muito como eu..., os commits constam no remote. Eu desenvolvo em um ambiente local, então desenvolvi vários branches, e fazendo o commit e merge com DEV a cada vez q terminasse o job. Ai gerava um novo branche com base em Dev, e seguia o jogo, até que na sexta-feira última, o outro Dev fez um merge com o branch que ele estava desenvolvendo e aí "sumiram" os códigos que tinham sido mesclados (merge).
Comment: Cara, uma recomendação, começa a utilizar ferramentas como o git-flow, fica mais fácil de trabalhar, são poucos comandos e faz tudo certinho. Para quem não está acostumado, é uma ótima entrada!
Comment: Se constam no remoto então os código estão lá, faz um outro branch local como o nome RECUPERAR e faz o rollback até o ponto que vc precisa pegar os tais arquivos, copia tudo o que precisa, deleta o branch, pega o que copiou e ajusta no seu branch de edição, pronto :)
Answer: Analisar problemas específicos de merge são complicados sem entender exatamente quais comandos foram dados, que ordem foram realizados, se existiu conflito, se alguém tem permissão para fazer force push, se os usuários podem commitar direto na branch dev, se o que sumiu foi código dentro de classes existentes, se sumiram até mesmo classes novas, etc.
Como o git é uma ferramenta muito flexível, existem várias maneiras diferentes de chegar nos mesmos resultados (bons ou não).
Mas melhor do que dar o peixe, é ensinar a pescar. E podemos também tirar algumas conclusões do que você disse.
Como o merge foi identificado como já feito na branch de dev, isto significa que o merge ocorreu mas algo se perdeu durante este merge ou depois dele. A maior possibilidade que vejo é que o merge foi realizado, ocorreu algum conflito e quem resolveu conflito escolheu considerar apenas as alterações da branch dele.
Como analisar
Tente identificar um ponto no histórico do seu repositório onde o código ainda estava na branch pelo git log:
git log

A partir dele, vasculhe o histórico procurando em que momento o código sumiu. Você pode ir fazendo isto fazendo um checkout direto para cada commit no histórico e vendo o código daquele momento no repositório:
git checkout eR43yUi

(para voltar ao HEAD, faça git checkout dev)
Se tiver alguma dúvida entre as alterações de dois commits, você pode ver as diferenças entre os commits com o git diff:
git diff eR43yUi..7yaoljM

Veja a diferença entre os commits antes e depois de cada merge realizado, pois provavelmente foi neste ponto que ocorreu o problema.
Se ver algum commit mencionando algum tipo de revert, veja se não foi este commit a causa do problema. Alguém pode ter revertido algum commit da branch "mergeada" com git revert após feito o merge.
Answer: Para constar para o caso de alguém passar por algo semelhante.
Concluímos que um dos devs da equipe fez uma feature nova e a base disso foi um branch antigo, sem as atualizações das últimas semanas e as enviou "matando" tudo que os demais devs fizeram.
Para resolver o problema, segui a ideia do Guilherme Nascimento, fiz um "rollback" até um update antes do branch que "matou" as alterações, e usei o comando:
git checkout HEAD~1

Onde o 1 representa quantos commits você quer retroceder o ponteiro no HEAD.
By: https://brorlandi.github.io/git-desfazendo-commits
Obrigado a todos que ajudaram.


AWS DMS validation fails

Question: I migrated data from SQL Server database to Aurora Postgres, using AWS DMS. Everything works and data is migrated correctly, but then validation fails. There are two types of validation errors:

GUIDS in the source database are all uppercase and in the target: lowercase.
{'record_id': 'DA7D98E2-06EA-4C3E-A148-3215E1C23384'}
{'record_id': 'da7d98e2-06ea-4c3e-a148-3215e1c23384'}

For some reason, validation fails between timestamp(4) column in Postgres and datetime2(4) column of SQLServer. It seems like the time in Postgres has two extra 0's at the end, but when selecting data from the table normally, the data is exactly the same.
{'created_datetime_utc': '2018-08-24 19:58:28.4900'}
{'created_datetime_utc': '2018-08-24 19:58:28.490000'}

Any ideas how to fix this? I tried to create transformation rules for columns, but they do not work.
Thank you.
Answer: Thanks to this article https://www.sentiatechblog.com/aws-database-migration-service-dms-tips-and-tricks, these new mapping rules fixed all validation issues. These rules cannot be added using AWS Console, only in the script.

AWS DMS validation fails


2 Probability questions: distributions - Expectations

Question: Q:
In the grocery store, there are 2 kinds of egg cartons (12 eggs each) .
$80\%$ of the cartons have exactly $1$ broken egg. In the other $20\%$ there are exactly $3$ broken eggs. You want to buy a carton that include exactly one broken egg, but you can't examine each egg (because you have no time ) you only check $3$ eggs for each carton.
If you find one or more broken eggs in the $3$ that you examine, you return the carton back, else you take it.
How many cartons do you need to return until you will find the carton you want?
My go:
This sounds like a Geometric distribution because you search and search until you find something (and then stop) so basically $X \sim G(p)$  The chance of finding the right carton is $0.8 \cdot \frac{1}{12} + 0.2 \cdot \frac{9}{12} \cdot \frac{8}{11} \cdot \frac{7}{10} \approx 0.143$
And so the mean is $E[X] = \frac{1}{p} = \frac{1}{0.143} \approx 6.9915 \approx 7$ so $7$ cartons, so you will return $6$
Am I right?

Another question:
Same exact story as described above.
You would like to take $4$ cartons, what is the probability you will need more than $7$ cartons in order to get $4$ that satisfy your rules? (that you examine 3 random eggs and if you find $\geq$ 1 eggs you return it and search another one)  ?
My go:
I did not quite understood how to approach it using distributions, it sounds like HyperGeometric however I am not sure!  The tip for the question is:

Define $X_3$ to be the number of cartons you return until you get to $4$ cartons

Thank you for helping!
Comment: "If you find one or more broken eggs in the 3 ..." Don´t you find always at least one broken egg in a carton?
Comment: @callculus you examine 3 eggs per carton , you can find 3 eggs that are completely fine
Answer: Let $X$ be a random variable indicating the number of broken eggs in a randomly selected carton, so $X = 1$ if it has one broken egg, and $X = 3$ if it has three.  Then $$\frac{X - 1}{2} \sim \operatorname{Bernoulli}(p = 0.2).$$  Let $$Y \mid X \sim \operatorname{Hypergeometric}(N = 12, n = X, m = 3), \\ \Pr[Y = y \mid X = x] = \frac{\binom{x}{y} \binom{12-x}{3-y}}{\binom{12}{3}}$$ represent the random number of broken eggs observed when a sample of $m = 3$ eggs are taken without replacement.  Then we want to compute the unconditional probability of acceptance $p$, i.e.,
$$\begin{align*}
p = \Pr[Y = 0] \\
&= \Pr[Y = 0 \mid X = 1]\Pr[X = 1] + \Pr[Y = 0 \mid X = 3]\Pr[X = 3] \\
&= \frac{\binom{1}{0}\binom{11}{3}}{\binom{12}{3}} (0.8) + \frac{\binom{3}{0}\binom{9}{3}}{\binom{12}{3}} (0.2) \\
&= \frac{3}{4} (0.8) + \frac{21}{55} (0.2) \\
&= \frac{186}{275}. \end{align*}$$
Therefore, the number of rejected cartons $R$ until the first accepted carton is a geometric random variable with success probability $p$; i.e. $$\Pr[R = r] = (1-p)^r p, \quad r \in \{0, 1, 2, \ldots \}.$$
For the second part of the question, this is simply a negative binomial probability.  Let $T$ represent the number of cartons you need to try until you get four that you want.  Then $$T \sim \operatorname{NegativeBinomial}(k = 4, p = \tfrac{186}{275}), \\ \Pr[T = t] = \binom{t-1}{k-1} (1-p)^{t-k} p^k, \quad t \in \{k, k + 1, k + 2, \ldots\}.$$  The desired probability is $$\Pr[T \ge 7].$$

Additional exercises for the reader:
In the first part of the question, we were interested in how many cartons on average it would take to accept the first one.  What is the probability that the carton we accepted has only one broken egg?
In the second part of the question, we were interested in the probability that we would need to try at least $7$ cartons before accepting $4$.  Once we accept $4$ cartons, what is the posterior probability distribution for the number of cartons we accepted with only one broken egg?
Comment: Thank you for your answer! just a little thingy I noticed: it is $\frac{186}{275}$ =) thank you!! I will take a shot at the bonus question you added
Comment: @Remember1312 Indeed you are correct; I made a calculation error which has now been corrected.


How to convert string value to decimal

Question: There is a string values
1. 28000 Million
2. 15592 Million

1.
Now I am converting these values as
decimal val=Convert.ToDecimal(28000)/1000//To convert it into billion.
Here val=28
return val.Tostring("F1");///Gives 28.0

2.
decimal val=Convert.ToDecimal(15592)/1000//To convert it into billion.
Here val=15.592
return val.Tostring("F1");///Gives 15.6

Now What I want here instead of 28.0 I want 28
15.6 is fine for me.
How can I ignore decimal in case of 28.0?
Comment: Format it with `"F0"` instead of `"F1"`?  You're explicitly specifying the formatter.  To use a different format, use a different formatter.  Note that this has nothing to do with the string from which you evaluated the decimal.  The only relevant line of code here is `val.ToString("F1")`.
Comment: you want to convert String to Decimal or Decimal to String ? Correct your title !
Comment: You just need to format it correctly.  See the [documentation](http://msdn.microsoft.com/en-us/library/fzeeb5cd(v=vs.110).aspx)
Answer:         var val =Convert.ToDecimal(28000) / 1000;
        Console.WriteLine(val.ToString("N")); // 28,00
        Console.WriteLine(val.ToString("F0"));  // 28
        Console.WriteLine(val.ToString("F1"));   //28,0

EDIT:
        var val =Convert.ToDecimal(15592) / 1000;
        Console.WriteLine(val.ToString("N")); // 15,59
        Console.WriteLine(val.ToString("F0"));  // 16
        Console.WriteLine(val.ToString("F1"));   //15,6

Comment: Work... somehow. Point for U. Correct is 'val.Tostring("N");'
Answer: Just use
return val.Tostring();

Maybe this is what you want. This is without a Limitation of decimal places
Answer: you should try parsing to integer
 decimal val=Convert.ToDecimal(28000)/1000//To convert it into billion.
 Here val=28
 int i = 0;
 Int32.TryParse(val.ToString(), out i);

  return i ==0?  return val.Tostring("F1") :  return i.Tostring();

How to convert string value to decimal


Função dando valores errados

Question: Por algum motivo, minha função de calcular distâncias está dando valores errados à vezes. Não só isso, mas os valores parecem ser de endereços de memória (pois são muito grandes), mas não tenho certeza se é isso.
A função:
float distancia(int ax, int ay, int bx, int by) // Calcula a distancia entre dois pontos, onde eh respectivamente (X1 Y1), (X2 Y2)
{
    return(sqrt((pow((ax - bx), 2)) + (pow((ay - by), 2))));
}

Uma das funções que chama a função acima. Ela escreve em um documento txt e os valores impresos lá saem errado:
void arquivoDistancia(float matrizDistancia[][30])
{
    FILE *aquivoDeSaida;
    int cont = 0, cont2 = 0;

    aquivoDeSaida = fopen("distancia.txt", "w");
    while( cont < 30 ) //loop para gravar os dados no arquivo.
    {
        while( cont2 < 30 ) //loop para gravar os dados no arquivo.
        {
           fprintf(aquivoDeSaida, "%.2f ", matrizDistancia[cont][cont2]); //grava garacter a caracter no arquivo apontado por custo.
           cont2++;
        }
        fprintf(aquivoDeSaida, "\n");
        cont++;
        cont2 = 0;
    }
    fclose(aquivoDeSaida);

}

e essa é a função que faz a matrizDistancia[][30]. Reparem que eu até coloquei um printf para ver os valores. O problema começa aqui pelo jeito. Ele imprime tudo certo no começo mas depois começa a aparecer números estranhos
void mDistancia(char cidadeXY[][150], int coordenadasX[], int coordenadasY[], float matrizDistancia[][30])
{
    int c, i, contadorC, contadorI;
    float dij;

    for(i = 0, contadorI = 0; i < 30; i++, contadorI += 2)
    {
        for(c = 0, contadorC = 0; c < 30; c++, contadorC += 2)
        {
            dij = distancia(coordenadasX[contadorI], coordenadasY[contadorI], coordenadasX[contadorC], coordenadasY[contadorC]);
            printf("%.2f ", dij);
            matrizDistancia[i][c] = dij;
        }
    }

}

Comment: Você precisa aprender a debugar o código sozinha. Imprima o valor retornado por `distancia()` na tela, bem como seus parâmetros, e veja se eles fazem sentido. Depois de garantir que esta parte está OK, você se preocupa em grava os dados no arquivo.
Comment: Eu imprimi os valores. Inclusive mencionei isso na pergunta.
Comment: Eu vi. Os números "estranhos" são resultados do cálculo que você faz. Imprima também **os parâmetros** que estão sendo passados para `distancia()`, e ao encontrar um resultado "estranho" você vai ter condições de usar sua calculadora para verificar manualmente se o resultado faz sentido (ou não). Eu suspeito que o problema são os valores armazenados por `coordenadasX` e `coordenadasY`.
Comment: Beleza. Vou fazer isso. Imprimi os valores das coordenadas x e y e não são eles.
Comment: Ao calcular manualmente com esses valores, você detectou que o resultado de `distancia()` está correto quando eles são usados ou nesse momento o resultado já não faz mais sentido?
Comment: O resultado de distancia() não está correto. Só no começo que ele faz certinho. Depois começa a surgir valores errados bem grandes.
Comment: Você poderia exemplificar com valores de exemplo? Que números são passados para `distancia()` e qual valor ele retorna nesse caso?
Comment: @jane eu não programo em C, mas creio que seu problema seja com a precisão. Você deve tomar cuidado com os tipos numéricos pois eles são diferentes e podem te dar muita dor de cabeça. A resposta do **karlphillip** certamente vai te atender.
Answer: É bom ter em mente que a assinatura de sqrt() informa que ele retorna um double. Ao tentar guardar seu resultado em uma variável float você poderá acabar perdendo informação, o que justificaria o problema que você observou.
Por outro lado, sqrtf() retorna um float, que seria mais apropriado no seu caso.
Answer: for(i = 0, contadorI = 0; i < 30; i++, contadorI += 2)
//                                     ^^^^^^^^^^^^^^
{
    for(c = 0, contadorC = 0; c < 30; c++, contadorC += 2)
    //                                     ^^^^^^^^^^^^^^
    {
        dij = distancia(coordenadasX[contadorI], coordenadasY[contadorI], coordenadasX[contadorC], coordenadasY[contadorC]);

Porque razao as variaveis contadorI e contadorC avancam de 2 em 2?
Desta forma nunca vais calcular as distancias entre pontos com indices impares; alem de que vais estar a aceder a elementos (provavelmente) inexistentes dos arrays.

Função dando valores errados


O que são os conceitos de coesão e acoplamento?

Question: Quais são as características de um código com coesão ou acoplamento? Até que ponto isso pode gerar problemas futuros?
Comment: @EduardoSeixas acredito que é porque ele quis um viés para esta linguagem, apesar do conceito ser válido para outras. Ela é um pouco supérflua, mas não chega atrapalhar e ajuda mostrar a intenção dele, mostra onde está está aplicando e está com dúvida.
Comment: Qual o motivo da tag java?
Comment: Relacionado: [Qual a definição do termo acoplamento?](http://pt.stackoverflow.com/q/11098/3117)
Answer: Os dois conceitos, apesar de diferentes, estão relacionados. E são muito importantes. Um monte de coisa que você vê por aí sobre o que fazer com o código é detalhamento sobre esses dois conceitos.
Coesão
Se refere ao relacionamento que os membros de um módulo possuem, não importa o que módulo significa. Indica se os membros tem uma relação mais direta e importante. Códigos coesos são aqueles de relação forte, onde seus membros estão intimamente ligados e estão ali por um objetivo comum. Membros que não são absolutamente necessários para aquele módulo não devem estar presentes em códigos coesos.
Módulos coesos são aqueles que possuem poucas responsabilidades. Desta forma a manutenção é mais simples e evita efeitos colaterais. Fica mais fácil alterar uma parte da aplicação sem afetar outras partes. Por isto é confundido com o princípio da responsabilidade única. E assim alguns paradigmas que isolam coisa podem ser mais coesos do que outros que incentivam por tudo junto, ao contrário da crença popular.
É importante tirar funcionalidades supérfluas de um módulo e transferir para outro modulo.
Isso lembra um pouco a normalização do banco de dados que, em última instância, determina que cada tabela possua apenas uma coluna de dado e uma ligação com as demais.
Há ainda uma maior facilidade para lembrar do que os módulos fazem quando eles fazem pouca coisa. O que não é coeso, é confuso, incoerente.
Exemplos óbvios de baixa coesão são módulos que cuidam ao mesmo tempo das regras de negócio, persistência de dados e interação com usuário. Mas existem casos menos óbvios quando você estabelece que um cliente pode decidir quando ele é inadimplente ou quais os vendedores que o atendem. É comum achar que isto pertence ao cliente mas os clientes existem independentes disto, e que clientes são papéis de pessoas em uma organização.
É extremamente comum vermos designs com baixa coesão, algumas em exagero, outras na mediada certa. Evidentemente que tentar a alta coesão a todo custo também se tornará um problema de design. Tudo tem uma desvantagem. Há casos de alta coesão em exagero. Raramente faz sentido ter um módulo com um único membro.
Formas de coesão (do pior para o melhor):

Por coincidência - Acontece sem planejamento, pode estar certo ou não. Em geral se considera como a pior coesão.
Lógica - Membros da mesma categoria lógica, mesma atividade, estão juntos.
Temporal - Se relacionam pelo momento que são executados.
Procedural - Formam uma sequência para realizar uma tarefa maior.
Comunicacional - Quando essa sequência de execuções ocorrem no mesmo dado.
Sequencial - Quando a saída de um membro serve de entrada para outro membro.
Funcional - Agrupamento ocorre só porque elas realmente precisam estar juntas para contribuir com algo muito bem definido.

Acoplamento
Se refere ao relacionamento entre os módulos. Indica quanto um módulo depende de outro para funcionar. Códigos desacoplados são aqueles de relação fraca, e não dependem de outros para fazer sua funcionalidade básica. É sempre desejável um baixo nível de acoplamento.
Quando há baixo acoplamento, a aplicação fica mais flexível, reusável e mais organizada. É possível intercambiar partes que se mostraram problemáticas, ultrapassadas ou que exigem novas funcionalidades.
Quando se busca coesão é comum fazer com que módulos novos sejam criados com alto acoplamento e uma nova avaliação se faz necessária para reduzir esta dificuldade.
Em geral o alto acoplamento mantêm o problema da baixa coesão, e de uma forma até mais complicada. Quando há uma mudança em um módulo altamente acoplado, gera a necessidade de mudanças em outros módulos, o que pode ser mais complicado de fazer e gera mais riscos do que um módulo com baixa coesão.
Um exemplo de acoplamento ruim é uma nota fiscal que pega dados de um imposto para fazer o cálculo. O ideal é que a estratégia de cálculo do imposto seja completamente independente e desconhecida da nota fiscal, assim pode ser trocado facilmente.
São raras as aplicações que usam o baixo acoplamento de forma adequada. E quando o fazem, em geral é seguindo um padrão de projeto consagrado. Mesmo assim de forma irregular. O que não seria algo de todo ruim se fosse sempre feito com consciência. O baixo acoplamento acaba tornando, por vezes, as aplicações mais complexas.
Formas de acoplamento (do pior para o melhor):

Conteúdo - Quando um módulo pode acessar, modificar ou se referenciar diretamente a conteúdos de outro módulo.
Global - Quando os módulos podem ler e escrever dados globais de um módulo.
Controle - Quando um modulo irá decidir como outro funcionará.
Estrutura de dados - Quando os dados de um módulo são passados em uma estrutura de dados passada como parâmetro.
Dados - Quando apenas os dados realmente necessários para outro módulo são passados como parâmetros

Não é possível eliminar o acoplamento por completo, apenas podemos mantê-lo o mais baixo possível.
Fazer com que módulos (classes) dependam especificamente um outro módulo, que exijam uma implementação específica, que não possa mudar o comportamento específico, ou mesmo que exija um outro módulo quando ele pode resolver de forma coesa, são exemplos de acoplamento excessivo.
Em OOP para reduzir o acoplamento devemos programar para a interface e não para a implementação.
Conceitos e paradigmas
Estes conceitos existem pelo menos desde a década de 60. E ao contrário do que muitos acreditam, não é um conceito intrínseco da orientação a objeto. Infelizmente algumas pessoas acham que só existe esse paradigma e acabam escrevendo coisas erradas na internet atribuindo informações incorretas ao que elas conhecem e gostam.
Já estava bem documentando em livros dos anos 70 e foram sendo disseminados nos livros mais atuais que privilegiam um paradigma sobre outros.
Tão pouco estão relacionados à linguagens. Na verdade o conceito transcende a computação.
As ferramentas de engenharia de software são bem antigas e podem ser aplicadas, de uma forma geral, a todos os paradigmas de programação. Quando isto é feito, alguns dos paradigmas que parecem ultrapassados se tornam relevantes.
É verdade que paradigmas como OOP podem ajudar a organizar o código melhor, mas quando a pessoa não sabe o que fazer, ela fará errado em todos os paradigmas. E de fato OOP ajuda em alguns pontos, mas complica em outros. É raro encontrar alguém que consiga definir classes bem coesas e desacopladas. Então estes conceitos se tornaram importantes neste paradigma. Em paradigmas mais simples e livres, quando usados da maneira correta, é mais fácil manter a coesão e o baixo acoplamento. Apesar de trazer algumas outras dificuldades de manutenção.
OOP incentiva a subclasse (herança) que é uma das piores formas de acoplamento existentes. OOP incentiva agrupar todos os comportamentos em uma classe, o que frequentemente é abusado. Para resolver isto uma série de padrões de projeto são criados, o que não seria necessário em outro paradigma.
Não estou dizendo que outros paradigmas são melhores e livres de defeito. Digo apenas que se a engenharia de software for aplicada corretamente, o paradigma não é tão importante.
Coloquei no GitHub para referência futura.
Comment: Essa resposta não tem mais votos pq n tem um citação do clean code, code complete ou afins hehe :). +1.
Comment: @rray eu vou melhorá-l mas é capaz de não gostarem porque bati no paradigma queridinho de muita gente :)
Comment: Ótima resposta.
Comment: @bigown excelentíssima resposta para uma excelente pergunta! Parabéns! Se pudesse mandar muitos upvotes faria!!!
Comment: @bigown posso dizer que um método `Coeso` é aquele que faz somente o que foi designado? Por exemplo: Método Inserir (Faz somente Inserção) ;Digo porque já encontrei uns métodos que além de inserção faziam atualizações. Deu muito trabalho para dá manutenção.
Comment: Sim, é exatamente isto, claro que tem que ver cada caso, não é simples afirmar abstratamente o que é coeso.
Comment: @bigown Quando aprendi na faculdade o pessoal implantava sempre essa idéia na nossa cabeça, já deixei o meu +1, sua resposta está excelente. Obrigado
Comment: @Maniero fez uma copia de um livro da resposta, isso está dentro do padrão do Site?
Comment: @itasouza cite a fonte então.
Answer: Esses dois conceitos são fundamentais para a Orientação a Objetos.
Coesão:

Coesão está, na verdade, ligado ao princípio da responsabilidade
  única, que foi introduzido por Robert C. Martin no inicio dos anos
  2000 e diz que uma classe deve ter apenas uma única responsabilidade e
  realizá-la de maneira satisfatória, ou seja, uma classe não deve
  assumir responsabilidades que não são suas.

Um código coeso é um código onde as classes e/ou métodos tem uma única responsabilidade. Ou seja, um método com o nome imprimeSoma() deve IMPRIMIR A SOMA e não CALCULAR A SOMA E IMPRIMI-LA. Por quê ??

Queremos mudar a maneira de como imprimir a soma: mudamos o método de imprimir a soma...
Queremos mudar a maneira de calcular a soma: mudamos o método que calcula a soma

Porém, se um mesmo método calcula e imprime, podemos ter problemas ao mudá-lo, já que estaremos mexendo em partes do código que não precisariam estar sob sua responsabilidade, caso o conceito de coesão, ou responsabilidade única, tivesse sendo implementado corretamente.
Assim, vemos que a coesão é importante para a manutenção e evolução dos softwares.
De maneira similar, podemos observar o acoplamento:

Já o acoplamento significa o quanto uma classe depende da outra para
  funcionar. E quanto maior for esta dependência entre ambas, dizemos
  que estas classes elas estão fortemente acopladas.

Quando uma classe está fortemente acoplada a outras classes, dificulta-se o gerenciamento do sistema, pois quando precisamos efetuar uma alteração em uma das classes, temos que alterar o código em outras classes também.
Fonte: DevMedia
Answer: Sei que o tópico é meio antigo, e já foi respondido, mas meu professor passou um exercício perguntando a diferença entre coesão e acoplamento, e depois deu a seguinte resposta. Como achei bem resumida, resolvi compartilhá-la aqui.

Ambos dizem respeito a módulos de um sistema, apesar de que
  normalmente são conceitos associados a classes em orientação a
  objetos. A coesão é o grau com o qual um módulo tem uma
  responsabilidade única e bem definida. O acoplamento é o grau com o
  qual um módulo depende de outros módulos para seu funcionamento. O
  ideal, para que um sistema seja flexível e compreensível, são módulos
  com alta coesão e baixo acoplamento.


XSLT for-each iteration (problems with attributes on ancestors)

Question: I got a simple problem, in my XML file I have parameters on my ancestors nodes, and when I try to iterate then, from my xslt file it doesn't work.
As example, my XML file:
    <?xml version="1.0" encoding="utf-8"?>
    <nfeProc versao="3.10" xmlns="http://www.portalfiscal.inf.br/nfe">
        <NFe xmlns="http://www.portalfiscal.inf.br/nfe">
            <infNFe Id="NFe99999" versao="3.10">
                <ide>
                    <cUF>35</cUF>
                    ...
                </ide>
                <emit>
                    <CNPJ>01881662000180</CNPJ>
                    ...
                </emit>
              </infNFe>
           </NFe>
     </NFeProc>

And my XSLT file:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">

My CNPJs/h2>

        Number

      <xsl:for-each select="nfeProc/NFe/infNFe/emit">

        <xsl:value-of select="./CNPJ" />

      </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

When I run this example, I don't get anything as a result.
On my tests, i discover that the problem (I guess) is related to the parameters inside the ancestors tag. If i remove the attribute xmlns tag, from both nfeProc and NFe tags, i get the result as expected (my CNPJ value)
xmlns="http:/www.portalfiscal.inf.br/nfe"

Somebody knows how to handle this problem? what are the problem exatcly and how to solve it?
Because I can't change the XML structure, as it comes from government.
Edit
As answered by the fellows, the problems is related to namespaces. I'll continue searching, and already made some changes, putting the namespaces in my XSLT file as follow:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:t="http:/www.portalfiscal.inf.br/nfe">

and changing my for each to:
<xsl:for-each select="t:nfeProc/t:NFe/infNFe/emit">

But continue not working, i doesn't return any erros, but don't work.
Thanks in advance.
Comment: Classic problem of default namespaces. Search the term and try for a solution.
Comment: You're right, as I was without direction i didn't know what search. I was thinking that xmlns was just simple parameter from the tag. I'll take a look at.
Comment: You have missed a `/` from the namespace. It should be `http://www.portalfiscal.inf.br/nfe` and not `http:/www.portalfiscal.inf.br/nfe`. Also, you need to use the `t:` prefix in front of all elements in the xpath `t:nfeProc/t:NFe/t:infNFe/t:emit`, as the default namespace is inherited (i.e. You don't need `xmlns="..."` on all elements in your XML, not unless the namespace is different for children)
Comment: Thanks, Tim C! you're right! everything is working now (or, at least, this part of the job... haha)
Answer: You can't remove all xmlns-namespace yes.
Or you can use it in xPath for all herited nodes :
t:nfeProc/t:NFe/t:infNFe/t:emit

With the declaration :
 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:t="http://www.portalfiscal.inf.br/nfe">

Comment: Thanks! but it don't seems to work for me. Searching I know now that your answer makes sense for what I posted! Thanks so, I'll continue trying.
Comment: What I missed is that every element in the xPath needed the t: prefix, as mentioned by @Tim C in comments above. Thanks, is working now. :)


Why two numbers not summarized in script?

Question: I am newer in bash.
I try to create script that summarizetwo numbers:
Here is script:
echo "the result is:" expr $1+$2

Here how I call the script:
./scr3 50 98

And here is result that I get after the script executed:
the result is: expr 50+98

While I get the the string with two summarized numbers I expect to get the summarize of two numbers.
My question is why I don't get the result of summarize of the two numbers?
Comment: You aren't telling it to *run* `expr` here at all. You're passing `expr` as an *argument*. Arguments passed to `echo` are strings for it to print.
Comment: https://unix.stackexchange.com/a/93030/62174
Answer: Why? Because echo prints its arguments, and you're passing expr as an argument.
A best-practice alternative would be:
echo "The result is: $(( $1 + $2 ))"

...though the a smaller change (albeit to very inefficient code; expr is an artifact of the 1970s, made irrelevant with the introduction of $(( )) in the 1992 POSIX sh standard, and should never be used in new development) is simply:
echo "The result is: $( expr "$1" + "$2" )"


Adicionar botão para gerar imagem

Question: qual a melhor forma para adicionar mais botões para selecionar outras fotos e ao gerar o PDF aparecer também no PDF?
o código abaixo funciona somente para um botão

    Gerar Imagem Base64

    Gerar PDF da imagem enviada no formulário

teste<input type="file" id="imagem-usuario" onclick="converterImagem()" />

<button type="button" onclick="converterImagem()">Gerar PDF</button>

Answer: Você pode usar o atributo multiple no input de ficheiro para selecionar várias imagens. Depois basta correr um ciclo para carregar as imagens no evento onchange e adicioná-las a um array. Ao gerar o PDF basta ir buscar as imagens a esse array.

Selecionar<input type="file" id="imagem-usuario" multiple onchange="converterImagens()" />

<button type="button" onclick="gerarPDF()">Gerar PDF</button>

Comment: muito obrigado pela ajuda

Adicionar botão para gerar imagem


When is a face of a monoid contained in a minimal direct summand?

Question: My question is motivated from studying logarithmic algebraic geometry. (For a detailed introduction to the subject, see this book by Arthur Ogus.) However, I believe my question is accessible to anyone who knows basic algebra.
An integral monoid is a finitely generated commutative monoid $M$ such that the cancellative rule holds: if $a + b = a + c$, then $b = c$. A face $F$ of a monoid $M$ is a submonoid such that if $a+b \in F$, then both $a \in F$ and $b \in F$.
My question is the following. Suppose $F$ is a face of an integral monoid $M$. Is there a unique submonoid $E \subseteq M$ such that:

$F \subseteq E$,
there exists some $E' \subseteq M$ such that $M$ is the (internal) direct sum of $E$ and $E'$, and
if $E''$ is some other submonoid satisfying (1) and (2), then $E \subseteq E''$ (that is, $E$ is minimal with respect to inclusion)?

Thanks!
Comment: There's a unique minimal submonoid containing $F$, but why do you think there should be one that splits $M$?
Comment: I mean to say that $E$ is the minimal submonoid that satisfies (1) and (2). For example, $E = M$ works, but there might also be a smaller one.
Comment: Are these monoids commutative? I ask because you're using + to denote the monoid operation.
Comment: Yes! Thanks for the clarification.
Comment: You should probably edit the clarifications into the original question.  Also: I'm guessing that you actually want M to be the internal direct sum of E and E', rather than just being abstractly isomorphic to their direct sum? (These are not the same in general).
Comment: Also: I'm guessing you probably want it to E to actually be the smallest such submonoid, rather than just e.g. unique minimal alongside some infinite chain? (Maybe that's ruled out, I don't know, but clarification would be nice.)
Comment: Yes, both guesses are correct. I've edited the question to reflect all of the suggestions so far.
Comment: If I were looking for counterexamples, I'd start with finite local rings. Their unique maximal right ideal is certainly a face of the integral monoid (the whole ring), and it might resist complementation. There could be a reason to rule this out, but I haven't seen it yet.
Answer: Consider the monoid $M\subseteq\Bbb Z^2$ generated by $(1,0),(1,1),(1,2).$ The submonoid $E=\langle (1,0)\rangle$ is a face of $M.$ Any $E'$ such that $E+E'=M$ must contain $(1,1)$ and $(1,2),$ so we must have $E'\supseteq\langle(1,1),(1,2)\rangle.$ Note that $(2,2)=2(1,1)=(1,0)+(1,2)$ is not uniquely expressed as a sum $f\oplus g$ for $f\in E,g\in E',$ thus, we cannot have $M=E\oplus E'$ in this case.

Edit: Following the comment. Suppose $E\neq F$. If $E$ contains $(1,1)$, then $E'$ must contain $(1,2)$ (otherwise $E=M$), and we have the same problem. If $E$ does not contain $(1,1)$, then $E'$ must. Further, if $E'$ contains $(1,2)$ then we are in the previous situation. So we are left with $(1,0),(1,2)\in E$ and $(1,1)\in E'.$ But again, $2(1,1)$ and $(1,0)+(1,2)$ are distinct sums giving $(2,2).$ So in this case we find that the only submonoid possible with the desired properties is $M.$
Comment: So here you show that for $F = <(1,0)>$, $E=F$ does not satisfy property (2). Keep in mind that I do not require $E=F$, and I do not require that $E$ is a strict submonoid of $M$. Indeed, the entire monoid $E=M$ obviously satisfies (1) and (2), and I have yet to find a smaller submonoid that violates (3). (I suspect that the answer to my question in this case is $E=M$.)
Comment: @MichaelKasa, I think you're correct that $E=M$ in this case, and I edited the question to prove this. I suppose I didn't help you prove/disprove the question here, but merely gave an example where the decomposition must be trivial. However, given that $M$ always satisfies 1 and 2 makes me feel like there should be some sort of "descending argument", like taking the intersection over the family of submonoids satisfying 1&2, which we know is non-empty.
Comment: I agree with your remarks about a "descending argument," except that heretofore I have been unable to show that (2) holds for the intersection (I suppose this is really the only tricky part).
Answer: The answer is "yes" in the special case of sharp monoids; that is, monoids where the only invertible element is 0. For a sharp integral monoid $P$, there is a finite collection of indecomposible elements, where an element $x\in P$ is indecomposible if whenever $x = y+z$, then either $y=0$ or $z=0$.
In this case, a face $F \subseteq P$ determines a subset of indecomposible elements (namely, the indecomposible elements contained in $F$). Thus, it is clear that $P$ has only finitely many faces.
Since any submoniod $E$ satisfying (2) in a sharp monoid is a face, it suffices to show the following: if we have two submonoid $E_1, E_2$ satisfying (1) and (2), then their intersection $E_1 \cap E_2$ also satisfies (1) and (2).
Write the indecomposible elements of $P$ as $f_1,\ldots,f_n,e_1,\ldots,e_m$.  Let $f_1,\ldots, f_n, e_1,\ldots, e_\ell$ be the indecomposible elements associated to $F_1$, and $f_1,\ldots f_n,e_p,\ldots, e_m$ be the indecomposible elements associated to $F_2$, where $1 \leq \ell < p \leq m$.  Let $F_0 = F_1 \cap F_2$, and let $E_0$ be the submonoid generated by $e_1, \ldots, e_m$.  Clearly $F_0 + E_0 = P$.
It suffices to show that if
$$ \sum_{i=1}^n n_i f_i + \sum_{i=1}^m m_i e_i = \sum_{i=1}^n n_i' f_i + \sum_{i=1}^m m_i' e_i$$
then both
$$ \sum_{i=1}^n n_i f_i = \sum_{i=1}^n n_i' f_i $$
and
$$ \sum_{i=1}^m m_i e_i = \sum_{i=1}^m m_i' e_i. $$
By the cancellative rule, one implies the other.
Because $E_1 \oplus E_1' \cong P$, we can conclude that
$$  \sum_{i=1}^n n_i f_i + \sum_{i=1}^\ell m_i e_i = \sum_{i=1}^n n_i' f_i + \sum_{i=1}^\ell m_i' e_i. $$
Because $E_2 \oplus E_2' \cong P$, we can conclude that
$$  \sum_{i=1}^p m_i e_i = \sum_{i=1}^p m_i' e_i. $$
If we add $\sum_{i=\ell+1}^p (m_i + m_i') e_i$ to the top equation, we have
$$  \sum_{i=1}^n n_i f_i + \sum_{i=1}^p m_i e_i + \sum_{i=\ell+1}^p m_i' e_i = \sum_{i=1}^n n_i' f_i + \sum_{i=1}^p m_i' e_i + \sum_{i=\ell+1}^p m_i e_i. $$
By the second equation and the cancellative law, we see that
$$ \sum_{i=1}^n n_i f_i + \sum_{i=\ell+1}^p m_i' e_i = \sum_{i=1}^n n_i' f_i + \sum_{i=\ell+1}^p m_i e_i . $$
Using either direct sum decomposition, we now can conclude that
$$ \sum_{i=1}^n n_i f_i = \sum_{i=1}^n n_i' f_i, $$
which is what we had to show.
Hence, the submonoid satisfying (1), (2), and (3) above is the intersection of all the monoids satisfying (1) and (2).


I want to Run a Service all the time Even App is closed,killed or terminated in Swift IOS

Question: Here is sample code service that i want to run all the time
<code>internal func backService()
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
            let anObject = try! Realm().objects(remindertbl).filter("status = 0")
            print("here")
            for loop in anObject
            {
                let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "dd/MM/yyyy hh:mm a"
                let  timestamp = dateFormatter.stringFromDate(NSDate())
                let timeStampint = dateFormatter.dateFromString(timestamp)!.timeIntervalSince1970
                if(loop.reminderdays == Int64(timeStampint))
                {
                    if(loop.status == 0){

                    let notification = UILocalNotification()
                    notification.fireDate = NSDate(timeIntervalSince1970: 0)
                    notification.alertBody = "\(loop.title)"
                    notification.alertAction = "swipe to opem VLB Cloud!"
                    notification.soundName = UILocalNotificationDefaultSoundName
                    notification.userInfo = ["CustomField1": "w00t"]
                    UIApplication.sharedApplication().scheduleLocalNotification(notification)

                    let updateObject = try! Realm().objects(remindertbl).filter("status = 0")
                    var reminderObject = remindertbl()
                    for updateStatus in updateObject{
                        try! Realm().write()
                            {
                                print("target")
                                reminderObject.status = 2
                                reminderObject.reminderId = updateStatus.reminderId
                                reminderObject.syncflag = updateStatus.syncflag
                                reminderObject.vehicleid = updateStatus.vehicleid
                                reminderObject.syncid = updateStatus.syncid
                                reminderObject.dateadded = updateStatus.dateadded
                                reminderObject.datemodified = Int64(Timestamp)!
                                reminderObject.remindertime = updateStatus.remindertime
                                reminderObject.reminerDate = updateStatus.reminerDate
                                reminderObject.reminderdays = updateStatus.reminderdays
                                reminderObject.title = updateStatus.title
                                reminderObject.targetdistance = updateStatus.targetdistance
                                reminderObject.currentdistance = updateStatus.currentdistance
                                reminderObject.remindertype = updateStatus.remindertype

                                reminderObject.synctype = updateStatus.synctype
                                reminderObject.recuringdays = updateStatus.recuringdays
                                reminderObject.recuringdistance = updateStatus.recuringdistance

                                try! Realm().add(reminderObject, update: true)
                                reminderObject = remindertbl()
                        }
                    }
                }
            }
        }

    })
}
</code>
Comment: You should simply your codes,it's too long and many lines is irrelevant.
Comment: Short answer, you can't. Refer to the background execution section in the iOS application programming guide from Apple for information on what background execution modes are available.
Answer: What you are asking is not possible for multiple reasons:

A task/app that has been killed or terminated cannot by definition
run some code
A few background modes are atuhorized by Apple on iOS
devices, if you are not specific task such as voIP, your app won't
be authorized to run at all times by the OS

If you want to learn more about executing some tasks on the background on iOS, I suggest you read the official documentation: Apple Documentation or this tutorial by the Ray Wenderlich team: Background modes for iOS


VS Code and Pycharm test command line

Question: In PyCharm you can set the command line parameters you want to test in your program in Run|Configurations.  Where is this hidden in VSCODE?  And I assume it does not exist in Wing?
Answer: Project| [filename] properties
click on Debug
Enter the command line on the Script Arguments line/

VS Code and Pycharm test command line


how to find location of missing library

Question: I have installed the mysql connector for c++.  I am writing a c++ cgi app.  The cgi page has been compiling.  I rebooted yesterday and it stopped compiling.  g++ -o sales.cgi sales.cpp -lcgicc -lmysqlcppcon. Gives the following error.  /usr/bin/ld cannot find -lmysqlcppcon
apt-get tells me I have the latest version of libmysqlcppconn7v5 and i have the latest version of libmyqlcppconn-dev.  How do I find the library.  I checked /usr/lib/ but I have no idea what I should be looking for.
Comment: The libmysqlcppcon-dev package [installs](https://packages.ubuntu.com/focal/amd64/libmysqlcppconn-dev/filelist) a `libmysqlcppcon.so` which is linked as -lmysqlcppcon. If that "stopped compiling", you accidentally removed that file or something?
Answer: Thanks for all of the help.  Huge typo on my side.  I needed g++ -o sales.cgi sales.cpp -lcgicc -lmysqlcppconn
Answer: Since you installed with apt-get, then you can use dpkg to determine which files were installed.
EXAMPLE (you would substitute "mysqlcppcon"):
dpkg -l|grep -i mysql
ii  php-mysql                        1:7.2+60ubuntu1                            all          MySQL module for PHP [default]
...  <= Search for the exact package name (here, "php-mysql")

   dpkg -L php-mysql
/.
/usr
/usr/share
/usr/share/doc
/usr/share/doc/php-mysql
/usr/share/doc/php-mysql/copyright
/usr/share/doc/php-mysql/changelog.gz
  <= List files installed to your system from that package

You can also use find
EXAMPLE:
find / -name "*mysqlcppcon*" -print 2> /dev/null

The *xxx* syntax let's you do a wildcard search;  2> /dev/null filters out irrelevant"noise" from your wildcard search, like "find: '/run/lvm': Permission denied".

how to find location of missing library


How to display tags inline?

Question: How can I display tags below an article inline? I have tried using firebug to no avail. I am using Drupal 7 and the zen sub theme.
Comment: put a link to ur site here for us to have a look at it
Comment: my website is not yet live as i am still developing it. however, when i added tags on a test article, they aligned vertically. i want them to align horizontally similar to how they appear on this site.
Answer: You can use CSS to style the tags.
If your html output is this:

Tag 1</l1>

Tag 2</l1>

Tag 3</l1>

Tag 4</l1>

Then use the following CSS to align tags horizontally.
.tags li { display:block; float:left; }

Comment: or you can use **.tags li { display:inline-block; }**
Comment: I agree, that would work too.

How to display tags inline?


Consider the IVP: $x^2y''+5xy'−5y=0,y(1)=0,y'(1)=1$

Question: Consider the IVP:
$$x^2y''+5xy'−5y=0,y(1)=0,y'(1)=1$$
Treating this as a Cauchy-Euler equation, find the unique solution on $(0,\infty)$.
my work
Answer: Dividing by $x^2$, we have
$$y'' + 5 \dfrac{y'}x - 5 \dfrac{y}{x^2} = 0$$
This can be rewritten as
$$y'' + 5 \dfrac{d}{dx}\left(\dfrac{y}x\right) = 0 \implies y' + 5\dfrac{y}x = c_1$$
Setting $y(x)=xv(x)$, we obtain that
$$y'(x) = xv'(x) + v(x)$$
Hence, we have
$$xv' + v + 5v=c_1 \implies xv' + 6v = c_1 \implies xv' + 6v-c_1 = 0 \implies \dfrac{dv}{6v-c_1} + \dfrac{dx}x = 0$$
This gives us that
$$\dfrac16 \ln(v-c_2) + \ln(x) = c_3 \implies (v-c_2)x^6 = 6c_3 \implies v(x) = \dfrac{k_1}{x^6} + k_2 \implies y(x) = \dfrac{k_1}{x^5} + k_2x$$
Now $y(1) = 0 \implies k_2 = -k_1$. And $y'(1) = 1 \implies k_2 - 5k_1 = 1$.
This gives us $k_1 = -1/6$ and $k_2 = 1/6$. Hence, the solution is
$$y(x) = \dfrac16\left(x-\dfrac1{x^5}\right)$$
Comment: Not a bad answer, but not quite what the question asks
Answer: Note that the problem asks to treat this as a Cauchy-Euler equation (you're doing a power series approach). Doing so, we find a solution of the form $y = x^m$. Taking derivatives and plugging in gives
$$ x^2m(m-1)x^{m-2} + 5xmx^{m-1} - 5x^m = 0$$
or
$$ m(m-1) + 5m - 5 = 0 $$
$$ m^2 + 4m - 5 $$
This gives $m = 1$ and $m = -5$, so the general solution is
$$ y(x) = c_1 x + c_2x^{-5} $$
Now apply the initial conditions to find the constants.


Define $f$ on $[0, 4]$ by $f(x) = x+ 1$ for $0 ≤ x < 2$ and $f(x) = 1$ for $2 ≤ x ≤ 4$. Use the extreme value theorem to show that f is not continuous

Question:
Define $f$ on $[0, 4]$ by $f(x) = x+ 1$ for $0 ≤ x < 2$ and $f(x) = 1$
  for $2 ≤ x ≤ 4$. Use the extreme value theorem to show that f is not
  continuous

So I'm having a little hard time doing this problem.
As I understand it, the extreme value theorem says

$\{f:[a,b]↦ω | ω⊆ℝ Λ a,b∈ℝ\} ⇒ \{∀p|p∈[a,b]:\lim \limits_{x \to p}f(x)=f(p)⇒∃c,∃d|c,d∈[a,b] : f(c) = \sup f ∧ f(d) = \inf f\}$

So, I imagine that in order to solve this problem, I should use the converse

$\{f:[a,b]↦ω | ω⊆ℝ Λ a,b∈ℝ\} ⇒ \{∀c,∀d|c,d∈[a,b] : f(c) ≠ \sup f ∨ f(d) ≠ \inf f ⇒ ∃p|p∈[a,b]:\lim \limits_{x \to p}f(x)≠f(p)\}$

So, if this is the graph of the function

I should prove that $f$ doesn't reach either its maximum or its minimum in $[a,b]$, and this would be a sufficient condition for $f$ not to be continuous in $[a,b].$ It's kinda' clear from the graph, but I'm having trouble proving it analytically.
What I see is that $\lim \limits_{x \to 2^{-}}f(x)=3$, so if $f(2)=3$, according to the graph, $3$ would be the maximum, but $f(2)=1$ so it never actually reaches its maximum. I could get closer and closer to $2$ in the domain and find the images of such values in the range closer and closer to $3$, but when actually reaching $2$, it wouldn't reach $3$, but $1$, thus not reaching the maximum.
However, I don't know if this reasoning is either correct or formal enough. It feels more like an intuition.
Could you help me?
Thanks in advance.
Comment: The intuition is right, but it needs to be formalized. I imagine you can use an epsilon delta proof to show that the limit of the function maxes out at three, but never reaches three.
Comment: You should show that the interval $[3, \infty)$ is not in the range of the function, which should be easy from its definition. Then, if $f(x) < 3$, find a way to define a $y$ (depending on $x$) such that $f(x) < f(y)$. This shows there cannot be a maximum.
Answer: Suppose on the contrary that it is continuous, then by extreme value theorem, then there is a maximum.
Let's prove that $f([0,2))=[1,3)$,
Let $y \in f([0,2))$, then there $\exists x \in [0,2)$ such that $f(x)=x+1=y.$ $0 \le x < 2 \implies 1 \le y< 3.$
Conversely, if $y \in [1,3)$, then we have $y-1 \in [0,2)$ and we have $f(y-1) =y$. Hence $y \in f([0,2)$.
$$f([0,4])=f([0,2))\cup f([2,4])=[1,3) \cup \{1\}=[1,3)$$
and it doesn't have a maximum value.


High pitch noise when playing high E string

Question: I can hear a strange high pitched noise when playing the high E open string on my standard Mexican telecaster.
The sound is present only when playing the string open. It sounds like something around E7 (or E8 maybe), it is quite high pitched. It also seems to affect the sustain on that open string. The sound get more noticeable when tuning down the string and sustain is even worse.
What could cause this to happen? How can I fix that noise and get the precious sustain back?
Comment: E7 and E8 are indeed overtones of the E string, so it would actually be weird if you _didn't_ hear them. They should not  _stand out_, granted, but well – the Tele is a bright-sounding guitar. Twangy, not sustainy, so... — For us to say anything specific we'd need to actually hear the sound you mean; you could add a recording, post it via SoundCloud. But if it really annoys you you should probably consult a luthier rather than the internet.
Answer: Seems like the problem is in the nut. If it doesn't occur anywhere else, even on the first fret, there's nowhere else. It could be that the string is loose in the slot. Try pushing the string to one side behind the nut, if that works, pack something - a strip of paper may do - under the string in the nut slot.
Another cause can be sympathetic vibration of something loose - a screw, a machine head, etc.
Comment: It seems like it's a combination of both problem. I first tried putting a piece of paper in the nut slot, the sound was slightly better but something was definitely still here. Then I notice the E string saddle was moving a bit. I pressed it against the B string saddle and the noise was gone. It seems like playing the E string made the E string saddle vibrate against the B string saddle and created that sound. Maybe the piece of paper is not needed after all but I will keep it here for good measure.
Answer: Try lying a nail under the string, near the nut, to lift the string. If the noise disappears and sustain returns that would suggest you have a high fret. The cure could be as simple as adjusting the neck relief, but you might need to see a luthier about some fret work.
Comment: It should be pointed out that the only possible fret that could be high, and not cause buzzing when the string is fingered, is the first fret.  Any higher fret buzz would get worse as you finger up the neck.
Answer: Third possibility - it could be the length of string between the nut and the tuning machine is vibrating. You can damp that area of the string with your fingers and then play the open string and see if it doesn't make the sound. If damping that piece of string helps, then you may have something wrong with your string tree or how the string was wound around the tuning machine, or as Tim mentions there might be a problem with your nut.
Comment: Indeed. In fact, there are lots of possibilities, some of which are very difficult to locate.  The ball of a ball end string can rattle; there can be a crack or open joint that buzzes, the winding of the string can be loose, the groove in the nut can be too wide....


Open dialog when clicking on event in fullcalendar

Question: I would like to open a dialog instead of an prompt. (so i can edit it). i currently have a delete event function when you click on an event a prompt shows and when you click ok the event is deleted. This works fine but i would like to have an dialog instead of an prompt.
The delete function:
eventClick: function(event) {
var decision = confirm("Weet u zeker dat u de afspraak wilt verwijderen?");
if (decision){
$.ajax({
url: '<?=base_url();?>testcalendar/fullcalendar/delete_events.php',
data: 'id=' + event.id ,
type: "POST",
});
$('#calendar2').fullCalendar('removeEvents', event.id);
var nTime = 1 * 50;
window.setTimeout("location.reload()", nTime);
}},

the delete_events.php:
    <?php
$id = $_POST['id'];
 try {
 $bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
 } catch(Exception $e) {
  exit('Unable to connect to database.');
 }
$sql = "DELETE from evenement WHERE id=".$id;
$q = $bdd->prepare($sql);
$q->execute(array($id));
?>

Answer: I would like to use a html form to edit relative data. this form would be hide, and shown when necessary.

<input id="index1" />

<input id="index2" />

<button id="submit" />

and write some function send these index to a php file, which deal with those data, like saving or changing.
I'm new here, and always searching for answers. This is my first answer, it can't be perfect, but I think I expressed my thought about this question, may it would help you. :-)


Variável em decimal removendo as casas decimais

Question: Tenho uma variável em decimal que recebe um valor de um textbox, porém quando essa variável recebe o valor com casas decimais ele remove a casa decimal e guarda o valor sem a mesma.
O que acontece:

Valor do TextBox: 2.5;
Valor da variável: 0;
variavel = Convert.ToDecimal(TextBox);
variavel = 25;

Não estou conseguindo entender o porque está acontecendo isto. Dá erro de inserção no banco de dados:

NpgsqlException was unhandled by user code ERROR: 42601: syntax error at or near "3"
Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Comment: Deixa eu entender melhor, o que aparece se você imprimir o valor do `TextBox` antes de gravar?
Comment: Aparece 2,5 - mas se eu inserir 2,5 no POSTGRE na hora da inserção ele da erro. Porque nenhum tipo de dado do postgre aceita virgula, porém quando eu estou manipulando o textbox e eu coloco .Replace(",",".") e mando o valor do txt pro numeric e o numeric recebe o valor ele já recebe sem o .
Comment: @LucasVasconcelos você precisa passar mais detalhes então. http://pt.stackoverflow.com/help/mcve
Answer: Se o erro está ocorrendo porque um dado foi digitado de forma incorreta, o que falta é uma validação. Você deve evitar usar qualquer dado sem antes ter certeza que ele é adequado para uso. Você nunca pode confiar em entrada de dados, ainda mais pela web.
Você pode fazer a conversão desta forma:
using static System.Console;
using System.Globalization;

public class Program {
    public static void Main() {
        decimal valor;
        if (decimal.TryParse("123.45", out valor)) WriteLine(valor);
        if (decimal.TryParse("123,45", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, new CultureInfo("pt-BR"), out valor)) {
            WriteLine(valor);
        }
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Coloquei duas formas para você ver como pode ser feito. Você pode ler a documentação para aprender outras formas de usar a conversão de forma apropriada.
Comment: Gostaria de saber qual é o erro aqui para ter um -1?
Answer: Eu tive esse mesmo problema esses dias,
no meu caso usei javascript com expressão regular  para corrigir o erro da seguinte forma.
remover todos os ponto do texto.
str = str.replace(/\./g, "");

altera a , por ponto
str = str.replace(",", ".");

Qual motivo para isso? os campo do tipo (Decimal , numeric) do SQL SERVER não aceitam , para especificar as casas decimais.
Os métodos abaixo pode ajudar com algumas coisas.
// ----- Decimal Extensions -----
public static Boolean IsValidDecimal(this String numStr)
{
    Decimal Dummy;
    return Decimal.TryParse(numStr.Replace(".", String.Empty),
        NumberStyles.Float, new CultureInfo(1046, true), out Dummy);
}

public static Decimal StringToDecimal(this String numStr)
{
    return Decimal.Parse(numStr.Replace(".", String.Empty),
        NumberStyles.Float, new CultureInfo(1046, true));
}

public static Decimal? StringToNullableDecimal(this String numStr)
{
    Decimal? DecVal = null;
    if (!numStr.IsNullOrWhiteSpace())
        DecVal = numStr.StringToDecimal();
    return DecVal;
}

// Converte um Decimal para um String com 2 casos decimais
public static String DecimalToString(this Decimal dec, Int32 scale = 2)
{
    return dec.ToString("#,##0.00000000".Substring(0, 6 + scale),
                new CultureInfo(1046, true));
}

public static String DecimalToString(this Decimal? dec, Int32 scale = 2)
{
    return dec.HasValue ? dec.Value.DecimalToString(scale): String.Empty;
}

public static String DecimalToSqlString(this Decimal dec, Int32 scale = 2)
{
    return dec.ToString("0.000000".Substring(0, 2 + scale),
                new CultureInfo("en-US", true));
}

public static String DecimalToSqlString(this Decimal? dec, Int32 scale = 2)
{
    return dec.HasValue ? dec.Value.DecimalToSqlString(scale) : "null";
}

 public static Boolean IsNullOrWhiteSpace(this String str)
{
    return String.IsNullOrWhiteSpace(str);
}


Model Perplexity explanation

Question: Not sure if this is the place to ask about model perplexity.
I have googled some explanations but it does not seem to yield much results besides the wikipedia explanation.
Can someone explain to me what is this exactly all about preferably with an example
Answer: It's a measure of how "surprised" a model is by some test data, namely $\mathbb{P}_\textrm{model}(d_1,\ldots,d_n)^{-1/n}$, call it $x$.  Equivalently, $\mathbb{P}_\textrm{model}(d_1,\ldots,d_n) = (1/x)^n$ .  Low $x$ is good, because it means that the test data are highly probable under your model.
Imagine your model is trying to guess the test data one item (character, say) at a time.  Then $x$ is effectively the "average-case" number of possibilities for each new character given all the previous ones.  Low $x$ means the model has few options for the next character, which is good.

Here's an example.  Suppose we have a data $ABABBBABABBA\ldots$ in which there are twice as many B's as A's.  Now:

Model 1 says that A's and B's are independent with $\mathbb{P}(A)=\frac{1}{3}, \mathbb{P}(B)=\frac{2}{3}$.  Test data of size $n$ will have probability under model 1 of about $\frac{1}{3}^{n/3}\frac{2}{3}^{2n/3}$, thus perplexity $3\times 2^{-2/3}\approx 1.89$.
Ah, but look closer: $AA$ never occurs.  This suggests model 2: $\mathbb{P}(A\rightarrow B)=1$ and $\mathbb{P}(B\rightarrow A)=\mathbb{P}(B\rightarrow B)=\frac{1}{2}$.  Under that model, test data of size $n$ will have probability about $1^{n/3} \frac{1}{2}^{2n/3}$, thus perplexity $2^{2/3} \approx 1.59$.

So in this example model 2, which picked up on a feature of the data that model 1 had missed, had the lower (better) perplexity, and would be able to predict a length-$n$ sequence from nothing with probability about $1.59^{-n}$.
Comment: The model should be able to "look" at any data and assign it a probability.  Under my model 1, for example, $ABABBBA$ would have probability $\frac{1}{3}^3\frac{2}{3}^4$ because there are 3 A's and four B's.  When I said that "low" $x$ means "highly" probable, I really just meant that if you have a bunch of potential models for your data then those that have lower perplexity on a brand new chunk of ("test") data, equivalently that assign higher probability to the test data, are better in general.  Here, "low" perplexity is a relative notion; there's no absolute scale of good<-->bad perplexity.
Comment: For the particular perplexity calculations shown in my answer, well, let's take the harder model 2 for example.  If the data have twice as many B's as A's and no AA's then there'll be about $n/3$ lots of $A\rightarrow B$ (because there are $n/3$ A's), about $n/3$ lots of $B\rightarrow A$ and about $n/3$ lots of $B\rightarrow B$.  Those transitions have probabilities $1, \frac{1}{2}, \frac{1}{2}$ respectively, so the total probability is $1^{n/3}\frac{1}{2}^{n/3}\frac{1}{2}^{n/3}$.  Now raise to the power $-1/n$ to convert probability to perplexity: $1^3 2^{1/3} 2^{1/3} = 2^{2/3} \approx 1.59$.
Comment: 2 parts I would like to clarify. What did you mean by highly probable under the test data? And the next part would be how did you perform the calculation for complexity
Comment: @Creosote Sorry for the late comment, but your last sentence makes no sense to me. You can't have probability 1.59 of predicting the next term. Are you missing a minus sign in the exponent?
Comment: @stella-biderman ... well spotted, now fixed.

Model Perplexity explanation


Expected number of cases, standardizing with age & sex of the whole population

Question: Starting with a toy example data (http://www.stata-press.com/data/r14/hbp.dta)
use http://www.stata-press.com/data/r14/hbp, clear

drop if mi(sex)
drop if mi(age_group)
sort city sex age_group year, stable
by city sex age_group: egen obs = total(hbp)
by city sex age_group:  gen pop = _N
by city sex age_group:  keep if _n == 1
drop year race hbp

replace city = 4 if city == 5 // used by the the loop later, so sequential better

bysort city (sex age): egen obs_city = total(obs)
bysort city (sex age): egen pop_city = total(pop)
gen crude = obs_city / pop_city

We have age & sex specific counts of events obs and population denominator pop in 5 different cities. Crude rate in a city is given by crude variable simply dividing observations by population within city and ignoring age structure.  Now, I'd like to use information from all cities to create age & sex specific rates and using that - calculated expected number of events given the study population.
I'm trying to achieve that by using city specific standardized rates:
dstdize obs pop age sex, by(city) print saving( "temp", replace )

mat b = r(adj)
matrix list b

gen adjusted = .
gen exp_city_ds = .

forv city = 1/4 {
    local bw = b[1, `city']
    display `bw'
    replace adjusted = `bw' if city == `city'
    replace exp_city_ds = pop_city * `bw' if city == `city'
}

So far so good, but when I look at results I'd obtain from simple poisson model - the numbers do not add up:
poisson obs i.sex i.age, exp(pop) irr
predict exp_p, n

bysort city (sex age): egen exp_city_poi = total(exp_p)
drop exp_p

gen dif0 = obs_city - exp_city_ds
gen dif1 = obs_city - exp_city_poi
gen dif2 = exp_city_ds - exp_city_poi
su dif? if sex == 1 & age == 2 // first obs by city

saveold "temp_old.dta", v(12) replace // data for R

I also tried to calculate from the same dummy dataset observed number of case using expected function of SpatialEpi package:
library(foreign)
library(SpatialEpi)

data <- read.dta("temp_old.dta") #, convert.factors = FALSE)

expected(data$pop, data$obs, 8)
seq(1, 4, 1)

city <- cbind(seq(1, 4, 1), expected(data$pop, data$obs, 8))
colnames(city) <- c("city", "E")

data <- merge(data, city, by="city")

data$poi_fit <- fitted(glm(obs ~ 1 + offset(log(pop)), data = data, family = "poisson"))

Again - I get different numbers, very close to Poisson fit (both Stata & R) but not the same.
Now, my question: is the reason of such difference lying in my calculations/methods? Or is it expected?
Answer: You are applying Poisson model to the dataset which does not behave this way -- the assumption of independence in time does not hold.
For the dataset in consideration. We look at the prevalence of hypertension for different cities and age/sex groups.
Try the following R code:
# As example read high blood pressure data
library(foreign)
d <- read.dta("hbp.dta")
# Reformat data
d$city <- as.factor(d$city)
d$age_group <- factor(d$age_group) # Remove misleading unused age groups
d$hbp <- as.numeric(d$hbp) - 1
# Fit logistic regression
fm <- glm(hbp ~ city + age_group*sex, data=d)
# Basic model selection
bm <- step(fm)
summary(bm)

You will find that the risk age group turns out to be (30-34) which are, indeed, the oldest subjects in the data. Being a woman is slight protective factor and the city3 has the highest prevalence. Therefore to test the Poisson behavior let us subset to, say, city1, men.
ind1 <- which(d$city == "1")
ind2 <- which(d$sex == "Male")
d2 <- d[c(ind1,ind2),]
ag <- aggregate(hbp ~ age_group, d2, sum)

The result is:
age_group hbp
15 - 19   5
20 - 24  12
25 - 29  19
30 - 34  24

Now fit Poisson:
x <- (1:4)
m1 <- glm(ag$hbp ~ x, family="poisson")

The model has $R^2 = 0.96$ so it is good.
Comment: Thanks. I'm aware that this is perhaps not the perfect dataset to analyse with this method - them main reason of using it was opportunistic availability in Stata. I'm more interested in general concepts and methods of approaching the problem that I could use with data I cannot share openly.


java swing, highligth item in jcombobox popup

Question: i want to highlight an item inside popup list.
I say "highlight" becouse i don't want to select it (for example by calling setSelectedItem) but only make it selected inside the jcombobox popup.
How can i do?
Answer: The following sort of works in that an item other than the first is selected. However, if you use the keyboard to change selection, it always starts from the first because that is the one that is selected.
<code>import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;

public class ComboBoxSelect extends JFrame
{
    public ComboBoxSelect()
    {
        String[] items = { "Item1", "Item2", "Item3", "Item4", "Item5" };
        JComboBox comboBox = new JComboBox( items );
        add( comboBox );

        comboBox.addPopupMenuListener(new PopupMenuListener()
        {
            public void popupMenuWillBecomeVisible(PopupMenuEvent e)
            {
                JComboBox comboBox = (JComboBox)e.getSource();
                BasicComboPopup popup = (BasicComboPopup)comboBox.getAccessibleContext().getAccessibleChild(0);
                JList list = popup.getList();
                list.setSelectedIndex(2);
            }

            public void popupMenuCanceled(PopupMenuEvent e) {}
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}

        });
    }

    public static void main(String[] args)
    {
        ComboBoxSelect frame = new ComboBoxSelect();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }
</code>
}
Answer: This write-up provides guidance on how you could modify JComboBox:

http://www.orbital-computer.de/JComboBox/

Although it's written for auto-complete functionality, a custom mechanism to highlight without selecting would be very similar (and probably easier).
Comment: This solution use setSelectedItem to highligth item in popup.


Number of places over a number field

Question: Let $\mathbb{K}$ a finite extension of $\mathbb{Q}$ and $\mathcal{O}_\mathbb{K}$ its ring of integers. Assume $\mathcal{O}_\mathbb{K}=\mathbb{Z}[\alpha]$, that is generated as a ring by a single element $\alpha\in\mathbb{K}$. I am asked to show that, for every prime $p\in\mathbb{Z}$, there are at most $p$ places on $\mathbb{K}$ over $p$, that is at most $p$ ways to extend the non archimedean value $|\cdot|_p$ to $\mathbb{K}$.
I don't know how to start attacking the problem, any hint?
Edit: there was a typo in the original problem. The correct question was to prove that there are at most $p$ places on $\mathbb{K}$ over $p$ of residue degree 1, and the proof follows from Adam Hughes' answer.
Comment: The correct statement is that there are at most $[K:\mathbf Q]$ ways to extend any absolute value from $\mathbf Q$ to $K$.
Comment: Sure, if you know about $p$-adics and that extensions of $|\cdot|_p$ from $\mathbf Q$ to $K$ correspond to different field embeddings of $K$ into an algebraic closure of $\mathbf Q_p$ then the bound is obvious.  It can be shown by other methods as well.
Comment: It's possible I've misread your question, but it appears to be false. See my answer for a detailed discussion, and please comment if you think I've misunderstood something about what you've asked.
Comment: @AdamHughes I've double checked both the exercise text and your answer, and it absolutely look like you're right and the "proposition" is wrong. I'll ask my teacher.
Comment: @KCd Which is kinda obvious since the number of such places is the number of irreducible factors in $\mathbb{Q}_p[X]$ of the minimal polynomial of $\mathbb{K}$ over $\mathbb{Q}$, whose degree is $[\mathbb{K}:\mathbb{Q}]$.
Comment: @AngeloRendina OK, that's definitely completely different, although you can get it from the early part of my answer:  note the description of how primes above a fixed prime are exactly in 1-1 correspondence with irreducible factors of $p(x)\mod p$ as in my answer.
Answer: Well we know that $\mathcal{O}_K$ is isomorphic to $\Bbb Z[x]/(p_\alpha(x))$ with $p_\alpha(x)$ the $\Bbb Z$-minimal polynomial for $\alpha$.
Then the number of primes over $p$ is determined by the splitting behavior of $p_{\alpha}(x)\mod p$. Since we see that if we have a prime $\mathfrak{p}|(p)$, then it comes from a factorization into (not necessarily unique) irreducibles
$$\overline{p}_\alpha(x)=\prod_{i=1}^r p_i(x)$$
via $\mathfrak{p}=(p_i(\alpha),p)$, since $\Bbb Z[\alpha]$ has trivial conductor in $\mathcal{O}_K$ (this is the critical fact).
But then your original result is false. Consider $K=\Bbb Q(\zeta_n)$ for a primitive $n^{th}$ root of unity, $\zeta_n$ then $\mathcal{O}_K=\Bbb Z[\zeta_n]$ by classical theory. We know that if we pick $n=p^{k}-1$ then consider the $n^{th}$ cyclotomic polynomial $\Phi_n(x)$, we know it will factor as the product of all irreducible polynomials of degree $k$ modulo $p$ since $\Bbb F_{p^k}$ is the unique finite field of order $p^k$ and consists of $0$ and the $(p^k-1)^{st}$ roots of $1$. So then if we can demonstrate more than $p$ such irreducible factors, we have disproven the statement. But we can count the number of irreducible polynomials of degree $q$, a prime not equal to $p$, namely ${p^q-p\over q}$ (I omit the proof, since it's not the subject of this post, but there are many available online, including here on MSE) so choose $p=2, q=5$ and we get $6$ distinct irreducibles modulo $p$, hence $6$ primes above $2$ in $\Bbb Z[\zeta_{p^q-1}]$, which is more than $2$.
Comment: As stated in the post edit, there was a typo. However I'm accepting the answer since it both proves the correct question and disproves the wrong one.

Number of places over a number field


Aumentar e Diminuir Fonte, como aplicar em um grande site?

Question: Tenho que aplicar o recurso de acessibilidade para aumentar e diminuir fonte. Atualmente tenho 3 botões: Fonte Pequena, Fonte Normal e Fonte Grande.
A ideia é que ao clicar em cada botão, seja chamada a respectiva função em javascript. E que a fonte aumente ou diminua para um determinado tamanho e pronto (não poder aumentar 2px a cada vez clicada por exemplo, era 12 foi direto pra 20 e para por ai).
O que está complicando é que se trata de um site grande, muitas classes, ids, muito conteúdo.
Pensei em realizar a alteração na fonte por meio do getElementsByTagName, porém uma mesma tag varia seu tamanho e espaço disponível de acordo com a página.
Por exemplo temos H1 com fonte 50 em uma página e que dá pra aumentar até 60, 70, mas também temos H1 com fonte 20 que aumenta até 30 (senão ultrapassa o tamanho da página e zoa tudo).
O que me resta de opção então? Fazer classe por classe?
Comment: Uma alternativa seria carregar dinamicamente o `css` usando `javascript`, carregando um arquivo que tenha todas as definições dos tamanhos.
Comment: Ricardo, obrigada pela ideia! Funcionou para o que eu queria.
Answer: Se eu entendi o que você quer:

const btns = document.getElementsByTagName('button');

//Muda a fonte do corpo da página para 5px
btns[0].addEventListener('click', () => document.body.style.fontSize = '5px');

//Muda a fonte do corpo da página para 20px
btns[1].addEventListener('click', () => document.body.style.fontSize = '20px');

//Muda a fonte do corpo da página para 35px
btns[2].addEventListener('click', () => document.body.style.fontSize = '35px');
/* Aqui define o tamanho base, não precisa ser em px */
body {
  font-size: 20px;
}

/* Os botões ficaram do mesmo tamanho idependentemente do tamanho */
button {
  font-size: 20px;
}

/* Os outros vão aumentar/diminuir proporcionalmente */
h1 {
  font-size: 1.5em
}
p {
  font-size: 1em
}
span {
  font-size: 0.5em
}

  <button> Pequeno </button>
  <button> Médio </button>
  <button> Grande </button>

Texto grande

Texto médio

  Texto pequeno

O em é uma unidade de medida que reflete o tamanho corrente da fonte, sendo 0.5em a metade do valor, 1em o mesmo valor, 2em o dobro do valor e assim sucessivamente
Aqui tem uma resposta sobre essas e outras unidades de medida do CSS
Comment: O ideal é isso mesmo, definir um tamanho base e os demais relativos a ele. Só que parece que o caso da pergunta é de um site que não foi construído pensando nisso.
Comment: Acredito que uns `Ctrl + H` resolve isso
Comment: Tomara. Fica +1 na sua resposta
Comment: Nesse caso, eu estaria com aquele problema de aplicar a alteração por tags. E em cada página, uma mesma tag tem um tamanho diferente, devido ao espaço disponível etc. Acabei criando um css alternativo e aplicando por uma função. Obrigada pela resposta.
Comment: @RecursodeAcessibilidade você pode usar classes (`.pequeno`, `.medio`, ...), usei tags apenas como exemplo,
Answer: Acredito que o mais simples será você trabalhar com variáveis no CSS e definir a propriedade font-size dos elementos que deseja mudar com base em sua variável.
Com JavaScript, basta você alterar o valor da variável no CSS que sua página se ajustará. Veja um exemplo, onde defini que o título
 será sempre o dobro da variável --font-size, enquanto os parágrafos serão a própria --font-size.

const buttons = document.querySelectorAll('button');

for (let button of buttons) {
  button.addEventListener('click', function (event) {
    document.body.style.setProperty('--font-size', this.dataset.fontSize);
  });
}
body {
  --font-size: 1rem;
}

h1 {
  font-size: calc(2 * var(--font-size));
}

p {
  font-size: var(--font-size);
}
<button data-font-size="0.5rem">Pequena</button>
<button data-font-size="1.0rem">Normal</button>
<button data-font-size="2.0rem">Grande</button>

Titulo

Texto

Comment: Sempre vale aquele alerta: https://caniuse.com/#feat=css-variables
Comment: Nesse caso, eu estaria com aquele problema de aplicar a alteração por tags. E em cada página, uma mesma tag tem um tamanho diferente, devido ao espaço disponível etc. Acabei criando um css alternativo e aplicando por uma função. Obrigada pela resposta.
Answer: Criei um css alternativo com as fontes maiores, personalizando cada classe da forma que eu queria e apliquei da seguinte forma:
<--! Defini  um id para o css externo atual-->
<link href="estilos.css" rel="stylesheet" id="css">

//altero a variável css (que recebe o arquivo atual) para que ela receba css externo, com as fontes maiores
function fontegrande ()
{
  var css = document.querySelector('#css');
  css.setAttribute('href', 'estilosmaiorecontraste.css');
}


JPA - List annotated with @OrderBy does not order items

Question: @Entity
@Table(name = "some_class")
@SequenceGenerator(name = "default_gen", sequenceName = "some_class_id_seq", allocationSize = 1)
data class SomeClass(

    @OneToMany(mappedBy = "someClass", cascade = [CascadeType.ALL], orphanRemoval = true)
    @OrderBy("date")
    var items: List<SomeItem>,
) : AbstractEntity()

@Entity
@Table(name = "some_item")
@SequenceGenerator(name = "default_gen", sequenceName = "some_item_id_seq", allocationSize = 1)
data class SomeItem(
    val date: LocalDate,

    @ManyToOne
    @JsonIgnore
    val someClass: SomeClass
) : AbstractEntity()

AbstractEntity contains trivial things such as id, createdAt etc.
I would expect items to be a sorted list, but it's not, it always contains items in the order in which I've created them.
EDIT: this question is kind of a duplicate of "JPA: can't make OrderBy work". The answer to that question pointed me in the right direction.
To make my tests pass, I need to call the following function before accessing the repository:
private fun clearEntityManagerCache() {
    entityManager.flush()
    entityManager.clear()
    entityManager.entityManagerFactory.cache.evictAll()
}

After having entityManager injected:
@Inject
private lateinit var entityManager: EntityManager

Comment: Did you try to put the direction in sort? `@OrderBy(value = "date asc")`? The default is ASC, but give a shot
Comment: @DeividiCavarzan Tried, does not work
Answer: You can get out of the standard JPA @javax.persistence.OrderBy, try one of the Hibernate sorting options, either @org.hibernate.annotations.Sort or @org.hibernate.annotations.OrderBy.
Adding a SQL fragment into your domain class isn't necessarily the most elegant thing in the world, but it might be the most pragmatic thing.

Reference:

https://dzone.com/articles/sorting-collections-hibernate

https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/order-by-annotation.html
Comment: but SomeItem is not a basic type or @Embeddable
Comment: Thanks, but I solved it by clearing the entityManager cache, see edited question
Comment: @andrew You're right, I made other suggestion... I hope this helps.


Do past probability results of a fair coin affect the present probability?

Question: I decide to play a game of heads or tails with an absolute "fair" coin $1,000,000$ times.
Suppose (however unlikely) I get $999,999$ heads in a row!
If I get heads on the 1 millionth toss, I win a prize!
Should the past coin tosses influence my present decision?
Logically, the last toss is still $50$% to get heads...
but can I allow my mind to bias the probability and favor heads over tails?
Thanks for any insights!
Comment: https://en.m.wikipedia.org/wiki/Gambler%27s_fallacy
Comment: It's tricky. Practically speaking the issue is that if you ever found yourself in this situation then it's extremely likely that the coin isn't actually fair. To do a complete analysis involves an analysis of why you think you know the coin is fair which is underspecified by the problem.
Comment: Say you believe that there is a one in a million chance that someone slipped you an unfair coin.  Then that possibility will loom very large given the preposterously improbable event you observe.
Comment: In addition to my answer - indeed as @QiaochuYuan has mentioned, if this happened in real life we would obviously start to question the fairness of the coin. But if we (theoretically) knew the coin was absolutely fair - as my answer states - the probability remains exactly the same on the last go (${50\%}$)
Comment: Call heads.  If the coin is fair, it doesn't matter what you do, and if the coin is biassed, it's overwhelmingly likely that the next toss will be heads.
Answer: The answer since you stated the coin was known to be fair:
If you get a huge number of heads in a row - the chance you get another heads on the next toss is still ${50\%}$. The thing is - those ${999,999}$ heads in a row have already happened, and the events are independent. [Basic conditional probability]: for independent events ${A,B}$ we know that
$${P(B|A)=P(B)}$$
In this case - ${B}$ is "I get a heads next toss" and $A$ is "I just got ${999,999}$ heads in a row".
If you ask "what's the chance I get ${1,000,000}$ heads in a row?" without having done any tosses already, then the answer is a small number. Nothing has happened yet. It may seem odd since your intuition tells you "come on, the last one must be a tails!" but it's still the exact same probability, since those tosses have now already occurred.
For a real world coin - if you throw it a lot of times in a row - it technically I guess could become slightly "weighted" overtime and have a slight bias as a result - but in a theoretically perfect coin - the probability remains the same. Also if you did get that many heads in a row with a real world coin - we would obviously start to question whether that coin really was fair.


Definition of positional terms (latitude/longitude) of basketball shots?

Question: What does latitude, longitude, and x,y positions mean in basketball?
These terms are from here, corresponding to 'lat', 'lon', 'loc_x', and 'loc_y'.
I would appreciate an explanation in layman's terms, since I'm not familiar with any aspects of basketball.
edit
I've noticed that the values of 'lat' and 'lon' fall near 34 degrees and -118 degrees, respectively. 'loc_x' and 'loc_y' are both 0 for 'dunk's and 'layup's that the mentioned basketball player made.
edit2
Here are some of the dataset:
action_type,combined_shot_type,game_event_id,game_id,lat,loc_x,loc_y,lon,minutes_remaining,period,playoffs,season,seconds_remaining,shot_distance,shot_made_flag,shot_type,shot_zone_area,shot_zone_basic,shot_zone_range,team_id,team_name,game_date,matchup,opponent,shot_id
Jump Shot,Jump Shot,12,20000012,34.0443,-157,0,-118.4268,10,1,0,2000-01,22,15,0,2PT Field Goal,Left Side(L),Mid-Range,8-16 ft.,1610612747,Los Angeles Lakers,2000-10-31,LAL @ POR,POR,2
Jump Shot,Jump Shot,35,20000012,33.9093,-101,135,-118.3708,7,1,0,2000-01,45,16,1,2PT Field Goal,Left Side Center(LC),Mid-Range,16-24 ft.,1610612747,Los Angeles Lakers,2000-10-31,LAL @ POR,POR,3

Comment: Just a note...variables from a dataset may or may not help you become more familiar with basketball. Looking at said dataset (which isn't available without signing in to Kaggle -- so a sample would be appreciated), there's nothing to suggest these are standardized terms and could potentially be specific for the purposes of this dataset.
Comment: I highly doubt that the dataset is not standardized. It supposedly contains all of the shots attempted by the basketball player since the start of his career.
Comment: The terms you ask about may be important from a dataset perspective, but I have never heard these terms used in a layman basketball perspective.
Answer: LOC_X and LOC_Y are what you want to look at; those are the location on the floor.  X is left-right along the endline with 0 centered at the basket (negative numbers left of the basket if the basket is on the bottom of the chart), and Y is positive towards halfcourt with 0 being at the basket (so very small negative numbers are possible, since the basket hangs just over the baseline).
See this R tutorial for more information.  The NBA doesn't actually suggest people use these data, so they don't publish a glossary, but this page does a good job of explaining it.
The latitude/longitude I suspect is useless information; the values are approximately equal to Los Angeles's Lat/Lon even when playing an away game, so they really make no sense.


How to update/edit custom_properties in laravel spatie?

Question: I'm using laravel spatie in my app. I have a problem.
When an user updates his list of image. Admin must to be approve a list of image which an user just update. If user add image, i just add more. But when an user change an image he had, how to do it? I can't change collection_name because if i change, this image is not appear in user profile. Do you have any ideal for me?
I have an ideal: i add an in custom_properties column with value {'change' => 'false'}. When user change this image, i will change custom_properties to {'change' => 'true'}. And when admin approve the change, i must update custom_properties to {'change' => 'false'}. But i can't access in value of custom_properties  column. (As you know, laravel spatie give us an media table , it has a column custom_properties have json data in it). So help me access in to this column and update data in it.
So sorry because my english is not good.
    $mediaOld = Media::where(['model_id' => $doctor_id, 'collection_name' => 'doctor_achieved'])->get();
    if (isset($mediaOld[$index])) {
        $mediaOld[$index]->update(['custom_properties->change' => 'true']);
        $mediaOld[$index]->save(); // Its not working
        return $mediaOld[$index]->custom_properties;
    }

This is data response of this record
Answer: this might help:
$mediaItem = Media::find($id);

$mediaItem->setCustomProperty('name', 'value'); // adds a new custom propery or updates an existing one
$mediaItem->forgetCustomProperty('name'); // removes a custom propery

$mediaItem->save();

https://docs.spatie.be/laravel-medialibrary/v7/advanced-usage/using-custom-properties/
Comment: save() method is important here. In my case I forgot about it.


Variable variable for array

Question: I have defined an array $array[1][1][test]="hello world". I would like to get this value by using variable variables. I have tried this, without success:
$var1="array";
$var2="[1][1]";
$var3="['test']";

echo ${$var1}{$var2}{$var3};

Output is null.
Comment: See [The manual page for Variable Variables](http://php.net/manual/en/language.variables.variable.php) I dont think you can put the indicies into this concept though.
Comment: @RiggsFolly, yes, `eval()` is kind of a like `goto`. It does great deal of damage when you don't know what you are doing and when you know enough to use it, you know you don't really need it.
Comment: So you declaring a multi Dimensional array and you would like to display the values?
Comment: If you really *really* want to do this, you can use `echo eval("return \$$var1$var2$var3;")`. I would strongly advise against it, however.
Comment: I just knew someone would get to `eval()` eventually. Please read the [**CAUTION** on the manual page](http://php.net/manual/en/function.eval.php) before even thinking about using it. I bet if you stood back and looked at your requrement you could come up with something that worked without using `eval()`
Comment: @RiggsFolly Yeah. That's why I tried to put a big warning around its use and left it as a comment rather than an answer.
Answer: I don't understand your question
If you get var try this:
echo $array[1][1][test];

"more dynamically":
$i = 1;
$x = 'test';

echo $array[$i][$i][$x];

Comment: OP is asking for solution using variable-variables.
Answer: PHP manual doesn't cover use of variable-variable array indexes too thoroughly, but comments do mention that they don't work just as you have found out.
Some workarounds are provided, though:
$array[1][1]['test']="hello world"

$var1="array";
$var2="[1][1]";
$var3="['test']";

$tmp=$var1.$var2.$var3;

eval('echo $'.$tmp.';');

Above results in expected 'hello world' output. That said, I'd steer away from using eval() in any code.
Comment (by nick at customdesigns dot ca, dated 2006) on the manual page also provides function that can handle variable arrays with indexes, though.
Comment: Please read the [**CAUTION** on the manual page](http://php.net/manual/en/function.eval.php) before even thinking about using it.
Comment: Nice link to nicks comments. Much better idea than `eval()`

Variable variable for array


is_flagged with Views

Question: Is it possible to to check is_flagged in views ?
If I send POST request to this URL it works fine http://website/rest/flag/is_flagged but I want do it in Views ?
I am creating REST API using Services Module and what I am trying to check is that whether a Node is flagged by current user or not. /rest/flag/is_flagged this URL works fine but I want to do it in Views.
If its possible please tell me how I can do it ?
Answer: You could Create a Custom Service Resource for this, but IMO it's easier to do this:

Enable the Views JSON module (which is a sub module of the Views datasource module). This will allow you to get JSON output from a View.
Build a JSON data document page display for a View
Add a contextual filter for a node id, this value will be grabbed from the URL path
Add a contextual filter for a user id, this value could be grabbed from the URL path, or default to the current logged in user, that's up to you
Add a relationship to the flag in the View
Add your desired field output and watch the results preview to see your JSON assembled
Add the necessary filter(s) to limit the results to a certain user/flag/etc.

You then can consume this "resource" by doing a GET on the page path to your View.
Answer: I managed to do it, here are the steps I followed :
1) Add a Relation Add Relation : Flags: Content flag
2) While adding above relation Uncheck Include only flagged content
3) If you have more then one Flag created, select one for which you want to check.
4) Under "By" select Current User
5) Then Add a Field Flags: Flagged
6) While adding field select Relationship which you created above in point 1

is_flagged with Views