How to inprove SVHN result with Keras?

Question: I'm using keras to build to CNN to train the famous SVHN (street view house number) data set(fist version, without cropping). I train the pictures as they all have five digit spot, for pictures have less numbers, I treat the empty spot as another category. So, I have 11 categories for each digit spot. I didn't use bbox yet. I can just get only 30% accuracy best for first two accuracy. I try different dropout rate, or adding one more convolution layer. But accuracy still very low. How can I tune my model to get a better accuracy? I don't to use the bbox at this stage. Is that possible to get a decent perform model?
from keras.models import Sequential
from keras.models import Model
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Input
from keras.layers.core import Dropout
identifier = Sequential()
x = Input((30,70,1))
y = (Convolution2D(64,3,3,activation = "relu",border_mode = "valid"))(x)
y = (MaxPooling2D(pool_size = (2,2)))(y)
y = (Convolution2D(64,3,3,activation = "relu",border_mode = "valid"))(x)
y = (MaxPooling2D(pool_size = (2,2)))(y)
#y = (Dropout(0.5))(y)
y= (Convolution2D(32,3,3,activation = "relu"))(y)
y = (MaxPooling2D(pool_size = (2,2)))(y)
#y = (Dropout(0.5))(y)
y= (Convolution2D(32,3,3,activation = "relu"))(y)
y = (MaxPooling2D(pool_size = (2,2)))(y)
y = (Dropout(0.5))(y)

y = (Flatten())(y)
y =(Dense(output_dim = 512,activation = "relu"))(y)
y = (Dense(output_dim=256,activation = "relu"))(y)
y = (Dense(output_dim=256,activation = "relu"))(y)
y = (Dense(output_dim=128,activation = "relu"))(y)
digit1 = (Dense(output_dim =11,activation = "softmax"))(y)
digit2 = (Dense(output_dim =11,activation = "softmax"))(y)
digit3 = (Dense(output_dim =11,activation = "softmax"))(y)
digit4 = (Dense(output_dim =11,activation = "softmax"))(y)
digit5 = (Dense(output_dim =11,activation = "softmax"))(y)
identifier = Model(input =x, output = [digit1,digit2,digit3,digit4,digit5])
identifier.compile(optimizer = "adam", loss = "categorical_crossentropy",metrics = ["accuracy"])
nb_epoch =3
identifier.fit(training_data.reshape(29329,30,70,1),train_labels,batch_size= 64,nb_epoch= nb_epoch,
               verbose= 1,validation_data=(test_data.reshape(600,30,70,1),test_labels))

Answer: Follow the famous SVHN paper (https://arxiv.org/abs/1312.6082). He had great ideas how to improve the classification.
In this paper, they introduce a convolutional layer, composed by a convolution, like you created, a batch normalization, a activation and a maxpooling.
They added 11 convolutional layers in the architecture. The convolution has a 5x5 filter and they use sometimes a stride of 2 in the maxpooling and sometimes a stride of 1.
The number of filters is much bigger too, starting with 48 filters in the first layer and finishing with 192 filters in the end.
The convolutional layer should look like this:
def svhn_layer(model, filters, strides, name):

    model.add(Conv2D(filters, (kernel_size, kernel_size),
           padding='same', name='conv2d_' + name))

    model.add(BatchNormalization())
    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(2, 2), strides=(strides, strides),
              name='maxpool_2d_' + name))

    model.add(Dropout(0.2))

    return model

where model is a keras Sequential.
After defining this layer, you can play with many combinations, varying filters and strides. Considering the paper, the network should look something like this:
model = Sequential()

svhn_layer(model, 48, 2, 'hidden1')
svhn_layer(model, 48, 1, 'hidden2')
svhn_layer(model, 48, 1, 'hidden3')

svhn_layer(model, 64, 2, 'hidden4')
svhn_layer(model, 64, 1, 'hidden5')
svhn_layer(model, 64, 1, 'hidden6')

svhn_layer(model, 128, 2, 'hidden7')
svhn_layer(model, 128, 1, 'hidden8')
svhn_layer(model, 128, 1, 'hidden9')

svhn_layer(model, 192, 2, 'hidden10')
svhn_layer(model, 192, 1, 'hidden11')

model.add(Flatten())

model.add(Dense(3072))
model.add(Dense(3072))

x = Input((30,70,1))
y = model(x)

digit1 = (Dense(output_dim =11,activation = "softmax"))(y)
digit2 = (Dense(output_dim =11,activation = "softmax"))(y)
digit3 = (Dense(output_dim =11,activation = "softmax"))(y)
digit4 = (Dense(output_dim =11,activation = "softmax"))(y)
digit5 = (Dense(output_dim =11,activation = "softmax"))(y)

identifier = Model(input=x, output = [digit1, digit2, digit3, digit4, digit5])

You can play with other normalizations too, like selu and elu. My tests show they perform better than relu.
Remembering this will work with inputs like they described (images with dimension 64x64x3). Your input looks like different, so, maybe you have to remove some layers or strides.

How to inprove SVHN result with Keras?


Derivative of the inverse of exponential function a^x, with a>0 and a≠1

Question: While studying exponential functions, I understood that
$$\frac{d}{dx}a^x=(\ln a)a^x.$$
I also learned previously that if $g(x)$ is the inverse of $f(x)$, then the derivative of $g(x)$ and the derivative of $f(x)$ has reciprocal relationship. As stated in my math textbook,
"In general, if $y=g(x)=f^{-1}(x)$, then $f(y)=x$ and $f'(y)=\frac{dx}{dy}$. It follows from [the equation of the derivative of inverse functions] that $$g'(x)=\frac{dy}{dx}=\frac{1}{f'(g(x))}=\frac{1}{f'(y)}=\frac{1}{dx/dy}.$$ This reciprocal relationship is sometimes written as $$\frac{dy}{dx}=\frac{1}{dx/dy}.$$"
Because $log_ax$ is the inverse of $a^x$, it would have made sense to have the derivative of $log_ax$ as $\frac{1}{(\ln a)a^x}$. However, I know that the derivative of $log_ax$ is $\frac{1}{(\ln a)x}$. Could you explain why the derivative of $log_ax$ and that of $a^x$ does not have reciprocal relationship? You do not need to explain the derivative proofs of $log_ax$ and $a^x$. I understand them completely. What I don't understand is why they don't have a reciprocal relationship.
Comment: It is easy to confuse oneself with the inverse function theorem. You should be very careful to distinguish $x$ and $y$.
Answer: You have $$g'(x) = \frac{1}{f'(g(x))}$$
With $g(x) = \log_{a}(x)$ one obtains
$$\log_{a}'(x) = \frac{1}{(\ln a)a^{\log_{a}(x)}} = \frac{1}{(\ln a)x}$$
Your mistake was that you didn't look at the function at the point $f(x)$ but at the point $x$. Be careful with infinitesimals.


Weaker/Stronger Topologies and Compact/Hausdorff Spaces

Question: In my topology lecture notes, I have written:
"By considering the identity map between different spaces with the same underlying set, it follows that for a compact, Hausdorff space:
$\bullet$ any weaker topology is compact, but not Hausdorff
$\bullet$ any stronger topology is Hausdorff, but not compact "
However, I'm struggling to see why this is. Can anyone shed some light on this?
Comment: You might want to modify in _but not necessarily Hausdorff/compact_.
Comment: @Pece: The statements are correct as written. Recall the basic fact that a continuous bijection from a compact space to a Hausdorff space is a homeomorphism.
Comment: @Martin Ok then, _any strictly weaker/stronger_.
Comment: @Pece: Okay, we agree :-)
Answer: Weaker implies compact and stronger implies Hausdorff is a general fact (an open cover in the weaker one is an open cover in the original too, pick there a finite subcover and you conclude. If you can separate two point in the original topology you can do it in the richer one because you can use the same open sets).Then suppose $ (X, \tau)$ is the topological space from which we start, if $\sigma$ is a weaker topology on $X$ and $(X,\sigma)$ is compact-Hausdorff, then: $Id: (X,\tau) \rightarrow (X,\sigma)$ is a continous bijection between compact-Hausdorff spaces, thus an homeomorphism. As it's the identity we get $\sigma=\tau$; similarly for the other case.
Comment: Thanks, that cleared things up nicely. I got bogged down trying to utilise results from lectures to show that weaker implies compact and stronger implies Hausdorff rather than just going back to the definitions.

For weaker implies not Hausdorff, (correct me if I'm wrong) you're showing that Hausdorff implies topology can't be weaker, yes?
Comment: I assume that the topology is weaker (not strictly) and so it's automatically compact; suppose it's hausdorff too and you get that the two topologies are the same (observe that it's not a proof by contradiction, but by contraposition) so that if it's strictly weaker than you can't have hausdorff property.
Answer: Hint. $X$ being a set, a topology $\tau$ is weaker than a topology $\sigma$ on $X$ if and only if the application
$$ (X, \sigma) \to (X,\tau), x \mapsto x $$
is continuous.
Comment: Hmm, I knew this already, and I recall working out why this implies that a set with a weaker topology is compact (as the image of a compact set under a continuous function); I just didn't write it down!


Web API e Owin OAuth - redirecionar para outro domínio (redirect_uri)

Question: Boa tarde, eu estou tendo um problema para implementar login externo em um projeto no qual eu estou trabalhando.

ASP.NET Web API + Owin + OAuth.

Ambiente:
Trabalho com dois servidores Server1 e Server2.
Server1: Servidor publicado na WEB. Ele abriga arquivos (HTML, CSS, JS). Alem disso, ele funciona como um proxy. Todas as chamadas recebidas (que não são chamadas de arquivos) são redirecionadas para o Server2.
Server2: Servidor não publicado. Recebe chamadas apenas no Server1. Esse servidor abriga um WEB API e é nele que o usuário deve ser autenticado.
Problema:
Ao efetuar o login no Server2, o Owin retorna como redirect_uri o seguinte parâmetro:
&redirect_uri=http://server2/signin-google

Sendo que o parâmetro que eu preciso retornar seria:
&redirect_uri=http://server1/signin-google

A única configuração que eu encontrei foi a CallbackPath:
googleAuthOptions = new GoogleOAuth2AuthenticationOptions() {
    ClientId = "xxxxxxx",
    ClientSecret = "xxxxxxx",
    CallbackPath = new PathString("/path"),
    Provider = new GoogleAuthProvider()
};

Mas essa configuração não funciona uma vez que new PathString("http://server1/signin-google") não é um valor válido.
Alguém sabe como eu soluciono esse problema?
Answer: Tive uma dificuldade com Web API e Owin OAuth, segue abaixo a estrutura e como resolvi, talvez possa lhe ajudar.
1) Tenho um web site em asp.net mvc que faz login via identity e Owin OAuth normalmente: facebook e google;
2) Possuo um asp.net web api para servir 3 apps (android, ios e windows phone);
3) Os apps  precisam de autenticação via identity ou social (facebook ou google) para terem acesso ao web api;
Inicialmente tentei fazer com que o web api pudesse fornecer as opções de autenticação social aos apps e tive algumas dificuldades, desisti pois tinha urgência na implementação. Dai resolvi fazer requisição, confirmação e recebimento do token via web OAuth, em caso de social login. Com o token faço o registro no identity e passo a tê-los autenticados no identity normalmente.


How to factor this in a better way

Question: I want to factor the function $\frac{1}{z^4+1}$ over $\mathbb{C}$ to get the poles, so then I've got that
$$z^4+1=(z^2+i)(z^2-i)=(z-\sqrt{i})(z+\sqrt{i})(z-\sqrt{-i})(z+\sqrt{-i})$$
But this doesn't help me at all, so Can someone help me to get this please?
Thanks a lot in advance.
Comment: The pole are $\pm\sqrt i$ and $\pm\sqrt{-i}$, what's the problem with this ? You got them !
Answer: $-1=\mathrm e^{\mathrm i\pi}$, hence its fourth roots are
$$\mathrm e^{\tfrac{\mathrm i\pi}4+\tfrac{k\pi}2},\enspace k=0,1,2,3=\Bigl\{\mathrm e^{\tfrac{\pm\mathrm i\pi}4},\mathrm e^{\pm\tfrac{3\mathrm i\pi}4}\Bigr\}=\frac{\sqrt{2}}2(\pm 1\pm\mathrm i)$$
Answer: $$
i = 1(\cos90^\circ+i\sin90^\circ), \text{ so } {\pm}\sqrt i = \pm\sqrt 1(\cos45^\circ + i\sin45^\circ) = \frac{\pm(1+i)}{\sqrt 2}.
$$
Comment: Ok, so taking $\sqrt{}$ only divides the angle by two right ?
Comment: Yes.  Recall the trigonometric identity $$(\cos\alpha+i\sin\alpha) (\cos\beta+i\sin\beta) = \cos(\alpha+\beta)+i\sin(\alpha+\beta).$$  This is the case where $\alpha$ is the same as $\beta$, i.e. is just half of what you started with: $$(\cos45^\circ+i\sin45^\circ) (\cos45^\circ+i\sin45^\circ) = (\cos90^\circ+i\sin90^\circ) = i.$$ $\qquad$
Answer: Or, if you like to postpone the use of complex numbers for as long as possible:
$$
z^4 + 1 = (z^2 + 1)^2 - 2z^2 = (z^2 + 1 - z\sqrt{2})(z^2 + 1 + z\sqrt{2}).
$$
To factor the two quadratics, solve the corresponding equation.

How to factor this in a better way


powershell find and replace all in one line

Question: I have this line of code which gives me domain\username. However, I need to replace the \ with  _. Do I have to do this multiple lines or I can do this in one line?
<code>$UAN = $userProfile["AccountName"].Value
$UAN = $UAN.Replace("/","_")
</code>
The above does not work even if it's multiple line.
Comment: You're wainting to replace a backslash, but you have a forward slash in your replace arguments.
Answer: Use <code>-replace</code>
<code>$UAN = ($userProfile["AccountName"].Value) -replace "\\", "_"
</code>


Distillery Release doesn't find "release_ctl" in custom command

Question: I've created a custom command for my Distillery Release by following the instructions in the README, but the script I've created cannot seem to find release_ctl.  I'm using Distillery 2.1.1
For example, the following script...
#!/usr/bin/env sh

release_ctl --mfa "Elixir.IO.puts/1" --argv -- "$@"

...exits with an exit code of 1.  To make it even simpler...
#!/usr/bin/env sh

which release_ctl

...also exits w/ an exit code of 1.
Any ideas?
Answer: This was a simple brainfart.  I was missing eval.  I should have been using...
#!/usr/bin/env sh

release_ctl eval --mfa "Elixir.IO.puts/1" --argv -- "$@"


Erwin Kreyszig's Introductory Functional Analysis With Applications, Section 2.5, Problem 7

Question: Riesz's Lemma, which is 2.5-4 in Erwin Kreyszig's Introductory Functional Analysis With Applications, is as follows:

Let $Y$ and $Z$ be subspaces of a normed space $X$ (of any dimension), and suppose that $Y$ is closed and is a proper subset of $Z$. Then for every real number $\delta \in (0,1)$, there is an element $z\in Z$ such that $\Vert z \Vert =1$ and $\Vert z-y \Vert \geq \delta$ for all $y \in Y$.

Now Problem 7 in the problem set immediately following Section 2.5 in Kreyszig is as follows:

If $\dim Y < \infty$ in Riesz's Lemma, show that one can even choose $\delta = 1$.

I've read and I think I've understood fully the proof of the Lemma with $\delta \in (0,1)$, and I'm unable to figure out to modify that particular proof to include the case when $\delta = 1$. Nor am I able to give an independent proof of the assertion made in Problem 7.
Can anybody please help?
Comment: For future reference, the author's name is spelled Erwin Kreyszig.
Answer: Suppose $Y$ is finite dimensional. As $Y$ is a proper subspace of $Z$ you can find $z_0 \in Z$ such that $z_0 \notin Y$. Consider $Y' = Y + \langle z_o\rangle$. The dimension of $Y'$ is exactly one more than the dimension of $Y$ so $Y'$ is also finite dimensional. Consider $Y'$ as a normed space with the norm inherited from $X$.
Now you can find $z$ in $Y'$ such that $\|z\| = 1$ and $\| z-y \| = 1$ for all $y \in Y$ using that $Y'$ is finite dimensional. You can proceed like this:

take $z_n$ in $Y'$ with $\| z_n-y \| \geq 1-\frac{1}{n}$ for all $y \in Y$ and
$\|z_n\|=1$
every finite dimensional normed space is a Banach space and its unit
ball is a compact set in it
using the previous point, extract a convergent subsequence
$(z_{n_k})_k$ from $(z_n)_n$
the subsequence converges to some $z$ in $Y'$ with $\| z-y \| \geq 1$ for all $y \in Y$ and $\|z\|=1$

Observe that $z \in Y' = Y + \langle z_o\rangle \subseteq Z$ and $\| z-y \| \geq 1$ for all $y \in Y$. Also, $\|z\|=1$ so $dist(z,Y) =inf \{ \|z-y\|:y\in Y \}= 1$.
Comment: Just in case, the infimum is $1$ because $\| z - 0\| = \| z \| = 1$ and $0 \in Y$
Comment: thank you very much for answering my question so beautifully. However, there's one point which I would like to raise. After you've shown that $\Vert z \Vert=1$ and $\Vert z - y \Vert \geq 1$ for all $y \in Y$, in the very last sentence of your answer, you've stated that since $\Vert z \Vert = 1$ also, so $\Vert z-y \Vert = 1$. How did you conclude this last equality?
Comment: Typo corrected ;)
Comment: Wonderful! Excellent!!
Comment: how do you conclude that $\dist(z,Y) = 1$ from what has gone before?
Answer: If $Y$ is finite dimensional, we also consider $Z$ to be finite dimensional (by throwing away some parts of $Z$ if necessary). Then for each $\delta = 1-\frac{1}{n}$, apply Riesz lemma so that there is $z_n \in Z$, $||z_n = 1||$ and
$$||z_n - y|| \geq 1-\frac{1}{n}$$
for all $y\in Y$. Then as $Z$ is finite dimensional, there is $z\in Z$ so that $z_n \to z$. Thus $||z||=1$ and
$$||z- y|| \geq 1$$
for all $y\in Y$.


Evitar que menu Dropdown feche com o Clique direito dentro dele

Question: Gostaria que esse menu Dropdown não fechasse ao clicar com o botão direito do mouse dentro dele para abrir um link em uma nova aba.

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
 /* Dropdown Button */
.dropbtn {
    background-color: #3498DB;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
    background-color: #2980B9;
}

/* The container
 - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

  <button onclick="myFunction()" class="dropbtn">Dropdown</button>

    Link 1
    Link 2
    Link 3

Comment: Remova o código de `window.onclick`
Comment: Clique esquerdo ou direito?
Comment: @dvd é o direito, eu me confundi aqui, o que abre as opções do Browser, "Abrir em uma nova aba" etc...
Comment: Por favor, altera na pergunta senão a pergunta fica sem sentido.
Answer: Pelo que vi, isso só acontece no Firefox Quantum 57, que captura um clique direito do mouse no evento onclick, embora não faça ação no elemento (como se fosse um clique esquerdo).
Para resolver isso, você pode adicionar outro event handler no submenu com oncontextmenu, que detecta o clique direito do mouse. Neste caso você pode adicionar a classe .show ao elemento. Isso fará que ele não se feche mesmo clicando com o botão direito.
Como dito no início, deve ser testado no FF Quantum 57. Nos demais navegadores não existe esse problema:

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
      document.querySelector(".dropdown-content").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

var drop = document.querySelector(".dropdown-content");
drop.oncontextmenu = function(event) {
   drop.classList.add("show");
}
/* Dropdown Button */
.dropbtn {
    background-color: #3498DB;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
    background-color: #2980B9;
}

/* The container
 - needed to position the dropdown content */
.dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}

  <button onclick="myFunction()" class="dropbtn">Dropdown</button>

    Link 1
    Link 2
    Link 3

Comment: Perfeito. É exatamente isso. Obrigado.
Comment: pretendo usar 2 ou até 3 desses dropdowns numa mesma página, eu tentei aqui, mas existe conflitos. Como eu devera prosseguir? Eu queria algo semelhante a esses menus dropdowns com icones do StackOverflow. É claro que tentei furta-los, mas sem sucesso.. rsrs
Comment: @JohnQuimera Veja que o menu tem um id="myDropdown"... se vc duplicar vai dar conflito porque o script não sabe diferenciar um id do outro, ele sempre vai pegar o primeiro que encontrar... teria que adaptar o código e trocando id por class.. quanto aos ícones, tem um plugin que já vem com vários ícones, acho que é o font-awesome
Comment: eu já troquei todos os document.getElementById() por document.querySelector() e agora só estou usando classes, está funcionando do mesmo jeito, mas não funciona dois na mesma página.
Comment: @JohnQuimera Tem que fazer querySelectorAll para selecionar todos e depois fazer um loop
Comment: tem um dropdown que é igual a esse, em jquery, suporta vários desses, só preciso fazer o mesmo esquema do click esquerdo e resolver o problema de fechar o outro dropdown quando outro for aberto. https://codepen.io/johnquimera/pen/RxzEQr
Comment: @JohnQuimera Posta perguntas que a gente tenta resolver.
Comment: https://pt.stackoverflow.com/questions/271977/dropdowns-multiplos-na-mesma-p%c3%a1gina
Comment: acho que isso é algo que você consegue resolver, me dê uma mãozinha. https://pt.stackoverflow.com/questions/276470/jquery-dropdown-parar-propaga%C3%A7%C3%A3o-com-click-direito?noredirect=1
Comment: Blz, to vendo aqui.


How can I set variables only once per block?

Question: I have a block module that displays some data taken from XML. That module has multiple  (approx. 7) blocks, each of which displays a different "view" of the same XML. Each block can be positioned independently on the page, but all of the blocks are displayed at once and all of the blocks use the same data.
Since the XML parsing code runs inside the block_view() hook, it runs once for every block.
My problem is that the XML parsing is expensive in terms of time (not hugely so, but easily >95% of the total module runtime), and this is a page that I want to run as fast as possible.
How can I move the XML parsing out of the block_view() hook and run it once per page view? Is there another hook that will let me set some global variables or something like that?
function my_module_block_info() {
    $blocks[0]['info'] = t("My Module: block one");
    $blocks[1]['info'] = t("My Module: block two");
    $blocks[2]['info'] = t("My Module: block three");
    ...etc (~7 blocks total)...
    return $blocks;
}

function my_module_block_view($delta = '') {
    $parsed_stuff = parse_some_xml();
    switch ($delta) {
        case 0:
            $block['subject'] = t('Blah');
            $block['content'] = block_0_html($parsed_stuff);
            break;
        case 1:
            $block['subject'] = t('Yada');
            $block['content'] = block_1_html($parsed_stuff);
            break;
        case 2:
            $block['subject'] = t('Etc');
            $block['content'] = block_2_html($parsed_stuff);
            break;
        ...etc (~7 blocks total)...
    }
    return $block;
}

Answer: You can use static caching in your parse_some_xml function. Some people consider this a cleaner, less evil solution than using global variables (but I will not get into that discussion here).
With static caching, your my_module_block_view() would remain the same, but your parse_some_xml() would look like this:
function parse_some_xml() {
  static $parsed_xml;
  if (!isset($parsed_xml)) {
    // Do the actual parsing here, and store the data in $parsed_xml
  }
  return $parsed_xml;
}

See A Beginners Guide to Caching Data to learn more about static caching.
Answer: You can use hook_init() to setup a global variable.
function my_module_init() {
  global $parsed_stuff;
  $parsed_stuff = parse_some_xml();
}

Comment: Use static instead of global, see the answer from marcvangend.
Comment: I can't get the hook_init() to get called (`function live_results_init() {die;}` does nothing), but the global bit worked - I'm just doing `global $parsed_stuff; global $is_cached; if (!$is_cached) { $parsed_stuff = parse_some_xml(); }`. It's pretty much dividing my runtime by 7.


Isoceles Triangles on a Grid Proof

Question: Given: A Finite Set of Unit Squares on a Large Grid.
If we were to choose one of those sets of unit squares, we see that the squares of the set are tiled with isoceles right triangles, each with a hypotenuse of 2. Also these triangles do not overlap with each other and they do not extend past the set and all of the set is fully covered by the triangles. Aslo, the hypotenuse of every triangle lies along a grid line and all the vertices of the triangles lie at the corners of the squares.
Prove: All the number of triangles must be a multiple of four.
I have somewhat of an answer to this but I am not completely sure if it is correct. Is someone willing to look at my solution and give some feedback on it.
Comment: This question comes from the current USAMTS Round 3 problem set ([problem 5](http://www.usamts.org/Tests/Problems_26_3.pdf)). This question will remain locked until after the submission deadline of 19 Jan 2015.
Comment: This question was asked again: http://math.stackexchange.com/questions/1111897/a-finite-square-of-unit-squares-is-chosen-triangle-proof-problem
Answer: Let $S$ be the set of squares (as in the USAMTS problem statement)
and let $T$ be the set of triangles.
Due to the constraints on the placement of the triangles,
each triangle overlaps two squares, and each of these overlapping regions is a
right triangle whose hypotenuse is a diagonal of the overlapped square.
We can map the squares and triangles to the nodes and edges of a graph;
let each square with an overlapping triangle correspond to a node, and let each
triangle correspond to an edge connecting the two squares it overlaps.
Given a square in $S$ and a triangle in $T$ that overlaps the given square,
the "other" half of the square is covered by a different triangle.
That is, exactly two triangles must overlap each square.
Hence in the corresponding graph,
each node has exactly two edges connected to it.
From this and from the fact that there are only a finite number of squares in $S$,
we can deduce that the graph consists of a finite number of disjoint cycles.
Give each edge of the graph an orientation so that you can trace each cycle
always traveling in the same direction as each edge you traverse.
This gives us eight kinds of triangles in $T$,
based on the two squares overlapped by the triangle,
the direction from the square the triangle "comes from" to the square the triangle
"goes to" (orienting "from" and "to" the same as for the corresponding graph edge),
and whether the edge of the triangle in the "from" square is a left diagonal
(from the upper left corner to the lower right) or a right diagonal:

A triangle from the right diagonal of one square to the left diagonal
of the square to the right.
A triangle from the right diagonal of one square to the left diagonal
of the square above.
A triangle from the left diagonal of one square to the right diagonal
of the square above.
A triangle from the left diagonal of one square to the right diagonal
of the square to the left.
A triangle from the right diagonal of one square to the left diagonal
of the square to the left.
A triangle from the right diagonal of one square to the left diagonal
of the square below.
A triangle from the left diagonal of one square to the right diagonal
of the square below.
A triangle from the left diagonal of one square to the right diagonal
of the square to the right.

Let the number of triangles of each type be respectively $n_1, n_2, \ldots, n_8.$
Now consider a square whose overlapping triangles meet on the square's left diagonal.
If the edge into the corresponding node came from the square to the right or below,
the edge out of that node must go to the square to the left or above;
that is, for each type 1 or 2 triangle there must be a type 3 or 8 triangle, so
$$n_1 + n_2 = n_3 + n_8.$$
Similarly,
$$\begin{eqnarray}
n_3 + n_4 &=& n_2 + n_5, \\
n_5 + n_6 &=& n_4 + n_7, \ \mbox{and}\\
n_7 + n_8 &=& n_6 + n_1.
\end{eqnarray}$$
If we cut each square along both diagonals,
we dissect it into four small right triangles, one above the center of the square,
one below, one to the left, and one to the right.
There must be an equal number of each of these types of triangles when all
squares in $S$ are dissected this way,
but the triangles of types 1 or 4 each contain two small "below" triangles and
no small "above" triangles, and the only way to make the "above" and "below"
numbers equal is to have an equal number of triangles of types 5 or 8.
Applying similar reasoning to the other four kinds of large triangle, we can conclude that
$$\begin{eqnarray}
n_1 + n_4 &=& n_5 + n_8 \ \mbox{and}\\
n_3 + n_6 &=& n_7 + n_2.
\end{eqnarray}$$
Moreover, each cycle must contain equal numbers of edges going left and right
as well as equal numbers of edges going up and down, so
$$\begin{eqnarray}
n_1 + n_8 &=& n_4 + n_5 \ \mbox{and}\\
n_2 + n_3 &=& n_6 + n_7.
\end{eqnarray}$$
That's eight equations in eight unknowns, but the equations are not all independent.
In fact, by subtracting $n_1 + n_4 = n_5 + n_8$ from $n_1 + n_8 = n_4 + n_5$
we find that  $n_8 - n_4 = n_4 - n_8$ and therefore $n_4 = n_8$.
Similarly, $n_1 = n_5$, $n_2 = n_6$, and $n_3 = n_7$.
The first four equations are therefore just four different restatements
of the equation
$$n_1 + n_2 = n_3 + n_4.$$
The total number of triangles, however, is
$$\begin{eqnarray}
n_1 + n_2 + n_3 + n_4 + n_5 + n_6 + n_7 + n_8
&=& 2(n_1 + n_2 + n_3 + n_4) \\
&=& 2(n_1 + n_2 + n_1 + n_2) \\
&=& 4(n_1 + n_2)
\end{eqnarray}$$
which proves that the number of triangles is a multiple of $4$.

Isoceles Triangles on a Grid Proof


Self delete an object in C++

Question:
Possible Duplicate:
C++: Delete this?
Object-Oriented Suicide or delete this;

I wonder if the code below is run safely:
#include <iostream>
using namespace std;

class A
{
public:
    A() {
        cout << "Constructor" << endl;
    }
    ~A() {
        cout << "Destructor" << endl;
    }

    void deleteMe() {
        delete this;
        cout << "I was deleted" << endl;
    }
};

int main()
{
    A *a = new A();
    a->deleteMe();
    cout << "Exit ...";
    return 0;
}

Output is:
Constructor
Destructor
I was deleted
Exit ...

and program exit normally, but are there some memory access violents here?
Comment: Related: http://stackoverflow.com/questions/3150942/c-delete-this
Comment: Summary: no problem here, as long as you are careful (don't `delete` things that were not allocated with `new`, don't use an object after it has been destructed).
Comment: @RobertoWilko: My code is formatted with Visual Studio + Visual Assisstant, i don't know if this wrong :-(
Answer: It's ok to delete this in case no one will use the object after that call. And in case the object was allocated on a heap of course
For example cocos2d-x game engine does so. It uses the same memory management scheme as Objective-C and here is a method of base object:
void CCObject::release(void)
{
    CCAssert(m_uReference > 0, "reference count should greater than 0");
    --m_uReference;

    if (m_uReference == 0)
    {
        delete this;
    }
}

I don't think it's a c++ way of managing memory, but it's possible
Comment: @BìnhNguyên: I think yes, because you don't use the object, but I would prefere to print the message befoe `delete this` in any case
Comment: The same pattern is used in COM's `IUnknown::Release()`, see http://msdn.microsoft.com/en-us/library/office/cc839627.aspx .
Comment: If I remember correctly that manner is used also in DirectX library. When you want to delete an object and free its memory you call SomeObj::Release() which works in similar way as the code you've posted.
Comment: So is the line `cout << "I was deleted" << endl;` safely here?
Comment: "I don't think it's a C++ way of managing memory": it depends on the role of the object in the application (and on the type of application).  For many OO oriented applications, it will be the usual way objects get deleted.  (And I agree with Andrew's comment concerning doing the print before the delete.)
Comment: @JamesKanze: Yeah, possibly you are right, but I would at least write some strong_ptr or something like that to automate memory management in any case
Comment: @Andrew The only pointer concerned with memory management in these cases is `this`, and the language doesn't allow you to make it a smart pointer.  In the past, I've worked on an application which did use smart pointers to the object, which registered themselves with the object, and were automatically nulled in its destructor.  In practice, it's usually not enough, since the pointer itself is still left floating around in maps, etc.  You generally have to use the observer pattern so that everyone who holds a pointer to the object can do the right thing.
Comment: @JamesKanze: I ment some kind of scoped_ptr, which calls retain() in constructor and release() in destructor. It is possible and i did it
Comment: @Andrew It's certainly possible (calling release in some `deleteMe` function, however, and not in the destructor).  But it introduces additional complexity, for what?
Comment: @JamesKanze: This introduce no more complexity than any other smart pointer and frees you from remembering to call release()/retain()
Comment: @Andrew "no more complexity than any other smart pointer": but `this` isn't a smart pointer, and you need nothing more.
Comment: @JamesKanze: http://en.wikipedia.org/wiki/Smart_pointer
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/14750/discussion-between-andrew-and-james-kanze)
Comment: @Andrew The Wiki page you cite is very poor, and extremely inaccurate.  (For starters, smart pointers don't always have anything to do with memory management, and for another, Java has smart pointers (called WeakReferences) in its standard library.)
Comment: @JamesKanze: It's not said it always about memory management. Read the first sentence carefully
Answer: It's ok, because you have running simple method. After delete this, all variables and virtual table are clear. Just, analyze this example:
#include <iostream>

class foo
{
public:
    int m_var;
    foo() : m_var(1)
    {

    }

    void deleteMe()
    {
        std::cout << m_var << "\n";
        delete this;
        std::cout << m_var << "\n"; // this may be crush program, but on my machine print "trash" value, 64362346 - for example
    }

    virtual void bar()
    {
        std::cout << "virtual bar()\n";
    }

  void anotherSimpleMethod()
    {
       std::cout << "anotherSimpleMethod\n";
    }

    void deleteMe2()
    {
        bar();
        delete this;
        anotherSimpleMethod();
        // bar(); // if you uncomment this, program was crashed, because virtual table was deleted
    }
};

int main()
{
    foo * p = new foo();
    p->deleteMe();
    p = new foo();
    p->deleteMe2();
    return 0;
}

I've can't explain more details because it's need some knowledge about storing class and methods in RAM after program is loaded.
Answer: Absolutelly, you just run destructor. Methods does not belongs to object, so it runs ok. In external context object (*a) will be destroyed.
Answer: When in doubt whether theres strange things going on in terms of memory usage (or similar issues) rely on the proper analysis tools to assist you in clarifying the situation.
For example use valgrind or a similar program to check whether there are memory leaks or similar problems the compiler can hardly help you with.
While every tool has its limitations, oftentimes some valuable insights can be obtained by using it.
Answer: There is no memory access violation in it, you just need to be careful. But deleting this pointer is not recommended at all in any language, even though the code above would work fine. As it is same as delete a, But try doing it other way, the safe way.
For example there is something illogical in your posted code itself.
void deleteMe()
{
    delete this;
    cout << "I was deleted" << endl; // The statement here doesn't make any sense as you no longer require the service of object a after the delete operation
}

EDIT: For Sjoerd
Doing it this way make more sense
 void deleteMe()
{
    delete this;
}

 int main()
 {
 A *a = new A();
 a->deleteMe();
 cout << "a was deleted" << endl;
 cout << "Exit ...";
 return 0;
 }

The second line in your deleteMe() function should never be reached, but its getting invoked. Don't you think that its against the language's philosophy?
Comment: Re: "the object that invokes its member function is no more and so should its member functions" - that's complete nonsense. An object's non-static data is completely separate from any code that accesses it (including member functions), and destroying an object only destroys that data. The code still exists, is still executable, and is still well-defined as long as it doesn't access the destroyed object.
Comment: -1: Pure nonsense about "this line should never be reached."
Comment: You don't get the whole picture. Of course it gets executed. But go through my post once again, you may get it then:D
Comment: You contradict yourself: "this line should never be reached," but "of course it gets executed." Are you suggesting that it is a compiler bug?!
Comment: And what do you mean with "ofc it gets executed **as function body is placed in main**"? Why should `main()` be special in this case? Secondly, the function body is defined inline in the class definition, and not placed in main. If you mean that it might get inlined, that's true, but inlining or not has nothing to do with wether this code is safe.
Comment: Ah! deleteMe() is a member function of Object a, So it should be invoked by object a. But by doing "delete this" before that cout statement, the object that invokes its member function is no more and so should its member functions. So that cout statement is getting executed after the death of object a. That doesn't make any sense at all even though there is no errors in doing so. That's my point. Don't always be technical.
Comment: You are using a lot of "shoulds" that are unsupported by the C++ standard. Yes, object a does not exist anymore at the point of the cout, but that doesn't stop the function from executing. It's just not possible to use `this` anymore, which includes calling virtual functions. As long as you are very carefully, it is possible to execute some code after the `delete this;` and before the `return;` statement. However, to be really sure `this` is never used in that part, experts recommend to put everything *before* the `delete this;` statement.
Comment: WRT "Don't always be technical": When the question is whether it is **technically allowed**, one should get technically in the answer.
Comment: But as it is "Technically" allowed and considering I mentioned it, You should try coming the other way around. What I was just trying to say was that ain't a good programming practice.

Self delete an object in C++


Differentiate an integral with parameter

Question: If I want to differentiate the following integral $$F(x,y)=\int_0^x u(t,y)\,dt$$ with respect to the variable y, I get $$F_y(x,y)=\int_0^x\frac{\partial u}{\partial y}(t,y)\,dt$$ What about if I differentiate with respect to $x$? Does it become $0$ ? I'm asking because I see the $x$ at the limit of integration and I'm getting a little confused.
Comment: if $u(t,y)$ is continuous in $t$ then $\frac{\partial F(x,y)}{\partial x} = u(x,y)$. This is the fundamental theorem of calculus.
Comment: https://en.wikipedia.org/wiki/Leibniz_integral_rule
Comment: Your function $F$ is a function of both $y$ and $x$.
Comment: So if I want to calculate $\cfrac{\partial F}{\partial x}(y)$ how would it look like?
Comment: Your differentiation is a partial differentiation wrt $y$.
Answer: Hint: The FTC says that if $f$ is continuous, and $F(x)=\int_a^x f(t)\,dt,$ then $F'(x)=f(x).$


Understanding scipy nnls output

Question: I want to understand the output from nnls in scipy:
The code is:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import nnls
A = np.array([[30, 120, 90],[60, 90, 120]])
b = np.array([67.5, 60])
x, rnorm = nnls(A,b)
print x, rnorm

Output is:
[ 0.          0.42857143  0.17857143] 0.0
Comment: The official documentation is at http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.nnls.html , can you edit to specify what question you have that is not covered there?
Comment: I want to know what the each element of solution vector specifies?
Answer: The meaning of x is context dependent. I.e. if you are doing polynomial least squares it will be the coefficients in the polynomial. In general is the solution to though it is the value of x that satisfies the minimization problem found at http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.nnls.html.
argmin_x || Ax - b ||_2 such that x>=0.
as for rnorm it is the residual norm which is equal to ||Ax - b||_2. It's a way of measuring the error between the actual solution and the approximation.

Understanding scipy nnls output


What is the area of a reuleaux triangle, but with square angles as corners?

Question: Supposing we have a triangle where each of its edges comes from a section of a circle's edge, and that every corner is a right angle, I need to calculate the area and perimeter of it.
If the three circles that create this shape have radius one, one can show that their centers must be at $\sqrt2$ distance appart. But what is its area and perimeter? Thanks.
Comment: I suppose you have drawn a diagram. Divide the area into an ordinary triangle and three [circular segments](https://en.wikipedia.org/wiki/Circular_segment), and algebra the shit out of it.
Answer: Here it is our right-angled Reuleaux triangle.

Assuming that the sides of the inner equilateral triangle have unit length, the blue arcs are arcs of circles with radius $\sqrt{3}$, associated to chords with unit length. It follows that the length of each arc is $\frac{\pi}{6}\sqrt{3}$. The enclosed area is the area of the equilateral triangle, $\frac{1}{4}\sqrt{3}$, plus three times the area of a circle segment, which can be seen as the difference between a circle sector with area $\frac{\pi}{4}$ and a triangle with area $\frac{abc}{4R}=\frac{3}{4}$.


Find a Formula To Generate This Sequence

Question:
I took $n$th odd number, multiplied it by $3$ then added $1$. Then the
  number in the sequence is the number of times this result can be
  divided by $2$.
I need a function to give me the $n$th number in this sequence.

I observed so far that after a number appears in the sequence, the next appearance of the same integer $n$ occurs after $2^n$ steps (counting the number itself).
The first appearance of the integer $n$ occurs at the $a(n)$ spot, so far it follows:
$$ a(n) = \frac{ (1 + 2^n\times(3 + 2\times(-1)^n))}{3}$$

First $300$ numbers in the sequence:
$$ 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 8, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 7, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 10, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 7, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 8, 1 $$
Comment: @mathreadler For the sequence given you want $3(2k-1)+1=6k-2$.
Comment: theres this big database of integer sequences you may want to check out. http://oeis.org/
Comment: @mathreadler The sequence doesn't appear there, for the first $100$ numbers entered.
Comment: The numbers before division by $2$ can be written like $3(2k+1)+1$ for all k integers. Maybe that can help.
Answer: Let $g(n)$ be the number of times $n$ can be divided by $2.$
Let $h(n)=g(2n)$ be the number of times $2n$ can be divided by $2.$
As pointed out in the comments, the function you want is $f(n)=g(6n-2)=h(3n-1).$ The sequence $f(n)$ is not in the Encyclopedia of Integer Sequences, but $g(n)$ is sequence A007814 and $h(n)$ is sequence A001511.
Answer: One way to create this sequence algorthmically is start by writing down any even number, e.g. $10$
Next write before and after it the number two less than it, e.g. $8,10,8$
Next write the next number less than it in between each value and if the value is even write it at the start and end, e.g. $8,7,10,7,8$
Repeat this step until you get to 1. E.g.:
Inserting $6$:
$6, 8, 6, 7, 6, 10, 6, 7, 6, 8, 6$
Inserting $5$:
$6, 5, 8, 5, 6, 5, 7, 5, 6, 5, 10, 5, 6, 5, 7, 5, 6, 5, 8, 5, 6$
Inserting $4$:
$4, 6, 4, 5, 4, 8, 4, 5, 4, 6, 4, 5, 4, 7, 4, 5, 4, 6, 4, 5, 4, 10, 4, 5, 4, 6, 4, 5, 4, 7, 4, 5, 4, 6, 4, 5, 4, 8, 4, 5, 4, 6, 4$
Inserting $3$:
$4, 3, 6, 3, 4, 3, 5, 3, 4, 3, 8, 3, 4, 3, 5, 3, 4, 3, 6, 3, 4, 3, 5, 3, 4, 3, 7, 3, 4, 3, 5, 3, 4, 3, 6, 3, 4, 3, 5, 3, 4, 3, 10, 3, 4, 3, 5, 3, 4, 3, 6, 3, 4, 3, 5, 3, 4, 3, 7, 3, 4, 3, 5, 3, 4, 3, 6, 3, 4, 3, 5, 3, 4, 3, 8, 3, 4, 3, 5, 3, 4, 3, 6, 3, 4$
Inserting $2$:
$2, 4, 2, 3, 2, 6, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 8, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 7, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 10, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 7, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 8, 2, 3, 2, 4, 2, 3, 2, 5, 2, 3, 2, 4, 2, 3, 2, 6, 2, 3, 2, 4, 2$
Inserting $1$:
$2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 8, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 7, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 10, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 7, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 8, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2$


Python -->ValueError: incomplete format

Question: Alguém pode me ajudar nesse código?
Estou com dois problemas: O primeiro é o erro mencionado no título e o segundo é o vetor da função, que não recebe atribuição (quando fui debugar no compilador, percebi que U não estava recebendo valores nenhum).
Sou novo em programação, não se espante se houver algum erro bárbaro ;)
def calPercent(nvJ,tV):
    U = [0]*23
    for i in range(23):
        if nvJ[i]!= 0:
            U[i] = nvJ[i]/tV*100
    return U

V = [0]*23
P = [0]*23

voto = int(input("Numero do jogador (0=fim): "))
while voto!=0 :
    if voto<1 or voto>23 :
        print "Informe um valor entre 1 e 23 ou 0 para sair!"
    else:
        V[voto-1]+=1
    voto = int(input("Numero do jogador (0=fim): "))

P = calPercent(V,sum(V))

print "Foram computados",sum(V),"votos"

print "Jogador,Votos,%"
for i in range(23):
    if V[i]!=0 :
        print "%d,%d,%d%" %(i+1,V[i],P[i])

for i in range(23):
    if V[i] == max(V):
        print "O melhor jogador foi o numero %d, com %d votos, correspondendo a %d% do total de votos" %(i+1,V[i],P[i])

Comment: Já que você depurou, pode informar a linha do erro? Quanto a erros bárbaros, eu só recomendaria que você desse nomes descritivos às suas variáveis. Nada de U, V, nvJ etc.
Answer: O erro de "ValueError incomplete format" se deve ao fato de que o Python não reconheceu uma sequência de substituição começando com % em algum ponto onde você usou o operador % para substituição.
Se você olhar sua mensagem de erro, o Python sempre informa o número da linha onde ele aconteceu - isso evita que você, ou qualquer pessoa, tenha que ficar olhando o programa todo para saber onde um erro ocorreu.  Nese caso, como o programa  é pequeno, dá para notar que o problema é na última linha - ao tentar usar o % de porcentagem como ele mesmo, no trecho  correspondendo a %d% do total  - fica um % solto que gera o erro. Se você precisa usar um  % avulso numa string com esse tipo de formatação, ponha o sinal duas vezes seguidas - isso faz com que após a substituição, um deles seja mantido - ou seja, escreva o mesmo trecho como correspondendo a %d%% do total.
Quanto aos valores de U  - o problema é que você está usando Python 2 (e não Python 3 que tem várias melhorias significativas na linguagem) -  e em Python 2, por padrão, uam divisão entre números inteiros sempre retorna um inteiro - o que significa que na linha U[i] = nvJ[i]/tV*100  o valor da divisão sempre será "0", e não um coeficiente, como esperado.
A forma pontual de resolver isso é converter explicitamnete um dos valores da divisão para float, por exemplo, escrevendo:  U[i] = nvJ[i] / float(tV) * 100.
Para evitar o mesmo problema em outros lugares, você também pode indicar para  o Python tratar a  divisão  como acontece em Python 3, em que divisões não exatas entre inteiros sempre geram valores float - para isso, coloque próximo à primeira linha do seu programa a diretiva from __future__ import division.
(a primeira linha pode ser o indicativo de executável do Unix: #! /usr/bin/env python, a seguinte (primeira ou segunda), o informativo de codificação de caractéres do código fonte, de forma que você possa escrever caractéres acentuados sem que isso seja um erro de sintaxe: # coding: utf-8 )
Comment: Bem observado! Agora, sobre # coding: utf-8 eu já tinha tentado outras vezes, mas ainda continua sem reconhecer uns símbolos, como acentos.
Comment: POr que você está usando codificações incompatíves entre seu editor de textos, e o ambiente em que executa o script. Algo comum no windows.  (E  Mac e em Linux é tudo UTF-8)  - de qualquer forma, sempre é bom ler esse artigo aqui sobre unicode para entender as coisas:http://local.joelonsoftware.com/wiki/O_M%C3%ADnimo_Absoluto_Que_Todos_os_Programadores_de_Software_Precisam,_Absolutamente,_Positivamente_de_Saber_Sobre_Unicode_e_Conjuntos_de_Caracteres_(Sem_Desculpas!)
Comment: Sobre a primeira linha, a shebang não deveria ser colada na barra? `#!/usr/bin/env python` seria assim, não?
Comment: https://pt.stackoverflow.com/a/190895/64969
Comment: Acabei de ver shebang no seu formato: https://pt.stackoverflow.com/q/57702/64969; eu sempre havia imaginado que isso era uma heresia, que logo após a shebang dever-se-ia colocar logo o interpretador, com apenas a possibilidade de um único espaço na linha
Comment: são dois bytes: `#!`, seguidos de uma linha de comando do shell.
O uso  do `env` faz co mq ue sejam respeitadas variáveis de ambiente para achar o melhor `python`,e assim, o programa possa funcionar dentro de um virtualenv, por exemplo.

Python -->ValueError: incomplete format


Connecting Roland vb-99 to Personal Computer (USB)

Question: I have a Roland vb-99 and I'm trying to use its default editor (vb-editor).
When I open the program it asks me to perform the midi setup but when I open it I can't find the vb-99 in midi in or out.
I've been fiddling for ages with the system menu ---> midi in the vb-99 software without luck.
Drivers are installed correctly.
Anybody has hints? :(
Comment: This doesn't feel like the right place to ask the question. It seems like it's standard functionality of the device, which you should be able to get support for free from Roland.
Comment: @slim I thought this at first too, but based on [this meta question](http://meta.music.stackexchange.com/questions/296/are-technical-questions-about-how-to-use-a-particular-product-on-topic), I think it's on-topic actually. Just my 2¢ =)
Answer: You should uninstall and re-install the driver to be safe, for starters.
According to the owner's manual on the Roland website (Chapter 6, page 66):

You cannot use MIDI when STNDRD is selected as the driver mode.
If you want to use MIDI with the USB connection, set the VB-99 to the
  advanced driver mode.


calculating oracle users average session time

Question: How to write a PL/SQL program to calculate and display the username and average session time for all database users in oracle 11g ? kindly help
Comment: select * from v$session to start...
Comment: thanks a lot but how do i find the number of times a user had logged in to find the average session
Comment: Not sure why people are voting to close as NARQ.  Off topic because it belongs on DBA.SE, perhaps.  But it is a perfectly understandable question.
Comment: How come it is closed ?? i am surprised .. it is a very clear  question ...
Answer: By default Oracle does not audit things like user access.  There are built-in options, but they are switched off by default.
To enable Oracle's audit trail, we need to set the AUDIT_TRAIL parameter.  Set it to DB to have records written to a table; this is more convenient for querying than an OS file (unless your grep is better than your SQL).  Find out more.
To monitor user connections and disconnections, ask a DBA to issue the following statement:
AUDIT SESSION;

Then you can write your query off the DBA_AUDIT_SESSION view.  Something like:
select USERNAME
       , avg(LOGOFF_TIME - TIMESTAMP)
from DBA_AUDIT_SESSION
group by USERNAME;

Note that this is on;y going to give you meaningful information if you have an application with Old Skool named user accounts.  Web applications with connection pooling will all be audited as the same user, so you will need to write a bespoke logging tool.
Comment: I created a new table from v$session and from that table i calculated the average session time ..


How to enable mod_deflate on apache

Question: I've come across some article online to enable mod_deflate to gzip files while sending from the server.
For that, I tried to load the mod_deflate.so module by adding a line on my httpd.conf
LoadModule deflate_module modules/mod_deflate.so

But it seems the mod_deflate.so file is missing from the server.
I tried a find / -name "mod_deflate.so" -print but it returns no results.
So how do I compile and add mod_deflate to my modules directory?
Update:
I found out this tutorial at http://streetsmartingit.blogspot.in/2007/11/how-to-compileinstall-moddeflate-into.html?m=1
Step 1 says:
Hack apr-config located in the /usr/local/apache2/bin directory so
the LDFLAGS will have the "-lz" value similar below:
LDFLAGS="-lz"

What does 'Hack apr-config' this mean?
Comment: What is your OS?
Comment: I'm on Fedora..
Answer: Did you build apache from source?  If so, you may need to recompile apache with the option:
  --enable-deflate
Comment: I'm not sure about that because I took help from a friend. Can you please elaborate on that - recompiling apache (noob here). Thanks.
Comment: @ptamzz better ask your friend then, he should know what's installed and how.
Answer: try run "sudo a2enmod deflate".
Then restart apache.
eg:
$ sudo a2enmod deflate
Enabling module deflate.
To activate the new configuration, you need to run:
  service apache2 restart
$

How to enable mod_deflate on apache


Squeezing the ball between two feet and hopping across the field

Question: On occasion you see sometimes players try this tactic where they squeeze the ball between two feet and hop across the goal line in an attempt to score. This is usually kids learning the game or adults goofing around.
Is this legal or must a ball be kicked across the line to count as a goal?
Answer: This is completely legal, provided it is done in a manner in which it is still possible to safely challenge for the ball or there are no opponents nearby.
FIFA Laws of the Game, 2013/14, p. 121:

Playing in a dangerous manner is defined as any action that, while
  trying to play the ball, threatens injury to someone (including the player
  himself). It is committed with an opponent nearby and prevents the opponent
  from playing the ball for fear of injury.

If the referee decides that the action by the player makes it dangerous for opponents to challenge for the ball, an indirect free kick is awarded to the opposing team.
If this goes further, and playing the ball moves from being unsafe to an impossibility (for an unreasonable amount of time), a player is cautioned for unsporting behaviour. Note that there is no requirement here for opponents to be nearby.
This is no longer contained in the present text of the Laws, but was last seen in the 2006 FIFA Q&A to the Laws of The Game, p.30:

A player intentionally lies on the ball for an unreasonable length of
  time. What action does the referee take?
He stops play, cautions the player for unsporting behaviour and restarts
  play with an indirect free kick.

In the current (2013/14) laws, this roughly corresponds to the following on p. 123:

There are different circumstances when a player must be cautioned for
  unsporting behaviour, e.g. if a player:
...

acts in a manner which shows a lack of respect for the game

...

The restart is once again an indirect free kick.
Thanks to posdef, here is a clip of Cuauhtémoc Blanco using this technique.
Answer: A player is not allowed to control the ball (so that it can't move freely) at any time, which would include across the goal line.  Exceptions would be the goalkeeper, or during a throw in.
Comment: Well this answer is not entirely correct, see the Blanco dribble (aka the bunny hop) from WC'98 (https://www.youtube.com/watch?v=v5SB-L8jpbs)
Comment: And to answer the other part, it doesn't have to be kicked - it can be headed, struck with the body, leg, etc.
Comment: Hmmm... I read through the FIFA laws of the game, and couldn't find a clear prohibition. But it would probably fall under dangerous play. Same for sitting on a ball in play, or lying on top of it.
Comment: You could probably call a foul for impeding as well, although both of those would end up with an indirect free kick for the opposition. Of course, if you managed to **really** do something special it could count as a misconduct for unsporting behavior, but I really doubt that'd ever come up.
Comment: I haven't seen this in the rules either.  Do you have a reference?  Players trap the ball all the time and I've never seen anyone called for it.
Comment: Next time I'm playing, I'll try this hopping technique and see if my goal is allowed to stand!
Comment: Where is this written in the laws?
Comment: @posdef I was looking for this example for my answer for ages! Thank you! I couldn't put together the right web search, nor could I remember the player who did it.
Comment: @studro you are welcome :) It was not easy to try and remember Senor Blanco, especially with that amazing first name of his :)


How do I extend a configuration form without using hook_form_alter()?

Question: I want to extend some fields in a config form of a module with another module in Drupal 8. I created a config form in a module (e.g. custom_1) and now I want to add some more fields from another module (e.g. custom_2). custom_1 has a dependency on custom_2. I tried hook_form_alter() but it didn't resolve the issue.
Is there any other way to achieve this in Drupal 8?
Answer: Solution:
I came out to this solution:
I created a custom_1.routing.yml file and write the following code in it.
#Router settings for custom service page
custom_form.service_config:
path: '/admin/config/services/custom'
defaults:
  _form: '\Drupal\custom_1\Form\CustomConfigForm'
  _title: 'Custom Config Form'
  _description: 'Custom Configuration form.'
requirements:
  _permission: 'administer custom'

I created a CustomConfigForm.php file in custom_1/src/Form/CustomConfigForm.php.
    namespace Drupal\custom_1\Form;

    use Drupal\Core\Form\ConfigFormBase;
    use Drupal\Core\Form\FormStateInterface;

    class CustomConfigForm extends ConfigFormBase {
      public funtion getFormId() {
          return 'custom_form_service_config_form';
      }
      public function getEditableConfigNames() {
          return ['custom_form.service_config'];
      }
      public function buildForm(array $form, FormStateInterface $form_state) {
          // Form code here
         return buildform($form, $form_state);
      }
      public function submitForm(array &$form, FormStateInterface $form_state) {
         // Submit code here
      }
    }

Now, I have to merge some more form fields from another module custom_2. To achieve this, I followed the following steps.
I created a custom_2.routing.yml file and write the following code in it.
#Router settings for custom service page
custom_form.service_config:
path: '/admin/config/services/custom'
defaults:
  _form: '\Drupal\custom_2\Form\CustomTwoConfigForm'
  _title: 'Custom Config Form'
  _description: 'Custom Configuration form.'
requirements:
  _permission: 'administer custom'

I created a CustomTwoConfigForm.php file in custom_2/src/Form/CustomTwoConfigForm.php.
    namespace Drupal\custom_2\Form;

    use Drupal\Core\Form\FormStateInterface;
    use Drupal\custom_1\Form\CustomConfigForm;

    class CustomTwoConfigForm extends CustomConfigForm  {
      public funtion getFormId(){
          return 'custom_form_service_config_form';
      }
      public function getEditableConfigNames(){
          return ['custom_form.service_config'];
      }
      public function buildForm(array $form, FormStateInterface $form_state) {
           $form = parent::buildform($form, $form_state);
          // Form code here
         return parent::buildform($form, $form_state);
      }
      public function submitForm(array &$form, FormStateInterface $form_state) {
         // Submit code here
      }
    }

This resolve the issue for me without using hook_form_alter().
Thanks
Comment: I would honestly advise you to use hook_form_alter until it has been officially deprecated in favor of a cleaner method. Why did hook_form_alter not work? Also, I am not sure you want to call parent::buildForm twice on $form, only once. The buildFrom method should be named buildForm, or is it intentionally buildFrom? The naming is confusing because its easily read as buildForm (used a lot in D8). This is why hook_form_alter for editing existing forms is still a cleaner option.
Comment: @Kevin:  In the above code parent::buildForm called twice in custom_2 module because the first parent::bulidFrom will get all the fields from custom_1 module and the second return the current form. I have been facing problem in saving fields during form submission when used hook_form_alter. As drupal 8 is using symfony architecture, that is the other reason why I used this approach instead of  hook_form_alter.
Comment: It just doesn't look maintainable and in the end does the same thing hook_form_alter would do. Add some fields, and add validate/submit handlers, and call them. Until core provides a way to form alter that is more in line with the OOP parts of Form API, I would keep it simple.


For any point in $\Bbb R^2$ $f$ has a local inverse. Can I say $f$ is invertible on its range?

Question:
Define $f:\Bbb R^2\to \Bbb R^2$ by $$\begin{align}f(x,y)=(e^{2x+y},4x^2+4xy+y^2+6x+4y)\ . \end{align}$$
Define $U:=f(\Bbb R^2)$.
Prove that the inverse function of $f$ (say $f^{-1}:U\to \Bbb R^2$) exists.

I want to apply the inverse function theorem. I know that $f$ is $C^1$ and the Jacorbian determinant $J_f(x,y)=2e^{2x+y}>0$ for all $(x,y)\in \Bbb R^2$. But I have a question. If I know that for all $(x,y)\in \Bbb R^2$, I can find a local inverse, does this imply $f$ has a inverse from its range $U$ onto $\Bbb R^2$? Or I need to find some ways to prove that $f$ is injective from $\Bbb R^2$ to $U$?
Comment: Local inverse exists at every point the domain does not imply the global inverse exists.
Comment: What should I do to prove that  the inverse function of $f$ exists?
Comment: Have you tried to solve $e^{2x+y} = u$,$4x^2+4xy+y^2+6x+4y = v$?
Comment: Perhaps having a look to [this paper](https://doi.org/10.24033/bsmf.771) by Jacques Hadamard will answer your question: local invertibility will not solve your question, but local invertibility+something else (compactness of the map) will give you global invertibility (even in the infinite dimensional case).
Answer: Local invertibility without injectivity cannot give you global invertibility.
But here injectivity is easy to prove, as well as an explicit formula for the inverse. If
$$(e^{2x+y}, 4x^2+4xy+y^2+6x+4y) = (a, b)$$
then
$$y = \ln(a) - 2x$$
and you can check that
$$b = 4x^2+4xy+y^2+6x+4y = - 2x + 4 \ln(a) + \ln(a)^2.$$
You can easily conclude with this.


When using Rules, does a page refresh happen immediately if the event is set to 'Drupal is initializing'

Question: I have several views pages set up on my site that filter the content that is shown to normal visitors.  In general, these views will show users content that they have created.  However, when an admin user visits one of these pages, I want them to see all of the content (created by everyone.)  Currently, I have a rule set up which will redirect all admin users to a different url which has a different view (with access restricted to admin users and no filters)  Functionally, this does want I want (all users click on the same menu link, but eventually reach different pages.)
I am wondering, does the rules redirect event happen before the first view is loaded?  I want for the redirect to happen as soon as possible to save server resources and load time.  So, If the redirect happens after the page is created, it would be better for me to change my navigation strategy.
Answer: You have not specified the exact condition you are using. If you are using 'When content is viewed by an authenticated user' condition, then yes, views are being loaded in node load hooks, and they are already there by that time. The good news is that if these are cached, it will lighten things up, and the amount of admins is always limited, so a non-issue performance-wise.
But, if you really wanted to make one view show to one user and another to another, this is what you can do:

Create a separate block for each view display.
Put these blocks on the page.
Apply conditions for blocks that will show them for specific roles. Advanced to admins, and usual for non-admins, or all else.

And voila - you will have a solution without redirects and overhead.
Comment: Action: Drupal is initializing.  Conditions: Check path and User has role(s).  Action: Page redirect
Comment: Then it's ok, no views are loaded at that time.


Multilingual Taxonomy Views - Entity Translation

Question: I am trying to create a multilingual taxonomy view using Entity translation.  So far, I am stuck displaying an English view even when using a language code.
I'm looking for the steps needed for this. At the simplest, I am trying to create blocks or pages of taxonomy terms based on language.
Any suggestions?
Answer: Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.
Also, to make view results correspond to the language switcher, add a filter for Content Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).
If no option for the User's Current Language is available in the filter criteria form, then verify your configuration at Configuration -> Languages -> detection and selection: The order should be URL, Default, User and not something like Default, URL, User (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).
The above may turn out to NOT be the complete answer. Since you use the Entity Translation module, this option isn't there if you use it in 'entity' mode: if only some fields of the node are translatable the option is there but a bit more difficult to find. If you have the 'Body' of your nodes set to translatable entity then the option is "Body language" to be set to Current User Language.
Note: The Internationalizations Views module only has a DEV version for D7, but right now there are over 31K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because +31K users can't be wrong, right?
Answer: If you wont to show in views taxonomy terms, translated with entity_translate, try to use
"Entity translation: Name" field
instead
"Taxonomy term: Name (translated)"


How do you calculate the derivative of an integral

Question: How can you calculate $dy/dx$ here?
$$y=\int_{2^x}^{1}t^{1/3}dt$$
I get that the anti derivative is $3/4t^{4/3}$, but I don't understand what I'm supposed to do next.
The answer is
$$\int_x^1\sqrt{1-t^2}dt + 2$$
I have no idea how to get there
Comment: @MTurgeon, that seems to be accurate. Still, the issue of ever-changing questions, edited either by the OP or by someone else, is imo annoying, but alas it's something we can't do anything about, apparently. Thanks.
Comment: "the answer"...to what question?? That can't be the answer ( solution) to the integral you first talk about.
Comment: what is $y$? Are you saying $y=\int_1^{2^x} t^{1/3} dt$?
Comment: yes, I meant to say calculate dy/dx.
Comment: The question as posted *right now* doesn't fit the OP which says literally: "Integral from 1 to  2^x of : (t)^(1/3)

How can you calculate dy/dx here" ...why someone decided the lower limit is $\,2^x\,$ is beyond my comprehension but perhaps this illustrates the problem of getting into other people's questions and edit them freely.
Comment: BTW, and right now again, there are already 5 (five!) edits to this question, which was posted 40 minutes ago...
Comment: @DonAntonio If you look at the edit history, you will see that the OP himself changed the limits of integration to what they are at the moment. I can only conclude that the phrasing of the original version was wrong, and that the present version reflects the OP's original intention.
Answer: What about using the Fundamental Theorem of Calculus?
$$\begin{align*}\dfrac{dy}{dx} &= \dfrac{d}{dx}\left(\int_{2^x}^1t^{1/3}dt\right)\\
&= - \dfrac{d}{dx}\left(\int^{2^x}_1t^{1/3}dt\right)\\
&= -((2^x)^{1/3})\dfrac{d}{dx}(2^x)\\
&= -2^{4x/3}\ln 2.
\end{align*}$$
Comment: you probably meant $(2^x)^{1/3}$, not just $x^{1/3}$?
Comment: Fundamental theorem of calculus, plus the chain rule...
Comment: And you can combine terms for $2^\frac{x}{3}2^x$, of course.
Comment: @gt6989b Of course, thank you!
Comment: @ThomasAndrews Of course, thank you! The worst is, even when I teach, I make stupid mistakes like this one...
Comment: @MTurgeon , don't worry about making stupid mistakes while teaching. Perhaps you can do what I usually do: state at the course's beginning in front of all the students "Guys, you're expected to *think* and deduce stuff on your own in this course. After all, remember that **any** mistake I may do while teaching is your own responsibility". That way they won't be able to say, like little children, "Hey, the teacher said so and so!"
Comment: @DonAntonio Thanks for the tip!
Answer: $$y:=\int_1^{2^x}t^{1/3}dt=\left.\frac{3}{4}t^{4/3}\right|_1^{2^x}=\frac{3}{4}\left[(2^x)^{4/3}-1\right]=\frac{3}{4}(2^{4x/3}-1)$$
Added: $$\;\;\frac{dy}{dx}=\frac{3}{4}\frac{4}{3}2^{4x/3}\log 2=2^{4x/3}\log 2$$
Comment: He had the integral from $1$ to $2^x$, not from $0$.
Comment: Corrected. Thanks.
Comment: It's $\int_{2^x}^1$, not $\int_1^{2^x}$.
Comment: Say who, @S4M?? The ORIGINAL POST says EXACTLY the following: "Integral from 1 to  2^x of : (t)^(1/3)

How can you calculate dy/dx here" ...but if people gets into the OP and edits it according to their will then the can actually change deeply the OP!
Comment: Yeah, the OP changed it.
Comment: Seems so, @ThomasAndrews, and this is annoying as sometimes the edited question can be pretty different from the new one. I'll leave my answer as it is just the same but with the integral's limits interchanged.
Answer: If you call $\varphi(z)=\int_1^z t^{1/3}dt$, then you have $y=-\varphi(2^x)$, then $\frac{dy}{dx}=-\ln(2)2^x \varphi'(2^x) = -\ln(2)2^x (2^x)^{1/3}$
So: $\frac{dy}{dx}= -\ln(2)2^{4x/3}$


show that k-√2 is irrational number

Question: let k be rational number , show that k-√2 is irrational number
a rational number is any number that can be expressed as the quotient or fraction p/q of two integers, a numerator p and a non-zero denominator q
the irrational numbers are all the real numbers, which are not rational numbers,
could you please help me with that ?
Answer: SIOTDAC that $k-\sqrt2$  is rational. Then since $k$ is rational, let $k=p/q$ and say $k-\sqrt2 = a/b$. Then, by simple algebra:
$$p/q-\sqrt2 = a/b \Rightarrow bp - \sqrt2bq = aq \Rightarrow bp = q (a +\sqrt2b) \Rightarrow p/q - a/b = \sqrt2 \Rightarrow \sqrt2 = (pb-qa)/bq$$
which means that $\sqrt2$ is rational as it is expressible as a fraction. This is absurd.
(Even more simply, you could just move the $a/b$ to the other side of the equation and get the fraction).
Answer: The difference between two rational numbers is rational, viz. $a/b-c/d=(ad-bc)/bd$. Since $k$ is asked rational, if $k-\sqrt{2}$ were too then so would be $\sqrt{2}$, which it famously isn't.

show that k-√2 is irrational number


document.querySelect em body

Question: Como utilizar a sessão de código document.querySelector para alterar/mudar a imagem de fundo de uma página ...
Ex:
var imagem_lista = [
    "http://static.gamespot.com/uploads/original/1179/11799911/2324138-warface11.jpg",
    "http://glasshome.tv/wp-content/uploads/2013/10/Warface_Screenshot019_Climb.jpg",
    "http://hq.warface.com/updates/endless-skies/img/WF_ES_019.jpg",
    "http://lodik.ru/uploads/posts/2015-02/1423304948_warface-3.jpg",
    "http://hq.warface.com/updates/siberia/img/wf-update-coldpeak-03.jpg",
    "http://vignette1.wikia.nocookie.net/warface/images/4/43/Warface_WeapCustom_Combat_201.jpg/revision/latest?cb=20130301001625"
];

window.onload=function(){
    var url_pagina = window.location.href;
    if(!url_pagina.indexOf('/p/')){
        var numero_aleatorio = random_number(0, imagem_lista.lenght);
        mudar_imagem(imagem_lista[numero_aleatorio]);
    }
}

function random_number(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function mudar_imagem(image){

  // usar este
    document.querySelector('body').style.background-image=image;
  // ou este
    $('body').css('background-image', 'url(' + image + ')');
}

E um dos error é o seguinte:
Uncaught ReferenceError: Invalid left-hand side in assignment
Uncaught ReferenceError: imagem_lista is not defined
    at :2:7
    at Object.InjectedScript._evaluateOn (:905:140)
    at Object.InjectedScript._evaluateAndWrap (:838:34)
    at Object.InjectedScript.evaluate (:694:21)
OBS: O Arquivo que contém o script está hospedado em:
http://brasilr2.net76.net/js/webmaster.body.js
Na linha: indexOf
Eu quero identificar quando um usuário acessa meu blog para mudar o fundo da imagem de acordo com um tema definido.
Ex: A home do blog está definida para com uma dessas imagens em imagem_lista.
(http://warfeicebrasil.blogspot.com.br)
Agora por exemplo na página de modo sobrevivencia do jogo citado lá, o tema deve mudar logo o fundo também. (http://warfeicebrasil.blogspot.com.br/p/operacao-cold-peak.html)
Answer: Problema com os hifens
Isto está errado:
document.querySelector('body').style.background-image=image;

Note que o erro

Uncaught ReferenceError: Invalid left-hand side in assignment

É causado pelo uso de .background-image
Hifens são usados para operações no javascript e faltou o url(...), pra setar o background-image você deve fazer assim:
document.querySelector('body').style.backgroundImage = 'url(' + image + ')';

Note que backgroundImage usa o I em maiusculo, se fosse font-size, ficaria o S em maiusculo:
document.querySelector('body').style.fontSize

Então para cada hifen a proxima letra é em maiusculo, esta regra só não se aplica aos prefixos -webkit, -moz e -o, por exemplo -webkit-filter deve ficar assim:
document.querySelector('body').style.webkitFilter

No entanto se você está usando jquery (o que parece o caso), então aplique com:
$('body').css('background-image', 'url(' + image + ')');

Outros erros
Outro problema é que você escreveu imagem_lista.lenght, mas lenght não existe o correto é length.

Problema com o indexOf
indexOf não é retorna dados do tipo true ou false

Ele retorna de 0 ou mais para quando encontrar a string
Retorna -1 quando não encontrar

Então o correto seria:
//Se não tiver /p/ na url
if(-1 === url_pagina.indexOf('/p/')){
    var numero_aleatorio = random_number(0, imagem_lista.length);
    mudar_imagem(imagem_lista[numero_aleatorio]);
}

Se quiser que ele troque o background quando encontrar /p/ na url use assim:
//Se tiver /p/ na url
if(-1 !== url_pagina.indexOf('/p/')){
    var numero_aleatorio = random_number(0, imagem_lista.length);
    mudar_imagem(imagem_lista[numero_aleatorio]);
}

Comment: @Nathan1302 tá certo é isto mesmo, esqueci de ver este detalhe :)
Comment: Ok sua resposta foi muito válida mas quando eu entro na home do site ele ainda não muda com base no script: brasilr2.net76.net/js/webmaster.body.js
Comment: Na home deve-se alterar o fundo por qualquer imagem pelo array do __image_lista__
Comment: Ok lhe aguardo...
Comment: funcionou se eu invocar o metodo mudar_imagem
Comment: mas fora isso aparece isso __GET http://warfeicebrasil.blogspot.com.br/undefined 404 (Not Found)__
Comment: se eu apertar F12 e invocar o metodo acontede, mas fora disso GET http://warfeicebrasil.blogspot.com.br/undefined 404 (Not Found)
Comment: esta indicando a linha 24 do arquivo que da a exceção:

document.querySelector('body').style.backgroundImage = 'url(' + image + ')';
Comment: @Nathan1302 Achei o problema e atualizei a resposta :)
Comment: realmente agora funcionou! eu sempre me confundo com __lenght__ e __length__
Comment: @Nathan1302 eu também, vivo me confundindo, um que eu confundia muito era `keyCode` e `keycode`, na verdade o `C` é maiúsculo, mas eu as vezes esqueço :) é normal
Comment: : } obridago! e deixa eu pergunta na lista ex: tem 4 itens o length vai ser de 0, 1, 2, 3 não 1, 2, 3, 4. eu posso aplicar -1 no length?

document.querySelect em body


The difference between two population means

Question: I am trying to answer this question:
There is no difference between two population means. From each of these two populations
a sample is selected and then for both samples the means are calculated.

Consider this:
"since the null hypo is true, a significant result can never be found when we perform
a t-test for independent measures (two-tailed, alpha = 0.05)

Can we say that is statement is in/correct, partially correct, or insufficient to answer? I am really unsure of which path to take.
Answer: This is totally false. Let's do an R simulation.
set.seed(2021)
ps <- rep(NA, 1000)
for (i in 1:1000){

    # Simulate data from two identical distributions
    #
    x <- rnorm(100)
    y <- rnorm(100)

    # Test the means, save the p-value
    #
    ps[i] <- t.test(x, y, var.equal=T)$p.value
}

hist(ps)
summary(ps)

When you run this, you will notice that a number of the p-values fall below $0.05$. In fact, about $5\%$ will fall below $0.05$.
It turns out that, under the null hypothesis, the p-value has a uniform distribution on $[0,1]$.
Comment: @e.erhan The example I gave uses identical distributions: same mean, same standard deviation, same everything. $\text{//}$ A constant population is a population where every observation has the same value.
Comment: You can prove a far stronger and far-reaching statement: *no matter what the populations may be,* provided only that at least one of them is not constant, and no matter what significance level you choose, *the chance of finding a significant difference (using a t test) is always positive.*
Comment: I really appreciate both of your comments and effort in helping me out. I sincerely thank you both.
Comment: @whuber, can I ask what you meant by being not constant for a population? Also, should I understand that even if these two populations not only had the same mean but also the same standard deviation, there is still a positive chance of finding a significant difference?
Comment: @Dave Thanks for the clarification!


Stop a Symfony Console command

Question: I have a Symfony console command that loops continuously
protected function execute(InputInterface $input, OutputInterface $output)
{
   //...

   pcntl_signal(SIGHUP, [$this, 'stopCommand']);

    $this->shouldStop = false;

    while (true) {

        pcntl_signal_dispatch();

        if ($this->shouldStop) {
            break;
        }
        sleep(60);
    }
}

protected function stopCommand()
{
    $this->shouldStop = true;
}

I wish I could stop him from a controller
    public function stopAction()
{
    posix_kill(posix_getpid(), SIGHUP);

    return new Response('ok');
}

but I do not know why it does not work
Answer: It probably does not work, because console command is running in different process than controller action. Try to store PID number of console command into the file at the beginning of execution with something like:
file_put_contents("/tmp/console_command.pid", posix_getpid());

and then use this code in controller:
posix_kill(file_get_contents("/tmp/console_command.pid"), SIGHUP);

Stop a Symfony Console command


explanation of rethrow exception

Question: If I have the following code
try{
   // Some code that might throw a system_error
   -- snip --
} catch(const std::system_error& ex) {
  if(ex.code()!=std::errc::permission_denied){
    // Not a permission denided error
   throw;
  }
// Recover from a permission denied
--snip---
}

can someone explain the function of throw? Is it correct that the try-catch statement will re-execute until it finds a permission_denied error?
Comment: Please invest in [a good books or two](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). This is really a rather basic thing that should be explained in any decent beginners book, class or tutorial.
Comment: [Here's the big list of recommended books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list).  Since you already have a programming background you can skip most of *Programming: Principles and Practice Using C++* and maybe graduate straight on to *A Tour of C++*, but be warned *Tour* is extremely terse. Here's a older version of *Tour* you can browse to see if it's blowing past stuff you wanted better-explained. If it isn't, the third edition of the printed book should bring you right up to date with cutting edge C++.
Comment: No, this is the example from my book and I don't understand it.
Comment: Is it really a beginners C++ book? What have it said about exceptions and the `throw` statement before this example? It should have covered what the `throw` statement does, unless it's a intermediate book that assumes familiarity with basic C++? What *is* the book you're reading?
Comment: And please excuse me sounding rude, it's not really my intention. I'm not criticizing you, only your book. (Well, maybe you a *little* if you skipped or skimmed over the chapters and sections that taught the `throw` statement... ;))
Comment: Np, it's C++ crash course by Josh Lospinoso. I'm reading the book per-page. I used to know fortran 90, so many "low level" programming seem familiar, but others definitely not.
Comment: Back when I was reading a lot of C++ texts looking for a good one for new hires I don't think I found any worthwhile "Learn C++ in a hurry" books. C++ is a hard language to rush.
Comment: I would be very interested if you have an in-depth, yet understandable, reference. I don't mind spending time learning it.
Comment: At this time there are no truly good middle-ground books covering C++ from 2017 on. I mean to try out *Programming: Principles and Practice Using C++* and *tour* for the update to C++20 next time I get a C++ hire.
Answer: throw; will re-throw the caught exception, allowing it to be caught and handled by something higher up the call stack (or escape from main and terminate the program).
Comment: @user2820579 Up the call-stack to the next higher `catch` clause. Or to the termination of the program if no other suitable `catch` clause is found.
Comment: @user2820579 If another `catch` handler catches the exception it can do whatever it wants with it. But if you have no `catch` that catches the exception at all anywhere up the stack (whether thrown the first time or re-thrown), then the program is immediately terminated on the (re-)throw by an implicit call to [`std::terminate`](https://en.cppreference.com/w/cpp/error/terminate), potentially (but not necessarily) after stack unwinding called all destructors of automatic storage duration variables of the stack at the time of the (re-)throw.
Comment: If I don't get a permission_denied, where does the program execution go in this code?
Comment: @user2820579 what do you mean by "does it faithfully ends?"?
Comment: Ahg sorry! I got confused by your statement "or escape from main and terminate the program". So what you mean is that if another handler gets a system_error and know what to do with it, the program may actually terminate, right?

explanation of rethrow exception


Why does the last platform-specific dependency take precedence in Cargo?

Question: I have a dependency in my Cargo file that needs to be different by platform, specifically, the default features. Here's what I am trying to do:
[package]
name = "..blah.."
version = "..blah.."
authors = ["..blah.."]

[target.'cfg(target_os = "macos")'.dependencies]
hyper = { version = "0.9", default-features = false, features = ["security-framework"] }

[target.'cfg(target_os = "linux")'.dependencies]
hyper = { version = "0.9", default-features = true }

But this doesn't seem to do what I want. On my Mac it appears to be using the bottom target line as if I just specified hyper = "0.9". If I do cargo build as specified, I get errors with regard to openssl:

cargo:warning=#include <openssl/ssl.h>

However, if I build it like this:
[dependencies]
hyper = { version = "0.9", default-features = false, features = ["security-framework"] }

Then it builds fine. This indicates to me that the cfg for "macos" isn't working.
How do I make this work, or more specifically, how do I solve the problem where I need my dependency to use different features by platform?
Comment: @Shepmaster well in theory they are trying to solve the same problem, so I suppose my question then is "Why isn't my Cargo file selecting the right configuration for a dependency".
Comment: @Shepmaster [here](https://github.com/alexcrichton/curl-rust/blob/master/Cargo.toml) is an example which uses `target_os`, although in a `not`. The configurations should be the same as used in `#[cfg(...)]`, where `target_os` is listed in the [documentation](https://doc.rust-lang.org/reference.html#conditional-compilation).
Comment: Why is this not a duplicate of http://stackoverflow.com/q/29854912/155423?
Comment: I guess it is not a duplicate because the syntax above seems to match the examples in the [unit tests](https://github.com/rust-lang/cargo/blob/master/tests/cfg.rs) and [commit](https://github.com/rust-lang/cargo/pull/2328/commits/f5d786e05600720ba4671caf5b598624103c8f72).
Comment: @wimh I don't think I'm following. The [unit tests you linked to say](https://github.com/rust-lang/cargo/blob/4f57637fbeb9a79c86808609e388a1eed9a50e2f/tests/cfg.rs#L152) `[target."cfg(windows)".dependencies]`, **without** `target_os`. The [documentation likewise does not use `target_os`](http://doc.crates.io/specifying-dependencies.html#platform-specific-dependencies).
Comment: I'm suffering from the same issue… did you manage to solve it?
Comment: @lunaryorn nope. I've been meaning to file an issue on the Cargo GitHub repository.
Comment: @vcsjones I think it's a bug, so it'd be great if you could open an issue!  If you do could you CC me?  I've got the same username on Github.
Comment: Doesn't MacOS contain a Linux shell? I believe the Linux dependency is overriding the MacOS dependency by coming later in the list. Try swapping the dependencies around.
Answer: It does not look like it is possible with Rust 1.13.0 and Cargo 0.13.0-nightly. See Cargo issues 3195 and 1197.
As a workaround, you can tell Cargo to use Homebrew's OpenSSL:
export OPENSSL_INCLUDE_DIR=`brew --prefix openssl`/include
export OPENSSL_LIB_DIR=`brew --prefix openssl`/lib
export DEP_OPENSSL_INCLUDE=`brew --prefix openssl`/include

Comment: Using Homebrew's OpenSSL is also documented [here on SO](http://stackoverflow.com/q/34612395/155423), but I don't think that will help OP. Specifically, I believe they wish to *avoid using OpenSSL* on macOS, and use the built-in SSL framework instead.
Comment: Yes, that's why I said it was not possible for the moment and that the rest was a workaround. For my use case, I prefer my crate to compile without manual modifications to `Cargo.toml` rather than commenting/uncommenting a line in it to link against the framework... Bu tI agree it's not optimal and does not solve the issue.


How are drupal field collections stored in the database?

Question: I am trying to integrate a site made in drupal with a golang application. I just need to fetch data from the drupal site. I have database access and am trying to fetch data from the drupal site's database. However I dont understand how drupal stores field collections in the database. How can I find the field collections of a node from the drupal database?
Answer:
When a field collection is added to a user, node, or other Drupal entity it is represented with a field type of field_collection_item. The value stored in the field_collection_item field is the id of the field collection, not the individual values of the fields making up the field_collection_item.

Reference:
https://www.drupal.org/node/1477202
Basically it saves the field collection in the field_collection_item table and it saves all the other fields that are inside the field collection in the same convention as normal fields(their own table), except that inside the individual fields there is a bundle column inside that relates back to the field_collection_item's field_name. making a one to many relationship
Comment: Thanks for the answer. But what if there are multiple collections? Like a node has an image assets field with multiple image assets and each image asset has an image field, title and description fields?