O que é payload?

Question: Sempre tenho visto em alguns frameworks que trabalham com REST ou com envio de dados em formato  JSON numa requisição o uso da expressão payload.

O que significa esse nome em requisições HTTP?
O que é especificamente um payload? É um corpo de uma requisição em formato JSON?

Um exemplo do termo sendo usado pelo Google Chrome:
Exemplo 1:

Exemplo 2:
Comment: @WallaceMaxters Esta resposta no SOEN linka a RFC ainda não aprovada. A especificação corrente é esta: https://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html.  A nova RFC chama "tudo" de payload, dividindo entre "payload header fieds" e "payload **body**"; o que é bacana porque os campos do cabeçalho também podem conter informação relevante de aplicação e não apenas dados de transporte.
Comment: Payload em termos de hacking é um script que é injetado em um sistema através de alguma falha e depois é executado como uma espécie de administração remota. Só que acho que o termo que você procura é em outro contexto.
Comment: O nome formal e mais utilizado no contexto HTTP não é payload mas sim ***"body"***, em português *"corpo"*. "Payload" por sua vez é bastante utilizado em message queueing.
Comment: @Caffé não sei se é bem isso não, hein. Veja essa pergunta no [SOEN](http://stackoverflow.com/questions/23118249/whats-the-difference-between-request-payload-vs-form-data-as-seen-in-chrome)
Comment: Sobre a segunda pergunta: sim, em HTTP o payload body **pode ser** um JSON, o que é bastante comum nas APIs REST atualmente. Mas também pode ser um XML, um dicionário chave-valor dos campos de um formulário HTML, o próprio HTML de uma página, ou qualquer outra coisa. Veja que o "payload header fields", por sua vez, embora também chamado de "payload"  na futura RFC, não pode conter JSON, ou não deveria sob pena de causar uma bela bagunça no header e fugir do padrão e da proposta do header.
Answer: Seria o dado que realmente interessa sem metadados, sem o cabeçalho de transmissão ou outras informações acessórias usadas apenas como infraestrutura para transmitir o que importa. Então ele é o corpo da informação, é o que é útil de tudo o que está sendo transmitido.
A tradução literal "carga que paga" poderia ser chamada de "conteúdo que vale a pena".
O significado pode ser diferente em outros contextos, mesmo da computação.
Exemplo de pacote TCP (não achei um bom de HTTP, mas a ideia é parecida). O Data (verdinho) é o payload:

Em outra pergunta tem um diagrama mostrando as várias camadas de comunicação e todas possuem cabeçalhos que vão sendo adicionados em cada camada e a parte de "dados", que é o tal do payload. Se o payload for muito pequeno o overhead dos cabeçalhos de todas camadas se torna um fardo. Você pode ter algum controle sobre o tamanho do payload em camada alta, mas nas mais baixas o controle vai ficando menor, payloads muito grandes tendem ser fatiados antes de serem transmitidos.
O payload não tem formato de texto ou binário. O fato de ser JSON é apenas circunstancial. Em HTTP ele até é um texto por imposição do protocolo, mas pode ser o HTML, CSS, JS, texto bruto, binário codificado em base64, etc.
Coloquei no GitHub para referência futura.
Comment: Exemplo de mensagem HTTP: https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/images/HTTP_RequestMessageExample.png (sem mais observações à resposta pra não te chatear hehehe).
Answer: Em termos gerais, o payload ("carga", em português) é o conteúdo enviado por um meio de transporte, ou carrier. Alguns exemplos:

O conteúdo HTML é o payload enviado via protocolo HTTP;
O conteúdo JSON é o payload enviado via protocolo HTTP a partir do endpoint REST*;
O conteúdo XML é o payload enviado via protocolo HTTP a partir do endpoint SOAP*.

Em algumas terminologias o carrier é também chamado de envelope.
*Apenas para fins de exemplo. Endpoints REST e SOAP podem gerar payloads em outros formatos.
Comment: Sob o ponto de vista do HTTP, o HTML (ou qualquer outra sequência de bytes transportada) seria o payload. Entretanto, sob o ponto de vista da aplicação como um todo, a estrutura do HTML, do JSON e do XML seriam carriers, enquanto que a carga transportada seriam os dados que estão representados e estruturados neste HTML, JSON ou XML.
Comment: @VictorStafusa sim, exatamente - é uma questão do ponto de vista da camada consumidora.
Answer: Payload em termos de protocolo é nada mais nada menos que seu conteúdo. Por exemplo o Payload de um protocolo IP pode ser o TCP. Ou seja, a grosso modo é aquilo que representa o dado a ser transportado pelo protocolo. Acontece o mesmo com o HTTP e o Json. E o payload apresentado dentro deste contexto é o que vai ser transportado no Json da request.
Answer: Payload no contexto da tua pergunta é exatamente como OnoSendai respondeu, o que significa todo o JSON mostrado do teu exemplo.
Sempre vai do contexto da pergunta. Eu costumo entender como payload a carga extra que precisa ser trafegada quando existe um controle de autenticação e autorização por token, como por exemplo em JWT, neste caso além do registro trafegado você precisa trafegar o token e a cópia fiel do dado depois novamente para fazer um POST por exemplo, sendo assim uma "carga extra", payload, para trafegar a carga você é obrigado a trafegar também o token e sua dependência, pagar uma carga, por isso também é chamado PAYLOAD. Confuso? Mas no final das contas no teu contexto o payload é tudo o que vem no JSON mostrado, os dados e o token se houver.
Comment: Você definiu muito bem o que não é um payload.

O que é payload?


Restriction of a Lie group automorphism to the subgroup associated to an invariant Lie subalgebra

Question: Let $G$ be a Lie group with Lie algebra $\mathfrak{g}$, and let $\sigma \colon G \rightarrow G$ be a Lie group automorphism such that $\sigma^2 = \text{id}_G$. Let $\mathfrak{h}$ be a Lie subalgebra of $\mathfrak{g}$ such that $d_e \sigma (\mathfrak{h}) \subseteq \mathfrak{h}$.
Then, we know from general Lie theory that there exists a unique connected immersed Lie subgroup of $G$, $\iota \colon H \rightarrow G$, with $Lie(H) = \mathfrak{h}$.
Question: Does it follow that we get a restriction of $\sigma$ to $H$? More specifically, is it true that there exists a Lie group automorphism $\sigma' \colon H \rightarrow H$ such that $\sigma \circ \iota = \iota \circ \sigma'$?
My attempt: We have the restriction of $d_e \sigma$ to $\mathfrak{h}$, which is a Lie algebra homomorphism $\mathfrak{h} \rightarrow \mathfrak{h}$. I would like to lift this to a Lie group homomorphism $H \rightarrow H$, but a priori this result requires $H$ to be simply connected, which I don't have.
Context: I am studying Riemannian symmetric spaces, and this comes up when you try to prove that a totally geodesic submanifold of a Riemannian symmetric space naturally defines a Riemannian symmetric pair. (See Helgason, Remark after Theorem 7.2, page 224).
Comment: Note that $H$ is connected, and then you can use the fact that any element of $H$ is a product of exponentials to lift from the lie algebra
Answer: Hint: It is easy to see that it suffices to show that $\sigma(H)\subset H$ (and then defined $\sigma'=\sigma|_H$). Now show first that for $X\in\mathfrak h$ you get $\sigma(\exp(X))\in H$ and then use that $H$ is connected.
Comment: That's exactly what I was missing. Thank you!


Coda, segno; How to repeat chorus 3 times?

Question: I have a song in this form:
bar 1 = a
bar 2 = b
bar 3 = chorus
bar 4 = d
bar 5 = e
bar 6 = chorus
bar 7 = g
bar 8 = h
bar 9 = chorus
Do I need rewrite "chorus" every time? Or can I use some repetition effect like:
bar 1 = a
bar 2 = b
bar 3 = chorus **
bar 4 = d
bar 5 = e **
bar 6 = g
bar 7 = h **
??
Which one is musically correct?
I tried "Dal Segno Al Coda"-> "Segno" (chorus)-> "to coda" -> "Coda"
This works perfectly for the first repetition, but I can't use it for the second. (I'm using Guitar pro 5, but that shouldn't matter.)
Comment: Since it's a computer program, can't you just copy / paste the material?
Comment: @jjmusicnotes yes, I can..but my goal is to register the music, so I don't know if it is okay to copy and paste, or is there a better way (correct way)
Comment: Related question: [Is there a definitive notation for multiple repeats?](https://music.stackexchange.com/a/116391/70803).
Answer: By what you explain, it sounds like you want to repeat a section 3 times.
You don't need to use a Coda and Segno because a closing repet can be used more than twice as seen in the Guitar Pro manual:

Repeat close
This symbol replaces a closing bar-line, and sends you
  back to the last Repeat open sign. A dialog window will open up for
  you to indicate the number of repeats you want.
Answer: If you really need the playback to be like you ask, you could use repetition and alternate endings.

It will work "playback-wise" but I doubt this is a proper use of that in music notation.
But I think this does what you want :
Comment: Thank you for your solution! I could not to use it though, because there are some others repetitions between chorus and verses (the song has actually 50 bars). Playback is not important. I have decided to rewrite! But it was interesting.. thank you!
Comment: If the structure can be clearly notated using repeats and 1x, 2x etc ending brackets, don't be afraid to use them.  And "to coda 3rd x" is perfectly acceptable.
If in danger of getting unclear and complicated, write it all out.
Answer: D.S. al Coda is on the right track. Here is my recommendation:

OR

The chorus would be written separately from the rest of the tune — in the way a coda can be — with three endings: one returning to "d", one returning to "g", and one ending the song. The endings could be done using voltas or, since each chorus is identical, just with written instructions. Also, al fine could be added to the final "To C" for additional clarity for the reader. In the body of the song, just include a "to chorus" indication at the appropriate locations.
Answer: Write "3 verses" or "Play 3 times" over the repeated section.  At the To Coda sign write "To Coda after 3rd verse".   That's understandable for a live player.
If you want playback from your computer program you may have to be more ingenious.  How far is the To Coda jump from the End Repeat barline?  Is a 1,2 ending bracket and a 3 ending one feasible?
If ONLY playback matters, just write the whole thing out!
Answer: Here is an image with a solution:

This solution will play
a, b then Chorus followed by 1st ending with d and e,
then repeat Chorus followed by the 2nd ending with g and h,
then repeat the Chorus and end.
But apart from that I will say that is rather simple to actually write the whole thing out instead, rewriting the Chorus, because it is easy to rewrite it with copy and paste and it is easier to read for the musician without all this going back and fourth.


JasperReports with multiple detail bands

Question: I am a beginner with JasperReports and wanted to have example of how to create a solution for the following problem.
I have details, and for each row in detail there are again details for that particular row. Can we implement this using JasperReports? I have tried creating sample reports using iReport for single detail band and that works fine, but don't know how to create a detail band which will have details for each row in existing detail band.
Rahul
Answer: Use a sub-report. Each row in the main report will contain a sub-report, which will itself have its own detail band.
You should find an example using a sub-report in the JasperReports distribution.
Comment: Niznet, I am searching for example, but if you know any particular link it will be really helpful. Also, I was quite confused about how to pass combined JRBeanCollectionDataSource for same.
Comment: As I said, if you download JasperReports, you'll find examples in the distribution.


Does long term storage pricing apply to data from GA daily export?

Question: I'm wondering if anyone knows whether the long-term-storage pricing (https://cloud.google.com/bigquery/pricing#long-term-storage) applies to GA daily export (https://support.google.com/analytics/answer/3437719?hl=en) data in BigQuery?
Since these tables cannot be modified, does it mean there will always be a discount 90 days after a daily GA table is available in BigQuery?
Comment: looks like you answered your question! Yes. there will be long term storage pricing applied after 90 days :o) What other scenario you see?
Answer: As Mikhail said in a comment, the answer is yes: The long term storage discount will be applied on the GA tables, as in any other unchanged table you store in BigQuery for more than 90 days (https://cloud.google.com/bigquery/pricing#long-term-storage).


Golang, mgo update details for a user

Question: I have been having some trouble updating a user on a mongodatabase. Basically I want to select the user by username and than edit its details. I am using Gorilla Mux and mgo to connect with MongoDB.
Here is the code:
func ViewUserHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    username := vars["username"]
    session, err := mgo.Dial("mongodb://DATABASE_URL")

    if err != nil {
        panic(err)
    }

    defer session.Close()
    session.SetMode(mgo.Monotonic, true)
    c := session.DB("studnet").C("user")

    result := Person{}
    // get the user_id using a hidden field when clicked using javascript
    err = c.Find(bson.M{"name": username}).One(&result)
    if err != nil {
        log.Fatal(err)
    }

    if r.Method == "GET" {
        t, _ := template.ParseFiles("profile.html")
        t.Execute(w, result)
    }
    // update the user profile details
    if r.Method == "POST" {
        r.ParseForm()

        // TODO : update the user
        selectedUser := bson.M{"name": username}
        updatedUser := bson.M{"$set": bson.M{
            "Name":      r.Form["username"][0],
            "Gender":    r.Form["gender"][0],
            "Age":       r.Form["age"][0],
            "CreatedAt": time.Now(),
        }}
        err = c.Update(selectedUser, updatedUser)

        if err != nil {
            panic(err)
        }
        http.Redirect(w, r, "/view/"+username, 301)
    }
}

Comment: What was the **question** again?
Comment: Ok, can you explain the problems with your code? You might want to read [How do I ask a good question](http://stackoverflow.com/help/how-to-ask), which enhances the probability for getting a useful answer _drastically_. You might find [ESR](https://en.m.wikipedia.org/wiki/Eric_S._Raymond)'s excellent essay [How To Ask Questions The Smart Way](http://catb.org/~esr/faqs/smart-questions.html) helpful, too.
Comment: You may not be, but that's not an excuse to clearly document your issue. What's happening on your side? We don't see what you're seeing, and we certainly don't want to spend a half an hour debugging a program just because you refuse to provide an acceptable explanation. Please remember that we are helping you for free, and you are expected to be nice and cooperative with everyone. Thanks!
Comment: What happens with your code? Do you get any errors?
Comment: How can I query a user by username in mgo and than update its details ? Basically i dont know how to use Update function in mgo... Thanks for your time.
Comment: I am sorry, I was wondering are you familiar with golang ? Basically you can just copy paste the code and run it yourself . The question is self explanatory. I am not a writer !!!
Answer: Well I see at least one problem a that is the case sensitive queries. So if your struct uses lowercase keys in json, you must use a lowercase one.
// This shoud match
// against the "Name" property
selectedUser := bson.M{"Name": username}

updatedUser := bson.M{"$set": bson.M{
                "Name":      r.Form["username"][0],
                "Gender":    r.Form["gender"][0],
                "Age":       r.Form["age"][0],
                "CreatedAt": time.Now(),
 }}

Answer: data := model.Data {
            Name:      r.Form["username"][0],
            Gender:    r.Form["gender"][0],
            Age:       r.Form["age"][0],
            CreatedAt:  time.Now(),
        }

selectedUser := bson.M{"name": username}
updatedUser := bson.M{"$push": bson.M{"user": bson.M{"$each": []model.User{data}}}}
err = c.Update(selectedUser, updatedUser)

This will update the user array against matching username. It would be great if you can share the struct too. I have answered with the assumptions.

Golang, mgo update details for a user


Which topic(s) does this matrix come from? What is the name of this matrix?

Question: Which topic(s) does this matrix come from? What is the name of this matrix?
$$\pmatrix{1&1&1\\1&\omega&\omega^2\\1&\omega^2&\omega}$$
Comment: That's a Vandermonde matrix, as well as the matrix of the discrete Fourier transform of size $3$... It is not quite clear what the purpose of this question is, though!
Comment: We are assuming that $\omega$ here is a root of unity, of course (too bad OP did not define his/her notation)... if not, then it's just some symmetric matrix.
Answer: This is the discrete Fourier transform matrix of size $3$. It naturally appears mathematically in the representation theory (don't be intimidated by this!) of the cyclic groups $\mathbb{Z}/n\mathbb{Z}$, as well as practically in signal processing and related fields.


Unit Test case fails when whole Test Suite is executed

Question: I am writing the Unit test cases for my sqlite database class. I have five public API in that class.
My test cases goes something like below:
+ (void)setUp {  // Note, this is class method and hence called only once during start of this test suite.
    // Code to delete the existing sqlite DB file.
}

- (void)testDBManagerSingletonInstance {
    DBManager *dbMgr = [DBManager getSharedInstance];
    DBManager *dbMgr1 = [[DBManager alloc] init];
    XCTAssertEqualObjects(dbMgr, dbMgr1);
}

- (void)testSaveAndDeleteNicknameAPI {
    // Multiple Assert statements in this test.
}

- (void)testAllAccountStatusAPIs {
    // Multiple Assert statements in this test.
}

Each of the single unit test is executed without any errors. But it fails when whole test suite is executed.
Probably, I know the Root Cause for failing. It is because when entire test suite is executed then all test runs in parallel and there is simultaneous update-delete happens in the database. Hence, when all unit tests runs it will fail.
But I don't know how can I fix that, because this is not Async, and hence I cannot use XCExpectation class.
Need assistance to resolve & understand the problem.
Comment: You have already stated the answer..If tests are all using the same database then it's contents are all in a state of flux as you say... the solution is to have each unit test look at separate databases or separate instances or separate tables..... or force sequential execution. The rule when testing is you must know the contents of the database .. in this case you never know because it's being setup and tested by multiple processes simultaneously.
Answer: Tests based on XCTests don't run in parallel - they are run sequentially. To quote the docs :

Tests execute synchronously because each test is invoked independently one after another.

Since you've shown very little code, it's hard to say what is the real problem. It is very likely that you were close with your assumption - you should either improve your setUp (maybe switch to instance version from class version) and tearDown methods or introduce mocks, and perform your tests on a mocked database if possible.
Answer: You shouldn't work with singletons in a codebase you want to test. I think that your code uses the sharedSingleton instance of DBManager internally. Each unitest will change the internal state of that instance, all following unitests are therefore corrupted. You need to reset all changes after each test case in teardown.
But my suggestion is to avoid singletons in your base code by dependency injection. When creating an instance of your class inject the singleton instance of your DBManager. That makes unit testing easier. If you inject a protocol instead of an object you may even test your code with a protocol fake implementation.


Using view result as an input filter for another view

Question: Let me explain my scenario at first.
I have two content types in my site.
First is products and second is producer.
Each product has only one producer and each producer has one or more products.
Now in every product page, I want to show the producer information. I made a view block for this issue and it works well.
but in the product page, I also have a plan to show all products of the producer of current product in another block.
In order to show the product nodes of a specific producer I need the node ID of producer content type.
I tried to use Contextual filters --- Provide default value "When the filter value is NOT available" via Content ID from URL but this function returns node ID of current product not producer id. (because we are in a specific page of single product)
Now I am searching to find a solution for this issue.
thanks a lot for your guidance.
Answer: Say, the term reference field in the product content type is called "field_ref_producer". You need to have this block of code, and a view that accepts a contextual filter for "term reference producer ID" ready.Let this view be called "other_products_producer"
<code>$node = menu_get_object();
$output = '';
if(is_object($node)) {
  $producer_id = $node->field_ref_producer['und'][0]['tid'];
  $output = views_embed_view('other_products_producer', 'default',$producer_id);
}
echo $output;
</code>
Basic idea is, grab the node object from URL, get the producer tid from it and then embed a view passing the producer nid as contextual filter to the view.
Update:
Code to put in views PHP (default value of contextual filter):
<code>$node = menu_get_object();
if(is_object($node)) {
  $producer_id = $node->field_ref_producer['und'][0]['tid'];
  return $producer_id;
}
</code>
Please replace the name of the field to what you have in  your content type.
Comment: Hello

Please tell me should I use your mentioned block code in default value of "contextual filter" as a PHP code?
Comment: I don't normally suggest using PHP code in views. but in this case, I think it will be much easier. I am updating the code that you should put in there.
Comment: Updated the code that you can use. hope that helps.
Comment: Thanks a lot for your solution. It works well but I did a tiny modification on it that in next post I will write it because in comment format is not available for Drupal codes.
Answer: If the entity reference field is in the producer content type, this solution might work:
Add another field in your view - "the entity reference field" (i.e.field_ref_producer if your entity reference field is called field_ref_producer).
Use the relationship : Entity Reference: Referenced Entity
Use the contextual filter Content:nid
Provide default value "When the filter value is NOT available" via Content ID from URL. (This function returns node ID of current product not producer id.) "
When you render the view, you will get a list of the products from the producer.
What this does is, it essentially  (w.r.t. to the above case)
uses the product id to locate the producer id (using the entity reference field)  and then display the products ( i.e. all referenced entities) associated with the producer id.
Answer: Here is modified codes from Neo.
<code>$node = menu_get_object();
if(is_object($node)) {
    if(isset($node->field_producer['und'][0]['nid']))
    {
      $producer_id = $node->field_producer['und'][0]['nid'];
      return $producer_id;
    }
}
</code>
I added isset function for the nodes that don't have specific referenced field producer. (for example in pages or articles)
Thanks a lot Neo for you help.


How can I tell I'm using an XP server vs. an XP workstation?

Question: This should be obvious, but I can't seem to locate or think of anything that would indicate clearly whether I'm using an XP server or a workstation.
Thanks for the help.
Mark
Comment: Do you mean XP Professional vs. XP Home? (or Media Center, or Tablet, etc..)
Comment: This question is a result of trying to install XP disk mirroring. In some of the instructions, some people were saying that it's not possible on XP workstation edition. Maybe I just read it wrong.
Answer: XP is not a server OS.  It mainly comes in Workstation, Home, and Media Center versions.
MSKB on determining XP version:
http://support.microsoft.com/default.aspx?scid=kb;en-us;310104
Comment: This gives you some really interesting information about the version. I don't think I've ever seen or needed such detail info. I wonder when I would need it, if ever.
Answer: Easy way to tell:
Press the Windows Button Key and at the same time press PAUSE (or Break)
A box will appear, with all sorts of useful information and at the top, what version of XP you are using, its Service Pack level and a few bits of Hardware information.
This works on most MS products (there are lots of short cuts like that)
Answer: Right-click on 'My Computer' and click Properties, it will tell  you right at the top the version you are running.
Answer: There's no such thing as Windows XP server, so it's doubtful you're using that. The server equivalent of XP is Server 2003
If in doubt, bring up the start menu, that will tell you what you're running
I don't have an XP machine to get an example at the moment, but if you hit the start menu, select run and enter `winver' that application will also tell you what it is that you're running
There appears to be a semi-useful list of versions of Windows on Wikipedia
Answer: Just press Ctrl-Alt-Del, it tells you the Windows version there:
Answer: I suppose someone could be using an XP machine as a web server or a file server or even a print server.  Look at what processes are running.  Do you see any server-ish processes such as Apache?  What ports are open?  Is file and print sharing enabled?
Also, look at user accounts and shares.  Browse around on the machine a bit.  There should be some obvious tipoffs.
Comment: You're over-thinking my question. :-)
Comment: I must STILL be overthinking it...I read the question and the answers and think I have missed something....but it looks like you found your answer...


L'hopitals rule applied on probability density functions

Question: I'm going through a set of solutions for the following question
Let $Z_1,Z_2,\ldots$ be IID random variables with density $f$. Suppose that $P(Z_i>0)=1$ and that $\lambda = \mathrm{lim}_{x \rightarrow 0} f(x)>0$. Let $X_n = n \mathrm{min}\{Z_1,\ldots,Z_n\}$. Show that $X_n$ converges in distribution to $Z$ where $Z$ has an exponential distribution with mean $\frac{1}{\lambda}$.
I understand the solution up until it claims using L'Hopital's rule that $1-e^{\mathrm{log}(1-F(x/n))/\frac{1}{n}} \rightarrow 1-e^{-x\lambda}$. How can i prove this intermediate step with L'Hopitals rule?
Answer: It's easy to know that L'Hospital's rule can be applied. And then
\begin{align*}
\lim_{n\to\infty}\frac{\log(1-F(x/n))}{1/n}=\lim_{n\to\infty} \frac{f(x/n)\frac x{n^2}}{-\frac1{n^2}(1-F(x/n))}=-x\lim_{n\to\infty}\frac{f(x/n)}{1-F(x/n)}=-x\lambda.
\end{align*}


How to embed and play on same page like popup?

Question: I'm learning web development with Drupal 7.
I can embed youtube video using CKEditor on a node. I like to play embedded video looks like on YIFY and IMDB as popup/overlay. It means when I click on play button it will open as popup on the same page and on click outside the youtube player or whatever, it will stop and display nodes' content.
How this can be possible, JS/JQuery will be used? If yes then how and please suggest me the other ways as well.
Comment: Which ***other*** ways?
Answer: You can easily achieve this functionality by using something like colorbox. This will allow you to open videos in popup. Since you've just started learning drupal, I would recommend that you thoroughly follow documentation for this module.
Another alternative is using modules video_embed_field along with colorbox. This will allow you to use colorbox as field formatter.


Proof an equivalence of variance

Question: Given a sample of size N, how can you prove this?
$\frac{1}{N}\sum_{k = 1}^{N}(x_{k}-\bar{x})^{2} = \frac{1}{2N^{2}}\sum_{k = 1}^{N}\sum_{l = 1, l \neq k}^{N}(x_{k}-x_{l})^{2}$
So far I have:
$$ \frac{1}{N}\sum_{k = 1}^{N}(x_{k}-\bar{x})^{2} = \frac{1}{N}\sum_{k = 1}^{N}(x_{k}-\frac{1}{N}\sum_{l = 1}^{N}x_{l})^{2} = \frac{1}{N}\sum_{k = 1}^{N}((\frac{N-1}{N})x_{k}-\frac{1}{N}\sum_{l = 1, l \neq k}^{N}x_{l})^{2}$$
Any hint?
Comment: In your first step, you've lost the $1/N$ from the mean
Comment: $$\text{var}(X_1)=\dfrac{1}{2}\text{var}(X_1-X_2)$$
Answer: I think it's easiest to start with the U-statistic form
First, put back the $k=l$ terms
$$\frac{1}{2N^2}\sum_{k\neq l} (x_k-x_l)^2 = \frac{1}{2N^2}\sum_{k,l=1}^N (x_k-x_l)^2$$
Now, introduce $\bar x$
$$ \frac{1}{2N^2}\sum_{k,l=1}^N (x_k-x_l)^2= \frac{1}{2N^2}\sum_{k,l=1}^N (x_k-\bar x+\bar x- x_l)^2$$
giving
$$ \frac{1}{2N^2}\sum_{k,l=1}^N (x_k-\bar x)^2+(\bar x-x_l)^2-2(x_k-\bar x)(\bar x-x_l)$$
The first two terms are what we want, so we just need to show the last term vanishes.
The last term is
$$\sum_{k,l} (x_k-\bar x)(\bar x-x_l)=\sum_k \left((x_k-\bar x)\sum_l (\bar x-x_l)\right)$$
The inner sum doesn't depend on $k$ and is identically zero, so the whole thing is zero.

Proof an equivalence of variance


sftp only account: access via putty/winscp not working

Question: I set up a sftp only account some months ago.
I took roughly this guide: https://wiki.archlinux.org/index.php/SFTP_chroot
Access from linux is possible.
Now someone wants to access the sftp account via WinScP.
I did it according to these docs: https://winscp.net/eng/docs/guide_public_key
I created a public/private key pair via WinSCP and created the public key for the authorized_keys file with this command:
puttygen -O public-openssh -o foo.pub foo.ppk

I added the line of foo.pub to ~modsftp/.ssh/authorized_keys like usual.
Passwordless access from linux works, but not via putty/winscp:
===> psftp -i foo.ppk modsftp@remote-host
Using username "modsftp".
Server refused our key
Using keyboard-interactive authentication.
Password:

On the ssh server I just see this line:
sshd[26281]: Connection closed by 10.111.44.33 [preauth]

I am clueless why it works via openssh commandline tools, but not via putty/winscp.
Comment: Dear down-voters: Please tell me what's wrong with this question.  Thank you.
Answer: Problem solved: PEBCAK (problem exists between chair and keyboard).
Access via openssh tools worked, because the used my ssh-agent and not the -i foo command line argument :-)
Adding the public-key to ~modsftp/.ssh/authorized_keys was useless in this case.
If I did disable the ssh-agent like this (setting SSH_AUTH_SOCK to an empty string), it did not work for openssh tools, too:
SSH_AUTH_SOCK= sftp -i foo modsftp@remote-host

I turned on LogLevel DEBUG in sshd_config and saw the issue in the log file:
sshd[30819]: debug1: matching key found: file /etc/ssh/authorized_keys/modsftp, line 1

BINGO: sftp-only setup is different than normal ssh accounts. The authorized_keys are stored in a different file.
Issue solved. I hope this question+answer will help other people with similar issues.


Taking lists as input till enter is pressed

Question: I am having an integer N.and next N lines contain lists that can have distinct elements from 1-100.But i am not provided length of each list.How to handle this type of input.
If say i have vector > mylist;
I need to populate this list with those lists seperated by just next line.
Say if N=3
1 2 3
4
5 6

Then mylist[0]=[1,2,3] , mylist[1]=[4] , mylist[2]=[5,6].
How to do it in c++?
Mycode : Not correct but i tried.
int main(){
int t;
cin>>t;
cin.ignore();
while(t--){
    int n;
    cin>>n;
    cin.ignore();
    lists_t lists;
    std::string record;
    while ( std::getline( std::cin, record ) &&
        record.find_first_not_of( ' ' ) != std::string::npos && lists.size()!=n)
    {
        std::istringstream is( record );

        lists.push_back( std::vector<int>( std::istream_iterator<int>( is ),
                     std::istream_iterator<int>() ) );
    }

    for ( const auto &l : lists )
    {
        for ( int x : l ) std::cout << x << ' ';
        std::cout << std::endl;
    }
   }
 }

The problem is that if i enter t=1 and n=3 then instead of following n lines it takes 4 lines and then display the data.Why ?
Comment: @user3903285 If you look at the timings, your edit was a bit too late.
Comment: Guess having a stab at writing C++ code is a good starting point
Comment: So what you need is a `list` of `list` s? http://en.cppreference.com/w/cpp/container/list
Comment: @EdHeal I added code also.Even then its on hold.Can I ask reason?
Comment: @πάνταῥεῖ I added code also Even then on hold.Why?
Comment: @user3903285 - As you have added some code I have asked it to be reopened to give it another bite of the apple
Comment: Still not good enough. You should explain what exactly is wrong with your current code, and `not correct` is not really an explanation
Comment: @defaultlocale I mentioned my problem now
Answer: You can use standard function std::getline ans string stream std::stringstream and of course the container std::list itself.
Here is an example
#include <iostream>
#include <iterator>
#include <list>
#include <sstream>
#include <string>

int main()
{
    std::list<std::list<int>> lst;
    std::string record;

    while ( std::getline( std::cin, record ) &&
            record.find_first_not_of( ' ' ) != std::string::npos )
    {
        std::istringstream is( record );

        lst.push_back( std::list<int>( std::istream_iterator<int>( is ),
                         std::istream_iterator<int>() ) );
    }

    for ( const auto &l : lst )
    {
        for ( int x : l ) std::cout << x << ' ';
        std::cout << std::endl;
    }

    return 0;
}

The output is
1 2 3
4
5 6

if the input was the same lines.
If you need to enter a given number of lines then the code could look the following way
#include <iostream>
#include <iterator>
#include <list>
#include <sstream>
#include <string>

int main()
{
    std::list<std::list<int>> lst;
    std::string record;

    size_t n;

    std::cin >> n;
    std::cin.ignore();

    while ( n-- &&
            std::getline( std::cin, record ) &&
            record.find_first_not_of( ' ' ) != std::string::npos )
    {
        std::istringstream is( record );

        lst.push_back( std::list<int>( std::istream_iterator<int>( is ),
                         std::istream_iterator<int>() ) );
    }

    for ( const auto &l : lst )
    {
        for ( int x : l ) std::cout << x << ' ';
        std::cout << std::endl;
    }

    return 0;
}

The input could look as
3
1 2 3
4
5 6

Comment: I'd recommend `std::vector` over `std::list`
Comment: @VladfromMoscow As soon as i enter n the code terminates.Is their no role of n here?
Comment: @user3903285 I have not understood what you are speaking about and what is the n. I showed you code that works.
Comment: @Vlad from Moscow Could you please see my post once again
Comment: @user3903285  Why do you enter t and n? What is their meanung? The input will stop as soon as there will not be any more line with data. As for your code then after cin >> t and cin >> n you have to insert cin.ignore();;
Comment: @VladfromMoscow I needto enter N lists t times.So input format is firstline has only t then next line has n then next n lines are showing n lists.which are done t times
Comment: @VladfromMoscow Why it keep on taking input?I want it to be n times only


About hypotenuse of pythagorean triple

Question: The hypotenuse of any Pythagorean triple seems not to be divided by some primes such as $3, 7$. What are the others? Are there infinitely many such primes?
In other words, I am looking for number $c$ such that
$a^2 + b^2 = kc$  have no integer solutions for any positive integer $k$ and $a,b < c$.
Comment: Yes, these are the primes of the form $4n+3$ and there are infinitely many of them.
Comment: There are an infinite number of solutions of pythagorean triples. Sir Wiles proved that for the equation $ x^{n} + y^{n} = z^{n} $ has no solutions for n larger than two.
Answer: Suppose $a$ and $b$ are integers. I that case euclid formulas hold:
$$
\begin{align}
a &= m^2-n^2 \\
b &= 2mn \\
c &= m^2+n^2
\end{align}
$$
where $m,n$ are positive integers.
Now use the following Fermat theorem (have a look at Arturo's answer):

Theorem (Fermat) Let $n$ be a positive integer, and write $n$ in the form $$n = 2^{\alpha}\prod_{p\equiv 1\pmod{4}} p^{\beta} \prod_{q\equiv 3 \pmod{4}} q^{\gamma}.$$
  with $p$ and $q$ primes. Then $n$ can be expressed as a sum of two squares if and only if all the exponents $\gamma$ are even.

Since you are looking for only primes then it becomes $n = p$ such that $p \equiv 3 \pmod 4$.
Look for primes that can be written as $n = 4k + 3$ with $n$ integer.

About hypotenuse of pythagorean triple


Linear Algebra Transition Matrix calculation help

Question: I have an assignment question that I am having some hard time working out and would appreciate any help understanding and solving this please. Here is the question

Let $L:\mathbb{R}^3\to\mathbb{R}^3$ be given by $$(x; y; z)^T \mapsto (x - y; y - z; z - x)^T$$ Find the matrix $A$ of $L$ with respect to the basis:
  $$(-1; 0; 1)^T ; (1; 1; 1)^T ; (0; 1; 0)^T$$
  Then find the matrix $B$ of $L$ with respect to the basis:
  $$(0; 0; 1)^T , (0; 1; 1)^T , (1; 1; 1)^T$$
  Finally, find a matrix $P$ so that $$B = P^{-1}AP$$
Comment: Oops, sorry, I didn't see you edited it already. :)
Answer: To find the matrix $A$ of $L$ with respect to the basis $\beta=[(-1,0,1)^T, (1,1,1)^T, (0,1,0)^T]$, first write down the image of each basis vector under the linear transformation, and express it as a linear combination of the elements of $\beta$. The coefficients form the columns of $A$.
For example, evaluating $L$ at the second basis vector gives
$$L\left(\begin{array}{c}1\\1\\1\end{array}\right) = \left(\begin{array}{c}1-1\\1-1\\1-1\end{array}\right) = \left(\begin{array}{c}0\\0\\0\end{array}\right) = 0\left(\begin{array}{r}-1\\0\\1\end{array}\right) + 0\left(\begin{array}{c}1\\1\\1\end{array}\right) + 0\left(\begin{array}{c}0\\1\\0\end{array}\right).$$
This tells you that the second column of $A$ is all $0$s.
Similarly, to find $B$, evaluate $L$ at each of the basis vectors of $\gamma=[(0,0,1)^T, (0,1,1)^T, (1,1,1)^T]$, and express the value in terms of the vectors of $\gamma$. This gives you the columns of $B$.
Finally, to find $P$, you need a matrix that "translates" from $\gamma$-coordinates to $\beta$-coordinates. So $P$ should be the matrix that tells you how to write each of the vectors in $\gamma$ in terms of the vectors in $\beta$. Express each vector in $\gamma$ as a linear combination of vectors in $\beta$, and use these expressions to give you the columns of $P$.


Question about differentiation under integral sign

Question: In Folland's book Real Analysis, he proves the following theorem (Theorem 2.27) concerning differentiation under integral sign.

Suppose $f:X \times [a,b] \to C$ is a complex valued function such that $f(\cdot,t)$ is integrable for each  $t \in [a,b]$. Let $F(t)=\int_X f(x,t) d\mu(x)$. Then, if $\partial t f$ is dominated by an integrable function, we can differentiate $F(t)$ under the integral sign.

He then goes on to saying that if the parameter $t$ varies over a non-compact interval, we can still apply this theorem to any compact subinterval. But, my question is why is the theorem stated for compact interval $[a,b]$ in the first place? I do not see where/how the compactness of the interval is used in the proof
Answer: Since differentiability is only a local property, you can replace $[a,b]$ by any open set, or $\mathbb{R}$. However, the key-point is that $\partial_t f$ must be dominated by an integrable function independent of $t$. In this formulation the interval $[a,b]$ indicates that this property only need to be satisfied locally.
If you replace $[a,b]$ by $\mathbb{R}$, this restriction is too strong: It is enough that for any open neighborhoud of any point $t$ there exists a uniformly integrable majorant.
Answer: I had the same question about that theorem. After some thought, and after reading the accepted answer, here is my interpretation: Loosely speaking, $F$ is differentiable at some $t_0 \in \mathbb{R}$ so long as we can find an interval $I$ containing $t_0$ and an integrable function $g: I \to \mathbb{C}$ which satisfies $|\partial f/\partial t(x,t)| \leq g(x)$ for all $(x,t) \in X \times I$. To be precise:

Theorem. Let $(X,\mathcal{M},\mu)$ be measure space, let $A$ be an arbitrary subset of $\mathbb{R}$, and let $f: X \times A \to \mathbb{C}$ be a function. Suppose that $f(\cdot,t): X \to \mathbb{C}$ is integrable for every $t \in A$. Define $F: A \to \mathbb{C}$ by $F(t) := \int_X f(x,t) \,d\mu(x).$ Let $t_0 \in A$ be fixed, and suppose there exists an interval $I \subset A$ containing $t_0$ such that:

$\frac{\partial f}{\partial t}(x,t)$ exists for all $(x,t) \in X \times I$, and
there is an integrable function $g:I \to \mathbb{C}$ such that $\left|\frac{\partial f}{\partial t}(x,t) \right| \leq |g(x)|$ for all $(x,t) \in X \times I$.

Then $F$ is differentiable at $t_0$ and
\begin{align*}
      F'(t_0) = \int_X \frac{\partial f}{\partial t}(x,t_0) \,d\mu(x).
\end{align*}

We then immediately get the following corollary.

Corollary. Let $(X,\mathcal{M},\mu)$ be measure space, let $A$ be an arbitrary subset of $\mathbb{R}$, and let $f: X \times A \to \mathbb{C}$ be a function. Suppose that $f(\cdot,t): X \to \mathbb{C}$ is integrable for every $t \in A$. Define $F: A \to \mathbb{C}$ by $F(t) := \int_X f(x,t) \,d\mu(x).$ Suppose also that:

$\frac{\partial f}{\partial t}(x,t)$ exists for all $(x,t) \in X \times A$, and
there is an integrable function $g:A \to \mathbb{C}$ such that $\left|\frac{\partial f}{\partial t}(x,t) \right| \leq |g(x)|$ for all $(x,t) \in X \times A$.

Then $F$ is differentiable and
$$ F'(t) = \int_X \frac{\partial f}{\partial t}(x,t) \,d\mu(x) \quad \text{for all } t \in A. $$

Taking $A = [a,b] \; (-\infty < a < b < \infty)$ in the corollary gives the exact statement of Theorem 2.27 in Folland.


what is the solution of this limit. I am having a little bit trouble

Question: $F(x)$ is $x\cdot \tan{1\over x}$ ?What is the value of limit of $F(x)$ where $x$ tends to $0$.  Can I also do it using squeeze theorem here? If yes how ? If not why?
Answer: You have equivalently to consider $\lim_{x\to \pm \infty}\tan(x)/x$. It does not exist, indeed on the one hand
$$
\lim_{k\to \infty}\frac{\tan (2k\pi)}{2k\pi}=0,
$$
and on the other hand, for each positive integer $k$, it holds
$$
\lim_{\varepsilon \to 0^+}\frac{\tan(2k+\frac{1}{2}-\varepsilon)\pi}{(2k+\frac{1}{2}-\varepsilon)\pi}=\infty.
$$
Comment: why my considerations are wrong
Comment: @ShubhankarMondal You do not show any real considerations. (Just accept that the limit does not exist.)
Comment: Usually you use squeeze theorem to prove that a limit actually exists, and this is not the case
Comment: you mean to say that my function is not real at x tends to 0
Comment: I would just say that "$f$ is undefined at $0$"


How to use rasterio to store raster data with coordinate system information?

Question: I use the following code to save the modified raster data. The original data has a complete coordinate system, but the coordinate system information cannot be saved to the new raster data when saving. How should I modify my code
<code>for i in range(len(file_names)):
   file_name = file_names[i]
   image = process_tif(file_name)
   with rasterio.open(file_name) as src:
      meta = src.meta.copy()
   with rasterio.open("new_file_name.tif", 'w', **meta) as dst:
      dst.write(image.transpose((2,0,1)))
</code>
I want the saved raster data to have the same coordinate system information as the original image
Answer: If you are ok with using GDAL instead of rasterio, this is how I project my .tif files. Here we assume a 3 band array, but this supports the 4th if you have RGBA
<code># Open with tif
ds = gdal.Open(tif_file)
# Projecting
arr = np.array(image)
[rows, cols, channels] = arr.shape
driver = gdal.GetDriverByName('GTiff')
out_path = 'new_file_name.tif'
outdata = driver.Create(out_path, cols, rows, channels, gdal.GDT_Byte)
outdata.SetGeoTransform(ds.GetGeoTransform())
outdata.SetProjection(ds.GetProjection())
outdata.GetRasterBand(1).WriteArray(arr[:,:,0])
outdata.GetRasterBand(2).WriteArray(arr[:,:,1])
outdata.GetRasterBand(3).WriteArray(arr[:,:,2])
if channels == 4:
    outdata.GetRasterBand(4).WriteArray(arr[:,:,3])
outdata.FlushCache()
outdata = None
ds = None
</code>


Find the smallest value of the product $ab$

Question: From the 2018  Moroccan Mathematics Olympiad:

Let $(a,b) \in \mathbb{Z^2}$ such that $a+b$ is a solution of the equation $x^2+ax+b=0$. Find the smallest value of the product $ab$. ($\mathbb Z$ contains 0)

My Approach:
I've solved it by an extremely bashy method, which I don't think is worth showing. I just used the properties of quadratic equations, and basic divisibility properties. I then got all the possible solutions, and simply calculated the possible products. I found the m
Question :

Can one find the desired minimum without finding all solutions to the given equation?

Edit: Basically what I did, is find the equivalent equation: $(2a+b)^2=-b(b+2a+2)$, Now notice: $gcd(2a+b;b+2a+2)=1$ or $=2$, try all cases and get all solutions.
Edit 2: The solution given in the first edit, isn't the long bashy solution.
Comment: The equation is equivalent to $(b-4)^2=4^2+(4a+3b)^2$. But the only pythagorean triple with a side length of $4$ is $(3,4,5)$, together with the degenerate $(0,4,4)$. Hence $b-4=\pm4$ or $\pm5$.
Comment: Which is the answer you got?
Comment: I'm pretty sure that the only integer solutions are (-6,9), (-6,8), (0,0) (0,-1) but I need to write down a proof.
Comment: Just to be clear, when you say you wish to find the smallest value of $ab$, you don't mean absolute magnitude? That is, $-11$ is considered smaller than $-3$? And the relevant equation is $x=a+b \Rightarrow 2a^2+3ab+b^2+b=0$? That means one of $a,b$ is a negative integer.
Comment: @KeithBackman Yes, $-11$ is considered smaller than $-3$. And yes, the equation is: $2a^2+3ab+b^2+b=0$
Comment: @jjagmath I found -1
Comment: I confirm the equation and for sure a=-6 and b=9 is a solution of that equation thus the minimum can't be 0
Comment: @LucaGoldoniPh.D. Indeed, I somehow messed up the calculations
Answer: Starting from $2a^2+3ab+b^2+b=0$, use the quadratic formula to obtain an expression for $a$:
$$a=\frac{-3b\pm \sqrt{9b^2-8(b^2+b)}}{4}$$
This only has integer solutions when $(b^2-8b)$ is a perfect square. This occurs when $b \in \{-1,0,8,9\}$
Next, an expression for $ab$ can be stated without finding any particular solutions to the original equation
$$ab=\frac{-3b\pm \sqrt{9b^2-8(b^2+b)}}{4}\cdot b$$
Substituting the acceptable values of $b$ into that formula yields $-54$ as its smallest value, without ever identifying any of the values of $a$ or solutions to the original equation.


Deserialize IndexingPolicy(Azure Cosmos DB) from JSON

Question: I'm trying to deserialize from a json IndexingPolicy in order to update the Azure Cosmos DB.
Although IndexingPolicy and all its inner class are subclasses of JsonSerializable, it fails to be deserialized.
Index is one of the inner class of IndexingPolicy and is lack of empty constructor. Therefore, the deserialization fails. However, I find it hard to believe that the developers of the framework haven't tested it properly.
I have tried two ways to deserialize,
    var jsonString = @"{
      'indexingMode': 'consistent',
      'automatic': true,
      'includedPaths': [
        {
          'path': '/PartitionKey/?',
          'indexes': [
            {
              'kind': 'Range',
              'dataType': 'String',
              'precision': -1
            }
          ]
        }
      ],
      'excludedPaths': [
        {
          'path': '/*'
        }
      ]
    }";
    JsonSerializerOptions options = new JsonSerializerOptions()
    {
        IgnoreNullValues = true,
        IgnoreReadOnlyProperties = true,
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        AllowTrailingCommas = false,
        MaxDepth = 1000,
        PropertyNameCaseInsensitive = true
    };
    IndexingPolicy index = System.Text.Json.JsonSerializer.Deserialize<IndexingPolicy>(jsonString, options);

And also by LoadFrom() method,
        IndexingPolicy ip = new IndexingPolicy();
        using (var reader = new JsonTextReader(new StringReader(jsonString)))
        {
            ip.LoadFrom(reader);
        }

To be on the safe side I also tried with this JSON
{
      "indexingMode": 0,
      "automatic": true,
      "includedPaths": [
        {
          "path": "/PartitionKey/?",
          "indexes": [
            {
              "kind": 1,
              "dataType": 1,
              "precision": -1
            }
          ]
        }
      ],
      "excludedPaths": [
        {
          "path": "/*"
        }
      ]
    }

Answer: Using the default Newtonsoft.Json settings works without issues:
string serializedPolicy = @"{
  ""indexingMode"": 0,
  ""automatic"": true,
  ""includedPaths"": [
    {
      ""path"": ""/PartitionKey/?"",
      ""indexes"":[{""dataType"":""Number"",""precision"":-1,""kind"":""Hash""}]
    }
  ],
  ""excludedPaths"": [
    {
       ""path"": ""/*""
    }
  ]
}";
IndexingPolicy policy = JsonConvert.DeserializeObject<IndexingPolicy>(serializedPolicy);

Keep in mind that the index definition you are using in your example seems to be incorrect, the dataType and kind are numbers, which seem to have to be the actual names.
Comment: This really solves the issue. Thanks!
Do you know why it works in Newtonsoft.Json but not in System.Text.Json?
For your comment about `dataType` and `kind`, as you can see in the original post, I have tried the two options :)
Comment: If I add `Index.Range(DataType.String, -1);` before `ip.LoadFrom(reader);` it works fine. However it doesn't work with `JsonSerializer.Deserialize`.
Comment: It doesn't work with System.Text.Json because the SDK is currently tied to Newtonsoft.Json and these are SDK classes (not user data classes) so the are using Newtonsoft.Json decorators and converters, reference: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos/src/Resource/Settings/IndexingPolicy.cs


PCA Derivation with maximizing projection length

Question: I was reading a post about deriving PCA, So it considered an arbitrary row datum, $x_i$ and tried to maximize projection length for each row of data matrix, $X \in \mathbb{R}^{N\times D}$:
$$\sum_{i=1}^N(u_1.x_i)^2=\sum_{i=1}^N(u_1.x_i)(u_1.x_i)=u_1^\top \Biggr[ \sum_{i=1}^Nx_ix_i^\top \Biggr] u_1\stackrel{*}{=}u_1^\top X^\top X u_1$$
Up to step *, everything is great, but I don't realize why the step * holds?
Comment: I only see step *, where is step ⋆?
Comment: @mhdadk Just a wrong character, fixed!
Comment: "The goal of this thesis is to modify projection pursuit by trading accuracy for interpretability. The modification produces a more parsimonious and understandable model without sacrificing the structure which projection pursuit seeks."  https://www.rand.org/pubs/external_publications/EP51086.html
Comment: @MikeHunter Didn't catch that. I am a newbie.
Comment: @MikeHunter No, and I think it is way too complicated for me! I am just a junior student self-studying an introductory course to machine learning.
Comment: The final step relies on the definition of matrix multiplication: that's all that's going on.
Answer: There must be a typo here since $x_ix_i^T$ is a scalar value if $x_i$ is a row vector. What the author likely meant is
$$
\sum_{i=1}^N(u_1\cdot x_i)^2=\sum_{i=1}^N(u_1\cdot x_i)(u_1\cdot x_i)=u_1^\top \Biggr[ \sum_{i=1}^Nx_i^\top x_i \Biggr] u_1\stackrel{*}{=}u_1^\top X^\top X u_1
$$
where $x_i^\top x_i$ is an outer product ($D \times D$ matrix). In this case, we have
\begin{align}
X^\top X &= \begin{bmatrix}x_1^\top & x_2^\top & \cdots & x_N^T\end{bmatrix}\begin{bmatrix}x_1 \\ x_2 \\ \vdots \\ x_N\end{bmatrix} \\
&= x_1^\top x_1 + \cdots + x_N^\top x_N \\
&= \sum_{i=1}^Nx_i^\top x_i
\end{align}
Comment: Yes I think this makes sense, by the way how did you derive the second equality?
Comment: @user21232681 the second equality is just a result of the definition of matrix multiplication.
Comment: The initial expression in the chain of equalities in the question makes sense only when $x_i$ is a *column* vector, not a row vector.
Comment: @whuber which part are you referring to exactly? I'm a bit tied up with something, so feel free to edit my answer to make any corrections.
Comment: "$u_i\cdot x_i.$"
Answer: In my opinion, this may be easier to see with $D=2$. In this case, you have
\begin{align*}
X^\top X & =
\begin{bmatrix}
    1       & 1 & \dots & 1 \\
    x_{11}       & x_{12} & \dots & x_{1N} \\
\end{bmatrix}
\begin{bmatrix}
    1       & x_{11}\\
    1       & x_{12}\\
\ldots\\
    1       & x_{1N}\\
\end{bmatrix} =
\begin{bmatrix}
    \mathbb{1}^\top \mathbb{1}       & x_{\bullet1}^\top\mathbb{1}\\
    x_{\bullet1}^\top\mathbb{1}       & x_{\bullet1}^\top x_{1\bullet}\\
\end{bmatrix}\\
& = \begin{bmatrix}
    1+1+\cdots+1       & x_{11}+x_{12}+\cdots+x_{1N}\\
x_{11}+x_{12}+\cdots+x_{1N}       & x_{11}^2+x_{12}^2+\cdots+x_{1N}^2\\
\end{bmatrix}\\
&= \begin{bmatrix}
    1      & x_{11}\\
x_{11}       & x_{11}^2\\
\end{bmatrix} +
\begin{bmatrix}
    1      & x_{12}\\
x_{12}       & x_{12}^2\\
\end{bmatrix} + \cdots +
\begin{bmatrix}
    1      & x_{1N}\\
x_{1N}       & x_{1N}^2\\
\end{bmatrix}\\
&= x_{1}x_1^{\top} + x_{2}x_2^{\top}+\cdots+x_{N}x_N^{\top}\\
&= \sum_{I=1}^N x_i x_i^\top.
\end{align*}
Unless otherwise stated, all vectors are column vectors. I've used $x_{\bullet1}$ to denote the second column of $X = (x_{ij})$, $x_{j}$ to denote the $j$th row of $X$ (treated to be a column vector) and $\mathbb{1} = (1,1,\ldots,1)$ vector of length $N$.
Comment: I think $x_i x_i^\top$ is a scalar not a matrix, am I right? seems that the correct equality is $x_i^\top x_i$ but in this way I don't know how we can change the second equality in main question to $x_i^\top x_i$ instead of $x_i x_i^\top$
Comment: @user21232681 t depends on how you see the $i$th row of $X$. If you see it as a column vector, as I do, then $x_i x_i^\top$ is the correct formula. mhdadk (+1) considers these to be row vectors, which explains the difference in notation.


Valores do Choices estão sendo armazenados assim ['Cachorro', 'Gato', 'Pássaros']

Question: tenho um sistema que terá a opção de escolha de 1 ou multiplas opções no mesmo campo. Mau problema é que preciso que meu campo dentro do model seja charfield e no forms seja MultipleChoiceField para poder validar multiplas escolhas.
Sei que poderia usar o filedmultiple no model e funcionaria, mas dai dari erro no django filter.
Preciso que como o modelo está agora, tanto forms quanto model, mas que ele passe para dentro do valores limpos e nao como esta passando agora, agora passa assim:['Cachorro', 'Gato', 'Pássaros']
models.py
PETN_CHOICES = (
    ('Cachorro','Cachorro'), ('Gato','Gato'), ('Pássaros', 'Pássaros'), ('Peixes','Peixes'), ('Reptéis','Reptéis'), ('Roedores','Roedores')
)
class Negocio(models.Model):
   pet_aceitos = models.CharField(max_length=255, choices=PETN_CHOICES)

forms.py
PETN_CHOICES = (
    ('Cachorro','Cachorro'), ('Gato','Gato'), ('Pássaros', 'Pássaros'), ('Peixes','Peixes'), ('Reptéis','Reptéis'), ('Roedores','Roedores')
)

class NegocioForm(UserCreationForm):
    pet_aceitos = forms.MultipleChoiceField(
          widget=forms.CheckboxSelectMultiple, choices=PETN_CHOICES, )

Answer: Pelo que entendi você tem um form recebendo ESCOLHAS FIXAS.
Dentro do seu MODEL Negocio o campo pet_aceitos não precisa ter o CHOICES. Você pode fazer esse "bloqueio" do usuário inserir apenas os dados que você deseja no form como já fez, e converter isso para SRT na view que está o form. Veja se ajuda :)


Find the MLE density function of uniform [-\theta,\theta]

Question: For $X_1,\dots,X_n$, i.i.d $X_n \sim \mathrm{unif}[-\theta,\theta]$, the ML: $\hat\theta_{MLE}=\mathrm{max}\{-X_{(1)},X_{(n)}\}$. Find the density function. Hint: For $x_1,\dots,x_n$ : $\textrm{max}\{-x_{(1)},x_{(n)}\}=max\{|x_1|,\dots,|x_n|\}$.
Here is my work:
First i find the CDF  for $\hat\theta_{MLE}$ and then differentiate with respect to $x$:
\begin{align}
F_{\hat\theta_{MLE}}(x) &=
 P(\text{max}\{-X_{(1)},X_{(n)}\}\leq x) \\
&= P(\text{max}\{|X_{(1)}|, \dots ,|X_{(n)}|\}\leq x) \\
&= P(\text{max}\{|X_{(1)}|\}, \dots , \text{max}\{|X_{(n)}|\}\leq x) \\
&= \prod_{i=1}^{n} P(|X_i|\leq x) \\
&= \prod_{i=1}^{n} P(-x\leq X_i \leq x)\\
&= \prod_{i=1}^{n} F_X(x)-F_X(-x)\\
&= \left(F_X(x)-F_X(x)\right)^{n}\\
&= \left(\frac{x}{\theta}\right)^{n}
\end{align}
\begin{align*}
 \frac{d}{dx}\left[\left(\frac{x}{\theta}\right)^{n}\right] &= n\frac{x^{n-1}}{\theta^n}\\
 &= f_{\hat\theta_{MLE}}(\hat\theta) \ \text{,}\  0\leq x \leq \theta
\end{align*}
Is this correct?
Comment: Think of typos in what you have written.
Comment: This is a FAQ: See [this site search](https://stats.stackexchange.com/search?q=uniform+mle+theta+is%3Aquestion).
Answer: A few extra (and less) steps:
\begin{align}\require{cancel}
F_{\hat\theta_{MLE}}(x) &=
 \mathbb P_\theta(\text{max}\{-X_{(1)},X_{(n)}\}\leq x)\\
&= \mathbb P_\theta(-X_{(1)}\le x,X_{(n)}\leq x)  \tag{definition}\\
&= \mathbb P_\theta(X_{(1)}\ge -x,X_{(n)}\leq x)  \tag{inversion}\\
&= \mathbb P_\theta(X_1\ge -x,\ldots,X_n\ge -x,\\
&\qquad \qquad X_1\leq x,\ldots,X_n\le x) \\
&= \mathbb P_\theta(|X_1|\le x,\ldots,|X_n|\le x)\\
&=  \cancel{\mathbb P_\theta(\text{max}\{|X_{(1)}|, \dots ,|X_{(n)}|\}\leq x)}\tag{useless} \\
&=  \cancel{  \mathbb P_\theta(\text{max}\{|X_{(1)}|\}, \dots , \text{max}\{|X_{(n)}|\}\leq x)}\tag{incorrect}\\
&= \prod_{i=1}^{n}  \mathbb P_\theta(|X_i|\leq x) \\
&= \prod_{i=1}^{n}  \mathbb P_\theta(-x\leq X_i \leq x)\\
&= \prod_{i=1}^{n} \{F_X(x)-F_X(-x)\}\\
&= \{F_X(x)-F_X(-x)\}^{n}\tag{typo}\\
&= \left(\frac{\min\{\theta,x\}}{\theta}\right)^{n}\tag{correction}
\end{align}


Are there any violin family instruments built without a left shoulder?

Question: On the bass and cello (and probably violin and viola as well), it seems like many aspects of proper form serve the purpose of getting ones arm over the left shoulder to play high on the fingerboard. So, are there any instruments that have been built with the left shoulder made concave?
If there haven't, is it just a chance thing that no one has thought of it or felt the need for it, or are there acoustic reasons to keep the instrument roughly symmetrical?
Comment: @CarlWitthoft Is this with the viola/in facing you? It's still the same side as the bass and cello, if you orient them the same.
Comment: you are correct; I forgot the wrist twist.
Answer: As far as double basses are concerned, it's not uncommon to see a body with something like this:

Just a normal double bass body, with a left shoulder cutaway (if it is really called like that). They are used to help the player on the higher positions. One company (that comes to mind) that makes such basses is Framus :

I understand why you ask such a question, and for a beginner it would make the playing in higher positions easier, but (speaking as a double bassist), you just get used to the "traditional" built of it.
Answer: The "electric family" of string instruments are often designed without any shoulders. The below photos come from Wikipedia's entries for electric cello and electric upright bass, and an internet search will show you lots of other designs -- much in the way that electric guitars can be shaped in myriad ways.
For acoustic instruments, one consequence of eliminating a shoulder is that it would reduce the resonant surface area of the instrument.
To really get into the nitty-gritty on this, you could find a copy of The Cambridge Companion to the Cello. Chapter 3 is devoted to cello acoustics.
There is also the extensive "Acoustical Studies on the Flat-backed and Round-backed Double Bass," which, while examining a different property of the instrument, may offer some relevant insight.

an electric cello

an electric bass
Answer: Aside from electric instruments like @Aaron mentioned, this is not unheard of but extremely rare. I have seen a few upright basses over the years in bass shops with a cutout in the upper bout like this or even more pronounced.

I even found a pic of a viola with a similar feature:

I have never seen this on an acoustic cello or violin but I would not be surprised if there are some out there.
My take (and personal experience) is string players are used to and even rely on where the body meets the neck for physical cues on where to find upper register notes. Because of this most players prefer a symmetrical instrument. Even electric string instruments usually have some type of abbreviated shoulder because string players are used to a transition from neck to body.
As for acoustical properties, I cannot say for sure but changing the shape and symmetry of an instrument will probably have at least a minimal effect on the sound.
Comment: As a cellist, I can state that we do use the shoulder as a physical reference point.
Comment: @CarlWitthoft I don't follow your reasoning. The left hand goes up the neck on the treble side and supposedly is facilitated in reaching the upper register by the cutout.
Comment: John,  you are correct;  my apologies -- too many mirror twists and I fooled myself.
Comment: @CarlWitthoft no worries and thanks for your comment regarding the cello. As a bassist I wouldn't get a bass like the one in the picture, I like having my left forearm support and reference point when I play in thumb position!
Answer: It's hard to imagine a violin/viola player having a problem with the shoulder of the instrument, even with the worst posture imaginable. The arm, in particular, just doesn't touch the instrument. The smaller size of the instrument means that even the highest note on the fingerboard can be reached by just reaching the hand across.
I don't have my own video of this, but if you search for "violin highest note" you can find many examples. In reality even that isn't likely to be a problem since the very high notes are hard to play for other reasons.
Posture for violin/viola is more a product of:

Something (not your hand) has to hold the instrument up.
You have to reach across the fingerboard to the lowest string.
Comfortable movement of the bow.

And a few optional but handy things:

Being able to look at music/the conductor.
Being able to stand or even walk around.

There are some alternative positions that miss 4 and 5, such as holding it like a cello or the Indian position where the player sits on the floor and the top of the instrument is braced on the player's foot, but even with those variations 1-3 really limit the options.


Not reporting significant results from a model I am reporting other results from

Question: I'm trying to submit a chapter of my thesis to a journal. We used nested ANOVAs where we nested the group comparisons within year to account for potential bias due to different observers between the two years. There were stark contrasts between year although that is not of interest. My adviser says to leave all significant findings regarding year, out of the paper, because it's not relevant to our overall "story". I agree that it is not relevant, but I wanted to see what the consensus was on this. I know often that analyses that are run are left out of papers, but part of the results of a simple ANOVA model? Do I owe it to the readers to be clear about evidence of observer bias or can I just leave it out because it isn't important to the message of the paper.
Answer: If the bulk of your paper is taken up with discussion of the ANOVA results it would seem odd to omit to mention controlling for observer bias; & odd to want to, as your having taken it into account forestalls potential criticism for not having done so. If you're giving effect estimates and standard errors you need to specify the model they're embedded in if you want anyone else to be able to use them. If, on the other hand, you merely mention in passing some conclusions drawn from the ANOVA, it doesn't seem necessary to go into too much detail about it.
Comment: Well, what is the superfluous material? I think @Matt's answer covers the possibilities nicely. A results table is both conventional & handy, & there would be little sense here in not giving it fully if you give it - without necessarily expending a single word on discussion of an uninteresting effect.
Comment: Thanks for the answer. To be clear, I mention the model in the methods, my adviser just wants to take out what she views as superfluous material in the results section.
Answer: I would like to see the entire model included somewhere in the paper, probably in the methods section or in a supplement/appendix. If it the model is huge, a table is a nice way to present this. You could even organize the table to distinguish between "interesting" variables (e.g., drug dose) and boring covariates that are likely to be trivially true (e.g., rater). I saw this done recently and thought it was very convenient, but I'm having a hard time tracking the paper down.
However, once you've "disclosed" your model, there's no need to give equal time to each of its components when discussing the results. You could ignore the covariates completely, or you could start the results section with something like

After controlling for observer bias (see complete model in Appendix 1), we found that....

If the bias is particularly surprising or you have done something to control it (e.g., provide raters with a standardized rubric), then it might be worth a slightly longer mention.


How to rotate a 3D vector on the surface of a plane by a known angle?

Question: Available data

The plane β which is defined by a normal vector n and point P.
The vector v which lies on the surface of the plane.(the angle between v and n is 90 degrees).
The angle α to which v should be rotated.

How to obtain the rotated vector(vrot) ?
Note that the vectors are 3D.
Comment: Take a look at [this post](http://math.stackexchange.com/questions/1514364/find-the-vector-in-the-new-position-obtained-by-rotation). It will help. :)
Comment: It did help, in the sense that i have a clearer idea, but i don't understand what l in Rodrigues' rotation formula would be in this case.                           Is l = (v x n) / (||v x n||) ?
Answer: If $v \neq 0$ and $n$ is a unit vector, the vectors $v$ and $n \times v$ are an orthogonal basis of your plane, and the result of rotating $v$ counterclockwise (about $n$) by an angle $\alpha$ is
$$
(\cos\alpha)\, v + (\sin\alpha)\, (n \times v).
$$
Comment: Hi @Andrew, is there any this is possible without $n$, I mean asper my question here https://math.stackexchange.com/q/4386389/585488


Header add Content-Disposition "attachment" causes Internal Server error

Question: As the builtin browser of my ebook-reader (Sony PRS-T1) is quite stupid and wants to open .epub files as text-files instead of downloading them, I tried to force the browser to download the .epub files with this .htaccess file:
<FilesMatch "\.(?i:epub)$">
  ForceType application/octet-stream
  Header add Content-Disposition "attachment"
</FilesMatch>

However, this causes an internal server error:

Internal Server Error
The server encountered an internal error or misconfiguration and was
  unable to complete your request.
Please contact the server administrator, webmaster@localhost and
  inform them of the time the error occurred, and anything you might
  have done that may have caused the error.
More information about this error may be available in the server error
  log.

When I leave out Header add Content-Disposition "attachment" there is no error - however, the browser wouldn't download the file :(
Am I doing something wrong? Where does the Internal Server error come from?
[EDIT 2013-04-11]
I just earned the "popular question-badge" for this thread, which reminded me of adding some information.
I finally managed to force a download on Sony's PRS-T1 browser with the following php-function
function startDownload($path, $mimeType) {
if(!file_exists($path)) {
// File doesn't exist, output error
exit('file not found');
} else {
$size = filesize($path);
$file = basename($path);

// Set headers
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=\"$file\"");
header("Content-Type: $mimeType");
header("Content-Transfer-Encoding: binary");
header("Content-Length: $size");
// Read the file from disk
readfile($path);
}

exit();
}

Hope that helps somebody one day.
Comment: possible duplicate of [Set Content-Disposition header to attachment only on files in a certain directory?](http://stackoverflow.com/questions/3977159/set-content-disposition-header-to-attachment-only-on-files-in-a-certain-director)
Comment: sorry, not my server - maybe I can ask for the log, but don't really know.
Comment: I have a Sony PRS-T3 and it helped me, thanks! In my testing you only need the correct MIME type for it to be downloaded successfully.
Answer: This might be the answer:
http://diogomelo.net/node/24

The module headers is not enabled by default on Apache. So, we have to
  enable it manually.
To enable this module, log in as root, and create a symbolic link from
  mods-available/headers.load to mods-enabled. After that, reload apache
  and it's done. To do so, I've used this commands.
su - cd
/etc/apache2/mods-enabled/ ln -s ../mods-available/headers.load
headers.load sh /etc/init.d/apache2 force-reload

Comment: @Gregra Open `httpd.conf` and uncomment this line: `LoadModule headers_module modules/mod_headers.so` by removing the `#` character. Then restart your apache server.
Comment: How can this be achieved on Apache on Windows?
Answer: You may also want to make sure the headers module is enabled before using this in your htaccess file. The following line will generate an error if the headers module is not enabled:
Header set Content-Disposition "attachment"

here's an example that forces download of mp3 files only if the headers module is enabled:
<IfModule mod_headers.c>
    <FilesMatch "\.(mp3|MP3)$">
        ForceType audio/mpeg
        Header set Content-Disposition "attachment"
        Allow from all
    </FilesMatch>
</IfModule>

Note: it does not enable the module, it just ignores anything inside the IfModule tags if the module is not enabled.
To enable apache modules you'll either need to edit your httpd.conf file or in wamp server you can click the wamp tray icon and select "Apache -> Apache Modules -> headers_module" or make sure it is checked.
Answer: for ubuntu, theres is a shortcut to enable apache2 headers module, using:
sudo a2enmod headers

Problem solved ^_^


How can I anonymously logon to Exchange 2003 SMTP server to send mail?

Question: I have anonymous logon enabled on the my Exchange 2003's virtual SMTP server however trying to send emails (using the program VisualSVNServerHooks: http://www.visualsvn.com/support/topic/00018/), I get a failed to connect error when I dont supply a username and password. The event logs reveal nothing...
How can I anonymously logon to Exchange 2003 SMTP server to send mail?
Unfortunately since nothing is logged by exchange all I have to go by is VisualSVN's error:
<code>"E020014: The transport failed to connect to the server"
</code>
The server is localhost and firewall is not blocking.
Comment: what is wrong with this question??
Comment: I was wondering the same thing. Probably just explain more about your problem solving approach, with snippets of config and logs. You could also use tcpdump/wireshark to see what the traffic was for the "access denied" result.
Comment: I regret adding the VisualSVN details because I just want to know the answer to my original question: "How can I anonymously logon to Exchange 2003 SMTP server to send mail?", regardless of what my be wrong with VisualSVN here.
Comment: Have you tried sending mail without logging in from a normal mail client or directly through telnet? That will remove visualsvn from the equation and possibly give you a more useful error message.
Comment: Are you trying to use your exchange server as an SMTP relay?
Comment: By looking at the visualsvn hooks - you define the smtp server to use: which is your exchange server? That is exactly SMTP-relay.
It means that visualsvn uses your exchange (without auth), to send e-mails.
Answer: Applications sending e-mails through your exchange server, should be allowed to relay e-mail messages through your send connectors.
I found this by some googling: How-To
The list of allowed IP's in Exchange is empty by default.
Comment: I dont think I want to relay - relay is passing on emails i.e. my exchange would sit between the program and another exchange - I want my program to directly connect to exchange's SMTP and send an email to one of an email address it controls (i.e. in the its address list).
Comment: Relay is not exchange to exchange traffic. We use relay for sending e-mails from both web-apps and other software applications in need of "alerts". If it uses your exchange as an SMTP-Relay, it's no problem sending to addresses in your domain!

One example of use is "Nagios" alerting my address via smtp-relay on our exchange

Dependant on how you configure the relay - it can use only internal addresses if you want but also commonly used for external aswell (to pass PTR checks).


How to vocalize(or sing) chord progressions- with which syllables?

Question: I'm doing ear training to identify chord progressions. I don't have problem playing a melody by ear. my goal is to play chords by ear and recognize them in different songs.
To   this day, I've already learned to identify I IV V triads. When hearing the progression I-IV-V, I sing it with solfege syllables of the bass note  as "DO FA SO", no matter what the key is I always use the same syllables "DO FA SO" (what's called "Moveable DO"),even for minor chords. In this way I remember the intervals between the bass notes and the whole sequence of chords. This is fairly easy for me and works pretty well!
But I would like to advance with some more harmonic degrees (more progressions) and I came into a problem:
Let's say I hear the progression I-vi-IV-V. I want to memorize it .How do I vocalize this sequence of chords? what is the best way? Should I sing "DO LA FA SO"? how to emphasize that "LA" is "LA minor" .
Another example: The progression I-vi-ii-V, should I sing "DO LA RE SO"?
or is there any better way to do this?
Another problem is: How do I stress the function of the chord while singing? meaning: I know that vi is similar to the tonic I, and ii is similar to IV ,  How can I emphasize this principle while memorizing the progression...
On the other way .If it's not possible to really sing chord progressions, How should I hear the progression in my inner mind, should I just remember how it sounds (seems difficult) or can I assign to each chord a musical name that will remind me the chord or the sound of it. but which "names" should I use?
I saw in another questions that there are some who pronounce the numbers, does it mean to sing the numbers and is it a better method  ? How can one actually do that?
I have saw the question How to use solfege for chords? but it doesn't answer clearly what to do and how to really memorize progressions of chords....
I would like to have detailed instructions for what actually do. how to memorize the progressions and use them later for playing chords by ear or recognizing them in different songs. That's an information that I didn't find in this site or in the free internet. If I were a student at a music school, what would they teach me to do? I'm looking for a detailed practical guide.
Comment: You're right, it can be a problem when people edit questions so that existing answers no longer make sense. But in my opinion the new material shown here is close enough to the original question that answers *would* still make sense. It seems to have grown simply from "what should I say" to "what should I sing." I'm going to vote to close this one as a duplicate and encourage you to add its material to the original question.
Comment: Does this answer your question? [How to pronounce chord progressions](https://music.stackexchange.com/questions/133673/how-to-pronounce-chord-progressions)
Comment: You should edit your previous question ([How to pronounce chord progressions](https://music.stackexchange.com/questions/133673/how-to-pronounce-chord-progressions)) rather than re-posting. Or, if you have a new question that is related but different, reference it with a link rather than repeating it.
Comment: the answers to the previous question talking about all another concept, not what I intended to ask, so how can i replace the question while the answers still exist? i wrote it in  a comment there..
Comment: "It goes like this, the fourth, the fifth, a minor fall, a major lift..."
Comment: Meh, I take it back, there *is* enough different here to be a separate question. But I encourage you to remove language that's identical to the original question to avoid the perception of duplication.
Comment: thank you, this was indeed my previous question, and  i noticed that it's really misleading.... proof for this: someone added to the previous question  the tag "Roman-Numerals" while that wasn't my  intention... i didn't ask wat's the right way to define chords but actually how to sing them... by "how to pronounce"  i meant how to say it verbally so that it will let me remember the right sound....
Answer: You cannot represent chords by singing single notes. All you can do with single notes is sing the bass notes of the chords you are thinking of. There is no way to establish chord quality by singing only roots or bass notes.
One thing you can do is sing the notes in chords as arpeggios. Here is an example of one way to do that using a I vi IV V progression:

By doing this you are singing all the chord tones for each chord. I used 4/4 time to emphasize the root notes with a strong beat that is longer than the other two of each chord. You can also use 3/4 time and make the notes all the same duration or create your own way of doing it.
Comment: But you can sing something that identifies the chord regardless of what pitch you're singing.  For example, you could rewrite the lyrics in the image as "To-nic and sub-me-diant, sub-dom'-nant, dom-i-nant, home!"
Comment: @phoog Yes you can, very catchy! The OP seems to want to use solfège syllables so that is what I used for the example I provided
Comment: Note: in movable do systems "ti" is used instead of "si" for the leading tone because a raised fifth is called "si". WIth la-based minor and movable do we sing a lot of "do ti la si la".
Comment: @ToddWilcox Noted. Wouldn't that also apply to fixed do or does a raised 5th have a different name?
Comment: @phoog How can something like that  work? Does what I'm  singing needn't remind me the sound of it? How can I memorize such a thing?
Comment: @JohnBelzaguy But I can't sing the arpegiated chords of a progression, because when doing so (stating each individual note) I lose sight of the progression itself...
Comment: @JohnBelzaguy  another problem, when arpegiating LA Minor, which A should I use, the A in the current octave, or the A in the lower octave..?
Comment: @YtfuGjuf You can use either. In this case I made the first three chords descending but you can go in whatever direction suits your vocal range. Remember, this is just an example, not the way it has to be done.
Comment: @JohnBelzaguy That's good for encompassing the whole quality of each chord. definitely this kind of practice should also be done. But  I steel don't understand how to **memorize sequences** of chords: meaning , how to memorize common progressions in a way that I will be able later to distinguish which chord to use when playing by ear... or which chord comes next... what is the best method for doing that? how to **vocalize the progression** with just **one syllable** for each chord so that the "melody of the harmony" would be stored in my head for later use?
Comment: @Ynk The way to memorize the sound of chord progressions is to learn what they sound like. This is very difficult and maybe even impossible to do with just voice. I suggest you get an instrument capable of playing chords like piano or guitar and learn and practice playing simple chord progressions like I-IV-V, I-vi-ii-V etc. in different keys. Also listen to music with simple chord progressions and study them with and without looking at music. You have to internalize the sounds of the various chords and progressions. This takes time and work but is worthwhile in the long run.
Comment: @JohnBelzaguy OK, but when I hear my guitar playing I-vi-IV-V  what should I hear in my mind?? the sound of the chords as it is? it seems difficult to remember? Or should I assign to the chord some vocal syllable of any type? thank you.
Comment: @Ynk Your last questions are difficult or even impossible to answer because everyone hears and learns in their own way. Personally, I am mainly a bass player so I tend to hear things from low to high. First I try and grasp the bass notes and the relationships between them and then listen to the quality of the chords (major, minor, 7th, etc) over the bass notes. Understanding bass movement is a very big part of learning harmony.
Answer: As a former music school student and current composition/music theory teacher, I think we need to go back to your intention.

use them later for playing chords by ear or recognizing them in different songs If I were a student at a music school, what would they teach me to do?

You want to be able to hear a chord progression, and know what the "roman numeral" progression is. For the sake of brevity, I will assume you can play a keyboard or other polyphonic instrument(s), and also assume you know how to play chords by knowing the roman numerals – though in music school, we took piano lessons which taught us to know how to play chords both by reading western notation and roman numerals.
First of all, music students spend 4+ years building up to this as one of the end goals, and not everyone makes it out with this ability (though the students with perfect pitch caught on quickly), so be easy on yourself.
If you want to learn the same way a music school student would, the way I learned this was though a combination of:

listening to chord progressions while studying the sheet music with roman numeral analysis above each chord
listening to cadences (i.e. authentic, half, plagal, deceptive, etc.) - this will help you understand chord functions
LOTS of practice telling chord progressions and cadences apart (I highly recommend you get an aural theory workbook that comes with a CD/mp3), because there's really no substitute for being quizzed on this
analyzing sheet music and put the roman numerals above each chord change (usually as a predecessor of score reading)
score reading: listening to a recording of a piece while following along in the sheet music, from very basic Medieval music all the way through Contemporary atonal music. the score anthology we used - I still love this thing
reading about the historical and current uses of cadences, common and uncommon chord progressions, chord inversions, melodic ornamentation (non-chord tones), etc.

That all being said, I started out as a singer, and I often had to hum underneath my breath to be able to figure out the chords for a while before I began to "hear" and recognize the chords in my head on a subconscious level (and I definitely lose this part if I don't practice often).
Since you're already practicing solfege singing for your own theory practice, you can definitely use that to enhance the above "syllabus" by singing arpeggiations of each chord in solfege or even just "la la la" along with the chord analysis aural practice.

My unsolicited advice:
I have no idea about your situation/location, but you seem driven and motivated, which is an almost ubiquitous quality of students who get the most out of higher education.
I would really recommend you check out a college/university course in music theory. Community colleges in the US and public universities in many European countries have part-time options, night classes, and often financial support for people with special circumstances. Also, you don't have to pursue a degree to go to college classes. Another option: PhD/Masters students often charge very reasonable fees for music theory/aural theory tutoring.
I've been through the red-tape in academia in the US and Europe several times, so feel free to reach out if you decide it's something you want to look into and would like any mentorship through that process. Good luck!
Answer: If your target is being able to identify chords and their sequences by ear (your first paragraph),then the simplest is to actually give each piece a key. So the 1-6-4-5- that you quote will have real meaning in your playing - C-Am-F-G, B♭-Gm-E♭-F,  A- F&sharp-D-E, etc. That will also make your understanding of chords in relation to each other much stronger.
Doing it hypothetically, you could start with 'I'll pretend this is in key C', and move through all 12 keys, probably following the circle of fifths.
Then, when transcribing a song (something I do almost daily), all you'll need is the key - root chord - and away you go. You'll understand that C>Em is the same as G>Bm, is the same as A♭>Cm, etc.
The solfege system isn't really designed, or suited for what you're doing, and the RN analysis isn't too good unless you're writing it down. NNS works well for the written version, in fact that's what it's used for! Not that it will help in your case. I tend to write but use a mix of RN and NNS which suits me fine - it may do the job for you, but vocally, not a lot of help.
Comment: You've wrote "the 1-6-4-5- that you quote will have real meaning in your playing - C-Am-F-G, B♭-Gm-E♭-F, A- F&sharp-D-E, etc."     So what I actually need to say  when I memorize a chord progression? should i say  B♭-Gm-E♭-F  ?  Or should I say always C-Am-F-G  no matter what the key is? Or should I say 1-6-4-5?
Comment: Yes, either but it makes sense to quote whatever you're playing in the appropriate key, otherwise it is nonsensical. Hypothetically it won't make much difference. I've worked many times where 1645 makes enough sense to just play.
Comment: "but it makes sense to quote whatever you're playing in the appropriate key", But what do you mean by "quote", should I replace what I say in any new song?  in the key of C Major  say DO-FA-SO  and in   D Major say RE-SO-LA ?
Comment: @YtfuGjuf - that wouldn't work too well for chords with extensions. No, just as in my 1st paragraph, call out the actual names of the chords - if you know the key. If you don't, then invent one, and imagine the song is in that key.
Answer: First, recognize that what you're asking to do is unusual. It does seem worthwhile, but it's not something that's usually done, or at least taught. Singing as a part of ear training is usually focused on melodies, not chords. There's a simple reason for that: we only sing one note at a time!
But singing is a good way to internalize what's happening, so "singing chord progressions" seems like a worthwhile practice. Since it's not usually done, there's no standard approach and you can use whatever works for you. There are a few problems to solve, though.
First, which note out of the chord do you even sing? If you're in the key of C and faced with "C F C G," do you sing just that, a C, an F, a C, and a G? Is the F higher than the C, or in a lower octave? What if you're looking at not just letter names, but noted music? If you see

do you sing the bottom notes, which are the C F C G roots of the chords? But the top notes suggest a melody line; do you sing those? What about chord inversions? What do you sing for this:

In letter-name notation, that's "C F/A C/G G/D." If you sing the roots, you sometimes sing the bottom note, sometimes the middle, sometimes the top. If you just always sing the bottom notes then you're singing the bass line, but the pitch you sing doesn't match the note you say (or, if you use numbers, the location of that number within the scale).
So what should you do? Since you're asking about something that isn't commonly done, you can do whatever you want, and all I can say is what I would choose to do and why.

First, I would "sing chord progressions" only as a limited practice. I would do it to get a feel for the role of each chord within the tonality.
But at the same time and separately, I would practice sight-singing melodies in moveable do solfege. (This would have much the same effect; if I sing do fa sol I'm also hearing an implied I IV V.) And at the same time, I would do pencil-and-paper work to analyze examples in more detail than I can sing.
I would ignore chord inversions. Facing the example above, I would sing it just like the first one, just singing roots. This means I'm singing an "idealized" version, not necessarily exactly what's played. In fact, I would not try "chord singing" on very complex examples. If I want to focus on a bass line, maybe a cool walking bass line that results in lots of inverted chords, I'd treat it as a melody and probably use moveable do solfege for it. And I would leave it to the paper-and-pencil analysis to make note of voicings and inversions.
I would sing numbers. I'd choose this because you get the "moveable do" benefit of emphasizing tonal function (instead of the fixed-do equivalent of singing letter names), and I would not use solfege to avoid confusing this chord-singing with melody-singing.
I would not bother trying to sing anything that indicates chord quality (major, minor, diminished, etc.). Instead I would gradually internalize the sense that ii and vi are minor or III and IV are major. I suppose I could imagine, if one chord were altered from its normal quality, singing something like "minor threeee" out loud—but then again, I probably wouldn't use this approach for such a complex example.

Note, everything above is for what I would do to learn. I often do face the need to sing a chord progression out loud, most often when trying to teach it to someone else verbally. But then I most often use letter names since that's what they need most. "Ok, so the bridge goes F, C over E, D7 over F sharp, G."
Comment: "Since you're asking about something that isn't commonly done"  I thought that it's the most common method....  so what really is the common method that they teach in school? I'm autodidact .
Comment: "do pencil-and-paper work to analyze examples". my intention is to sing by ear, not theory. so how can this help me?
Comment: You said "First, I would 'sing chord progressions' only as a limited practice."... and later say "I would sing numbers ". how can i mix the two approaches? if I memorize DO FA SO,    it becomes stuck into my head with the solfege syllables, and how can I later sing 1-4-5 ?   dosn't the memory of the progression needs to be clear and defined verbally?   By the way, I dont have problem playing melodies by ear, my goal is to learn how to play chords by ear.
Comment: @YtfuGjuf There are many approaches to "ear training" or "aural skills." Many of them include some singing; this is usually singing melodic material using solfege. They also usually include listening exercises, like identifying intervals or writing down short melodies that are played for you. It's usually studied alongside music theory. You'd need to study *some* theory just to know what you're talking about. You seem to care about getting a sense for how each chord "works" within the key, like the way V wants to lead to I. That's some basic music theory. And...
Comment: @YtfuGjuf ... and the details like chord inversion or non-chordal tones wind up being useful too, because sometimes takes some analysis to even decide *what* chord we're looking at. In the key of C, if you have an C, an E, and a G in your chord, it's probably an F chord. BUT if the bottom note is the G, and the C and E quickly move to B and D, then maybe there never was a C chord, and it's just a G chord with a suspension. All of this is stuff you don't *have* to learn if the end goal is to hear a song and be able to play it. But it would help; you'd start to understand *why* certain chords
Comment: @YtfuGjuf come in a certain order, or have educated guesses about what comes next. Meanwhile: You ask: "You said 'First, I would 'sing chord progressions' only as a limited practice.'... and later say 'I would sing numbers '. how can i mix the two approaches?" I'm using "sing chord progressions" as a name for what you're asking for, using singing to represent chords. Usually in ear training people only try to sing melodies.
Comment: @YtfuGjuf "if I memorize DO FA SO, it becomes stuck into my head with the solfege syllables, and how can I later sing 1-4-5 ?" Correct, that's why I recommend *not* using solfege to represent chords, so you can use it instead to represent melodies.
Comment: Than why whenever I read about chords ear training they say "you need to learn intervals" ? intervals of what? the chord? the bass notes? what would they do with inversions and all of those problems? (I've already done interval ear training, but how it leads to better recognizing chord progressions?)
Comment: @Ynk "Intervals" are usually the distance between two notes. Chords are made up of stacked intervals, and melodies are made of intervals one after another. "Learning intervals" usually looks something like what you see at [this lesson](https://www.musictheory.net/lessons/30) and the ones immediately following it, and the ear-training for it often looks like [this](https://www.musictheory.net/exercises/ear-interval) (note the customizable options to hear the interval as two notes one after another or at the same time).
Comment: Interval training, I know what it is. I'm asking what is the connection between learning chord progressions- to interval training? If I had to recognize the interval between the bass notes of two fixed chords, than, we are talking about intervals. but how can it help when we are talking about recognizing the whole chord (sometimes inverted as you have said inside your answer) in a sequence of chords? thanks!
Comment: @Ynk Hm... At first I think of ear-training to recognize intervals, and chordal dictation to recognize chord progressions, as being two different skills, but I guess interval recognition helps with chordal dictation. When I'm asked to recognize a progression of chords, I don't consciously think "Okay, for the first chord I hear a sixth in the bass and a third on top of that," etc. I just think "This has the at-rest feel of I; this has the leading-to-something feel of a IV; this has the halfway-point feel of V" etc. But I guess it's likely that recognizing intervals is a...
Comment: @Ynk ... subconscious "underlying skill" to this one. You know, maybe the question you really need is not "what should I say/sing," but "what's the best learning regimen to be able to transcribe chord progressions." There have already been a lot of questions like that; try reading https://music.stackexchange.com/q/46/78419, https://music.stackexchange.com/q/73200/78419, https://music.stackexchange.com/q/70010/78419, https://music.stackexchange.com/q/92897/78419, and https://music.stackexchange.com/q/39456/78419.
Comment: @Ynk Note that much of the advice on those questions helps with transcribing *melody* rather than chords, but a lot of music has melody over chords. One thing I want to highlight from all that advice is the importance of *playing*, not just singing. Playing chord progressions, and knowing while doing it that they're I IV V I not just C F G C will help you hear the tonic, predominant, dominant, tonic in other songs.
Answer: You only have one voice, so if it's busy singing solfege syllables, you'll have to use other parts of your body to externalize other aspects of the music.
Part 1: You're (mostly) already doing that
Here's the thing about chord functions: That's what solfege is. One of the strengths of movable Do is that (in a major key) Do is always the tonic and So is always the dominant. So if you learn to think of "Re" as shorthand for "subdominant", you're already communicating that information as efficiently as possible, in one syllable.
Similarly, if major keys are centered around Do and minor keys are centered around La, you can always,* irrespective of mode, expect that the chords based on Do, Re, Mi, Fa, So, La, and Ti are major, minor, minor*, major, major, minor, and diminished respectively. That's just how scales work.
If you're willing to put in a little bit of memorization, you'll find the information you need is already there—as long as the music you're singing is diatonic. So the most important thing to physically drill is when it deviates from that framework.

*Yeah, I'm pretending harmonic minor doesn't exist for simplicity, but it's easy to add back in once you get the idea.
Part 2: How to do it anyway
Non-diatonic functional analysis gets complicated (and subjective, and beyond my knowledge set) fast. Let's focus on chord quality, which is a lot more straightforward.
With only a few things to indicate (major, minor, augmented, diminished, and a neutral default when no indication is needed), the options are numerous. Downturned fist, upturned fist, downturned palm, upturned palm, relaxed hand? That's what springs to mind, but you'll know best after you workshop it.
One variable is how accustomed you are to a particular system of solfege hand signs, and how much it bothers you if they overlap. Speaking of those, if you really want a physical indicator of harmonic function, you could do the solfege sign with the other hand only when the function is known, strengthening the mental connection, or invent a similar system that doesn't care whether the key is major or minor.
Comment: @AndyBonner I've been assuming the opposite.
Comment: So would you recommend using this method of memorizing progressions of chords by solfege syllables? Can you elaborate more about  how should I do it practically? thanks you!
Comment: @Ynk Can you clarify what you're asking?
Comment: I want to focus on diatonic chords. as I have said in the question, how should I memorize the progression **I-vi-IV-V**? the LA is LA Minor . should I sing DO-LA-FA-SO ?  or maybe   DO-LA minor-FA-SO ?  How should I distinguish major chord from minor?
Comment: @Ynk Right. Diatonic Do, Fa, and So-based chords are always major, and La, Re, and Mi-based chords are always minor (and Ti is diminished). This stays true for minor keys as long as you consider La the root, rather than keeping Do as the root and using chromatic solfege for flat notes.
Comment: (Note, this assumes "do-based minor" rather than Kodaly's "la-based minor")