Redirecionar ou negar acesso direto a pasta public

Question: Estou usando htaccess para acessar as pastas css, js, images que estão em /public diretamente:
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /
    RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [QSA,L]
</IfModule>

Por exemplo, quando acesso está url http://localhost/css/file.css ele mostra o conteudo de http://localhost/public/css/file.css
Porém eu quero negar acesso se o usuário digitar o "public" no endereço, por exemplo http://localhost/public/css/file.css. É possível negar acesso acaso haja o /public no endereço?
Answer: Considerando que  a diretiva RewriteBase é a raíz de http://localhost/, adicione a seguinte regra:
RewriteRule ^(public/) - [F,L,NC]

Essa regra negará acesso a pasta public/.
Caso queira adicionar algum outro path específico, veja um exemplo
RewriteRule ^(public/|outrapasta/) - [F,L,NC]

Nesse exemplo, está aplicando a regra para public/ e outrapasta/.
Comment: Obrigado Daniel, olhei direito agora, na verdade o problema é outro, quando tento tento acessar `http://localhost/css/file.css` aparece o erro 403 também, o que deveria só aparecer em `http://localhost/public/css/file.css`
Answer: Para resolver o problema você pode usar %{THE_REQUEST} com RewriteCond, examplo:
RewriteCond "%{THE_REQUEST}" "^GET\s/public/"

Se precisar de todos metodos (GET, POST, PUT, etc), exemplo de redirecionamento:
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /

    RewriteCond "%{THE_REQUEST}" "^[A-Z]+\s/public/"
    RewriteRule ^public/(.*)$ other-directory/$0 [QSA,L]

    RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [QSA,L]
</IfModule>

Nega acesso (será necessário criar um caminho falso):
<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /

    RewriteCond "%{THE_REQUEST}" "^[A-Z]+\s/public/"
    RewriteRule ^public/(.*)$ fake-directory/$0 [F]

    RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [QSA,L]
</IfModule>


difference in learning rate between classic gradient descent and batch gradient descent

Question: I am learning how to use TensorFlow and started with a example of regression problem. So the first thing was a simple gradient descent using the learning_rate = 0.1 I noticed that the MSE was going up at every step. I managed to get it converge by putting learning_rate=0.00000005 (weird isn't it ? ).
Anyway, the next step was building a batch gradient descent batch_size=100 and learning_rate=0.1 which worked perfectly.
My question here is: Why such a difference between both learning rates ? I would understand if it was a difference of 10^-2 but here the difference is huge.
Both programs :
-Gradient descent
n_epochs = 1000
learning_rate = 0.00000005
m, n = housing.data.shape
print 2/m
scaled_housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]

X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y")
theta = tf.Variable(tf.truncated_normal([n + 1, 1],stddev=0.001), name="theta")
y_pred = tf.matmul(X, theta, name="y_pred")
error = y_pred - y
mse = tf.reduce_mean(tf.square(error), name="mse")
#gradients = tf.gradients(mse, [theta])[0]
#training_op = tf.assign(theta, theta - learning_rate * gradients)

#~~~! Very efficient optimize !~~~#
optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate,momentum=0.9)
training_op = optimizer.minimize(mse)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    for epoch in range(n_epochs):
        sess.run(training_op)
        if epoch % 100 == 0:
            print("Epoch", epoch, "MSE =", mse.eval())

    best_theta = theta.eval()
    print best_theta

-Batch gradient descent:
batch_size = 1000
n_batches = int(np.ceil(m / batch_size))
n_epochs = 1000
learning_rate = 0.01
m, n = housing.data.shape

scaled_housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
target = housing.target.reshape(-1, 1)

X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X")
y = tf.placeholder(tf.float32, shape=(None, 1), name="y")

def fetch_batch(epoch, batch_index, batch_size):
    start_idx = (batch_index-1)*batch_size + 1
    end_idx = batch_index*batch_size
    if batch_index == 0:
        start_idx = 0
        end_idx=batch_size
    #print("s",start_idx,"e",end_idx)
    X_batch = X.eval(feed_dict={X: scaled_housing_data_plus_bias[start_idx:end_idx,]})
    y_batch = y.eval(feed_dict={y: target[start_idx:end_idx]})
    return X_batch, y_batch

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(n_epochs):
        for batch_index in range(n_batches):
            X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size)
            sess.run(training_op, feed_dict={X: X_batch, y: y_batch})
        if epoch % 100 == 0:
            print("Epoch", epoch, "MSE =", mse.eval())
    best_theta = theta.eval()
    print best_theta

Answer: Attempting to use theory to answer your question, not looking at the code.
SGD looks at one sample at a time and computes a gradient that, over the entire dataset, is supposed to be a good estimate of the "true" gradient. This means that there is often a lot of variance in the gradient, which a high learning rate would exacerbate. In contrast to this, GD (or batch gradient descent) looks at 100 samples at a time in your case, which means that the variance is not as high.
There are a lot of factors that determine what you saw with SGD. Maybe it converged at a fairly different minimum than GD, maybe the MSE was going up only at the start and if you had let it run with a higher learning rate, it would have eventually converged somewhere reasonable, maybe it already started from somewhere very close to a minimum, hence you needed to use a small learning rate. You can test the last hypothesis by seeing how much of a drop there was in MSE between the first step and the last. Compare that to GD. What about the initial MSE, say for one batch of GD and 100 iterations of SGD? How close are they?


How to learn to create the right tone for my guitar?

Question: This is quite a generic question.
Since the day I started learning guitar, I have been lazy and never tried to understand how sound really works. I plugged the guitar in the amp and just turned the button to "clean" or pushed another one when I wanted to play some metal. Treble? Gain? Compressor? Tone? Drive? All of this is almost a foreign language to me.
I want to change this now and understand how to create a tone from the beginning. I bought an iRig and use GarageBand now. The guitar presets seems pretty good, but I didn't found an "amazing" tone for metal, for example. And I have the feeling I should create this amazing sound by myself to learn, rather than count on presets.
Now that I have good software and hardware, the only missing thing to reach my purpose is knowledge :)
I already tried a lots of combinations, but it feels like I'm trying to fly a plane and pushing all the cockpit buttons. Not very effective...
Can you give me some advices or tricks?
Comment: Possible duplicate of [What are some of the things that influence a player's "tone"?](https://music.stackexchange.com/questions/2224/what-are-some-of-the-things-that-influence-a-players-tone)
Answer: The tone of electric instruments, especially distorted guitar, is driven by harmonic saturation.
Consider a sine wave at 440 hz. There is no harmonic complexity, only a single tone. Compare that sound to a plucked A string on an instrument, and the plucked string contains a greater variety of frequencies, creating a more complex sound. Different instruments are described as 'full' or 'tinny' because of what harmonics they emphasize, and whether that harmonic content is pleasing. The wikipedia about the harmonic series has a physics-oriented description of how this harmonic content is created by vibrating objects.
https://en.wikipedia.org/wiki/Harmonic_series_(music)
To create a richer, thicker, and then distorted tone, the first thing we want to do is increase the volume of the harmonic content, so that many frequencies are prominent. This is what is usually meant by a 'boost' or 'drive' pedal. Compressors can also have this effect by reducing the volume of the fundamental frequency, so the upper harmonics are easier to hear.
The next step is to create 'clipping' in the wave forms. When a frequency reaches the maximum possible amplitude for a stage in the circuit, it will flatten out. If you have a synthesizer, try creating a sine wave, and then a square wave at the same frequency. This will give you a sense of how the two waveforms sound different.
https://en.wikipedia.org/wiki/Clipping_(audio)
Distorted guitar sounds are a complex waveform, with a lot of upper harmonic content, and lots of clipping. If you record your guitar, you can see that the waveform almost looks like a rectangle. That is clipping and harmonic saturation in action. If you want to play metal guitar use 'boost' or 'drive' pedals to increase the harmonic saturation and create clipping, and then EQ sound that the pleasing parts of the harmonic content are emphasized. Changing the order of the effects will influence the final sound. If you put an EQ with a big bump to the mid frequencies before a distortion, then you will get more aggressive clipping in that frequency range, because more of the waveform will hit the maximum possible amplitude.
Comment: From a less technical perspective, here's a quick run down of common effects. Distortion - add grit, noise, and crunch to the sound (the main tool of heavy rock music). Try one that imitates a "Big Muff" or "Tube Screamer", these are some of the most famous distortions in rock music. Reverb will make your guitar sound like it is in a big room, and create artifical reflections like the sound is bouncing off the wall. Delay - think of the opening riff from 'Another Brick in the Wall', that repeated sound that fades away is a delay. Compression - very complex, a whole lesson in itself.
Comment: Very interesting explanations, thanks, even if it may seems hard to start with :)
Answer: While iRig is a nice piece of kit, and GarageBand is okay I would not suggest it will let you create an amazing metal sound.
Really, what everyone does is try effects.  Loads of them.  Physical stomp boxes, software effects etc.  Work out which ones you like and if necessary tweak them. Don't try and create one from scratch as there are too many things to adjust. And it's not just the effect that makes the sound - the amp is critical to the final sound.
Get down to your local guitar shop and just play.
Comment: And always bear in mind that the great sound you have with certain settings on effect pedals, etc., won't ever be the same in a different room/hall...
Comment: Very true - or with a different guitar...
Comment: The second-hand market is full of interesting effects you can buy, try for a few weeks and re-sell at the exact same price. Has worked pretty well for me so far to try plenty of them for free and find the ones I like. I'm not good enough to get a feeling of them in 30 minutes at a shop.
Comment: @Marc Q. But the thing is I'm using only my mac and an iRig so every effects are "virtual" now. It's a lot easier because I can test potentially everything in garageband. I know some purist won't like this, but for now I'm happy with it, I have no visible latency and I call have all the sounds I want for free. I just miss some skills ^^
Comment: So download ones that sound interesting and mess with them. You don't need to waste time trying to work out how every setting works, just grab one you like.
Answer: I think some of these answers are making what you're after seem overly complex.
Want a metal sound? Try adding a distortion effect to your guitar track, or maybe even several in succession. Experimenting is important - be patient.
With that out of the way, understanding EQ is important. You mentioned treble. Treble refers to the high frequencies of an audio signal. To put it simply, it's the opposite of bass - at the extreme, it's the hissy sounds. When you see the Tone dial, this will emphasize whichever area of the frequency spectrum you wish to emphasize. If the tone dial is low, it will emphasize the lower frequencies (bass). If the tone dial is high, it will emphasize the higher frequencies.
Another concept to be familiar with is compression. Compression refers to the dynamic range of an audio track. With high compression, an audio track will usually remain at a constant volume and have no peaks/valleys in volume. With low compression, an audio track can fluctuate from lower volumes to very high volumes.
Garageband is fantastic for experimenting and learning tone/sound design. Don't let anyone try to convince you that it is not.
Comment: Thanks a lot for your explanations and encouragements. I'll experiment a lot :) For example today I was blown away when I added a reverb on my guitar tone, it was really nice to hear. The sound was less "self contained", don't know how to define this.
Answer: Look no further than YouTube! Personally, I like CSGuitars' channel. His first video about metal tones specifically is here, though there are plenty more that cover issues like "Overdrive vs Distortion vs Fuzz: What's The Difference?" "Do I need a compressor?" etc. There are also plenty of other channels that will probably show up in the suggested videos.
Comment: Oh thanks a lot for the good link ;) Exactly the kind of thing to make me progress step by step I guess :)


java.lang.StackOverflowError: stack size 1038KB

Question: Estou fazendo um algoritmo que converte um bitmap deixando-o em tons de cinza.
Consegui fazer usando for mas gostaria de fazer de maneira recursiva.

Usando for (Esta funcionando bem)
//BUTTON - ON CLICK . . .
public void go(View v){
    //BM_3 É UM BITMAP, VARIAVEL GLOBAL QUE JÁ POSSUI UMA IMAGEM EM SEU CONTEUDO . . .
    bm_3 = bm_3.copy(Bitmap.Config.ARGB_8888, true);

    for (int x = 0; x < bm_3.getWidth(); x++){
        for (int y = 0; y < bm_3.getHeight(); y++) {

            String hex = Integer.toHexString(bm_3.getPixel(x, y));

            if(hex.length() == 8) {
                String hexX = "#" + convert_Hex_to_grey("" + hex.charAt(0) + hex.charAt(1),
                                                        "" + hex.charAt(2) + hex.charAt(3),
                                                        "" + hex.charAt(4) + hex.charAt(5),
                                                        "" + hex.charAt(6) + hex.charAt(7));

                bm_3.setPixel(x, y, Color.parseColor(hexX));
            }
        }
    }
    //IMG É UMA IMAGEVIEW . . .
    img.setImageBitmap(bm_3);
}

Com base no algoritmo acima, tentei implementar o mesmo de forma recursiva. Porém, esta apresentando erro de java.lang.StackOverflowError: stack size 1038KB

Usando recursão (java.lang.StackOverflowError)
RECURSÃO
private Bitmap grey_scale(int x, int y, Bitmap bm_3) {
        //IF PARA PERCORRER TODO Y . . .
        if (y < bm_3.getHeight()) {
            String hex = Integer.toHexString(bm_3.getPixel(x, y));
            if (hex.length() == 8) {
                String hexX = "#" + convert_Hex_to_grey("" + hex.charAt(0) + hex.charAt(1),
                                                        "" + hex.charAt(2) + hex.charAt(3),
                                                        "" + hex.charAt(4) + hex.charAt(5),
                                                        "" + hex.charAt(6) + hex.charAt(7));

                bm_3.setPixel(x, y, Color.parseColor(hexX));
            }
            //O ERRO OCORRE NESTE RETURN ! ! !
            return grey_scale(x, y+1, bm_3);

        }
        //IF PARA PERCORRER TODO X, ZERANDO Y A CADA TROCA DE X.
        if (x < bm_3.getWidth()) {
            return grey_scale(x+1, 0, bm_3);
        }
    //RETORNA BITMAP
    return bm_3;
}

BUTTON ON CLICK QUE CHAMA RECURSÃO
public void go(View v){

    bm_3 = bm_3.copy(Bitmap.Config.ARGB_8888, true);
    //FAZ RECURSAO DENTRO DE UMA THREAD . . .
    new Thread(new Runnable() {
        @Override
        public void run() {
            //CHAMA A RECURSAO
            bm_3 = grey_scale(0, 0, bm_3);

            //VOLTA PRA THREAD PRINCIPAL PARA ATUALIZAR O IMAGEVIEW . . .
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    img.setImageBitmap(bm_3);
                }
            });
        }
    }).start();
}

Comment: Qual o tamanho da imagem?
Comment: A profundidade aproximada é de 621 mil chamadas recursivas. Não deve ter configurado o tamanho da stack para isso. Creio que só ajeitar o tamanho da stack não ajeita para casos maiores.
Comment: Cada chamada acrescenta pelo 12 bytes na pilha só de argumento, sem contar as informações extras de estrutura de chamada de função. A maioria das chamadas também acrescenta pelo menos 4 bytes de referência à variável local `hex`. Talvez o compilador seja inteligente ao ponto de soltar a referência a `hex` antes de fazer a chamada recursiva.
Comment: `-Xss` é com o tamanho da stack, `-Xmx` é o tamanho inicial da heap; mais detalhes aqui: https://stackoverflow.com/q/3700459/4438007
Comment: Está rodando pelo eclipse, linha de comando, outra ide ou como?
Comment: Já tentou com uma imagem de 1 pixel de altura? Só para garantir que não é erro no algoritmo?
Comment: O tamanho da imagem é 5.577 bytes, dando 788 por 788 pixels
Comment: Como configura o tamanho dela?
Comment: `-Xms` eu acho. Mas você precisa ter uma ideia do quanto vai consumir, ou testar até não dar mais stack overflow
Comment: tentei este = Thread(ThreadGroup group, Runnable target, String name, long stackSize) . Mas mesmo colocando 80m, ele ta erro.
Comment: tentei com uma imagem menor, 252x252 e deu o mesmo erro
Comment: Pelo Android Studio
Comment: Pelo que vi, a JRE é livre para definir o tamanho da stack, tomando como referência uma sugestão do que é passado como argumento. Também não sei qual a relação entre a stack da thread secundária e a da principal. Também não sei se é dependente de plataforma
Comment: nesse caso, eu acho que tentar usar os argumentos da máquina virtual Java não vai ajudar.
Comment: Fiz algo semelhante isso quando estava testando com a imagem grande printava a cada troca de linha, ele trava na linha 2. Mas ele chega a começar ela. Na imagem menor, ele trava na linha 55 (com a Thread) com limite de 80m
Comment: tenta uma imagem menor e mais controlada. Por isso o 1 pixel
Comment: Pode ser recursão indireta? Por em uma pilha e processar o resultado? A vantagem desse modo é que a pressão fica na parte dinâmica da memória
Answer: O problema aqui é o tamanho da recursão. Sua recursão é de aproximadamente 621 mil chamadas, dada a imagem de 788 x 788.
Cada chamada recursiva faz pelo menos a inserção dos argumentos da chamada na pilha. No caso, são dois inteiros e uma referência; os inteiros são 4 bytes cada, a referência é de 8 ou 4 bytes (8 bytes para 64 bits e 4 bytes para 32 bits). Portanto, se põe no mínimo 12 bytes para cada chamada recursiva. Assim, não considerando outros fatores, o mínimo necessário para a stack é de uns 10 ou 12 megabytes só de argumentos da chamada recursiva. Quem sabe o quanto mais de outras informações?
Enfim, talvez com 64 megabytes de stack? Para determinar esse valor, o argumento de máquina virtual -Xss 64M define isso. Fonte

Bem, o AP está com o problema executando no Android Studio, então tentar fazer esses tweaks com a JVM pode não resultar em nada.

PS: pouco antes de terminar a escrita desta resposta, vi que setar o tamanho da stack na thread não deu certo. Vou inspecionar mais um pouco e então editar a resposta com o que achar


Solving Poisson's Equation in 1-D for a point charge?

Question: Ok so I was trying to solve the Poisson's equation for a point charge with a Fourier transform to get the familiar equation.
This is what I did so far:
So ultimately I am trying to solve this in 3 dimensions but I am embarrassingly struggling with the 1-D solution right now.
$\frac{\partial^{2}}{\partial x^{2}}   f(x) = \rho(x) $
I express f and ρ in terms of their Fourier transforms:
$f(x) = \frac{1}{ \sqrt{2 \pi}} \int_{-\infty}^{+\infty} f(\vec{k})e^{i \vec{k}\vec{x}}dk$
and
$\rho(x) = \frac{1}{ \sqrt{2 \pi}} \int_{-\infty}^{+\infty}\rho(\vec{k})e^{i \vec{k}\vec{x}} dk$
So from here I bring the derivative into the integral that is $f(x)$ and operate on the $e^{i \vec{k}\vec{x}}$ term:
$\frac{\partial^{2}}{\partial x^{2}}   f(x) = \frac{1}{ \sqrt{2 \pi}} \int_{-\infty}^{+\infty} -k^{2} f(\vec{k})e^{i \vec{k}\vec{x}}dk$
I have:
$\frac{1}{ \sqrt{2 \pi}} \int_{-\infty}^{+\infty} -k^{2} f(\vec{k})e^{i \vec{k}\vec{x}}dk = \frac{1}{ \sqrt{2 \pi}} \int_{-\infty}^{+\infty}\rho(\vec{k})e^{i \vec{k}\vec{x}} dk$
And I am able to drop the integrals because the Fourier transform is unique.
$-k^{2}f(\vec{k}) = \rho(\vec{k})$
So Now I can solve for $f(x)$:
$f(\vec{k}) = \frac{\rho(\vec{k})}{-k^2}$
So now for a point charge I know that $\rho(x) = q \delta(x)$ which will leave me with the following result when i try to use Fourier transforms to transform $f(\vec{k})$ back to $f(\vec{x})$:
$f(\vec{x}) = \frac{-1}{2 \pi} \frac{q}{\epsilon_o} \int_{-\infty}^{+\infty} \frac{1}{k^2}e^{i \vec{k}\vec{x}}dk $
However I do not know how to integrate this to find the answer back in x-space. Have I went wrong somewhere or is their a certain trick to this integral?
Answer: This is more of a maths question. You're working is mostly fine (see below), but Fourier transforms are a sledgehammer to crack a nut here: moreover, you need to be comfortable with tempered distributions if you use them in a problem like this.
The calculation you have done is for a particular integral of the linear equation $\mathrm{d}_x^2 f(x) = \rho(x)$ (I'll absorb the electric constant into $\rho$ hereafter). Your working is pretty much OK, aside from the fact that you've written a couple of equations with a Fourier transform on one side and an untransformed function on the other. The scale factor of $2\,\pi$ in the last line: you don't pick up a factor of $2\,\pi$ if you work through carefully.
Having found a PI, you need to understand that you can add any solution of the form $\mathrm{d}_x^2 f(x)=0$ to it and still have a solution. Here you can add any solution of the form $f(x) = A\,x + B$ where $A$ and $B$ are integration constants to be fixed by boundary conditions/ initial values.
The particular integral when $\rho$ is the distribution $\delta$ is the distribution given by the double integral of $\delta$, the integral of a step function namely the ramp:
$$f_0:\mathbb{R}\to\mathbb{R};\;f_0(x)=\left\{\begin{array}{ll}0;&x<0\\x;&x\geq0\end{array}\right.$$
So adding the PI we get:
$$f:\mathbb{R}\to\mathbb{R};\;f(x)=\left\{\begin{array}{ll}A\,x+B;&x<0\\(A+1)\,x+B;& x\geq0\end{array}\right.$$
and now we must add restrictions / use our physical intuition. You're solving for a potential, so we can add an arbitrary constant to the solution: offsets are a global gauge symmetry. Hence, you cannot hope to determine $B$, any real $B$ implies the same physics. For $A$, note that your problem corresponds to an infinite sheet of charge: the electric field will be constant and pointing in the $-x$ direction for $x<0$ and it will have the same magnitude but point in the opposite direction for $x>0$. This symmetry lets you find $A$.


Benefits of compression apparel

Question: Compression apparel seems to be very popular with athletes. Brands like Under Armour and Nike show athletes in different sports wearing their apparel.
Personally, I wear compression apparel when I'm playing sports or training, but I haven't worn it enough to notice a significant difference. I'm sure those who are athletes for a living have more insight on this than I do.
What are the benefits of compression apparel?
Answer: The main benefit for me is in preventing body fluids from pooling in my legs (I have very low blood pressure).  This is billed as assisting in recovery post exercise.
Answer: This is similar to my answer to this question but I felt that it was also appropriate here.
Livestrong has a great page that illustrates a lot of points and references medical studies to support it.
Some key points:

limits extra muscle motion, or "oscillation" ... [which] reduces the amount of energy you are expending

assist[s] the hamstrings in controlling leg movement at the end of the swing phase ... delay[s] muscle soreness by compressing the muscle tissue enough so that less damage occurs

reduces impact force to muscles by 27 percent

increases the amount of lactate retained in muscles and thus reduces the amount that is  released into the blood

Compression from the shorts may protect against a venous thrombosis

Compression shorts may help cool the body by wicking sweat from the body and allowing it to disperse faster

Take a look at the page for more details.
From a personal opinion standpoint, I've found that I personally perform much better (running and soccer are the main events I use compression). The shorts also offer much needed support for the man-specific area.
Additionally, I use compression sleeves for my calves.  I suffered from shins splints and the compression sleeves seemed to almost completely alleviate the shin splints when I would run.  I've spoken with therapists about this and the reason I was given was because the compression sleeves keep the muscle attached to the bone during running (shin splints are micro tears of the muscle away from the bone).
Comment: Good answer, good personal insight, but please refrain from passing off others work as your own. See [this](http://meta.sports.stackexchange.com/a/193/527) for more info.
Answer: Firstly, compression means less work needed by stabilisers to maintain the position. An example is powerlifting. Secondly, it improves the post-recovery particularly in athletes who have very low recovery HR. Thirdly, they are timeless. Different compression clothes originates from nursing and old people care where for example compression stockings are used to improve the blood flow in legs during night and usually removed on the morning. They can be used in different age groups and different activities to improve different kinds of performance, sometimes it is just ability to walk, sometimes it is the ability to lift heavier and sometimes it is the ability recover faster. Fourtly, they can be super sexy. Compression stockings are almost like fashion gimmick but they do help with recovering from walking with high-heels, particularly with amateurs and if not they can make you look better.
Examples

The compression allows Powerlifters lift with larger weights, example about the champion Jarosław Olech below

Running: the compression stockings improve the circulation and your legs feel less heavy. This is partially mentioned in other answer: "The main benefit for me is in preventing body fluids from pooling in my legs (I have very low blood pressure). This is billed as assisting in recovery post exercise."
Endurance training and particularly their interval training: the compression stockings help to deal with achilles tear and its development worse, one of the most common injury in sports such as running and skiing.
Old people care

Compression stockings can also make people look sexy, more slimmer legs and more blood in the core.
Answer: From Wikipedia

The main benefits of compression sportswear is that it keeps the
  muscles warm to prevent muscle strain and fatigue, and wick sweat away
  from the body to prevent chafing and rashes.    In addition, there is
  some evidence that compression shorts may enhance athletic
  performance. Compression sportswear also helps to keep undergarments
  in place, and for certain sports, like baseball and softball, come
  with padding at the hips to protect players from injuries due to
  sliding.
Compression shorts are also popular among female athletes, especially
  among those who wear skirts or kilts during games. In those
  situations, athletes wear compression shorts under the skirt so if
  they fall over and their skirts ride up, their underwear will not be
  exposed. This is seen particularly in women's lacrosse, field hockey
  and roller derby, all being sports in which players often wear skirts.
The alleged benefits of wearing compression tights are:

Improving athletic performance by maintaining repeated jump performance
Reduce muscle movement and vibration and focus the direction of the muscle
Reducing the risk of sports injuries
Maintaining body temperature and moisture wicking
Reducing the build up of Creatine kinase which is an indicator of muscle tissue damage.
Reducing the time taken for muscles to repair themselves
Reducing muscle soreness during post workout recovery
As an alternative to compression stockings they can be worn during long flights to reduce the risk of Deep Vein
  Thrombosis (DVT)
  caused by pooling of blood in the lower legs

These factors allow an athlete to increase both the duration and
  intensity of training and competition.
Comment: Please don't just quote wikipedia wholesale. Give your own answer using quotes where necessary.
Comment: While I like mine, its good to point out that there's no real evidence that they actually provide these benefits. So its probably wise use the same phrasing as Wikipedia used: "The **alleged benefits** of wearing compression tights are:". Have a look at my answer on [Fitness for more info](http://fitness.stackexchange.com/questions/6867/do-compression-socks-help-prevent-shin-splints/6890#6890)
Comment: @DorCohen are you admitting your other answers "quote wikipedia wholesale?"
Comment: @waxeagle 3 downvotes in 10 min? seems a little bit intention.. No קncouragement in our days.. I guess none of my other answers or question is not deserved to up vote
Comment: Wikipedia is a legit source! and if it answer the question it's great as any other!

Benefits of compression apparel


Virtual networking, can ping and traceroute, can't apt-get update

Question: I'm building a virtual network with 6 virtual machines in virtualBox.
One of them acts as router/nat/firewall.
This first machine uses 4 network cards:
eth0 -> Internet
eth1 -> Subnet 1
eth2 -> Subnet 2
eth3 -> Host-Only Network

I got to the point where the machines in the subnets could connect to the internet by setting the nat in the "router" like:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Then I started to set up a third subnet that comes out of another virtual machine in subnet 2 with these network cards:
eth0 -> Subnet 2
eth1 -> Subnet 3

Only one other machine connects to subnet 3, but I'm going to set up an ssh server on it so I need to route from the router to the machine in subnet 2 to this other one.
For that I used:
iptables -t nat -A PREROUTING -p tcp --dport 22 -j DNAT --to-destination 192.168.20.46:22

In the "router" and
iptables -t nat -A PREROUTING -p tcp --dport 22 -j DNAT --to-destination 192.168.30.50:22

In the ssh server machine.
Also, to get every machine to "see" each other I used:
route add default gw 192.168.20.46
route add -net 192.168.30.0 netmask 255.255.255.0 gw 192.168.20.46

On the "router" machine.
Now every machine can ping everything from the other machines to 22.214.171.124 and traceroute them. However,
apt-get update

in any of the machines but the router send the package to the router and no answer comes back and so it gets stuck in the first line:
 0% Connecting ftp....(126.96.36.199)...

And never goes any further than that. (just errors when it times out)
My guess is the nat is sending the packages correctly but on the way back they can't reach the subnet machines.
Comment: This is probably not particularly helpful, but at this scale, why are you using Virtualbox, why not KVM or similar?
Comment: That's the software they taught me to use, if I use another one part of it may  be diferent. Risky, that's all. Interesting either way. I'll look into it, thanks.
Comment: Lot easier to back up VMs, and can run on one physical machine (power, heat, noise). The savings let you build up that central server with things like RAID10 SSDs that the whole "cluster" will benefit from in terms of reliability, speed, access times, etc.

At his scale though I would use docker containers, assuming the services running on each are compatible ...
Answer: I guess was wrong. The machines were sending requests and the router redirected them to another subnet that either didn't know what to do with it or bounced it back to the router.
Solution being adding -i eth0 to the iptables line so that only external traffic is redirected.


mysql update one table from another

Question: I have a massive database over over 2.7 million rows. It contains data on uk property prices.
The first Table is called PricePaid And has a column called Price and Loc4.
Now I am trying to get the average for each year grouped by loc4 and update another tabel called PricePaidByCounty.
I have created this SQL statement :
INSERT PricePaidByCounty (County, Avg2013)
SELECT Loc4,
Avg(Price) as AvgPrice2013 FROM PricePaid WHERE Date Like '%2013%'
Group BY Loc4

This works fine for inserting initial row but I want to use an update statement instead as I will need to run this SQL query each month.
Can anyone show me how to change this Insert into an update.
I am doing this as I need to quickly display average house price for each location by year. And the Database is that big I dont want to do this on the flu
Thanks
Comment: You can use JOIN and subselects inside your update-statements
Comment: this database schema is assumed to be poorly designed is all I can say. The fact that you have a column called Avg2013, and doing a `like`
Comment: the way to do it is to have a Junction table, and in it have avg information by year. and a `composite` on a generic column named something like `theYear` (along with another column). See my answer [here](http://stackoverflow.com/a/32620163/1816093). He wanted to do data as CSV in one column. You want to add columns per year (same difference bad design)
Comment: As such you have fast access via joins and index use, versus using a `like` which is a no no
Answer: You can update your table using following query using insert ... on duplicate key update statement (https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html):
INSERT INTO PricePaidByCounty (County, Avg2013)
SELECT Loc4, Avg(Price) as AvgPrice2013
FROM PricePaid
WHERE Date Like '%2013%'
GROUP BY Loc4
ON DUPLICATE KEY UPDATE Avg2013=AvgPrice2013

For this to work you need to make sure that a set of (County, Avg2013)  is defined as unique key.
Answer: Looks like table PricePaidByCounty needs three columns Country, Year and Average so that while updating by year you can choose to update by particular year. Then the query would be like:
UPDATE PricePaidByCounty ppbc JOIN (SELECT Loc4,
Avg(Price) as AvgPrice FROM PricePaid WHERE Date Like '%2013%'
Group BY Loc4) ap SET ppbc.Average = ap.AvgPrice WHERE ppbc.Country = ap.Loc4 AND ppbc.Year = 2013;

This can be enhanced to group by Loc4 and Year and directly update to PricePaidByCounty. It may run for days as you have multiple records. :D

mysql update one table from another


Solve an inequality involving entropy of random variable X

Question: Im working through Elements of Information Theory and came across a question which is stumping me. The problem states Let $p(x)$ be a probability mass function. Prove, for all $d\ge0$ that $$\text{Pr}(p(X)\le d)\log\frac1d\le H(X)$$ Where $H(X)$ is an entropy. The presence of the $log\frac1d$ term makes me believe that this is related to a change of base as $H_b(X)=\log_b(a)H_a(X)$ but I can't see why the Pr$()$ term would be related to entropy in any way. Any help on the actual method to solving this is appreciated!
Answer: This is a consequence of Markov's inequality, which says the following: let $X$ be a nonnegative random variable and $a>0$, then $Pr(X \geq a) \leq \mathbb{E}[X]/a$. In this case, let the random variable $X$ be $-\log p(X)$. Then an application of Markov's inequality gives, for all $a>0$:
$$P(-\log p(X) \geq a) \leq \frac{\mathbb{E}[-\log p(X)]}{a} = \frac{H(X)}{a}$$
Now, set $a = \log \frac{1}{d}$, so that we get
$$P(-\log p(X) \geq \log \frac{1}{d})\log \frac{1}{d} \leq H(X)$$.
Finally, notice that $-\log p(X) \geq \log \frac{1}{d}$ is equivalent to $p(X) \leq d$.
Comment: Aha! Thank you. At a glance I could also do this with X=log(1/p(x)) with assumptions about how it behaves at x=0 right? Thats been the more natural choice for me as I learn about entropy
Comment: $\log (1/p(x)) = - \log p(x)$
Comment: Right but 1/p(x) has an undefined value for p(x)=0 so we have to add assumptions no? ie the coeffecient of 0 takes precedence by my estimation


How to route .html and .js files as PHP on Nginx FastCGI server?

Question: For web servers using PHP as apache module:
AddType application/x-httpd-php .html .htm

For web servers running PHP as CGI:
AddHandler application/x-httpd-php .html .htm

I have an Nginx server and I want to run .js files and and .htm files as PHP, so I will have full PHP code inside them. Anyone know how to configure the Nginx to do this?
Comment: Are you sure this is a wise idea? It means that for every request for a HTML or JS file, the PHP interpreter will be started. It might be more resource saving to use URL rewriting for this
Comment: Can you explain the reasoning for wanting to do this? (It is a possible security risk and drag on the server).
Comment: @ikano it's a performance problem but I can't see how it is a security risk, can you elaborate? (Edit: Ah, I suppose you mean that code may get executed in arbitrary uploaded files)
Comment: Exactly, code execution in uploaded files :-)
Comment: I will serve it on a subdomain. Basically I am creating an ad server for a client. And they want to serve ad codes to their sites. So http://ad.nginx.com/serve.js?client=2343&zone=2&banner=22 example
Answer: Passing to fastcgi didn't work for me. After a few hours of searching, I have found solution here:
http://ffct.cc/solving-nginx-php-fpm-access-denied-issue/
In short:
since PHP versions > 5.3.8, to make it works, you should add directive to your php-fpm.conf:
security.limit_extensions = .php .html .js

The recognition sign is "Access denied." (notice that it's different from HTTP error 403) when accesssing .html or .js file.
Answer: Simple; just change
location ~ \.php$ {
        root           html;
       fastcgi_pass   127.0.0.1:9000;
       fastcgi_index  index.php;
       fastcgi_param    SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

to
location ~ \.(php|html|htm)$ {
        root           html;
       fastcgi_pass   127.0.0.1:9000;
       fastcgi_index  index.php;
       fastcgi_param    SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

Comment: location ~ \.php|\.html|\.htm$ {  ... would also work.
Comment: Another +1 for simplicity.
Answer: Example for .htm, .html files
  location ~ \.htm$ {
            root           html;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.htm;
            include        fastcgi.conf;
  }

Example for .js files
location ~ \.js$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

just change the extension and port settings if needed
Comment: Can it be limited to subdomains. Only .JS files I want to do this in a select folder area.
Comment: hmmm, getting a 502 now on all my js files.
Answer: Replying to this thread many years later, I spent three hours trying to solve this issue, I had all the right settings in my location block (php|html|htm) and in PHP-FPM (security.limit_extensions), my problem was that I already had the .html extension in a previous location which was used for some static files, so if anyone else is having issues despite using the right settings, please make sure that you're not making the same dumb mistake I did :)
Comment: Wow! Such a novice mistake to make and we all make these. Great find though! That would have been really painful and tiresome to NOT miss. Interestingly enough you did not just try a PHP and HTML file to see if it worked regardless :)
Answer: Tom's answer with the link:
http://ffct.cc/solving-nginx-php-fpm-access-denied-issue/
was really helpful. However, I was using php with php-fpm installed on mac os yosemite w/ homebrew. Changes to the php-fpm.conf file did not take effect until I added the following to my .bash_profile:
 # for homebrew php55
 export PATH="/usr/local/sbin:$PATH"

For details see:
brew info php55

Answer: In macOS 11.5 with PHP 8.0, when I browse http://localhost/index.html, it ends with 403 Forbidden
I had to change file /usr/local/etc/php/8.0/php-fpm.d/www.conf to set
security.limit_extensions = .php .html

PHP code blocks in my .html files are properly executed, following is my server block in nginx .conf file
server {
  listen 80;
  server_name example.local;

  root "/var/www/html";
  index index.html;

  location / {
    try_files $uri $uri/ =404;
  }

  location ~ \.html$ {
    fastcgi_pass   127.0.0.1:9000;
    include        fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
  }
}


How to let my application to be running even when Logged off the machine?

Question: I have developed a TCP Server. I want my TCP server to be running even when I log off my machine. So clients can connect to it even when my computer is logged off.  I was thinking if I must create a Windows Service to implement this approach, but I am not sure how to do so.
Please tell me how can I let my application to keep working even when my machine is logged off.
Comment: Here is a good place to start. http://msdn.microsoft.com/en-us/library/d56de412(v=vs.80).aspx
Comment: The only way to do what you want is to write a service or run your application as a service--as @JohnAtwood referenced.
Comment: Thank you for your answer, I am checking the link that you given me.
Comment: Can you please give me a link to learn how to write a service in C# ?
Comment: First task in @JohnAtwood link: http://msdn.microsoft.com/en-us/library/9k985bc9(v=vs.80).aspx
Answer: You could launch it as a task from Windows Task Scheduler and set it to run even if you aren't logged in. This would work even if the application isn't a service.
Comment: Thank you for your answer,  and it's a good answer but i need a more real time solution
Answer: You can create a service by following these instructions:
http://support.microsoft.com/kb/251192
And then installing it to your PC should be as simple as using
installutil MyService.msc

(installutil will be part of your .NET installation, eg in C:\Windows\Microsoft.NET\Framework\v3.5)
You can the configure it to Startup Automatically by running services.msc from the command prompt.
Answer: If you want to be able to shut down your machine and still let the client connect then you need to deploy your application on a server.
Comment: My application already running on a dedicated server, But the problem is when I log off the my server machine my application get closed. I need it to be running when logged off , i have no need it to be running when the machine is shut downed, I think you understand what I am talking about
Answer: Create a windows service and run it as LocalService http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.80).aspx


Find Sin Function from points?

Question: I have these points and I need to find the sine function can anyone please show me how to do this step by step? Or just give me pointers on where to start and what the equation actually is?
(0,2.8) (2.4, 3.3) (6.2, 2.9) (8.6 2.7) (9.9, 2.85)
Comment: Perhaps the connection between the given points and "the sine function" you "need to find" is clear to you, but it is a matter of guesswork for us Readers.  I suggest you compare this to worked exercises in your textbook for more context.
Comment: I am using a water bottles curves to calculate the area under the sin curve. I'm honestly have no clue how to find the sin function. @peter
Comment: To me the sine curve is simply $y = \sin x$.  Apparently it has a different meaning in your problem.  To calculate "area under [a] curve" will be a standard calculus exercise once a simple formula can be found, so perhaps you are thinking about a more general function, like $y = a \sin bx + c$, to fit the data points?
Comment: Is that a homework / assignment question? If so, can you show the entire question? A point (0, 2.8) seems funny as $|sin(x)|<=1$ so not sure what 2.8 is doing there?
Answer: The figure below shows the result of fitting with the function $y = a_0+ a_1\sin(\omega x) + a_2\cos(\omega x)$
Of course, this result can be written on the form $y = a_0+ a_3\sin(\omega x + \phi) $

Find Sin Function from points?


How can I create internal links?

Question: Can someone please explain how site internal links work in Drupal? What is the most reliable way to display a link so that it goes to the same location every time?
I'm working on a preliminary website and right now, the only reliable way I can get a link to work the same way on all pages is to use absolute links (starting with http://and including the domain name for the host)  for each link. Since this website is currently local, this is not practical because I'll need to change all the links in the website when it goes live.
Eventually, I'd like to put these links in a menu I've got displayed at the top of all pages in my site.
Comment: It's not clear what you are asking. Please post some example code and explain how it behaves currently and how you wish it would behave.
Answer: In HTTP, links starting with http:// and including a domain name (e.g. http://example.com/foo/bar) is known as absolute paths.  On a Drupal site, they should only be used for off-site links.  Links not starting with http:// (e.g. /foo/bar) is known as relative paths. Relative paths should be used for internal links on your site. When a relative path starts with a slash (/) it is relative to the Drupal site root.  When it does not, it is relative to the location where it is embedded.
By making sure all internal links are specified using relative paths, they will not have to be changed when you move your site from one server to another.
For example, to link to /node/42, (provided you've clean URLs enabled) you can use the following markup:
 Link to node 42

(For menu items, as described bellow, you should omit the initial /, as menu items are always relative to the Drupal root.)

Eventually, I'd like to put these links in a menu I've got displayed at the top of all pages in my site.

Support for this use case is already in place in Drupal.
Navigate to: Administration » Structure »  Menus and click on the link "List links" for the Main menu.  Then click on Add link.  In the field "Path" type in the relative path to the location (e.g. node path) in your site you want this menu item to point. Also provide meaningful "Menu link title" and "Description" strings.  End by clicking Save. Now the link will appear in your main menu, which in most (including the default "Bartik") themes are displayed at the top of all pages on the site.
Comment: Thanks! using the preceding "/" to refer to the root worked! I feel like I tried this before with strange results but for now, it seems to be working!
Answer: Drupal 6 (obsoleted)
Path Filter rewrote internal:node/123 links to e.g. http://example.com/en/content/my-node-alias
Drupal 7
Pathologic offers the same feature (though only minimally documented)
Drupal 8
Pathologic is currently (2018-01) not yet usable.
Internally drupal has uri schemes like base:robots.txt, entity:node/1, route:myroute/arg1/arg2 that you can use in e.g. menu links. But there seem not to be a text filter that leverages these.
Answer: If you're still fairly new to Drupal and haven't seen it yet, you might want to add in ckeditor and ckeditor_link modules. This will provide your users with an easy way of adding internal links within your site without having to worry about paths and links with any markup.

How can I create internal links?


Adding and subtracting variables which are part of an interval

Question: I am following a paper proof which starts with the following constraint:
$$\forall v \in [a,b], \forall \tilde{v} \in [a,b]$$ $$f_{i}(v) \geq f_{i}(\tilde{v}) + (v-\tilde{v})g_{i}(\tilde{v})$$
In the proof, the author writes let $h = \tilde{v} - v$ therefore we have:
$$ f_{i}(v) \geq f_{i}(h+v) + h*g_{i}(h+v)$$
I understand that this is when
$\forall v \in [a,b]$
However, what interval will $h$ be defined in? Would it be that all $\forall h \in [a,b]$?
If $v=a$ and $\tilde{v} = a$ then $h \not\in [a,b]$?
Answer: You can show that $h$ will verify $$-|a-b| \leq h \leq |a-b|$$
So indeed, often $h\not\in [a,b]$
Comment: Thank you for your help. Put then if $\tilde{v}=h+v$, how can it be that $\tilde{v} \in [a,b]$? For example, letting $[a,b] = [0,1]$, $h \in [-1,1]$ and as $\tilde{v} = h+v$, we get $\tilde{v} \in [-1,2]$? This contradicts the fact that $\tilde{v} \in [0,1]$
Comment: The value of h depend of the value of v : you can't have h=-1 if v is different from 1, and you can't have h=1 if v is different from 1


Auto correlation function in R what are the error lines

Question: If one invokes acf() function in R the estimated acf values are plotted together with blue error lines. What are they (the lines)?
Answer: This question has been answered before here. They represent statistical significance, where the null hypothesis is:
$$H_0: r_k=0$$
The test statistic is:
$$\mid r_k\mid>\frac{1.96}{\sqrt{n}}$$
See Cowpertait & Metcalfe (2009) for more about time series analysis in R.


Tangent at a point on a PathGeometry

Question: GetPointAtFractionLength
pathGeometry.GetPointAtFractionLength(progress, out point, out tangent);
GetPointAtFractionLength gives a point on the pathgeometry and a tangent at that point if factional length is given.
I have the point already but I don't have the (factional length)progress. Is there a method just to get the tangent to the pathgeometry at a given point on the pathgeometry?
Answer: You could use the Bisection method (Wikipedia article on Bisection) to find the fraction at which the output point is closest to your given point and then use the out tangent at that value.  Depending upon the shape of your curve you could have local minima that could cause problems, so you may want to start with a linear search until you get close, and then use Bisection to find an accurate answer.
Answer: Have a look at this question: Getting length of a PathGeometry (lines) in C#/WPF
This question and its answers show a way to calculate the point by flattening the curve.

Tangent at a point on a PathGeometry


Why $\frac{|1-z|}{1-|z|}\le K$ corresponds to the region defined by the Stolz angle?

Question: In his presentation of Abel's theorem, Ahlfors mentions that for a fixed positive number $K$, the region defined by \begin{equation}
\frac{|1-z|}{1-|z|}\le K
\end{equation} corresponds to the region inside the unit circle and in a certain angle with vertex $1$, symmetric around the x-axis.
This should not be too difficult, but I cannot actually see how that inequality is related to that geometric picture.
Can someone give a hint?
Thanks!
Comment: Cf. https://math.stackexchange.com/q/1861413/96384
Answer: It's not an equality. The Stolz angle with opening $\alpha > 0$ and radius $r$ is
$$S(\alpha,r) = \{1 - \rho e^{i\varphi} : 0 < \rho < r,\; \lvert\varphi\rvert < \alpha\},$$
a circular sector that for $\alpha < \pi/2$ and small enough $r$ (depending on $\alpha$) is contained in the unit disk. Its boundary consists of two straight line segments, and one circular arc.
For $0 < K < \infty$, the region
$$R(K) = \left\lbrace z \in \mathbb{D} : \frac{\lvert 1-z\rvert}{1-\lvert z\rvert} < K \right\rbrace$$
is bounded by a curve that contains no straight line segment. But as $z$ approaches $1$ on the boundary of $R(K)$, the angle between between the real axis and $1-z$ approaches a limit $< \pi/2$ (namely $\arccos K^{-1}$).
The equivalence of the two conditions is to be understood in the sense that if we consider $R(K,r) = \{z \in R(K) : \lvert 1-z\rvert < r\}$, then for every $K \in (0,\infty)$, there is an $\alpha < \pi/2$ with $R(K,r) \subset S(\alpha,r)$, and for every angle $\alpha \in (0,\pi/2)$, there is a $K < \infty$ with $S(\alpha,r) \subset R(K,r)$ (where $r$ is always supposed small enough that $\overline{S(\alpha,r)}\setminus \{1\}$ is contained in the unit disk). Demonstrations at wolfram.
Comment: How do you come to the conclusion that "as $z$ approaches $1$ on the boundary of $R(K),$ the angle between $1 - z$ and the real line approaches a limit which is $\arccos K^{-1}\ $"?
Comment: How do even you come to the conclusion of the equivalence that you mentioned at the end? Diagrams are only there to build some intuition but it cannot be considered as a proof. So the visual demonstration you mentioned is not a valid proof.


number of subrectangles

Question: I have a square matrix generated by a cyclic shift of a vector which contains only 0's and 1's. For example,
$$
\begin{matrix}
1 \; 1 \; 0 \; 1 \; 1 \\
1 \; 1 \; 1 \; 0 \; 1 \\
1 \; 1 \; 1 \; 1 \; 0 \\
0 \; 1 \; 1 \; 1 \; 1 \\
1 \; 0 \; 1 \; 1 \; 1
\end{matrix}
$$
I would like to count the number of rectangles which have 1's as their vertices and which edges are parallel to rows and columns of the matrix. Here are the examples of such rectangles (the vertices are bold):
$$
\begin{matrix}
\textbf{1} \; \textbf{1} \; 0 \; 1 \; 1 \\
\textbf{1} \; \textbf{1} \; 1 \; 0 \; 1 \\
1 \; 1 \; 1 \; 1 \; 0 \\
0 \; 1 \; 1 \; 1 \; 1 \\
1 \; 0 \; 1 \; 1 \; 1
\end{matrix} \; \; \; \; \;
\begin{matrix}
\textbf{1} \; 1 \; 0 \; 1 \; \textbf{1} \\
1 \; 1 \; 1 \; 0 \; 1 \\
1 \; 1 \; 1 \; 1 \; 0 \\
0 \; 1 \; 1 \; 1 \; 1 \\
\textbf{1} \; 0 \; 1 \; 1 \; \textbf{1}
\end{matrix}
$$
I believe, there is an algorithm which solves this problem, but since the structure of the matrix is known it seems to me there must be an analytic approach. Is it possible to compute this number in general case for arbitrary generating vector?
Answer: For each $i\in \{0,1,\dots,n-1\}$, let $b_i$ be the zero-one vector describing the $i^\text{th}$ row. The number of rectangles between $b_i$ and $b_j$ is $\binom{b_i\cdot b_j}2$, where $b_i\cdot b_j$ is the dot product between rows numbered $i$ and $j$. This is because there are $b_i\cdot b_j$ columns where there is a one in both rows $i$ and $j$, and a rectangle is given by choosing two such columns.
You can then get the total number of rectangles by summing that quantity over all $0\le i<j\le n-1$.
$$
\sum_{i=0}^{n-1}\sum_{j=i+1}^{n-1} \binom{b_i\cdot b_j}{2}=\frac12\sum_{i=0}^{n-1}\sum_{j=i+1}^{i+n-1}\binom{b_i\cdot b_j}2=\frac n2\sum_{j=1}^{n-1}\binom{b_0\cdot b_j}2
$$
Writing our initial vector as $b_0=(x_0,x_1,\dots,x_{n-1})$, with each $x_i\in \{0,1\}$, you can express the dot product $b_0\cdot b_j$ as $\sum_{k=0}^{n-1} x_kx_{k+j}$.
Comment: Thank you for your answer!

number of subrectangles


Session breaks Entity API

Question: Whenever I try to use $_SESSION or variable_set it breaks the Entity API. It says

"Fatal error: Call to undefined function entity_get_info() in
  mydrupal\sites\all\modules\entity\includes\entity.inc on line 55"

And then I have to reinstall the entire website because this fatal error shows up on every page. So I can't even access any of the adminscreens or anything to uninstall the modules or anything.
Does anybody here know if this is just a bug or am I doing something wrong? I was just filling the session with an entity.
Comment: Drupal keeps it's own cache of entities. If you keep it in a session, on the next page load there will be a discrepency between what Drupal thinks the state of the object is and what you think it is. Best to avoid this, keep the ID instead.
Answer: Variables are serialised (as are session writes as I understand it), and complex objects like entity API entities don't serialise well.
The better solution would be to store the entity type and ID in the session, then load it when reading:
<code>$_SESSION['saved_entity'] = array('type' => 'node', 'id' => 1);

...

$saved_entity = entity_load($_SESSION['saved_entity']['type'], array($_SESSION['saved_entity']['id']));
</code>
And do the same thing for the variables.

Session breaks Entity API


Error in Milnor's Characteristic Class Chapter 12?

Question: I've read the proof of theorem 12.5, and in the last step, he said

... If the dimension $n$ is odd, then the Euler class itself has order $2$ by 9.4, so we have proved that $\mathfrak{o}_n(\xi) = e(\xi)$.
If the dimension $n$ is even, we must prove that $\lambda_n = +1$...

In here, $\xi$ is an arbitrary $n$-vector bundle over some manifold $B$ with fibre $F$.
But, we know that $\pi_{n-1}V_1(F)$ is same with infinite cyclic group if $n$ is odd and $\mathbb{Z}/2\mathbb{Z}$ if $n$ is even. (Note that, the top obstruction class $\mathfrak{o}_n(\xi)$ is in $H^n(B; \{ \pi_{n-1} V_1(F)\})$. It seems not to match what he want to prove and what we know.
What am I missing?
Answer: I'm not sure where you're getting your description of $\pi_{n-1}V_1(F)$: it is in fact always $\mathbb{Z}$.  Indeed, $V_1(F)$ is nothing other than the unit sphere in $F$, which is $S^{n-1}$ since $F$ has dimension $n$.  The chosen orientation on $\xi$ moreover gives an orientation on these unit spheres in all the fibers of $\xi$ at once, and so makes the local coefficients system $\{\pi_{n-1}V_1(F)\}$ just the trivial system of coefficients in $\mathbb{Z}$.
What is true is that if $n$ is odd, then the class $e(\xi)\in H^n(B;\mathbb{Z})$ satisfies $2e(\xi)=0$, and so $\lambda e(\xi)=e(\xi)$ for any odd integer $\lambda$.  That's why the proof is complete in the case where $n$ is odd, having shown that $\lambda_n$ is odd.


Is it possible to refresh chrome without having inspected HTML collapse?

Question: Every time I make a change and refresh the page I all the HTML in the dev tools view collapses and I end up loosing my place. Is it possible to stop this from happening?
Comment: A temporary fix is to select a different tab form the developer menu before refreshing.
Answer: It looks like this is a bug that has returned. It should keep the currently selected node expanded upon refresh. I have added a comment to an existing bug, which needs to be re-opened. In the meantime, you can expand all nodes with Ctrl+Alt+Click (Windows) or Alt+Click (Mac).
Update (Sep 2 2016):
A new issue was re-opened for this and the progress can be followed here.
Comment: So this had started working again and now it literally just broke. Is it just me? Do i need to reinstall or something? or is the bug back?
Comment: Thanks! I thought I was going crazy cuz I was sure it didn't used to do this, and my friend confirmed that it happened with him to and he thought It was always like this.

I just made an account and added a comment, will I get notified of any updates now? I couldn't find a "watch" feature.


Sum of derivatives of a polynomial

Question: Let $p(x)$ be a polynomial of degree $n$ satisfying $p(x)\geq 0$ for all $x$. That is, for all $x$, $p(x) = a_n x^n + a_{n-1} x^{n-1} + \cdots + a_1 x + a_0 \geq 0$, $a_n\neq 0$.
Show that $p(x)+p'(x)+p''(x)+\cdots+p^{(n)}(x)\geq 0$ for all $x$ where $p^{(i)}(x)$ is the $i^\text{th}$  derivative.
My interest: I know that, we can rewrite the LDE as follows
$$
p(x)+p'(x)+p''(x)+\cdots+p^{(n)}(x) = Lp(x)
$$
where $L := I + D + D^2  + \cdots + D^{(n)}$. Can we say anything about a linear operator of this kind so that it does not change the sign of the input it takes? I can try to solve the question by writing for all the derivatives and factoring them using $p(x)$, but I think there should be a clever way of showing this by the properties of $L$. Can I figure out a solution by just looking at $L$ and the sign of $p(x)$ as in the question? Where should I look for that?
Comment: I seem to remember that there was a slick trick exploiting that $(I-D)Lp = p \geq 0$, but I don't remember how that worked.
Answer: I have to admit the following solution was proposed to me by a friend, I did not find it:
Let $$f(x) = p(x) + p^\prime(x) + ... + p^{(n)}(x) $$
Note that
$$ f^\prime = p^\prime + p^{\prime \prime} + ...+ p^{(n)} $$
that is,
$$ f = p + f^\prime$$
Clearly $n$ is even. Hence $f$ has even degree, too.
This implies that $f$ attains it's absolute minimum (it's not a maximum, as $f$ behaves like $p$ at infinity) in some point $z_0$, hence
$ f^\prime(z_0) = 0.$ Consequently, $\forall x$,
$$f(x) \ge \min(f) = f(z_0) = p(z_0) + f^\prime (z_0) = p(z_0) \ge 0 $$
Comment: That's nice! And it seems to be completely different from my answer. After getting $f = p + f'$, your (friend's) answer uses the fact that $f$ attains an absolute minimum; my answer uses the fact that $e^{-x}f(x) \to 0$ as $x \to \infty$. So between them, the two approaches cover more classes of function that either answer alone.
Answer: Instead of $L_n := (1 + D + D^2 + \dots + D^{n})$, use $L_{\infty} := (1 + D + D^2 + \dots)$, which comes to the same thing for polynomials of degree $n$ or less. If we let
$$\sigma(x) = p(x)+p'(x)+p''(x)+\dots+p^{(n)}(x) = L_{\infty}(p)(x)$$
then we can sum the geometric progression in $D$ to get
$$\sigma(x) = ((1 + D + D^2 + \dots)p)(x) = ((1-D)^{-1}p)(x)$$
Thus
$$p(x) = ((1-D)\sigma)(x)$$
This might look like trickery, but if you check it against the original expression for $\sigma$ you can see that it works:
$$((1-D)\sigma)(x) = p(x)+p'(x)+p''(x)+\dots+p^{(n)}(x) -
(p'(x)+p''(x)+\dots+p^{(n)}(x))$$
$$= p(x)$$
Now define $\tau(x) = e^{-x}\sigma(x)$, so $\tau'(x) = e^{-x}(\sigma'(x) - \sigma(x)) = e^{-x}((D-1)\sigma)(x) = -e^{-x}p(x)$. By hypothesis, this is $ \le 0$ for all $x \in \mathbb R$. Also, $\sigma$ is a polynomial, so $\tau(x) \to 0$ as $x \to \infty$. Therefore $\tau(x) \ge 0$ for all $x$.
Hence $\sigma(x) \ge 0$ for all $x$, which is what we wanted.
Comment: @Didier: That is a question of style, not formal correctness.
Comment: +1. A similar argument shows that $p(x)+tp'(x)+t^2p''(x)+\ldots+t^np^{(n)}(x)\gt0$ for every $x$ and every $t\geqslant0$.
Comment: @Didier: Thank you for correcting my mistake. I have reverted a couple of your gratuitous edits, because it is, after all, my response.
Comment: Of course. Sorry for the trouble. Nice answer.
Comment: Very nice! Not that it matters much, but there is now a switch from $1$ to $I$ in the second displayed formula (meaning: before that you write $1$ consistently, afterwards $I$).
Comment: Note however that using $1$ (one) to denote $I$ (the linear map identity) is (1) formally incorrect and (2) in contradiction with the question itself.
Comment: @t.b.: I've tidied it up now.
Comment: You even proved $\sigma(x)>0$.
Answer: You can use the identity $\int e^{-x} p(x)dx = e^{-x}\sum \frac{d^n}{dx^n}p(x) + C$: Set $F(x) = \int_{-\infty}^x e^{-t}p(t)dt$ and obviously $F(x) \geq 0$ when $p(x) \geq 0$.

Sum of derivatives of a polynomial


Reset identity column with last value of table's identity in postgres

Question: I would like to changes my existing column as Auto Identity in a Postgres Database.
I used below script to set auto identity column and set default start with 1.
But here i would like to reset identity column value to table's last value.
Let me know if you have any solutions.
ALTER TABLE patient
    ALTER patientid SET NOT NULL,
    ALTER patientid ADD GENERATED ALWAYS AS IDENTITY (START WITH 1);

Here I'm setting up something like this:
 ALTER TABLE Patient
   ALTER COLUMN PatientId RESTART WITH (select Max(patientId) + 1 from patient);

Answer: An identity columns is also backed by a sequence, and pg_get_serial_sequence() will return that sequence name. That can be used together with setval().
After running the add generated always part you can adjust the sequence using this statement:
SELECT setval(pg_get_serial_sequence('patient', 'patientid'),
                                      (select max(patientid) from patient));

Comment: @NayanRudani: as I wrote in my answer: an `identity` column also uses a sequence. The above code **will** work for `identity` columns just as well.
Comment: That solution i already know. but i don't want to use serial.here i would like to use identity as describe in a question.
Comment: I got it. Thanks


Enterprise Samba fileserver management

Question: Can anyone recommend a gui (webbased or windows) to manage a samba fileserver (active directory integration, smbcquotas,...)?
Answer: SWAT is the official web based tool from SAMBA. Can't comment on how good or bad it is as I don't use it.
Answer: RHEL (and it's variants) come with system-config-samba which does a pretty decent job of managing Samba shares, and it works even better if you use SWAT to setup the who Samba installation
Answer: http://gadmintools.flippedweb.com/index.php?option=com_content&task=view&id=16&Itemid=30
you can try above link!!
Answer: There are many listed on the samba website .
I cannot recommend one over the other as our samba setup is so minimal I just edited the configuration files.
Answer: Webmin is a web based config / monitor tool for Linux. It uses perl, so should run out the box on most distros. It has samba modules, and many more.
But if you make up a lot of shares then it may be worth you learning the share syntax of shares in the the smb.conf file.

Enterprise Samba fileserver management


Confidence interval for proportion of Successes

Question: I have the following histogram showing a dataset (1200 samples):
Histogram
My goal with this, is to say that with a certain confidence, that 90% of all samples are within -0.25ms and +0.25ms. Since it's been a while since I've worked with statistics, I'd like some help.
How do I find that confidence level?
Best regards.
Answer: One possibility: Let $X$ be the number of Successes in $n = 2000,$ where a Success is
an observation within $\pm 25ms.$ Also, let $P(\text{Success}) =\theta.$
Then $\hat \theta = X/n.$ A 90% confidence interval for $\theta$ is
of the form
$$\hat \theta \pm 1.645\sqrt{\frac{\hat \theta(1-\hat \theta)}{n}}.$$
Using this in a paper or report, you'd need to explain carefully because you have two intervals, $\pm 25$ms and
and the confidence interval for $\theta.$
I have removed the word 'guarantee' from your title, because a
confidence interval is hardly a guarantee.


Calculate Bockstein homomorphism

Question: I would like to ask how to compute the Bockstein homomorphism $\beta: H^k(M^d,\mathbb{Z}_n) \to H^{k+1}(M^d,\mathbb{Z}_n)$? Can one compute the Bockstein homomorphism from the universal coefficient theorem
$$0 \to H^d(X, \mathbb{Z}) \otimes M \to H^d(X, M) \to \operatorname{Tor}(H^{d+1}(X, \mathbb{Z}), M) \to 0$$
and/or other needed information (such as the cohomology rings $H^*(M^d, \mathbb{Z}_n)$, $H^*(M^d, \mathbb{Z})$, and homology groups $H_*(M^d, \mathbb{Z})$)?
Answer: The Bockstein homomorphism (between homologies with coefficients in $\mathbb{Z}_n$) has some relation to the universal coefficient theorem. Roughly speaking, it is$$\text{H}_k(X, \mathbb{Z}_n) \to \text{Tor}(\text{H}_{k - 1}(X), \mathbb{Z}_n) = \text{Tor}(\text{H}_{k - 1}(X)) \otimes \mathbb{Z}_n \to \text{H}_{k - 1}(X) \otimes \mathbb{Z}_n \to \text{H}_{k -1 }(X, \mathbb{Z}_n)$$(I say "roughly" because the equality in this composition is not canonical). But it seems to be more natural to relate the Bockstein homomorphism to the coefficient homology sequence induced by the short exact sequence$$0 \to \mathbb{Z} \to \mathbb{Z} \to \mathbb{Z}_n \to 0.$$Certainly, the cohomological Bockstein homomorphism is related to the cohomological multiplication by the usual product rule.

Calculate Bockstein homomorphism


Count all numbers from matrix list in python

Question: def count(matrix: list, number: int):

    count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 0)

I am trying to make function that counts all zeros or any other number from matrix list but for now its 0.
Comment: Because your input list contains only lists none of each equals 0. You need to [flatten it](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) first
Comment: So what does your code look like right now?
Comment: Also, does this answer your question? [python .count for multidimensional arrays (list of lists)](https://stackoverflow.com/questions/17718271/python-count-for-multidimensional-arrays-list-of-lists)
Answer: try this:
def count(matrix: list, number: int):
    return sum(l.count(number) for l in matrix)

count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 0)
# 9

count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 6)
# 2

Answer: import itertools
def count(matrix: list, number: int):
    return list(itertools.chain.from_iterable(matrix)).count(number)

count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 0)

9


Modificar estado de um determinado componente pela resolução da tela usando ReactJS

Question: Estou realizando um trabalho onde dependendo do tamanho da resolução da tela, mostre um texto ou outro. Gostaria de saber que é possível utilizar, no contexto de ReactJS, um useState ou algo semelhante para que, quando a resolução da tela for alterada, o texto de um certo componente mude. Abaixo, tem minha tentativa de realizar essa operação, mas gostaria que fosse verificado toda vez que a resolução for alterada (um exemplo, quando virar a tela de um smartphone ou tablet)
export default function Teste() {
  const [texto, setTexto] = useState(
    window.innerWidth <= 768
      ? "Exibe esse aqui, no mobile/tablet"
      : "Exibe esse cara aqui em resoluções maiores"
  );

  return (
    <Grid container>
      <Grid
        item
        xs={12}
        sx={{
          paddingTop: ["22px", "54px", "95px"],
          paddingLeft: ["38px", "93px", "254px"],
          height: ["16px", "21px"],
          fontSize: ["14px", "18px"],
          fontWeight: 700,
        }}
      >
        {texto}
      </Grid>
    </Grid>
  );
}

Answer: Tal como escreveste, podes utilizar um operador ternário e fazer:
const [texto, setTexto] = useState(
window.innerWidth <= 768
  ? this.setTexto('Exibe esse aqui, no mobile/tablet')
  : this.setTexto('Exibe esse cara aqui em resoluções maiores'));


derive the formula for the left rectangle sum $f(x)=x^2+1$ from $0$ to $3$

Question: Simply that, derive the formula for the left rectangle sum $f(x)=x^2+1$ from $0$ to $3$
This is when you use like rectangles and Riemann sums to approximate an integral.  Not really sure what this means to derive the formula ?
Comment: see example at: http://en.wikipedia.org/wiki/Riemann_sum
Comment: It's not clear to me whether you don't know the formula for the left rectangle sum, or whether you know it but you don't know how to get to it. To derive a formula means to show how someone might arrive at that formula. Roughly speaking, it means to prove that the formula is correct.
Comment: Yea I can work these problems out, it's pretty straightforward compared to the rest of calculus . But I'm not good at proofs though like don't even understand what its asking me to put down at all.
Answer: Can you follow the very similar example on this web site?
http://www2.seminolestate.edu/lvosbury/CalculusI_Folder/RiemannSumDemo.htm
It is important for you to learn what is going on here.
I would strongly recommend you use all three (left, right and midpoint) to find the integral.
Of course, you know what the answer should be by doing the integral.
Hint 1: Area = 12
Hint 2: See the left sum here:
http://www.wolframalpha.com/input/?i=INTEGRATE%5Bx%5E2%2B1%2C%7Bx%2C0%2C3%7D%5D&t=crmtb01
Please show your work if this is confusing.
HTH ~A


RTSP is the only stream working from my WOWZA streaming engine

Question: I have every stream type enabled on my wowza server.
a week ago i had it working in the wowza test players
now the only one that works is the RTSP in VLC
now every stream just shows a black screen.
If i try to access the m3u8 via Safari browser i can hear the audio but no visual
Any assistance on this would be a major help.
Answer: this is due to incompatible video, audio codec. you need to user right encoder or you can use wowza transcoder to transcode your stream (h.264 , AAC) . it will resolve your playback problem. if you are using flash media live encoder you can select h.264 encoding method, and audio codec should be aac or mp3.
Answer: Some quick troubleshooting steps:

What source encoder are you using? Can you playback the source URL on VLC as well? What codec info is displayed in VLC for the source stream? It should be one of the supported codecs for Wowza.
What codec info is displayed in VLC for the RTSP playback link generated by your Wowza server?
Do you see any errors/warnings in the access log when you publish and playback your HLS (m3u8) stream?

Usually, this kind of error is due to an incorrect video codec, or an encoding setting, or network saturation where the video packets are not coming through correctly. You can check what error or warning messages are being generated by tailing the access log found in logs/ folder of your Wowza installation directory.
Hope this helps.


Drupal 8 register link?

Question: I have a clean Drupal 8 install with bootstrap theme.
I just want to add a simple link to the registration form in the user account menu and to it only be visible if you are not logged in.
The login and my account links are already standard in, why isnt the register button there? What would be the solution to this?
Creating the link normally in the menu -> add link option makes it visible all the time.
Comment: Really? Anyone here?
Answer: Why create new route? There is one already! Via admin panel, create new menu item at 'account' menu. Link hidden after login (RegisterAccessCheck class will hide it).
<code>fill fields:
name = Register
uri = route:user.register
</code>
UPDATE1
You will see link as admin, but others - don't
Answer: We've contributed a small module which solves this issue: https://www.drupal.org/project/registration_link
Answer: I haven't been able to find a contributed module that might make this easier, so the only other possibility is code.
What you are basically asking for is the altering of an existing route, that was defined by the User module.
I'm not sure how much experience you have with the new Drupal 8 architecture and APIs, so I'm going to just dump a few links here :p
The first is the documentation of the new routing system that Drupal 8 is using.
The route that you want to change is the one with the path /user/register, so you will have to look for the route's name and alter it.
A good article about how to do that can be found here. Your use-case is very similar to what the example shows with the logout route.
So basically you will have to write a RouteSubscriber that will alter your route, based on the current user's loggedIn status. I'm not at my PC at the moment, so I can't give code example, but if you need, then I can share a solution.
Be advised, that there are lots of new concepts that you will have to understand first, but if you already know Drupal 8, then you will have no problem with the aforementioned solution.
Another possibility would be to hide the link from the theme layer, in a Account Menu's preprocess function.
Comment: Thank you very much for your links, I try to read about it.
The concept of Drupal 8 are new to me, I'm used to the Drupal 7 way, so it feels like I'm a total beginner...
Its really really out of my understanding, why a registration link isn't an out of the box link...
Comment: You are welcome!

If I had to guess, user registration is not something that can always be done by the user, as Drupal allows administrators to restrict user registration. So maybe that's why there's no out of the box functionality the way you want.

You could create new menu and add your registration link to that and then from the block layouts page you can add it between main menu and user account menu.

And if you have access to the code base, then you could alter the CSS so that your new block will have the properties of .navbar-right .navbar-nav CSS classes.
Comment: Thank you! You were pretty helpful. Thats probably the best way to do it easy, though its not super clean :)

Drupal 8 register link?


How to edit how Commerce outputs the Billing and Shipping information in the checkout review table?

Question: Drupal Commerce on the Review page of the checkout process (e.g. checkout/4/review) by default outputs billing and shipping information above each other in a table, with each line as a different
 row containing one table cell:

I'm trying to re-theme this such that it's responsive and has the two addresses side-by-side on wider breakpoints. I know how to code that HTML, my problem is, how to get my HTML into the Commerce page template?

There's no corresponding tpl file I can find anywhere in the Commerce module, and other answers linked below seem to confirm there isn't one
I can't find a corresponding View to edit
I've read theming checkout pages in Drupal commerce, where an answer suggests creating a file page--checkout--review.tpl.php - but no such file exists already, and I don't want to recreate the template from scratch and potentially miss some important subtlety from the logic of the original, I want to read, understand and then edit the original.
The answer to Customize drupal commerce checkout page doesn't offer the HTML control I need, likewise How to theme checkout completion page in Drupal Commerce. I know I can edit the form array using hooks, but I can't use hooks to make the fine adjustments to the HTML output that I need, removing them from the table to make them responsive.
I wrote the answer to Customize commerce cart form page, which uses a custom module to allow the table to be editted in Views - but this only works for the cart, not checkout

How can I edit (not re-write from scratch) the HTML of the checkout review table?
Answer: At time of writing, this isn't a viable solution, but I'm posting it because it might become one, one day.
Commerce Responsive UI module
There's a massive long 5-year-old issue matching my problems theming Commerce checkout in the Commerce issues queue. The "fix" was the creation of a module, Commerce Responsive UI, that aims to modernise the markup of the checkout (and other) pages and make them themable. It sounds like exactly what I'm looking for.
Problem is, there's no stable release, no release at all since November 2015, and it appears to have some serious unresolved issues, like breaking normal cart/checkout page paths. This might become a good answer to the question, but right now it's an unfinished work in progress.


How do I install rmagic 2.13.1 and imagemagick on OS X 10.8.2

Question: I've read a lot of posts it seems with issues on getting the rmagick gem installed on OS X but none of the solutions for setting PATH veriables for MagickCore seem to work for me. I keep coming up with the same stack trace when trying to install the gem.
Here is what I get every time and I am at a loss for how to get past it.
Installing rmagick (2.13.1) with native extensions
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

        /Users/mwallace/.rvm/rubies/ruby-1.9.3-p194/bin/ruby extconf.rb
checking for Ruby version >= 1.8.5... yes
extconf.rb:128: Use RbConfig instead of obsolete and deprecated Config.
checking for clang... yes
checking for Magick-config... yes
checking for ImageMagick version >= 6.4.9... yes
checking for HDRI disabled version of ImageMagick... yes
Package MagickCore was not found in the pkg-config search path.
Perhaps you should add the directory containing `MagickCore.pc'
to the PKG_CONFIG_PATH environment variable
No package 'MagickCore' found
Package MagickCore was not found in the pkg-config search path.
Perhaps you should add the directory containing `MagickCore.pc'
to the PKG_CONFIG_PATH environment variable
No package 'MagickCore' found
Package MagickCore was not found in the pkg-config search path.
Perhaps you should add the directory containing `MagickCore.pc'
to the PKG_CONFIG_PATH environment variable
No package 'MagickCore' found
Package MagickCore was not found in the pkg-config search path.
Perhaps you should add the directory containing `MagickCore.pc'
to the PKG_CONFIG_PATH environment variable
No package 'MagickCore' found
checking for stdint.h... yes
checking for sys/types.h... yes
checking for wand/MagickWand.h... yes
checking for InitializeMagick() in -lMagickCore... no
checking for InitializeMagick() in -lMagick... no
checking for InitializeMagick() in -lMagick++... no
Can't install RMagick 2.13.1. Can't find the ImageMagick library or one of the dependent libraries. Check the mkmf.log file for more detailed information.

*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/Users/mwallace/.rvm/rubies/ruby-1.9.3-p194/bin/ruby
    --with-MagickCorelib
    --without-MagickCorelib
    --with-Magicklib
    --without-Magicklib
    --with-Magick++lib
    --without-Magick++lib

Gem files will remain installed in /Users/mwallace/.rvm/gems/ruby-1.9.3-p194@recruittalk/gems/rmagick-2.13.1 for inspection.
Results logged to /Users/mwallace/.rvm/gems/ruby-1.9.3-p194@recruittalk/gems/rmagick-2.13.1/ext/RMagick/gem_make.out
An error occurred while installing rmagick (2.13.1), and Bundler cannot continue.
Make sure that `gem install rmagick -v '2.13.1'` succeeds before bundling.

Answer: I'm having the same problems. I need to say though that I'm very new to Ruby, Rails, Homebrew, (and yes Unix file structures)... but...
I suspect that once you solve the PKG_CONFIG_PATH issue, you'll have another one. I'll make a quick suggestion that may or may not work for the first one and then explain what I did for the second.
First, somewhere I found a suggestion to add this to .bashrc: PKG_CONFIG_PATH="/usr/local/lib/pkgconfig". I did this a couple hours ago and it may have fixed the first problem for me. I don't remember exactly though.
Second, I think that imagemagick version 6.8 has deprecated methods needed for these:
checking for InitializeMagick() in -lMagickCore... no
checking for InitializeMagick() in -lMagick... no
checking for InitializeMagick() in -lMagick++... no

and so an earlier version will still have them. I followed an instruction here (http://wearepandr.com/blog/article/homebrew-and-installing-old-package-versions) for installing an older version of a package. After uninstalling imagemagick, running the suggested command in /usr/local/Library/Formula/, and reinstalling imagemagick, I was able to successfully install the rmagick gem. I picked 6.7.1-1 kind of randomly.
I really think somebody ought to update rmagick to reflect changes to it's dependencies (it's stale by a year or two). But I don't know enough to do that myself.
Answer: I recommend switching to the mini_magick gem. You get all the capabilities provided by ImageMagick, but much easier installation and a somewhat lower memory footprint.


Proving that a punctured disk is not simply connected, using a specific definition

Question: I am dealing with the same set based on my previous question. I want to show that the set $H = \{z \in \mathbb{C} : 0 < |z| < 1\}$ is NOT simply connected, using the following definitions, that our teacher insists upon us using:
A region $G$ is simply connected iff $\mathbb{C}^{\infty} \setminus G$, its complement in the extended plane, is connected in $\mathbb{C}^{\infty}$.
A set $H$ is not connected if $\exists$ open sets $U$ and $V$ such that $$U \cap H \neq \varnothing, V \cap H \neq \varnothing, \ H \subseteq U \cup V, \ \mathrm{and} \ U \cap V = \varnothing.$$
If I can show that the set $\mathbb{C}^{\infty} \setminus H$ is not connected in $\mathbb{C}^{\infty}$, then I will have that $H$ is not simply connected.
But how can I come up with sets $U,V$?
Thanks in advance for help.
Comment: Still, link to the pervious question.
Comment: The complement of your set is $\{0\} \cup \{z \in \Bbb C^\infty : 1 \leq |z|\}$.
Answer: Note that the punctured disk is punctured, in that it does not contain $0$. Further, you can enclose $0$ in a small open ball $B$, and $\{ z:|z| \geq 1 \}$ in the complement of a closed ball. Calling this ball $C$, we need it to be such that $B \cap C^{\complement} = \emptyset$. The complement of $H$, which is $ \{ 0\} \cup \{ z: |z| \geqslant 1 \} $, is contained in these two disjoint open sets.
Comment: Well, you can take something like $\{ z : |z| \leqslant 9/10 \}$, for example. That gives you plenty of room if you use $\{ z_S: |z| < 1/10 \}$ to cover $\{0\}$.
Comment: @arabhimanachra Couple of typos. Fixed.
Comment: Thanks. What is an example of such a closed ball $C$? I am not able to think of one!
Comment: In that case... $B \cap C^{\complement} = \varnothing,$ not $B \cap C = \varnothing$, as in your answer.
Comment: Hm. Bracketing error. Made it unambiguous.
Comment: I really understand now.


I want to login with twitter in Cakephp2.5.4

Question: I am a new in cakephp 2.x platform. Now I am trying to connect my application login with twitter. I get lots of tutorial from the net. But all are not specified exactly for better understanding.
I'm searching for some docs or examples on CakePHP and logging in with Twitter.
If I use this program, do I have to download the Opauth CakePHP plugin? Is this plugin a must or is it optional, if I didn't use this plugin can I run this program?
Please show me some good tutorials for this program.
Answer: Have to tried this tutorial given by Mifty - http://miftyisbored.com/complete-social-login-application-tutorial-cakephp-2-3-twitter-facebook-google/
Please try this, it will help you.


How do I Estimate Joint Entropy Using a Histogram?

Question: I am trying to estimate the entropy for two time series, defined by random variables $X$ and $Y$, each distributed according to an unknown PDF which is to be estimated empirically (using a histogram approach, and binning data equally according to Sturge's rule)

In one dimension, I believe that we can use the estimated PDFs to then estimate the entropy of $X$, which is defined in this case for $n$ bins by:
$H(X)= -\sum \limits_{i=1}^{n} P(x_i)\log P(x_i)$

Am I correct in my understanding that, considering the histogram approach, we can simply take the  proportion of the total samples which lie within the bin as $P(x_i)$, multiplied by the log of the same, and perform a weighted sum across all bins using the midpoint value within each bin as the weight?

However, to calculate the joint entropy between X and Y, we have multiple dimensions:$H(X,Y) = - \sum\limits_{i=1}^{m}\sum\limits_{j=1}^{n}p(x,y)\log p(x,y)$

I am not sure that performing the same procedure as above, only now in the $X$ and $Y$ direction, quite achieves this. Is the approach correct? Should we perhaps only consider the bins on the diagonal? (i.e. $i=j$)

Finally, as I am performing an autoregressive analysis, I also have additional variables representing lagged time series (e.g. $X - \Delta$, $X - 2\Delta$ etc.). I therefore need to be able to perform the calculation in the N-dimensional case.

I am using Pandas data frames in Python to store the time series and perform the calculations, so answers with code samples are welcomed!
Answer: Joint entropy fundamentally relies on the joint distribution and there is no way to approximate it based on marginal distributions: histograms for each $X$ and $Y$. You need a joint histogram for $(X;Y)$ that is a 2D histogram with $n\times m$ bins.
For example, if $X$ and $Y$ are independent, $H(X,Y)=H(X)+H(Y)$ but whether they are independent or not is in the joint distribution and there is strictly no information about it in marginals.
If your dataset is large enough so that each $n\times m$ bin is far from empty, it may work. I don't think using the diagonal only is likely to produce anything useful.
Maybe you can read advanced methods for continuous entropy estimation that would work in dimension $N$. KDE is often used. I found this article.
Comment: Thank you! I was envisaging a multi-dimensional histogram. However i'm not sure if my planned way to use it is correct. Specifically, in the 2D case, I'm assuming I should sum the midpoint in X of each bin, multiplied by the midpoint of Y in each bin, multiplied by the proportion of samples sitting in that rectangular bin, multiplied by the log of the same.  In the 3D case, I'd do the same over all cuboid bins. Will this return a valid cross-entropy estimate between (Y, X-$\Delta$, X-2$\Delta$) (assuming enough samples). Can we provide a bound on this estimate accuracy in this case?
Answer: Having spent more time working on this, it appears that the pdf can be estimated simply by considering the volume (in the 2d histogram case) of each bin as a proportion of the total volume. Since all bins in my implementation are the same size, I think I can use the height of each bar as a proportion of the total height (which equals number of samples N). Dealing with empty bins remains an outstanding question though, given the log term.
Using np.histogramdd() generalises to the many-dimensional case. I provide my current solution in the 2D case below, with sample time-series data. I still need to refactor the code to allow for a many-dimensional analysis, based on additional timelags, as the example doesn't yet consider lagged time series $Y - \Delta$, $X-\Delta$ etc.
<code>import numpy as np
import pandas as pd
from itertools import tee, islice, chain
from numpy import ma
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Function to return midpoints of bins in any dimension
def get_midpoints(hist_bins):
    l_bound, u_bound = tee(hist_bins, 2)
    u_bound = chain(islice(u_bound, 1, None), [None])
    return [(i+j)/2 for i,j in zip(l_bound,u_bound) if j is not None]

# Dummy data
N = 1000
ix = np.arange(N)
sin = np.cos(2*np.pi*ix/float(N/2)).reshape(N,1)
cos = np.sin(2*np.pi*ix/float(N/2)).reshape(N,1)
columns = ['Y','X1']
df = pd.DataFrame(np.hstack((sin,cos)),columns=columns, index=ix)

# Split data into bins according to Sturges formula
y_bins = np.log2(len(df['Y']))+1
x_bins = np.log2(len(df['X1']))+1

# Create 2d histogram
Hist, [by, bx] = np.histogramdd((df['Y'],df['X1']),bins=(y_bins,x_bins), normed=False)

# Get midpoint of bins
midpoints_y = get_midpoints(by)
midpoints_x = get_midpoints(bx)

# Get width of bins
width_y = (np.max(midpoints_y) - np.min(midpoints_y))/len(midpoints_y)
width_x = (np.max(midpoints_x) - np.min(midpoints_y))/len(midpoints_x)

# PDF array across bins = area of histogram bin divided by total area (since bins equal size we can just use height)
p_xy = [[ Hist[y][x] for x in range(len(midpoints_x))] for y in range(len(midpoints_y)) ]
pdf = np.array(p_xy)/np.sum(p_xy)

# Single entropy for each dimension H(X) = -sum(pdf(x) * log(pdf(x)))
H_Y = -np.sum( pdf.sum(axis=0) * ma.log2(pdf.sum(axis=0)).filled(0)) # Use masking to replace log(0) with 0
H_X1 = -np.sum( pdf.sum(axis=1) * ma.log2(pdf.sum(axis=1)).filled(0))

# Joint entropy H(X,Y) = -sum(pdf(x,y) * log(pdf(x,y)))
H_XY =  -np.sum(pdf * ma.log2(pdf).filled(0)) # Use masking to replace log(0) with 0

# Output
print('Joint Entropy H(Y,X1): ' + str(H_XY))

plt.plot(df)
plt.xlabel('Time')
plt.legend(['Y','X1'])
plt.title('Two time series Y, X1')
plt.show()

# Define 3d axes
fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

# Create an X-Y mesh of the 2D data
x_data, y_data = np.meshgrid(np.arange(Hist.shape[1]),np.arange(Hist.shape[0]))

# Flatten out the arrays to pass to bar3d
x_data = x_data.flatten()
y_data = y_data.flatten()
z_data = Hist.flatten()
ax.bar3d( x_data, y_data, np.zeros(len(z_data)), 1, 1, z_data)

# Finally, display the histogram
plt.show()
</code>
Comment: The log term is not a problem with empty bins if you code it correctly.  You're just trying to sum up terms of the form $f(x)\log(f(x))$ where $f(x)$ estimates a density near location $x$.  As $f(x)\to 0$, this expression goes to $0$, too.  Therefore, create a function `xLogx` which returns $0$ when its argument $y$ is exactly $0$ and otherwise returns $y\log(y)$ and use that in the computation.  The *real* issue to deal with concerns how much your code depends on the choice of bins and bin cutpoints.
Comment: Thanks; regarding the first point I believe I've achieved the same effect using the masking, so hopefully that is all acceptable.   To the second, agreed that the number/width of bins will make a large difference. Do you have any advice on how to improve this?
Comment: @Zac can you please share your final code? Also, did you get anything or experience regarding the bin width? Thank U


cannot use my model on my controller " Undefined type 'App\Usuario' " Laravel

Question: Hello I cannot use my model inside controller Undefined type 'App\Usuario' on Laravel.
When I try to, create, edit or remove an user I am getting error Undefined type 'App\Usuario' appears.
A few days ago the code worked for me but when I made another model called "paintings" they both stopped working. Maybe has some relation.
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class Usuario extends Model
{

    use Notifiable;
    use HasFactory;

    // ...
}

namespace App\Http\Controllers;

use App\Usuario;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class UsuariosController extends Controller

{
    public function index()
    {
        $usuarios = DB::table('usuarios')
            ->select('usuarios.*')
            ->orderBy('id', 'DESC')
            ->get();
        return view('usuarios')->with('usuarios', $usuarios);
    }

    public function store(Request $request)
    {
        $id = 0;

        // Validation ...

            $usuario = Usuario::create([
                'id' => $request->id,
                'nombre' => $request->nombre,
                'email' => $request->email,
                'contrasena1' => Hash::make($request->contrasena1),
                'contrasena2' => $request->contrasena2,
            ]);
            return back()->with('UsuarioAgregado', 'Usuario agregado con éxito');

    }

    public function destroy($id)
    {
        $usuario = Usuario::find($id);
        $usuario->delete();
        return back()->with("El ususario se elimino correctamente");
    }

    public function editarUsuario(Request $request)
    {

        $usuario = Usuario::find($request->id);

        // Validation ...

            $usuario->nombre = $request->nombre;
            $usuario->email = $request->email;
            $validator2 = Validator::make($request->all(), [
                'contrasena1' => 'required|min:7|required_with::contrasena2|same:contrasena2',
                'contrasena2' => 'required|min:7'
            ]);
            if (!$validator2->fails()) {
                $usuario->contrasena1 = Hash::make($request->contrasena1);
            }

            $usuario->save();
            return back()->with("El usuario se actualizo correctamente");

    }
}

Sorry if my English is not good.
[1]: https://i.stack.imgur.com/MCKnl.png
Comment: You seem to be missing the namespace at start of the model class.

namespace App;
Comment: Pleaz reformat your question! and tell what version of Laravel are you using if you can.
Comment: @MuhammadTashfeen OMG I LOVE YOU SO MUCH, THANK YOU.
It fixed my problem.
Now i have the same problem with "Pinturas" controller, i didnt make it using the console, could this be the problem?
Comment: "[CODE IMG AT THE END][1]" -- don't. Code should come as text, in many cases in the form of a [mcve], along with the output it produces, which should also be text.
Answer: Assuming that the class Usuario is located in the folder App this can be a Laravel 5 project.
the top of your model needs the namespace line
<?php

namespace App;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class Usuario extends Model

Comment: Thank u so much. It fixed my problem, now I have the same problem with "Pinturas" Model, i didnt make it using console, could this be a problem?
Comment: You can make your project files either manually or using **Artisan**. But the command line is the recommended way to avoid typo errors. like you did by forgetting the namespace. share you `painturas` class to get a solution
Comment: On my way medilies.
Oh i just fixed it, it was a similar error on my Model, thank u so much Medilies u helped me a lot, im making my final project of my grade formation.
Comment: @Esprulo lucky you for knowing how to use Laravel before your graduation :D. I did my graduation with PHP from scratch XD. good luck and don't forget to mark your question as answered/solved
Answer: maybe you need to use this code on the header of your controller :
use App\Models\Usuario;

that's a common problem. it depends on the structure of your project's directory.