Services Module - 500 Internal Server Error When Accessing REST URL

Question: I created a services endpoint but any time I access the REST URL, e.g. http://www.mysite.com/endpoint I get a WSOD and the following in the firebug console:
"NetworkError: 500 Internal Server Error"

No errors in the dblog.  No errors in the apache error log.
The site is hosted on aegir.  So as a troubleshooting step I moved the entire drupal files and database to my local machine, hoping that I could step through with a debugger.  Guess what, everything works fine!
I've tried uninstalling modules one by one - no luck
I've tried with a clean drupal install on aegir - same 500 error
I'm wondering if anyone can suggest any further troubleshooting steps?
It seems that it could be something to do with the server or aegir configuration.
Comment: Maybe because you're contacting an endpoint without requesting a resource? Do you get a 500 for `http://www.mysite.com/endpoint/user/login`, for example (assuming of course you have that resource enabled)?
Comment: Hmm strange that it works locally, definitely points to some sort of server config issue. Are you using session authentication, and if so are you including the CSRF token header as part of the request? It's been required since v3.4 and caused me a couple of issues very recently
Comment: Same problem at `http://www.mysite.com/endpoint/node` - 500 error, resource is enabled.  Usually Services gives a message saying "This endpoint has been setup correctly" when contacting `http://www.mysite.com/endpoint` but getting 500 error and no success message.
Comment: No session authentication is turned on.  It's got me stumped!
Answer: The problem turned out to be the PHP version on the server.  The Rest Server had a line of code that requires PHP 5.3.
There is an issue at https://drupal.org/node/2003396 and a patch at https://drupal.org/files/ServicesRESTServerFactory.inc_.patch
Installing the patch solved the problem without the need to upgrade the php version on the server


Why does (int)(float.Parse("0.04", System.Globalization.CultureInfo.InvariantCulture) * 100) equals 3

Question: My boss reported my a bug today because my configuration was decreasing whenever he wanted to specify a value below 5%. I know that I can just round my number before casting it as int to fix my problem, but I don't understand why this problem occurs.
I have a app.config file with the value "0.04" and a configuration section with a float property. When the section is read, the float value retrieved is 0.04, which is fine. I want to put this value in a windows forms TrackBar which accept an integer value so I multiply my value by 100 and a cast it as int. For some reason, the result is not 4, but it's 3. You can test it like this :
Console.WriteLine((int)(float.Parse("0.04", System.Globalization.CultureInfo.InvariantCulture) * 100)); // 3

What happened?
Comment: Read "What Every Computer Scientist Should Know About Floating-Point Arithmetic".
Answer: It's because 0.04 can't be exactly represented as a float - and neither can the result of multiplying it by 100. The result is very slightly less than 4, so the cast to int truncates it.
Basically, if you want to use numbers represented accurately in decimal, you should use the decimal type instead of float or double. See my articles on decimal floating point and binary floating point for more information.
EDIT: There's something more interesting going on here, actually... in particular, if you assign the result to a local variable first, that changes the result:
using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        // Assign first, then multiply and assign back, then print
        float f = Foo();
        f *= 100;
        Console.WriteLine((int) f); // Prints 4

        // Assign once, then multiply within the expression...
        f = Foo();
        Console.WriteLine((int) (f * 100)); // Prints 4

        Console.WriteLine((int) (Foo() * 100)); // Prints 3
    }

    // No need to do parsing here. We just need to get the results from a method
    static float Foo()
    {
        return 0.04f;
    }
}

I'm not sure exactly what's going on here, but the exact value of 0.04f is:
0.039999999105930328369140625

... so it does make sense for it not to print 4, potentially.
I can force the result of 3 if the multiplication by 100 is performed with double arithmetic instead of float:
f = Foo();
Console.WriteLine((int) ((double)f * 100)); // Prints 3

... but it's not clear to me why that's happening in the original version, given that float.Parse returns float, not double. At a guess, the result remains in registers and the subsequent multiplication is performed using double arithmetic (which is valid according to the spec) but it's certainly a surprising difference.
Comment: Yes Jon, we know, your [ponies](http://msmvps.com/blogs/jon_skeet/archive/2009/11/02/omg-ponies-aka-humanity-epic-fail.aspx) again ... ;)
Comment: "here's something more interesting going on here, actually... still investigating..." hm? I see nothing special here. `f*100` is `4-8,940697E-08` on my system, and gets displayed as `4` because the default `ToString()` conversion neglects the least significant digits. And the rounding errors don't cancel out, because some intermediate results are kept as double/extended.
Comment: Intermediate results can be kept at a higher precision than the static type. AFAIK assigning to a local variable may or may not change that. Explicitly casting to `float` (even if the type is already `float`) on the other hand guarantees degradation of the value to what `float` can represent.
Comment: @CodeInChaos: Yes... I believe the results will depend on CLR version and CPU architecture.
Comment: @CodeInChaos assigning to a local variable *does* change that because it causes the compiler to issue an instruction truncating the value to the exact precision of `float`.
Answer: This happens because the float value is really more like 0.039999999999; you are therefore converting a value like 3.99999999999 to int, which yields 3.
You can solve the problem by rounding:
Console.WriteLine((int)Math.Round(float.Parse("0.04", System.Globalization.CultureInfo.InvariantCulture) * 100));

Answer: It's actually not 4 but 3,99999 and lots of other numbers. Do something like this:
(int)(float.Parse("0.04") * 100.0 + 0.5)

Casting to float is like a floor operator and as this is not exactly 4 it is truncated to 3.
Comment: To add to this, if you need precision and you know it is only 2 decimal places, use the decimal type.
Answer: As a float 0.04*100 might well be represented as 3.9999999999, and casting to an int just truncates it, so that is why yo are seeing 3


Forward-sync to HDFS? (OR continue an incomplete hdfs upload?)

Question: Anyone have a good suggestion for doing a forward sync to HDFS? ("forward-sync" in contrast to "bi-directional sync")
Basically I have a large number of files I want to put into the HDFS. Its so large that I'll often, say, lose connectivity before it is finished. What I would like to do is just do a "resume" of my file upload. However hadoop fs -put will just upload the whole directory again  (or complain if it exists).
Anyone have a good way to continue an incomplete hdfs upload?
Answer: If you're running a new enough Hadoop, you could mount hdfs using FUSE and just use rsync.
Might also be possible to build a local-only hdfs and then use distcp.


Rewrite rule in apache httpd-ssl.conf

Question: I want to redirect user in following way.
This is part of my snippet from -ssl.conf
<virtualhost>
 RewriteEngine on

 RewriteRule ^/login.html? /

</virtualhost>

If the user makes request to https://mysite.com/login.html , I want to direct them to https://mysite.com/
Either I get a race condition or a 404 with apache log stating
Name-based SSL virtual hosts only work for clients with TLS server name indication support  apache 2.4
Comment: What's Apache logging when it sends the 404 response?  Do you want to redirect the user, as in, change the address in their location bar?
Comment: Posted the info from the apache log file. I could go either way as far as changing the url in address bar
Comment: What type of OS/Distro/browser are you using? Note: SNI wouldn't work on windows XP
Comment: Apache24/windows/chrome
Answer: There ought to be some "file does not exist" warnings in the logs as well, but no matter.
Try adding a redirect to your rule:
RewriteRule ^/login\.html? / [R=301]

If that doesn't work, then it's likely a problem with virtual host mapping as the log entry is alluding to; provide the output from apachectl -S?

Rewrite rule in apache httpd-ssl.conf


Ataque DDOS servidor

Question: Olá,
Tenho um servidor que está sofrendo ataque DOS, eu usei o comando:
watch -n1 'attackers'

no SSH para ver os ataques. Basicamente tem UM ip que faz umas 380 conexões, e faz o servidor cair em poucos minutos.
Eu bloqueio o IP pelo FireWall, mas passa 30 minutos e o rapaz engraçadinho muda de IP e faz o processo de novo.
Faz 5 dias que isso está acontecendo, e a equipe de suporte da Host não consegue dar um JEITO.
Coloquei os sites do meu servidor na CloudFlare, mas nem assim parou. Me falaram que é um DDOS Layer 7..
A cada vez que entro no suporte, me passam um jeito diferente ou que precisam de tempo para fazer algo lá.
Alguém já passou por isto e quer sugestionar alguma possivel solução? Estou cogitando é mudar de HOST.. Mas se eu conseguir fazer algo, melhor e evita menos transtornos.
Servidor é LINUX.
E a empresa que trabalho é a HostGator.
Dedicado Pro.
Comment: Sim, e existem várias formas de se proteger. Uma delas é configurando o AWS WAF no CloudFront. Isso é uma coisa que também preciso fazer num site aqui....to estudando. Mas tb é possível fazer via aplicação um controle de requisições.
Comment: perdão, pensei que Cloudfare era da Amazon....vc esta num ambiente que nao conheço
Comment: maneira rápida de resolver, desenvolva um script em shell, que conte a quantidade de IP's da mesma origem fazendo tentativas de acesso, para os ips com grande número de tentativas aplique uma regra de drop com iptables, coloque seu script no crontab para rodar a cada 1 minuto...
Comment: instale e configure o fail2ban que tbm vai te ajudar
Comment: Certo amigo. Obrigado de qualquer forma pela tentativa.
Comment: qual servidor http vc está usando? Apache?
Comment: Sim! É um plano Dedicado Pro da HostGator, inclusive bem carinho para o serviço.. Esperava um suporte melhor pelo preço. Eles atendem bem, mas é que demorar 5 dias para resolver um problema de DDOS que acredito que até um criança de 8 anos aprende e faz é complicado, ainda mais que é na Camada 7, que acredito que seja requisições no servidor que estão deixando a CPU 100% e fazendo cair..
Comment: Olá, @ederwander , se precisar eu faço isso também. Vou fazer o que o amigo Karl recomendou, ai eu consigo mensurar o que surtiu efeito, certo? Obrigado também. E pelo visto já vão fechar meu tópico. :(, faz parte.
Answer: A solução também depende da sua versão de Apache e do Linux, vou colocar a solução com o mod_evasive do Apache2.
Primeiro instale o mod_evasive
sudo apt-get -y install libapache2-mod-evasive

Crie o arquivo de log:
sudo mkdir -p /var/log/apache2/evasive

De as permissões pro arquivo:
sudo chown -R www-data:root /var/log/apache2/evasive

Altere o arquivo /etc/apache2/mods-available/mod-evasive.load
DOSHashTableSize 2048
DOSPageCount 20  # maximum number of requests for the same page
DOSSiteCount 300  # total number of requests for any object by the same client IP on the same listener
DOSPageInterval 1.0 # interval for the page count threshold
DOSSiteInterval 1.0  # interval for the site count threshold
DOSBlockingPeriod 10.0 # time that a client IP will be blocked for
DOSLogDir

DOSPageCount Irá definir quantos requests o usuário pode fazer para a mesma página
DOSSiteCount Irá definir quantos requests um mesmo ip poderá fazer para o site
DOSPageInterval e DOSSiteInterval é o intervalo de tempo em segundos para esta contagem acima
DOSBlockingPeriod é o tempo em que ficará bloqueado em segundos
Reinicie o Apache:
sudo service apache2 restart

Cuidado que dependendo da métrica que você colocar ele pode barrar usuários humanos.
Comment: Claro! Fez certo...estranho...acho q é um RedHat ele tem q ter algum gerenciador de pacotes, apt-get, yum, rpm
Comment: Karl, vou pedir para implementar este serviço, e volto aqui para dar um feedback. Obrigado pela resposta. :)
Comment: Vc não tem acesso ao servidor via ssh? Pq dai da pra vc mesmo implementar e nao fica dependendo deles.
Comment: Tentei fazer via SSH, mas deu um aviso: sudo: apt-get: command not found. Acredito que esse tal de "apt-get" não esteja disponivel para uso.
Comment: Digita isso `uname -a` no terminal e veja qual linux vc está usando. Coloca o resultado aqui.
Comment: Linux yyy.xxx.com 2.6.32-696.20.1.el6.x86_64 #1 SMP Fri Jan 26 17:51:45 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux - Só ocultei o servidor ali, to receoso já com esses engraçadinhos atacantes.. rsrs
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/73968/discussion-between-karl-zillner-and-alexandre-c-caus).

Ataque DDOS servidor


How to create a vocal line

Question: I have been singing since I was three years old and since then I cannot recall a single day I have not sung at least a few minutes. I have also learned the guitar (classical 3 + electric 12 years), bass (5 years), piano (3 years) and drums (3 years).
I have sung in quartets and choirs and solo everything from classical through opera and musical to swing, pop and rock. I have even been awarded some prizes for it ( - even though uncomfortable mentioning that, I do so to show that it is not just me thinking my singing is okay).
Now here's what has bothered me for years now: All I have ever done in that area has been reproduction, singing along preexisting vocal lines or notes or recordings or my ear and so on.
A few years back on a quiet day in the studio when I was thinking about that I sat down at the piano and recorded a simple "backing track", a few chords in a single key, and tried creating a new vocal line and failed miserably. Without the orientation I was so used to I could not find a note that sounded "right" to me apart the base note. My voice was swaying up and down looking for that hold I usually have with thar orientation note in my head.
Now for the question I have been thinking about asking for months: While I am aware I may just not have any talent for that, what are good ways to create a vocal line, how can I be more confident in finding notes when your ears and brain is highly accustomed to having a firm orientation?
Thank you
Edit: Thank you for your great and constructive answers. So much in fact I am hard pressed to pick which to accept
Comment: You probably don't remember when you started singing but think about your first day on the drums. You weren't that good, were you? Now your first time creating a melody didn't go so well, but why should it have? But you kept playing drums and now after three years you can play pretty well and if you keep practicing you'll be amazing after ten years, right? So practice inventing vocal melodies every day. Maybe start with one every day. Three years from now, you'll probably be happy. At this rate in ten years you might have a Grammy!
Comment: Are there any special techniques, maybe making use of the piano? Creating the line in key with the piano and then singing past it or is it more something coming naturally? How do songwriters do it?
Comment: I would try learning to improvise solos on guitar and also improvise wordless solo vocal melodies. Learning to improvise is a very important and useful musical skill that you'll want to have no matter what. It also helps with the brainstorming part of the creative process.
Answer: Some folks just have an ear for what to sing over a chord progression.  But if your ear is failing you - I offer a formula below that you can use - even if you are unable to pick the notes intuitively.
Creating a vocal line is pretty much the same as creating a melody line and can be done with the aid of any one of the instruments you play. You might want to start by using an instrument to play the melody notes as you derive them from the methodology outlined below -  and write them down and then you will be able to play the melody and sing the melody notes that you played.
Here is a simple formula that will enable you to write a melody that works for any chord progression you create or use.
Start by limiting the notes you use to the notes that are in the key of your song.  That is not mandatory, but will always keep you in safe territory.  This would limit your note choices to 7 notes but any of those could span one or more octaves.
Next (as you have mentioned that you have done) create your chord progression in the key you are composing in.  Then for the melody notes that are sung or played over a particular chord, start with one of the 3 or four chord tones (notes used to form the chord) for that chord.  The first note sung on a chord change does not have to be (but can be) the root note of the chord, but you will find that most melody lines will have a chord tone as the first note sung over a new chord at (or right after) the chord change. This is not an absolute rule, but will serve you well as a guideline.
Any of the chord tones will go with the chord but to give your melody more interest, you can add a few other notes to sing over the chord. To be safe, try to make most of the notes (maybe at least every other note) sung over a particular chord one of the chord tones.
One way to narrow your choices for notes to sing over a chord that are not one of the chord tones - is to choose notes from the key that corresponds to the chord but that also fall within the key of your song.
So for example if we are composing in the key of C major our major chords are C, F and G.  When playing over a C chord we would choose one of the chord tones as the first note sung over that measure of C (C, E, or G) and the non chord tone notes we sprinkle in could be any note in the key of C which is any of the 7 notes we already narrowed it down to in step one.
Let's say the next chord in our progression is F.  The same principle will apply for using one of the 3 notes in the F major triad (chord) as our first note in this measure. That gives us a choice of F, A and C. The same guideline applies to make most of the notes in that measure either an F, A or C (any octave).
The other notes available will be derived from a combination of the F major scale and the C major scale. We want to choose from notes that are common to both scales. We want to keep our notes within the C major scale because our song is in the key of C and if we are singing or playing melody notes over an F chord, they will sound better if they are in the key of F.
The notes in C major are C,D,E,F,G,A,B. The notes in F major are F,G,A,Bb,C,D,E. So the notes we should not use while playing the F major chord is Bb because it is not in the key of C and B because it is not in the key of F major. This leaves the notes common to both the C major scale (key of our song) and the F major scale (the chord we are now playing) which would be F,G,A,C,D and E.
The same logic will apply to the other chord sequences. Again, first note played after the chord change should be one of the notes that form the chord. If it's a four note chord (7th, augmented, etc.) you can use any of the four notes and often the note that makes it something other than a triad will be suggested strongly as a melody note or two while playing that chord.
If you must use a formula, a safe bet is to choose the notes that are common to the chord being played AND the key of the song. In other words choose from the list of notes that are common to both of these two scales. There are exceptions that will work in some circumstances, but this will keep you in safe territory.
For the minor chords, choose notes from the minor scale corresponding to the chord and use the process describe above to boil it down to the notes common to both the key of the song and the key suggested by the chord.
To summarize (TLDR)- the chord being played in a particular measure will give you a basic framework for notes to sing with that chord. That framework is supported primarily by the chord tones of the relevant chord and can be decorated by a few other notes common to the key corresponding to the chord and the key of your song.
Hope this helps.
Comment: In addition to this answer I wish to add: Don't build borders and instead experiment a lot. Try building a melidy first and tgen the chord progression. Don't just try a 4/4 time signature, go for 3/4 or 6/4, 7/4, 5/4 or any other. Try to singing in different durations not just simple ones but triplets and dotted notes and combine them. Try playing in different scales and switch them. Say you play a melidic minor and then go for a dorian scale and then to a blues minor pentatonic.
Comment: @SovereignSun  You make some excellent points.  Perhaps you could add an answer to this question on Stack Exchange Music (http://music.stackexchange.com/q/30210/16897)
Answer: I'm no composer, but I think I have an idea as to how to help with 'finding a grip'. Start by taking a song you like and can sing well. The first time, go for an easy song with no more than two parts. Now, change some notes (pitch and rhythm) - it doesn't have to be a lot for the first time, but try to go for at least one note per measure.  Play it on the piano (or any other instrument where your mouth can stay open) and sing along with it. If it sounds good- perfect! Change some more notes, eventually trying to get away from the original as far as possible. If some intervals don't sound good or hurt the ear, try to find a note somewhere near that sounds better.
Another way to start is more fun, I believe, but you need to already be more or less musically 'independent'. Play three-five random notes. Think about how they sound- is this a march of an army going into battle, a couple in love singing to each other, or a lullaby? It's better if you already have the words for this method, because then it's easier to eliminate some choices right away. Once you find a good combination, play a few more random notes and attach them to your first pack. Listen to see if they sound good together and whether this melody carries the meaning you're trying to achieve. Continue until you have a phrase. Then, sing it while playing it and see how you like it. If you do, keep going like this until you finish the whole song. If you don't, change something until you do.
Remember, it all comes down to practice. The more you try this, the easier it will be. Good luck and have fun!
Answer: you should sing what you think sounds good, music is not robotics or a food production, not a heavy lifting or a military operation, if you   feel it is a good music and it makes you high and feverish 100% someone in the world will appreciate your efforts and passion. Otherwise you should read scores from a songbook of your chosen style and you`ll see that notes usually in consonance with chords, in a third or an octave higher/lower, however music can be dissonant and unpredictable in lines and chords.
Answer: While not being a very good singer myself I can tell this:
I've been making different arrangements and composing a lot, especially solos for voice, keyboard, guirar, sax, flutes and etc. The hardest thing is to come up with the main melody. You have to try different ways, test different intervals and even sometimes throw it all away to start all anew. Come up with a simple melody, just sing and record. Once you have that write it down. After that you might want to try singing to a chord progression to establish an interesting harmony. Just improvise, keep testing different chords. Once you have that record it and write down. Try removing the vocal line and think up another one and another, write them all down. Thys you'll have a variety of choices. After that you can blend them together to see which phrase is good to your ear or sounds interesting. Often after that I start composing back vocals that might either mix with the lead vocals or be a really separate part. Arranging this way gives a variety of choices from which you can build up a good and interesting song. Sometimes I change some chords according to the back vocals that don't go too well with the lead vocals creating a very interesting harmony in result. It also depends on what you wish to get in result.
A good way of making up an interesting vocal line is too record multiple takes, take the best sounding parts or change some that seem right and blend them all together
Sometimes I make up vocal lines. or solo lines on the piano instead of singing. Not always do I have a text at hand to start.
For instance: I take an F chord (F,A,C) and start the melody not in any of those notes but in, let's say, E or G or even D and start experimenting. Perhaps the next chord I take is Am (A, C, E) then while most would fall on any of those three notes upon hitting the chord I try a G, D, F, A# and see how interesting that sounds. If I wanted I might play an A,C,G chord and play an E in the melidy to make it an Am7 chord. There is also a good way of changing chords while keeping the same note in the melody. First you start with C (C,E,G) and sing B and then while still singing B you try Bm or Am or G or D or A or F or Em and see how everything changes.
Comment: This is a very interesting approach. Trial and error is very time consuming.
Answer: Good comments by every body. How ever, I think I find it very easy. Mine is talent. But I also learnt.
There are two ways of composing for me.
1). Tune before the lyrics. Just like you said you came up with a backing track, one of the persons who commented said you could solo with the guitar. Just keep playing it over and over you would see that with time, you would keep repeating some lines, write down the notes for each progression until your satisfied. When u finally get the lines right, try to introduce some lyrics, ensuring that your notes does not change the meaning of the words (I.e emphatic stress).
2) second method is to write down your lyrics as it best expresses the message you want to pass. Once ur done, pick up you guitar or go to the keyboard, try to put some notes to the lyrics. It might be embarrassing at first, but keep at it.
    Finally, analyse some of the best songs you've heard. See how they were composed. It would help teach you how to go about it.
I hope this helps?

How to create a vocal line


A counterexample for which the diagonal matrix of a symmetric matrix is not unique

Question: Consider the symmetric matrix $ A=\left[\begin{matrix} 1 & -1 & 3\\ -1 & 2 & 1 \\ 3 & 1 & 1   \end {matrix}\right]$.
Since it is symmetric, there exists an orthogonal matrix $P$ and $D_1$=$\left[\begin{matrix} -\sqrt{6} & 0 & 0\\ 0 & 4 & 0 \\ 0 & 0 & \sqrt{6}   \end {matrix}\right]$ such that$$D_1=P^{-1}AP=P^{t}AP.$$
However, when consider the case when A is congruent to $D_2$, $D_2=\left[\begin{matrix} 1 & 0 & 0\\ 0 & 1 & 0 \\ 0 & 0 & -24   \end {matrix}\right]$, and $Q=\left[\begin{matrix} 1 & 1 & -7\\ 0 & 1 & -4 \\ 0 & 0 & 1 \end {matrix}\right]$ we have that $$A=Q^{t}D_2Q.$$
So, $D_1$ doesn't equal to $D_2$.

My question is what is the missing point so that this weird thing happened. Thank you!
Comment: $Q$ isn't orthogonal.
Answer: Congruency is different from similarity in that the former does not preserve the eigenvalues, but it does preserves the sign of them.
Example:
$$
\begin{bmatrix}
1 & 0 \\ 0 & 2
\end{bmatrix}, \quad
\begin{bmatrix}
1 & 0 \\ 0 & 1
\end{bmatrix}
$$
you could clearly give a congruence between these matrices.
Comment: @Ivy Glad to help you here!
Comment: I got it. Thank you very much!


definition of generalized eigenspace

Question: If $G_\lambda$ is the generalized eigenspace corresponding to the eigenvalue $\lambda$, and $E_\lambda$, the eigenspace, then why is both of the following true?

$G_\lambda = \ker(T-\lambda I)^{\dim V}$
$G_\lambda = \ker(T-\lambda I)^m$

Where $m$ is the algebraic multiplicity? $\dim V$ is not necessarily equal to the algebraic multiplicity an eigenvalue?
This is really confusing since Axler's Linear Algebra Done Right book on pg. 255 defines the algebraic multiplicity $m = \dim(G_\lambda) = \dim(\ker(T-\lambda I)^{\dim V})$. On the other hand, Friedberg's Linear Algebra on pg. 486 theorem 7.2 defines $G_\lambda$ as in $2.$
Am I missing something? I know that dimension of kernel of any power of $T$ is at most $\dim V$. I may have gone as far as thinking it has something to do with the restriction of $T$ to $G_\lambda$.
Comment: Turns out that anything that lies in $\mathrm{ker}(T-\lambda I)^k$ for *some* $k$, will necessarily lie in $\mathrm{ker}(T-\lambda I)^m$ where $m$ is the algebraic multiplicity. In general $\dim(V)\geq m$, but $\ker(T-\lambda I)^m=\ker(T-\lambda I)^{m+r}$ for any $r\geq 0$. $\dim V$ is often used because that is the smallest number that is sure to work in any instance for any eigenvalue.
Answer: Both 1 and 2 in the original question are true, and the two definitions of the generalized eigenspaces given by 1 and 2 lead to the same subspace. The two definitions arise from the two different approaches taken by the two books mentioned in the question.
Suppose $T$ is a linear operator on a finite-dimensional vector space $V$. In Linear Algebra Done Right, the generalized eigenspace $G_\lambda$ corresponding to an eigenvalue $\lambda$ is defined to be the set of vectors $v \in V$ such that $(T - \lambda I)^j v= 0$ for some positive integer $j$. The (algebraic) multiplicity of $\lambda$ as an eigenvalue of $T$ is then defined to be $\dim G_\lambda$. This definition is equivalent to the usual definition but it is much more geometric, defining the (algebraic) multiplicity as the dimension of a natural subspace instead of defining the (algebraic) multiplicity to be the multiplicity of $\lambda$ as the root of a mysterious polynomial.

definition of generalized eigenspace


React Native with Redux Action not passing data to reducer

Question: I have a problem in which action is not passing data to the reducer.
I re-render by change any things use hot reloading. it is receive data and try again to reload all the app. the same issue.
Reducer file
const initialState = {
  categories: null,
  error: '',
  isLoading: false,
};

const CategoriesReducer = (state = initialState, action) => {
  console.log(state.categories);
  switch (action.type) {
    case CATEGORIES_STATE:
      return {
        ...state,
        isLoading: true,
      };
    case CATEGORIES_SUCCESS:
      return {
        ...state,
        categories: action.payload,
        isLoading: false,
      };
    case CATEGORIES_FAILED:
      return {
        ...state,
        error: action.error,
        isLoading: false,
      };
    default:
      return state;
  }
};

export default CategoriesReducer;

Action file
I use Axios for fetch data and redux-thunk
const onCategoriesActionState = () => {
  return {
    type: CATEGORIES_STATE,
  };
};

const onCategoriesActionSuccess = (data) => {
  return {
    type: CATEGORIES_SUCCESS,
    payload: data,
  };
};

const onCategoriesActionFailed = (error) => {
  return {
    type: CATEGORIES_FAILED,
    error,
  };
};

const CategoriesAction = () => {
  return async (dispatch) => {
    dispatch(onCategoriesActionState());
    try {
      const { data } = await axios.get(`${Api}categories`);
      dispatch(onCategoriesActionSuccess(data));
    } catch (error) {
      dispatch(onCategoriesActionFailed(error));
    }
  };
};

export default CategoriesAction;

Call in Screen
useFocusEffect(
  React.useCallback(() => {
    if (categoriesReducer !== null) {
      setCategories(categoriesReducer);
    }
  }, [])
);
React.useEffect(() => {
  categoriesAction();
}, []);

anyone to help me to find where is the problem in my code
Comment: Have you debugged or used browser networking output tools?  For instance to see what (if anything) is coming back at: `const {data} = await axios.get(`${Api}categories`);`
Comment: Response data from API
Comment: Maybe check to see if `const {data} = await axios.get(${Api}categories)` should be `const data = await axios.get(${Api}categories)`
Comment: If I use it. I will use await two times like : const data = await axios.get(${Api}categories); const result = await data.data
Comment: I wouldn't think you would need to use await 2x.  const data = await axios.get(); const result = data.data;  Besides, using data as a const here is confusing.  I'd do const response = await axios.get();  const categories = response.data ?? {};
Comment: The same problems not passing
Comment: But if I change any thing in screen . The data is passing
Comment: Hmm, also React documentation says that useFocusEffect is analogous to useEffect hook, so I'm not sure why you have useEffect nested within the useFocusEffect, this doesn't look right to me.  Additionally, the effect will run whenever the dependencies passed to React.useCallback change, i.e. it'll run on initial render (if the screen is focused) as well as on subsequent renders if the dependencies have changed. If you don't wrap your effect in React.useCallback, the effect will run every render if the screen is focused.  https://reactnavigation.org/docs/use-focus-effect/
Answer: You are creating a redux action with side effects, in order to run that you'll need to dispatch it from your component

First get the dispatch object from your props or use the dispatch hook then
dispatch your action.
Without dispatching your action from your component Redux has no way
to find out about your action or event therefore without wrapping
your action inside dispatch function you are only calling a simple
function.
NOTE: to dispatch async action and side effects you'll need to use Thunk or
Saga middleware

useEffect(() => {
  dispatch(categoriesAction());
}, []);

Comment: I use thunk. data is not a problem. I have problem in useEffect did not re-render state.
Comment: I know you forgot to call dispatch on useEffect
instead of calling categoriesAction(); call dispatch(categoriesAction()) inside useEffect
Comment: I use connect bottom in my file: const mapStateToProps = (state) =>
{
    return {
        productsReducer: state.productsReducer.products,
        isLoading: state.productsReducer.isLoading,
        categoriesReducer: state.categoriesReducer.categories,
        isLoadingCategories: state.categoriesReducer.isLoading,
    }
};
const mapDispatchToProps = (dispatch) =>
{
    return {
        productsAction: () => dispatch(ProductsAction()),
        categoriesAction: () => dispatch(CategoriesAction()),
    }
}
Comment: You can see my code for this screen by this link: https://snack.expo.dev/@younisabuzayed/069eed
Comment: Thanks for response. I solved problem: useFocusEffect(
  React.useCallback(() => {
    if (categoriesReducer !== null) {
      setCategories(categoriesReducer);
    }
  }, [categoriesReducer, categories]);
Comment: Glad to hear that, Thanks


Is the uniform continuity condition required in the following question?

Question: Let $f$ be a uniformly continuous real function on a bounded subset $E$ of $R$. We have to show f is bounded on $E$.
My proof:  Now $diam(E)=diam(cl(E))$, and $cl(E)$ is closed, so $E$ is compact. Since $f$ is uniformly continuous( therefore continuous) $f(cl(E))$ is compact and therefore bounded. Since $E$ is contained in its closure, so is it's image. So f is bounded on $E$.
Now what I don't understand is that why do we need the uniform continuity condition? I request anyone  to shed some light on this matter.
Comment: $f$ is defined on $E$, not on the closure of $E$.
Comment: If $f$ were defined (and continuous) on the closure of $E$, then it would be uniformly continuous to begin with, by the way.
Comment: It's a rudin problem btw.
Comment: $E$ itself need not be closed (and therefore $E$ need not be compact).
Comment: Uniform continuity is even necessary, as @G.Sassatelli remarked.
Comment: $f(x) = \frac{1}{x}$ is continuous (not uniformly) on $E= (0,1)$ which is bounded. $f[E]$ is not.
Answer: Note that in your proof idea, $f$ need not be already defined on $\operatorname{cl}(E)$ at all. Something extra beyond continuity is of course needed for $f$ as $f(x) = \frac{1}{x}$ is continuous (not uniformly) on $E= (0,1)$ which is bounded, while $f$ is certainly not bounded on $E$, and not definable on $\operatorname{cl}(E)$.
Suppose that $f[E]$ were unbounded, then we can find points $x_n \in E$ such that $|f(x_n)| > n$ for all $n$. As $\operatorname{cl}(E)$ is closed and bounded, and hence compact, there is some $p \in \operatorname{cl}(E)$ and a subsequence $(x_{n_k})_k \to p$ ($k \to \infty$). The sequence $(x_{n_k})_k$ is Cauchy on $E$ (it's convergent in a larger subspace) and as $f$ is uniformly continuous on $E$ it's easy to check that $(f(x_{n_k})_k$ is Cauchy as well. But $|f(x_{n_k})| > n_k$ makes this impossible. Contradiction , and $f[E]$ is bounded.


Is this grouping with duplets correct for 6/4?

Question: Very sorry for bad photo quality, but I hope the notes are visible.
Here, have I done anything wrong with the grouping?!
Comment: Can you tell us what kind of rhythm is intended in the first measure? How many beats are the first two notes meant to occupy, and on (or during) which beat of the measure does the long note start? Otherwise, all we can say is "Yes, something is wrong in the first measure."
Comment: Is the first measure perhaps meant to be just like the second, but backwards, and with a rest taken out of the long note?
Answer: The second measure is fine, but the first one is wrong.  The general rule is that your notes should never cross the "major beats" of the bar.  In 6/4, the "major beats" are two dotted half notes, and so the double-dotted half note that crosses this boundary is needlessly confusing.
Instead, use ties to "restart" the note at the beginning of the second beat while indicating that it is to be held:
X:1
M:6/4
K:C
L:1/8
(2 FF z F2- F4- F z | F6 (2 F2 F2

The initial duplet in this version also has the advantage that it crosses two "minor" beats (the quarter-note subdivisions of the dotted half-note "major" beats.)  I would personally find the following easier to interpret:
X:1
M:6/4
K:C
L:1/8
F>F- F z F2- F4- F z | F6 (2 F2 F2

This is equivalent to the first version but also more clearly shows the subdivision of the first dotted half-note.  (The quarter-note duplet also obscures the subdivisions in the same way, but it is easier to interpret since it takes up the entirety of a "major" beat, so I'd be inclined to leave it as it is.)
Comment: I agree that the first measure is wrong, but I think the reconstructive surgery went awry. I'm guessing the OP simply intended ordinary 8th notes, and was mistakenly under the impression that the "2" marking was necessary. I'm guessing what was intended was two ordinary 8th notes (taking up beat 1), an 8th rest, and then a tied note occupying all the rest of the bar except for a final 8th rest. Without confirmation, impossible to say more than "Yes, something is wrong in that first measure."
Comment: @AndyBonner:  Fair point.  I assumed that since the given notes added up to the right amount of time, that the note lengths were written as intended.  But I suppose that it's possible that things went even more wrong than I assumed.  :-)
Comment: I came up with the same notation for the first measure as this answer. If the first two eighths are ordinary followed by eighth rest, double dotted half, then eighth rest... then there is one more eighth note value remaining.
Comment: For some reason when people add music notation in this way I sometimes get a very random series of beamed 8th notes followed by a dotted half which has nothing to do with the question. Any thoughts?
Comment: @JohnBelzaguy:  [It's a known bug in ABCjs on this site.](https://music.meta.stackexchange.com/questions/3737/abc-shows-up-scrambled-on-first-loading-correct-only-after-page-refresh)  It can often be cured by doing a "hard" reload of the page (shift-reload in your browser or something like that.)
Answer: I'm just adding some detail re. @MichaelSeifert's answer.
The first measure is confusing, but the values all add up to a full measure. But because the major beats aren't notated in the OP's example it's hard to read. Below is how I got the final notation step by step from two major dotted half note beats, to quarter note subdivision, eighth subdivision, ties, then finally the duplet on beat one.

At first all the ties may seem busy on the page, but the point is to visually show the major beats. If you think about beating time with your hand, visually showing the major beats helps you keep track of the down beats you are keeping with your hand.
Given the compound time signature, I would expect a duplet to apply to the groupings of three, for example...

...I don't mean that is the only way to use a duplet, but it's the basic example to demonstrate it.
But the duplet is only on the first beat and one half. Wouldn't it be easier to read with a simple tie?


My foot gets tired quickly when I tap it for rhythm - what to do?

Question: To keep playing in rhythm, I tap my right foot. However, it gets tired quickly (1 minute), and then I have to stop. I can continue playing without tapping, but tapping is important for me because I am working on improving my rhythm.
I play guitar using classical position, without a footstool, like described here.
What can I do?
Comment: I hope the guitar tag doesn't cause drummers to skip over this as I'm sure some of them would have good tips for foot stamina.
Answer: In addition to the other answers, I'd like to suggest the null method: don't tap anything.  Internalize the beat.  This doesn't work for everyone, but it works for me and many others.  Practice with a metronome by all means to make sure your internal beat is keeping on track, but don't feel obliged to make it physical.  It's worth a shot.
Answer: You are probably tapping one foot 4 times in a 4/4 bar. This can be slowed to twice, making the upward movement count as beats 2 and 4. Or, be like a drummer, and tap RLRL as on kick and hi-hat. Even further down the line, tap r for 1-2 and l for 3-4. Others use toes down for 1, heel up for 2, etc.
When playing in 3/4, you could alleviate the problem with R=1, L=2, nod=3.Often in any time sig, counting all beats is not necessary, so saying 1 at each bar's beginning is good enough.
If it could be another way, try counting out loud. You may already use a metronome, but if not, start. Now!
You can count on one of these ideas to work...
Answer: Honestly, I recommend that you nod your head for rhythm, this can help because you get constant strain in your tendons from bending your foot upward. This is because this is not a natural motion that the body can naturally do, you have to sort of force it to get your body to do it. Nodding your head is natural for the body and it is better for your body in general. Also try head banging sometimes if you like rocking out. Peace brother ✌✌✌
Answer: Tim offered some great suggestions.  In addition to following some of his advice, I might suggest some other possible solutions looking at the problem from more of a mechanics, muscle stress view.
First of all, if you are playing in classical position without a footstool, and you play typical right hand guitar, your guitar would rest on your right knee (in classical position) so you should be tapping your left foot (the one your guitar is NOT resting on).  It's not just the weight of the guitar but the position you must hold your leg in to keep the guitar balanced on your leg that might place additional stress on the muscles used to tap your toe.
Even if you are tapping the opposite foot from the one attached to the leg which supports the guitar, the seating position can play a big role in increasing or minimizing the fatigue induced by the movement of raising your toe or heel.
You will find it much less strenuous to lift your toe if your foot is placed out in front of your knee.  If your heel is directly under your knee or your leg is curled such that your heel is behind your knee (which might be the case if your guitar is on the foot tap leg), too much stress will be placed on the muscles used to raise your toe.  Experiment and you will see what I mean.
Also try altering your seating height which will change the geometry of your lower leg as it relates to the floor.  You will find that some seating heights (too high or too low) will place additional stress on the muscles used to raise your foot.  Experiment to find a balance between a comfortable position for your guitar and a position that minimizes the stress on the muscles used to lift your toe. You might find that wearing a strap even while seated will permit you to vary your seating position without relying solely on your leg to support the guitar.
Be sure your are low enough that your heel is firmly on the ground so that you can use your heel as a fulcrum.  It may also help some to try different type shoes to see if shoes with higher heels make it less or more stressful to lift your toe from your preferred seating position.
If you do prefer a seating position that places your toe under your knee, then you might find it easier to raise your heel rather than your toe.  Some positions may even allow for heel and toe to be raised alternately - as suggested in Tim's great answer.
Other methods of keeping time might include nodding your head to the beat or a rhythmic movement of your torso (like dancing while playing).  Remember, you don't need exaggerated movements, just a steady, continuous, evenly spaced movement that you can detect.
Keep experimenting with different positions and different ways to keep the beat while you play and eventually you will settle into something that is comfortable  and effective for you personally - that won't induce unnecessary muscle stress or fatigue. Good luck!


Does any standard Python3 object have a get method that doesn't have positional arguments?

Question: I am trying to figure out how to use a barely documented feature of a poorly documented API. I have distilled the chunk of code that is giving me trouble down to this for simplicity:
def build_custom_args(args):
    custom_args = {}
        for key in args:
            custom_args.update(key.get())
        print(custom_args)

I can tell from the function that constructs args that it is a list. Problem is, a list of what? No matter what I put in the list, key.get() raises one exception of another.
For example, if I execute that code like so: build_custom_args(['foo']) then I get an understandable error message: AttributeError: 'str' object has no attribute 'get'.
Or, try a dictionary: build_custom_args([{'foo': 'bar'}]), but the error is raised: TypeError: get expected at least 1 arguments, got 0.
As best I can tell args is a list of some standard python objects - there is no indication that these are special objects with a custom get() method.
Am I missing something obvious? Is there some standard python object that has a get() method which takes no positional arguments? Is this a syntax of some older version of Python? Or have I found a bug in the API?
Edit
The accepted answer shows that I was mistaken believing that args had to be a python built-in.
Jack's answer is worth a look because it actually does solve the problem "what Python built-in could args be that would cause this function to not throw an error?"
Comment: Python is duck typed, so there could be more than one type that implements a `.get`, talk less custom classes. You could start by telling what exactly the function is supposed to do, with the args
Comment: Are there any standard python types that have a `.get` method which takes no positional arguments?
Comment: Is this a Tkinter-based application, by any chance?  StringVar, IntVar, etc. have a zero-arg ``get()`` method.
Comment: I suppose there is no need for me to be cryptic about the API I'm looking at, I just wanted the answer to be more generally applicable than very specific. The API I am looking at is https://github.com/sendgrid/sendgrid-python. To answer your question specifically, no searching the repo for tkinter I don't see anything. The specific file I'm working on is https://github.com/sendgrid/sendgrid-python/blob/master/sendgrid/helpers/mail/mail.py at about line 70
Comment: You have a [`Header`](https://github.com/sendgrid/sendgrid-python/blob/master/sendgrid/helpers/mail/mail.py#L213) or [`CustomArg`](https://github.com/sendgrid/sendgrid-python/blob/master/sendgrid/helpers/mail/mail.py#L267) instance.
Answer: Well... I found this in the github link you have provided
class Email(object):
    # code...

    def get(self):

Matter of fact, a lot of those classes have get methods.
Since Python is duck typed, there isn't really a way to determine what object is correct, but you're just building a dictionary, so shouldn't matter too much
Comment: And I found this: class `CustomArg(object): ... return custom_arg`. I got so caught up thinking the custom_arg was a standard python type that when searches for custom_arg didn't turn anything up, I got completely side tracked going down this rabbit hole. Thanks, this clearly lead me to the right answer.
Answer: AFAIK the only class with a get method that can take zero arguments is a Queue.
Which in your example is probably a Queue of dicts
Comment: However, `Queue` is not a built-in, so OP should check the imports to see if `queue` module is imported.
Comment: `Queue` is part of Python, but you only need to import if you're creating a new `Queue`. The way the method is in the question would NOT require it to be imported in that file.
Comment: That said, I agree doing a grep for `queue` or `Queue` in the full project would almost certainly lead to if this is the correct answer or not...although if the method just _expects_ a `Queue` it would not require an import anywhere else.
Comment: Yeah, I did not mean "the imports of the file", but "the imports in the whole project".
Comment: Jack is certainly right, and +1 for actually answering the question that I asked and not digging into github to answer the question that I needed answering.


If E is a Hilbert space and $T \in B(E)$ is compact, show $T(E)$ does not contain a closed infinite dimensional subspace

Question: It's the problem from "Essential Results of Functional Analysis," R.J. Zimmer, Chapter 3, problem 3.1.
I try to prove this problem and I am confused with the condition "closed infinite dimensional." Consider a compact operator T, given by diagonal matrix $T_{ij} = \lambda_i\delta_{ij}$, with $\lambda_i \to 0$. Then for Hilbert space $E$, we have $T(E) = E$. That means $T(E)$ has a closed infinite dimensional subspace($E$ itself). Where did I go wrong?
Comment: You don't have $T(E) = E$ for such an operator. The $\lambda_i \to 0$ condition ensures that only sequences that converge fast enough to $0$ are in $T(E)$ (I'm identifying $E$ with $\ell^2$ here via ONB).
Comment: Thank you for the help, but I still cannot understand very clearly. For any $x \in E$, we can take an orthonormal basis $e_i$ of $E$ and express $x$ as $\Sigma a_i e_i$. Thus I can construct $y = \Sigma \frac{a_i}{\lambda_i} e_i$ and $Ty = x$?
Comment: $$\sum \left\lvert \frac{a_i}{\lambda_i}\right\rvert^2$$ will in general be $\infty$, so the "inverse image" of $x$ isn't in $E$. Expressed differently, the inverse $T^{-1} \colon T(E) \to E$ isn't a bounded  linear operator.
Comment: Oh, right! Thanks a lot, I think I got the idea.
Answer: Hint: For each closed subspace $F \subset E$, there is an orthogonal projection $P_F$ onto $F$. The composition $P_F \circ T$ is also compact. So if $T(E)$ contained a closed infinite-dimensional subspace $F$, we'd have a compact map onto an infinite-dimensional Hilbert space. Why can that not happen?
Comment: I tried to use the method as the following: The map $F \cap T : E \to F \cap T(E)$ is compact. Since $F$ is infinite dimensional, we have an orthonormal basis $\{T(x_i)\}_i$. It is clear that $\{T(x_i)\}_i$ has no converge subsequence. But I stucked since I don't know if $\{x_i\}_i$ is bounded.
Comment: Try with the other characterisation of compact maps (the definition, usually), $K$ is compact if (and only if) $\overline{K(U)}$ is compact ($U$ is the unit ball in the space).
Comment: Thank you so much, I know how to do now. One question remained is that how can I prove the $P_F \circ T$ is a compact map? I have a basic idea: since $\overline{T(E_1)}$ is compact, for any open covering on $\overline{P_F \circ T(E_1)}$, we will have a corresponding open covering on $\overline{T(E_1)}$. But I don't know how to construct such correspondence very clearly.
Comment: You generally have the fact that the composition of a compact operator with a continuous operator is compact. Let $K$ be compact and $S$ continuous. Since $S$ is continuous and $\overline{K(U)}$ compact, $S(\overline{K(U)})$ is compact, in particular closed. But then we have $\overline{S(K(U))} \subset S(\overline{K(U)})$, so that is compact too, hence $S\circ K$ is compact. Composing on the other side, $S(U)$ is contained in a multiple of the unit ball by continuity, so $\overline{K(S(U))} \subset \overline{K(c\cdot U)} = c\cdot\overline{K(U)}$ is compact.
Comment: I tried the statements as following: suppose $F$ is infinite-dim subspace of $T(E)$, let $T_F:T(E)\to F$ be the projection. $\overline{T_F(T(E)\cap T(E_1))}=F\cap\overline{T_F\circ T(E_1)}$ is compact. Since F is infinite-dim, $\exists \{f_i\}_i\subset F$ orthonormal basis. But I don't know how to prove $\{f_i\}_i\subset \overline{T_F\circ T(E_1)}$. Maybe I got something wrong again?
Comment: By the open mapping theorem, $P_F(T(E_1))$ (if I haven't misunderstood, you denote the unit ball by $E_1$?) is a neighbourhood of $0$ in $F$. By compactness of $T$, it is relatively compact. So together that says $F$ is a locally compact space. But only finite-dimensional spaces are locally compact.
Comment: Thanks for your help, I've got the solution:)


Nginx + php-fpm VS Nginx as a reverse proxy for Apache

Question: Can someone enlighten me whats the advantage of having NginX as a reverse proxy to Apache. People suggest it so that static content is handled by nginx and dynamic content (php files) are handed over to Apache.

Wouldn't directly letting php-fcgi/php-fpm handle those PHP files a lot more reasonable than letting Apache's mod_php handle it?
What are the advantages (performance wise)
If I choose to reverse proxy, would I need to do a nginx rewrite or would the .htaccess from apache work as it is? (because its reverse proxied, so the calls are directed to apache right?)

TY in advance
Answer: Reverse proxying is slower and generally worse, however, some reasons to use it is to maintain (some) compatibility with .htaccess files (which you would have to write (and that isn't always practical) is you use a pure nginx setup) or if you require specific apache modules. (Some may argue that is you have these requirements, it is easier to just use apache.)

PHP-FPM with nginx would be the preferred solution - you get the fast static file serving of nginx and good PHP performance without adding additional overhead, proxying, or the (typically) significant memory usage of apache.
nginx+PHP-FPM is (typically) faster and uses less memory. Nginx + Apache + FastCGI/FPM will still serve static files fast, but will have additional overhead on the dynamic files (not as bad as mod_php, but worse than if you eliminate apache).
You will need a bit of both - nginx would need to know how to deal with the paths (e.g. for serving static files, denying access to .htaccess, etc) and apache will need to know how to handle the files. In some cases, if your .htaccess file doesn't pertain to static files (so every request that needs rewriting is going to go to apache), then it may be acceptable to simply deny access to certain locations, and have apache do the rest via .htaccess - it doesn't seem ideal, will cost a bit in performance, and its reliability is questionable - but it could work on a simple setup).

If you can, go with the straight nginx+PHP-FPM setup. If you can't, while there may be some merits to reverse-proxying, think through the repercussions, especially if you are dependent on .htaccess files.
Comment: Thanks for the clear answer. I actually went with nginx+php-fpm+mysql way. I was just wondering about the advatages of reverse proxy, as I've heard it does some 'caching' too. (well if I would want caching, i'd go with varnish). A competitor of mine have setup a nginx server to serve static video files. The actual setup was nginx reverse proxy -> nginx server. I just don't get it why he even setup a nginx installation to proxy a nginx installation.
Comment: Nginx is a very versatile server - it certainly can do caching (and SSL termination, and even some rudimentary load balancing) however the limitation of caching is telling nginx when to expire the cache (typically adding versions to your files) - it doesn't have the same caching capabilities as varnish which can be triggered to clear the cache on application specific events.
Answer: I would say that it's the other way around: cutting Apache out of the mix will increase performance. You'd keep Apache around if you like some of the other modules Apache provides, or if you have some external reason to keep using Apache for your dynamic content.
It should be fine to let Apache handle the rewrites, so long as you don't do anything to accesses of your static content. But make sure to have an exclude for .ht* in your nginx conf: don't want to accidentally serve those particular static files out to the general public.
Comment: Hi, Yes thats what I was thinking. Leaving out apache out of the system is more reasonable than reverse proxying. I was just wondering about the advantages of reverse proxying to letting nginx handle it all. Or does it even have any advatanges? (other than apache modules that I would need)
Answer: I have recently move from Apache, to Nginx. While I do not claim to be an expert, I would recommend dropping Apache and using nginx with PHP-FPM, instead of reverse proxy. Using Nginx without Apache will give you a slight performance gain for non-static content and large performance gain for static content. Since Nginx does not use .htaccess files, this means you will have to configure Nginx to handle all your redirects ect. This may seem a little daunting at first, but once I learnt how to configure Nginx, I actually found it a lot simpler and easier than using .htaccess files. There are tools that automatically convert .htaccess rules to Nginx rules for you, but I would recommend learning to do it yourself instead. I found the tools did not convert accurately enough and used way too many if statements. See: If Is Evil.


How to get the Object based on File ID (FID)

Question: I'm inside mytheme_image_formatter($variables) function and I got the image's FID (from $fid = $variables['item']['fid']).
Question:
Is there a way to know which object is using the image file?
Using file_usage_list(file_load($fid)), I can see which objects may use the file. But I want to know which one is using the image file, inside my function.
Tried to use mytheme_preprocess_image(&$variables), but I also found the same situation.
This is the same problem as discussed here, without a solution.
Thanks
Comment: What I'm trying to do is to put an ALT text in all images of all site's pages. If there is no pre-defined ALT text, I want to inject the node's title in it.
Answer: You can use an EntityFieldQuery, e.g.
$field_name = 'field_something';
$fid = 123;

$query = new \EntityFieldQuery();
$query->entityCondition('node')
  ->propertyCondition('type', 'the_type')
  ->fieldCondition($field_name, 'fid', $fid);

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  // $nodes contains all nodes that reference the given file via field_something.
}

Comment: Thanks! But the problem with this approach is that $field_name is yet another information I want to know, because I don't have it. I just know what comes in $variables.
Comment: Those theme functions are re-usable so they can't rely on a node/field context (that's why they're not in the vars). You'll probably have to be a bit more specific, like implementing `hook_node_view()` and targeting the specific fields in `$node->content`, based on `$node->type`. You should be able to add an alt to the image field structure that way
Comment: You're right, this wasn't the best approach. I ended up taking another completely different way for getting my problem solved.


how to Find the period of complex exponential function?

Question: How we can find period of this sequence?
$x[n]= e^{jn2π/3}$
Is it equal to   $T=2π/(2π/3) $  or  not?
I mean relation $T=2π/\omega$   will be valid in this case or not?
Comment: thanks jose carlos
Answer: The sequence $x[n]=e^{jn2\pi/3}$ is actually a discrete complex exponential sequence. One thing to keep in mind is that the values of $n$ will always be an integer and never a fraction. To find the period of a discrete sequence we can use the fact that,
$$x[n+N]=x[n]$$
where $N \gt 0$, and the $N$ is the least positive integer for which the sequence repeats itself.
That is to say, since $x[n]$ is periodic with period $N$ it repeats itself after $N$ samples. And it is also periodic with the period $2N$,$3N$,$4N$, and so on so we choose the smallest possible positive integer $N$. So:
$$e^{j(n+N)2\pi/3}=e^{jn2\pi/3}$$
Solving you will get,$$e^{jN2\pi/3}=1$$
$$\cos(\frac{2N\pi}{3})+ j\sin(\frac{2N\pi}{3})=1+j0$$
$$\cos(\frac{2N\pi}{3}) =1=\cos 0,\cos2\pi,\cos4\pi...$$
Or,
$$\sin(\frac{2N\pi}{3}) =0=\sin 0,\sin2\pi,\sin4\pi...$$
Both are same. We will choose the value $2\pi$ because the period should be positive and least.
So,
$$\frac{2N\pi}{3}=2\pi$$
giving you $$N=3$$
So the period is $N$, now you can also see why the formula $$T=\frac{2\pi}{\omega}$$ actually works.Graphically this sequence can be plotted as a continuous sinusoid sampled at 1 second,  Hope this helps...
Answer: $e^{jn2\pi / 3} = cos(2n\pi/3) + i\cdot sin(2 n \pi/3)$ From there, it is easy to see that the period is $\frac{2 \pi}{2\pi/3} = 3$
Answer: Yes it is, as the complex exponent have the properties:
$$
e^{z_1+z_2}=e^{z_1}e^{z_2},\text{ and }e^{2\pi i}=1.
$$
Consider now the function:
$$
f(x)=e^{i2\pi\frac xT},
$$
where $T\in\mathbb R$.
Can you find the relation between $f(x)$ and $f(x+T)$? Can you link the result to your particular function?
PS. I have used $i$ for $\sqrt{-1}$.
Comment: e^2πi=1      i can't understand it ?and how it is applicabile to this question?
Comment: @student How do you understand $e^{ix}$  in general? $e^{z+2\pi i}=e^{z}e^{2\pi i}=e^{z}\cdot1=?$


How do you call a string that matches /^\w+$/?

Question: Strings that match /^\w+$/ are quite common. For example many authentication systems use that pattern to validate usernames. I'm wondering if a term exists that identifies this kind of strings.
I've been thinking of the term "alphanumeric" but is a string alphanumeric if it contains an underscore?
Answer: I do not think that it is a good idea to give it a potentially confusing name. Alphanumeric could be misunderstood. If you need to refer to it, for example in your documentation, define it with an unique name like 'username_pattern', and refer to that definition of yours whenever you talk about it.
Answer: From perldoc perlre:
'\w       Match a "word" character (alphanumeric plus "_")'.
I personally call it a "word".
Comment: That's an interesting suggestion but wouldn't it be confusing to call "123" a word?
Comment: If '123' is a username, for example, it's a word, even though it is made of numerals.
Answer: Personally, I'd call it "a string that matches <code>^\w+$</code>" if my audience knows what this means. That is probably the most succint "name" that doesn't significantly sacrifice accuracy. If I had to say it, I might call it "a non-empty string containing only word characters", but once again I need to assume that my listener(s) know the technical meaning of word character.
If you want to come up with an English name for it, you are necessarily going to sacrifice a lot of accuracy and end up with something much more vague than the hard and well-defined regular expression — especially if your audience is not technical and/or does not recognise the term as a technical term with this precise meaning.
Answer: I'm with hlynur, (some) POSIX character classes call this a word.
So it would be consistent to call this a word.
Comment: But then that would mean that you don't mind calling `123` a word.
Comment: Well, it _may_ be a word, then again it may be not. :-) What I tried to explain was: In another place there Is a name for this thing and it's a reasonable one -- why not use it?


How can I give a list_string BaseFieldDefinition in a content entity a default starting value?

Question: I have an entity with a list_string field in my content entity that outputs to the entity form as a list of checkboxes. IE:
<code>$fields['colors'] = BaseFieldDefinition::create("list_string")
  ->setSettings([
    'allowed_values' => ['blue' => 'Blue', 'red' => 'Red', 'green' => 'Green']
  ])
  ->setLabel('Color')
  ->setDescription('Select color')
  ->setRequired(TRUE)
  ->setCardinality(-1)
  ->setDisplayOptions('form', array(
    'type' => 'options_buttons',
    'weight' => 2,
  ))
  ->setDisplayConfigurable('form', TRUE);
</code>
Is there a way for me to give this field a default starting value. IE, when the user creates a new entity, red and green start out selected on the form?
Answer: You can use setDefaultValue method:
<code>BaseFieldDefinition::setDefaultValue([['value' => 'red'], ['value' => 'green']])
</code>
That will also work for entities not created in the UI.
Comment: Where can we see the documentation of all the setSettings options / methods for list_string BaseFieldDefinition?
Answer: From https://api.drupal.org/api/examples/content_entity_example%21src%21Entity%21Contact.php/function/Contact%3A%3AbaseFieldDefinitions/8.x-1.x
<code>// Role field for the contact.
  // The values shown in options are 'administrator' and 'user'.
  $fields['role'] = BaseFieldDefinition::create('list_string')
    ->setLabel(t('Role'))
    ->setDescription(t('The role of the Contact entity.'))
    ->setSettings([
    'allowed_values' => [
      'administrator' => 'administrator',
      'user' => 'user',
    ],
  ])
    ->setDefaultValue('user')
    ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => -2,
  ])
    ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => -2,
  ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);
</code>
Answer: I found that adding this to the entity form file did the trick:
<code>  public function buildForm(array $form, FormStateInterface $form_state) {
    /* @var $entity \Drupal\mymodule\Entity\MyEntity */
    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;

    if($entity->isNew())
    {
      $form['colors']['widget']['#default_value'] = ['red', 'green'];
    }
</code>


How many tennis players have announced retirement after winning Grand Slam?

Question: Flavia Pennetta has announced the retirement after winning her first Grand Slam of the career.
I guess she is the only tennis player who has taken retirement after winning major.
Can you remember any other player or star who took retirement after achieving such kind of milestone in his career or he/she took retirement when he was at the top in his/her career?
Answer: While he didn't announce it like Pennetta did - Pete Sampras decided to retire a few months after defeating Andre Agassi in the 2002 US Open Final for his final match as a pro. It was the same opponent in the same tournament where Sampras won his first major title too - against Agassi in 1990.
Marion Bartoli also retired from tennis very shortly after winning Wimbledon in 2013. She only competed in 3 matches after winning the Wimbledon title before announcing her retirement.


How to insert data from a list to SQLite3 Database

Question: This is a list below imported the data from qwidgets.
list = ['2020/02/21', 'name', 'location', 'item1', 'item2', 'item3', 'item4', 'item5']

or
list = ['2020/02/21', 'name', 'location', 'item1']

or
list = ['2020/02/21', 'name', 'location', 'item1', 'item2', 'item3']

How to insert this list data in to SQLite3 database. I am using below database structure.
conn = sqlite3.connect('test.db')
conn.execute("INSERT INTO \
    maintable(date,name,location,item1,item2,item3,item4,item5,item6, item7,item8, item9, item10) \
    VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')

Comment: Please read the docs of the sqlite API, you need a cursor from the connection, then you should fill the lists with empty items, so it has the same length on every insert. Then you need to access the list items on insert (with list[0], list[1] etc.). Also never name a variable `list` in python, because that will shadow the built-in function `list()`. Use `my_list`or something.
Answer: You should never build a request by adding parameter values into the query string. I used to be the vector for the old SQL injection attack that allowed an attacker to pass arbitrary SQL commands by simply forging a parameter value.
The recommended way is to used a parameterized query.
Here you should simply do:
conn.execute("INSERT INTO \
    maintable(date,name,location,item1,item2,item3,item4,item5,item6, item7,item8, item9, item10) \
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", lst + [None] * (13 - len(lst)))

BTW I renamed your list variable lst to avoid hiding the built-in list function.
Comment: I used the code but getting the error like this. TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
Comment: Oops... There was a typo in my code: the closing `]` was misplaced. Fixed.
Comment: I updated your code. Now TypeError: unsupported operand type(s) for +: 'type' and 'list'
Comment: There was a second typo: I renamed `list` to `lst` at only one place...
Answer: It's better and safer to use placeholders (?) wherever you want to use a value to protect against SQL injection attacks.
Since the size of the list can vary you need to build it dynamically. You can do that like this:
l = ['2020/02/21', 'name', 'location', 'item1', 'item2',...]
query = "INSERT INTO maintable(date,name,location"

for i in range(len(l) - 3):
    query += ',item{}'.format(i+1)

query += ") VALUES (?, ?, ?"

for i in range(len(l) - 3):
    query += ', ?'.format(i+1)
query += ')'

conn.execute(query, l)

Make sure you supply all the values for the placeholders and remember to commit and close the connection to save the changes:
conn.commit()
conn.close()

Comment: Showing the error: sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 13, and there are 5 supplied.
Comment: @user3030327 I don't think you have supplied all the parameter values. There should be 10 item values in the list after date, name and location. The number of ? and values have to match exactly.
Comment: If the list has 13 items  the code is  working. But i need some times the list has less than 13 items. so the error is coming.
Comment: @user3030327 So if the list has less than 13 items then do you want to leave it blank?
Comment: Yes. I want to leave them blank.
Comment: @user3030327 Try my updated answer. You have to build the query string dynamically depending on the size of the list.
Comment: Its also Working.
Comment: @user3030327 Good to hear that. Initially I didn't realise you were not writing to all item columns. I also like Serge Ballesta's answer.


Get blank value if field value is not available

Question: I have following query on my D7 project
$query = db_select('payment_logs', 'p');
$query->join('field_data_field_frequency', 'd', 'd.entity_id = p.nid');
$query->join('field_data_field_maid_id', 'm', 'm.entity_id = p.nid');
$query->join('field_data_field_coupon_code', 'c', 'c.entity_id = p.nid');
$query->join('field_data_field_tip_amount', 't', 't.entity_id = p.nid');
$query->fields('p');
$query->fields('d', array('field_frequency_tid'));
$query->fields('m', array('field_maid_id_uid'));
$query->fields('c', array('field_coupon_code_value'));
$query->fields('t', array('field_tip_amount_value'));
$query->condition('p.section','booking','=');
$result = $query->execute();
$res = $result->fetchAll();
return $res;

this query returns data where field_tip_amount_value and field_coupon_code_value are available. I want to get all data with blank field values if not available. these two fields are optional other fields will be there always. so if tip or coupon is not there data must return blank for this field.
I was doing it with separate queries before but it was taking too much time with multiple loops. is there a way to get it done with join ?
Answer: You can change $query->join to $query->leftjoin.
This will cause the query to return a row, even if there's no entry in the joined table.
Hope this helps.


Converter um objeto do tipo 'System.Collections.Generic.List no tipo 'System.Data.DataSet'?

Question:
Não é possível converter um objeto do tipo 'System.Collections.Generic.List no tipo 'System.Data.DataSet'?

Após fazer uma consulta de um relatório, estou guardando os dados em uma lista e mostrando os dados na tela, mais eu tenho uma opção de exportação dos dados para o Excel, então para não repetir a consulta estou guardando os dados em uma sessão.

Session:

repeater_teste.DataSource = retorno;
Session["Ultimo_Relatorio"] = retorno

Na opção de exportação estou fazendo desta forma (gerando erro):
 DataSet ds = (DataSet)Session["Ultimo_Relatorio"];
 DataGrid dg = new DataGrid();
 dg.AllowPaging = false;
 dg.DataSource = ds.Tables[0];
 dg.DataBind();

Eu encontrei este artigo que fala que era possível.
Comment: Dúvida: por que não simplesmente setar a lista como binding de um DataSet?
Comment: @jbueno, me mostre como, posta um exemplo por favor
Comment: Tá, lá. Bom proveito!
Comment: O artigo fala sobre armazenar o DS na session e não de cast de List para Dataset. Pela mensagem de erro parece que o problema é do cast. Complementa a pergunta com a parte do código que vc armazena o DS na session.
Comment: @Pagotti, pergunta ajustada. mais completa
Answer: Dica
Eu, sinceramente, não vejo um bom motivo para fazer isso. Isto é, é possível simplesmente fazer com que uma lista seja o binding de um DataGridView, então por que se dar o trabalho de fazer toda essa conversão?
Ex.:
dg.DataSource = minhaLista;

Resposta
De qualquer forma, aqui vai um código que faz exatamente o que você precisa
public static DataSet ToDataSet<T>(this IList<T> list)
{
    Type elementType = typeof(T);
    DataSet ds = new DataSet();
    DataTable t = new DataTable();
    ds.Tables.Add(t);

    // Adicionar uma coluna para propriedade pública em T
    foreach (var propInfo in elementType.GetProperties())
    {
        Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

        t.Columns.Add(propInfo.Name, ColType);
    }

    foreach (T item in list)
    {
        DataRow row = t.NewRow();

        foreach (var propInfo in elementType.GetProperties())
        {
            row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
        }

        t.Rows.Add(row);
    }

    return ds;
}

Comment: eu não conseguir usar o "DataSource" pede uma referência mais ela já existe  "using System.Data;"
Comment: @itasouza Jovem, eu dei uma confundida nos nomes. Veja a edição.
Comment: então. está resposta eu já tinha "dg.DataSource = minhaLista;" só que eu preciso fazer uma nova consulta apenas para exporta para o excel, eu queria usar o que já estava na memoria
Comment: Tudo bem, mas a minha resposta tem exatamente o que você pede no final. O início é apenas uma dica.
Comment: Mais eu vou ter que fazer uma nova consulta para ter "dg.DataSource = minhaLista;" ? ou dar para deixar uma variável publica ?
Comment: Não entendi o que você quis dizer @itasouza
Comment: Tenho uma consulta de dados que já me traz o retorno dos dados mostrado na tela para o usuário, estou guardando o retorno da consulta dos dados em uma Session, porque se o usuário clicar em exporta para excel, eu vou precisar fazer uma nova consulta dos dados, então no seu exemplo eu tenho que fazer novamente a consulta porque não vou conseguir usar o conteúdo que está na memoria. @jbueno


Adding localhost subdomains in apache virtual hosts

Question: I am trying to redirect all subdomains of hothouse to go to hothouse\testsite, but I cannot get it to work.
I dont understand the difference between DocumentRoot and VirtualDocumentRoot, not sure if that makes any difference.
Any ideas why it is not working 'testsite.hothouse' redirects fine. 'test.hothouse' or any subdomain.hothouse does not (redirects to 'www.subdomain.hothouse').
I have spent all day trying to work this out I have cleared all my browser caches. BTW I am using WAMP
<code>DocumentRoot "D:\wamp\www"
<Directory "D:\wamp\www">
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

<VirtualHost *:80>
DocumentRoot "D:\wamp\www"
ServerName localhost
</VirtualHost>

<VirtualHost *:80>
VirtualDocumentRoot "D:\wamp\www\hothouse\testsite"
ServerName testsite.hothouse
ServerAlias test.hothouse
</VirtualHost>

<VirtualHost *:80>
  VirtualDocumentRoot "D:\wamp\www\hothouse\testsite"
  ServerName subdomain.hothouse
  ServerAlias *.hothouse
</VirtualHost>
</code>
Comment: What version of Apache are you running?
Comment: OK I feel stupid, I needed to make the changes to my windows hosts file.
Answer: The issue was not the apache settings but I hadn't updated my windows host file to redirect to the localhost.


Drupal 7 Forum - Allow Users to 'hide' their online status

Question: I am desperately trying to find a way for my users to 'hide' their online status from other users. Currently all users online are displayed in the drupal 'who's online' box.
Ideally I would look for a way to create a custom checkbox field (online_status) and then find a way for the who's online block to check that.
Any ideas, modules or approaches anyone can recommend.
My current thinking is to do it via Views and a custom block
thanks
Answer: You can use hook_block_view_alter to alter the content that is returned by who's online block. Ideally use the same logic that was implemented in user.module user_block_view function, delta who's online block but with extra validations.
Add a field called Show online status to User Profile. Let's say yes or no.
Read the above field value in the alter function for all users online and filter them before displaying.
Hope it solves !


ERRO ao acessar chaves JSON com carácter especial

Question: Boa noite, Pessoal!
Estou escrevendo um NodeJS que acessa uma URL que contém um JSON nesse JSON as chaves contém carácter especial "-" que está causando erro na minha aplicação qual seria a maneira correta para acessa-las?
Exemplo Erro:

var tocando = ('#TocandoAgora: ' +
  parsedRadio.data.current-music.song);
  ReferenceError: music is not
  defined

Exemplo JSON:
data: {
    current-music: {
        singer: "NOME_BANDA",
        song: "NOME_MÚSICA"
    }
}

Exemplo Código:
const request = require('request');

request('http://myplayer.myradio.com.br/tocando.php', function (error, response, body) {
  console.log('error:', error);
  console.log('statusCode:', response && response.statusCode);
  var parsedRadio = JSON.parse(body);
  var tocando = ('#TocandoAgora: ' + parsedRadio.data.current-music.song);
  console.log(tocando);
});

Já tentei das seguintes maneiras e não obtive sucesso.
parsedRadio.data.[current-music].song
parsedRadio.data.['current-music'].song
parsedRadio.data.'current-music'.song
parsedRadio.data.currentmusic.song
parsedRadio.data.{current-music}.song

Me perdoem caso for um erro básico, ainda estou aprendendo NodeJs.
Agradeço a todos.
Answer: Acredito que isso resolva, usei Object.values() para pegar os valores do objeto.
Se o objeto estiver dessa forma:
data: {
    current-music: {
        singer: "NOME_BANDA",
        song: "NOME_MÚSICA"
    }
}

const dados = Object.values(data); //retorno sera singer e song, dentro de uma lista
console.log(dados[0])//{ singer: 'NOME_BANDA', song: 'NOME_MÚSICA' }

Acredito que nao precise converter para objeto json, utilize ele da forma que vêm no body. Só usar object.values. Eu coloquei desta forma, mas se ouver um sub-objeto dentro do body ai sim voce deve colocar algo como body.myobject dentro do object.values.
const request = require('request');

request('http://myplayer.myradio.com.br/tocando.php', function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
var dados = JSON.parse(body)
var parsedRadio = Object.values(dados.data)
var tocando = ('#TocandoAgora: ' + parsedRadio[0].song);
console.log(tocando);
});

Reference
Comment: Boa noite, @AndersonMendes! Obrigado por responder! porém obtive o seguinte erro ao seguir sua solução `var parsedRadio = Object.values(body.data)
                         ^
TypeError: Cannot convert undefined or null to object`
Comment: Extrai o objeto do body da mesma forma que você estava fazendo antes e depois usa object.value para pegar os valores do objeto.
Comment: Testei aqui do jeito q eu deixei e realmente deu esse erro, checa agora, modifiquei a resposta.
Comment: Funcionou, obrigado!


What is a good method for short text clustering?

Question: I am working on a text clustering problem. The data contains several sentences. Is there a good algorithm which reaches high accuracy on short text?
Can you provide good references?
Algorithms such as KMeans, spectral clustering does not work well for this problem.
Answer: That mostly depends on how much "state-of-the-art" (SOTA) you want versus how deep you wish to go (pun intended...).
If you can live with just shallow word embeddings as provided by word2vec, Glove, or fastText, I think the Word Mover Distance (WMD [yes, really...]) is a nice function for measuring (short) document distances [1]. I've even seen several Python Notebooks in the past that provide "tutorials" for this distance measure, so its really easy to get going.
However, if you are more interested in SOTA, you will have to look into deep (sequence representation) learning, using some kind of recurrent network that learns a topic model from your sentences. In addition to integrating (semantic) embeddings of words, these approaches go beyond the [good, old] "bag-of-words" approach by learning topic representations using the dependencies of the words in the sentence[s]. For example, the Sentence Level Recurrent Topic Model (SLRTM) is a pretty interesting  deep, recurrent model based on the ideas of the more traditional LDA (by Blei et al.) or LSA (Landauer et al.), but it's only an arXiv paper (so all default "take-this-with-a-grain-of-salt warnings" about non-peer-reviewed research should apply...) [2]. None the less, the paper has many excellent pointer and references to get your research started should you want to go down this rabbit hole.
Finally, it should be clarified that I don't claim that these are the agreed upon best-performing methods for bag-of-words and sequence models, respectively. But they should get you pretty close to whatever the "best" SOTA might be, and at least should serve as a an excellent starting point.
[1] Matt J. Kusner et al. From Word Embeddings To Document Distances. Proceedings of the 32nd International Conference on Machine Learning, JMLR, 2015.
[2] Fei Tian et al. SLRTM: Letting Topics Speak for Themselves. arXiv 1604.02038, 2016.
Comment: Just to be sure: My answer above does not recommend to use word2vec (alone) for short text clustering. Rather, it recommends to use WMD (over embedded vectors) and/or Deep Learning methods. (Yet, if you can train your own vectors, you get very good results with them alone, using the *Soft* Cosine Similarity, at least for a "workable prototype.")
Comment: i tried word2vec and it does not perform well for short text.
Answer: https://github.com/RandyPen/TextCluster
This is a Cluster method specific to short text, which outperforms KMeans etc. No Need to set latent variable number.
The basic idea is to tokenize the sentence into words. Then direct to different bucket according to text component. In each bucket, calculate similarity between the sentence and the bucket. If the similarity score is higher than specific value, append this sentence into that bucket, else search for the next bucket.
Comment: You need to elaborate on your answer. Don't just cite a link.


How would I get taxonomy info using the taxonomy term ID, in order to theme it?

Question: I need to be able to extract a taxonomy array and use it to create links.
Answer: taxonomy_term_load() looks promising.

Return the term object matching a term ID.
Parameters
<code>$tid</code> A term's ID
Return value
A term object. Results are statically cached.
Comment: No problem @user840. Please check useful answers as answered.


KVM virtualized CentOS can send/recieve TCP but not UDP

Question: I've installed CentOS 5 inside KVN on FC12. I've setup a bridged network that works fine. I can ping the virtualized host from any of my other computers and the other way as well. I can also access apache on the virtualized host from other computers on the LAN. I also have no problems doing 'yum update'
However, when I try to access any UDP service eg. DNS that resides outside my LAN I never get a reply. eg. nslookup google.com - <known nameserver>. When I try this from the host OS, the exact same command I get a reply.
I've tried sniffing the traffic by port mirroring the port that goes to the ADSL modem router (DG834G Netgear) in both directions. The DNS request travels out to the internet but I dont get a reply. Just casually comparing the packet sent by the host and the virtual OS I dont notice any significant differences. Then again I'm not sure what to be looking for.
Other info:
iptables host FORWARD has one rule (guest iptables is off):
ACCEPT     all  --  0.0.0.0/0  0.0.0.0/0  PHYSDEV match --physdev-is-bridged
Network is simple, one L2 managed switch and everything connected to it.
I've also tried creating a port forwarding rule for various UDP services and testing them but no luck there either.
The host and guest are configured using static IPs but there is a DHCP entry for the same ip/mac on the router.
Update:
It appears to be the DSL modem router. I just swapped out the current one for a one on loan and it works just fine. I have absolutely no idea why, I just used the default factory settings on the loaner. Any idea what might be the cause? I've tried changing various settings etc. but I'm not sure what specifically it might be.
Answer: This sounds relatively complex, if everything you're saying is accurate.
Can the VM host send and receive UDP traffic as well?
Comment: yes. I've managed to narrow it down to the gateway. just swapped out the DSL router modem for another one and it suddenly works! But I'd like to use the old modem as this was just a loaner. any thoughts why this could be? what setting I should change?
Comment: I'd do a factory reset on it, just in case something got screwed up. That's not exactly operating according to spec.
Comment: Factory reset fixes it! The strange thing is that I've narrowed it down to changing basic things like static IP reservation for DHCP + firewall rules. It seems that adding static IP reservation to other (not host OR guest mac) mac's causes certain inbound UDP traffic to become blocked, adding firewall rules and everything falls apart. I've reproduced it twice so far. And again any non-guest OS has no problems sending/receiving UDP including PC's on the LAN. I guess it must be some strange router firmware bug then....
Comment: Wow! That is bizarre, but good find! What model of router is it?
Comment: Netgear DG834Gv5 f/w V1.6.01.34. I went back and captured a single DNS query packet from both the host & guest and replayed them from another system to rule out config errors on virtualization/networking somehow and got the same result. Compared the packets and the only difference I could come up with was the IP & MAC address. Edit to another MAC - no change but changing the guest IP fixed it(!!??). Thought I had an IP conflict but with the rest of the network isolated the issue persists. The offending static ip 192.168.1.234, changed to .236 works! That was the ONLY change & restart network.


Does "data" in Cauchy data come before or after the coinage of data in computer science

Question: Is the usage of data as in Cauchy data (i.e. initial conditions) borrowed or came before the usage of data in computer science and do both usages mean roughly the same thing (data ~ information)?
Comment: Did you check a dictionary? The word is 350 years old.
Answer: The use of "data" in mathematics is quite old.  Oxford English Dictionary has a quote from
1645:   T. Urquhart Trissotetras 53

The verticall Angles, according to the diversity of the three Cases
  being by the foresaid Datas thus obtained.

I would suspect that its use in Latin is much older (as well as the use of the equivalent Greek term).  What does Euclid use for what is "given" in a geometric construction?
Comment: Okay because I came across this term in a computational PDE text so I thought what's traditionally simply referred to as "initial condition" might have gotten a computational spin, hence the term "cauchy data" it would be interesting to know when this term, the entire term "cauchy data" was coined and I doubt it was coined during cauchy's time
Comment: I found "Cauchy data" e.g. in Math Reviews from 1941 (MR0003909), with no indication that this was anything other than standard terminology.  This was long before there was such a thing as Computer Science.


State-space initial conditions

Question: I have a state space system represented by the following system of equations. The state vector is defined by:
$$ \dot{X}\left(t\right)=\left[\begin{matrix}0&1\\a&b\\\end{matrix}\right]\left[\begin{matrix}x_1\\x_2\\\end{matrix}\right]+\left[\begin{matrix}0\\1\\\end{matrix}\right]u(t)$$
and the output vector by
$$Y\left(t\right)=\left[\begin{matrix}c&d\\\end{matrix}\right]\left[\begin{matrix}x_1\\x_2\\\end{matrix}\right]+[e]u(t) $$
I'm wondering how I would impose the initial condition that $  \frac{dY\left(0\right)}{dt}=C$ such that I could represent it in the from $$ x(0)=\left[\begin{matrix}x_{1,o}\\x_{2,o}\\\end{matrix}\right]$$
Let me know if you have any suggestions for how I would do this.
Comment: This will not be possible. Because you cannot write a state-space system for which the derivative of $I$ can be expressed as a proper transfer function from $u$ to $\dot{I}$. This is because of the presence of the nonzero direct feedthrough term.
Comment: The question is not clear: For real-world systems, $e = 0$. The system needs to be redefined. Also, initial conditions are defined in terms of the state vector consisting of $x_1$ and $x_2$ and not on the output function $y(t)$.
Comment: Ok, that's kinda why I was confused before. I was trying to differentiate the output expression but I couldn't get rid of the $V_r$ term or the $\dddot{x} $ term that arises from differentiating. Is there any way around using the direct feedthrough term in this analysis?
Comment: You could just select a controller, e.g., u = -Kx. Then solve for $x(t)$ and plug it into $\dot{y} = (C-K)\dot{x} = (C-K)(A-BK)x$ and compute what the initial conditions need to be ($C=[c\ d]$ and not your initial condition).
Comment: @Dr.Sundar That somehow misses the point. The system could describe a controller which should at some point be re-initialized to a defined state, with a constraint on its output derivative. A controller doesn't need to have $e=0$ and if your system actually has a feedthrough term, you need to express that in the equations.
Answer: To compute the required initial conditions just solve the derivative of the output for your desired rate of change. You have:
$$
\begin{align}
\dot{x}_1 &= x_2 \\
\dot{x}_2 &= a x_1 + b x_2 + u \\
y &=  c x_1 + d x_2 + e u
\end{align}
$$
So the derivative of the output is
$$
\begin{align}
\dot{y} &= c \dot{x}_1 + d \dot{x}_2 + e \dot{u} \\
&= d (u + a x_1 + b x_2) + c x_2 + \dot{u} e
\end{align}
$$
So solving $\dot{y} = C$ for $x_1$, $x_2$ provides you some initial conditions:
$$
\begin{align}
x_1(0) &= -\frac{\dot{u}(0) e - C + d u(0)}{a d} \\
x_2(0) &= 0
\end{align}
$$
This choice will guarantee that $\dot{y}(0) = C$, while $a d \neq 0$ is required for this computation.
We can check that by setting for example $a=-2,b=-3,c=2,d=1,e=1,C=-10$. Assume the system input is $u=\sin(2t)$ so that $\dot{u}=2\cos(2t)$ and hence $u(0)=0,\dot{u}(0)=2$. Then a quick simulation gives:

So you can see that with this choice of initial conditions you can impose any initial output derivative you want.
Of course you need $\dot{u}(0)$ for this computation. If you don't have it available you could do several things to circumvent this problem, like:

Since you control $u$ demand $u = 0$ during the initialisation, since then $\dot{u} = 0$.
If your system is stable, use feedforward during initialization so that you can compute $\dot{u}$.
Approximate $\dot{u}$ with a high pass.
If $e$ is small, ignore the contribution of $\dot{u}$.

Which one of those (if any) will work for you will depend on your application and the goal you are trying to achieve.

State-space initial conditions


Pointwise Supremum of Quasi-convex Function

Question: In Boyd and Vandenberghe, Convex Optimization, page 102, I read that if function $g(x,y)$ is quasi-convex in $x$ for each $y$, then
$$
f(x)=\sup\limits_{y\in C}(w(y)g(x,y))
$$
is also quasi-convex, where $w(y)\geq0$.
My question: If the set $C$ depends on $x$, for example, $C_x=\{y:y\leq x\}$, then under what conditions can this conclusion still hold?
Thanks!!
Answer: Typically you can solve such problems by introducing an indicator function $I_{C_x}(y)$ (for your example it takes the value $0$ if $y\leq x$, $\infty$ otherwise):
$$f(x) = \sup_{y \in C} \left\{ w(y)(g(x,y)-I_{C_x}(y)) \right\}$$
The condition is now that $g(x,y)-I_{C_x}(y)$ is quasiconvex in $x$ for each $y$, which is not true, so we cannot use this trick.
Going back to page 102, it was concluded that $f$ is quasiconvex, because $f(x)\leq \alpha$ iff
$$w(y)g(x,y) \leq \alpha \quad \forall y \in C.$$
In other words, the sublevel set of $f$ is convex, since it is the intersection of convex sets. If you replace $C$ with $C_x$, this argument no longer holds, because $C$ depends on $x$. In other words, the sublevel set of $f$ cannot easily be expressed as the intersection of convex sets.
Comment: if the max exists, it does not matter
Comment: Thanks! I need some time to understand it...
Comment: I got it. But I'm wondering what if we replace "sup" by "max" (provided it exists)? Does it matter?
Comment: Thanks. I think the indicator function should take the value of $-\infty$ when $y>x$, is it right?
Comment: Here comes another question. The indicator function $I_{C_x}$ depends upon $x$, thus I cannot prove function $g(x,y)+I_{C_x}(y)$ is still quasi-convex in $x$...
Comment: @Huaixin you are right about the $-\infty$ (however, I subtract the indicator function instead of changing its function value); I have updated the answer
Comment: Thanks for the reply. So you mean $f(x)\leq\alpha$ iff $w(y)g(x,y)\leq\alpha\ \forall y\in C_x$? I'm a little confused about this since set $C_x$ is not fixed.
Comment: @Huaixin you are right, this is by no means easy. I now think that $f$ is often not quasiconvex.