How to figure out the log of a number without a calculator?

Question: I have seen people look at log (several digit number) and rattle off the first couple of digits.
I can get the value for small values (aka the popular or easy to know roots), but is there a formula.  Similar to how to tell if a number is divisible by an integer.
I have read this and this but could some one explain why it works?
Comment: To answer the _title_: Check the CRC Handbook or use a slide rule.
Comment: Links are broken. Could you update them?
Comment: The first link is simply using the basic rules for logarithms - the log of a product is equal to the sum of the logs (working in base 10). As an example, take $log(3025) = log(3.025 \times 10^3)=log(3.025)+log(10^3) = log (3.025)+3 \approx 3.48$ (using that $log(3)$ is 0.48). The power of 10 was chosen because $log(3)$ was known.
Answer: The idea of the first article is to rewrite any positive number $x$ as :
$$\tag{1}x=m\cdot 10^{\,e}$$ with $m$ the 'mantissa' : a real number between $1$ and $10$ (excluded)
and $\,e\,$ the 'exponent' (or "power of ten") which is a signed integer.
From this we have $\;\tag{2}\log_{10}(x)= e+\log_{10}(m)$
(to keep notations short I'll write $\,\log(x)\,$ for $\,\log_{10}(x)\,$ and use $\,\ln(x)$ for the 'natural' logarithm)
Since the mantissa is between $1$ and $10$ the idea is to memorize the first logarithms (here I'll use up to $5$ digits, you may use fewer or more digits if you prefer) :
$$
\begin{array} {ll}
m & \log\,m\\
1 & 0\\
2 & 0.30103\\
3 & 0.47712\\
4 & 0.60206\\
5 & 0.69897\\
6 & 0.77815\\
7 & 0.84510\\
8 & 0.90309\\
9 & 0.95424\\
\end{array}
$$
This seems to be much work but these values (except $\log(7)$) are not independent :

$\log(2^n)=n\,\log(2)\;$ so that $\;\log(4)=2\log(2),\;\log(8)=3\log(2),\cdots$
more generally $\;\log(a\cdot b)=\log(a)+\log(b)\;$ so that the table could be rewritten (using $\,1=\log(10)=\log(2)+\log(5)$) :

$$
\begin{array} {lll}
m & \log\,m\\
1 & 0\\
2 & 0.30103 &\log(2)\\
3 & 0.47712 &\log(3)\\
4 & 0.60206 &2\,\log(2)\\
5 & 0.69897 &1-\log(2)\\
6 & 0.77815 &\log(2)+\log(3)\\
7 & 0.84510 &\log(7)\\
8 & 0.90309 &3\,\log(2)\\
9 & 0.95424 &2\,\log(3)\\
\end{array}
$$
The table may thus be rebuilt with just three values (two if $\,\log(7)\,$ is omitted)!
One should memorize too $\;\ln(10) \approx 2.3026\,$ and its multiplicative inverse $\;\dfrac{1}{\ln(10)}=\dfrac{\ln(e)}{\ln(10)}=\log(e)\approx \dfrac 1{2.3026}\approx 0.4343$.
The classical expansion $\;\ln(1+x)\approx x\;$ will be rewritten as :
$$\tag{3}\log(1+x)=\frac{\ln(1+x)}{\ln(10)}\approx 0.4343\cdot x$$
(with $x$ replaced by $\;x-\dfrac{x^2}2+\dfrac{x^3}3-\cdots\,$ if needed)
Let's apply all this to recover the (unfortunately lost...) value of $\,\log(7)\,$ using only $\;\log(2),\log(3),\log(e)$. One method is to use $\;\log(7)=\dfrac{\log(7^2)}2\;$ and :
\begin{align}
\log(49)&=\log\left(50\;\left(1-\frac 1{50}\right)\right)\\
&=\log\left(\frac{100}2\right)+\log\left(1-\frac 1{50}\right)\\
&\approx\log(100)-\log(2)-0.4343\left(\frac 1{50}+\frac 1{2\cdot50^2}\right)\\
&\approx 2-\log(2)-\frac{0.8686}{100}\left(1+\frac 1{100}\right)\\
&\approx 2-0.30103-0.00877\\
&\approx 1.69020
\end{align}
Dividing by $2$ will indeed give the wished $0.84510$. Without the $\dfrac{x^2}2$ term we would get $\,0.84514$ : also not that bad!
$$-$$
Let's further practice and compute $\log(29012)$ as in your article : $\log(29012)=\log(2.9012\cdot 10^4)=4+\log(2.9012)$
In first approximation we have $\;\log(2.9012) \approx \log(3) \approx 0.477\;$ and deduce that $\log(29012)\approx 4+0.477 \approx 4.477$.
we have $\;2.9012\approx 3\cdot 0.9671 \approx 3\cdot (1-0.0329)\;$ so that
\begin{align}
\log(2.9012)&\approx \log(3)+\log(1-0.0329)\\
&\approx 0.47712-0.434\cdot 0.033\\
&\approx 0.47712-0.0143\\
&\approx 0.4628
\end{align}
and we got $\;\log(29012)\approx 4.4628\,$ not so far from the exact $4.4625776\cdots$
It is important to understand that the table of logarithms allows too the reverse computation that is to compute $10^{\,x}$.
Of course $10^{\,\log(2)}=2$ so that for example $10^{\,0.3}$ will be just a bit smaller than $2$.
For additional precision and for $x\ll 1$ let's write the useful $\displaystyle 10^x=e^{x\ln(10)}\approx 1+\ln(10)x\;$ or
$$\tag{4}10^{\,x}\approx 1+2.3026\cdot x$$
To compute $10^{\,x}$ decompose $x$ in its integer part $i$ and fractional part $f$
then $10^{\,i+f}=10^{\,i}\cdot 10^{\,f}$ : the mantissa of this result $10^{\,f}$ will be found using the table and $i$ will of course be the exponent.
After that all applications may follow : compute $a^b$ for any positive real $a$ and real $b$ using $\,\log(a^b)=b\,\log(a)\;$ so that
$$a^b=10^{\,b\log(a)}$$
Computing the $n$-th root of a positive real number will just be the special case  $\;b=\dfrac 1n$.
Example $\sqrt[5]{1212}$ :
\begin{align}
1212&\approx 3\cdot 4\cdot 100\cdot 1.01\\
\log(1212)&\approx 2+\log(3)+\log(4)+0.4343/100\\
\dfrac{\log(1212)}{5}&\approx \frac{2+0.47712+0.60206+0.00434}5\\
\approx 0.6167
\end{align}
The answer (approximatively $10^{\,0.6167}$) will thus be a little over $4$.
More exactly $\,0.61670=0.60206+0.01464\,$ and since $\,10^{0.01464}\approx 1+2.3\cdot 0.0146 \approx 1.0336\;$ an approximate result will be  $4\cdot 1.0336$ that is : $$\sqrt[5]{1212}\approx 4.134$$ while the exact result is $4.1371429\cdots$.
Many methods may be used to get more precision :

from $1212=1200\cdot 1.01$ expand the logarithm (and/or the power of $10$) to second order as done for $\log(7)$
compose (+ -) different exact values of logarithms to get values near the searched one (example $\,1.33\approx \dfrac 43$ and thus $\;\log(1.33)\approx \log(4)-\log(3)$)
memorize values nearer to $1$ : $\log(1.1)\approx 0.041393,\ \log(1.2)=\log(\frac{3\cdot4}{10})\approx 0.07918$ and so on (you should nearly 'recognize' $\log(1.01)= 0.004321$... (see $\log(e)$) and won't need to memorize $\log(1.001)$)
$\cdots$

Wishing you much fun discovering yourself other tricks,
Comment: thanks, this is a great answer.
Comment: @MaoYiyi: Thanks for that, you are welcome!
Comment: There was a suggested edit of this answer by this user: http://math.stackexchange.com/users/30581/oluwatola-imoleayo, which I rejected.
Comment: Thanks for the information @Aryabhata !
Comment: can i mail Raymond Manzoni in person. i am new here, and i have 1 reputition. i however need help
Comment: @oluwatolaimoleayo You should use the button at the top-right "Ask question" to get mathematical help here (or perhaps edit your question if the subject is logarithms)! Concerning my email see this [thread](http://mathforum.org/kb/message.jspa?messageID=7047633)
Comment: Good explanation, but there's an easier way of doing it.  This is extremely complicated, plus you use approximation which is lacking precision.
Comment: @annoying_squid: Well I know other methods but chose to present this one here (retrospectively I think I shouldn't have added the evaluation of $\log(7)$ to second order but else I am rather satisfied by this answer). Of course you are encouraged to present your own easier method here or in a more recent thread like this [one](http://math.stackexchange.com/questions/1793127/calculating-logs-and-fractional-exponents-by-hand?lq=1) !
Answer: One can get very good approximations by using
$$\frac 1 2 \log  \left|\frac{1+x}{1-x}\right| =x+\frac {x^3} 3+ \frac {x^5}5+\cdots$$
Say you want to get $\log 3$. Then take $x=1/2$. Then you get
$$\log 3 \approx 2\left( \frac 1 2 +\frac 1 {24} + \frac 1 {140} \right)=1.0976190\dots$$
The real value is $\log 3 = 1.098612289\dots$
Take another term to get
$\log 3 \approx 1.098065476\dots$.
Note that this particular series has the advantage that for $x < 1$ (which is where it works) you get "exponentially increasing" approximations.
Comment: One can get slightly more bang for the buck with Padé approximants. As already shown by Peter, using the $\mathrm{artanh}$ series is a great idea (due to the oddness of $\mathrm{artanh}$), but comparing $$x+\frac{x^3}{3}+\frac{x^5}{5}+\frac{x^7}{7}$$ and $$\frac{x-\frac{11 x^3}{21}}{1-\frac{6 x^2}{7}+\frac{3 x^4}{35}}$$ for $x=1/2$, the Padé approximant has a slight edge over the series...
Answer: This can be done by recourse to Taylor series. For $\ln(x)$ centered at 1, i.e. where $0 < x \leq 2$:
$$
\ln(x)= \sum_{n=1}^\infty \frac{(x-1)^n}{n}= (x-1) - \frac{1}{2}(x-1)^2 + \frac{1}{3}(x-1)^3 + \frac{1}{4}(x-1)^4 + \cdots
$$
Comment: Unfortunately, this is a pretty miserable way to do calculations, except in the situation where you have a number that is close enough to 1 that you only need 1 or 2 terms.
Comment: The related series $\ln x = \ln a + \frac{x-a}{a} - \frac{(x-a)^2}{2a^2} + \ldots$ for $0<x\leq 2a$ is also not very useful in this regard.
Comment: @oenamen and you too, Kaleb. Thanks for those equations.  Always good to build up one's equation notebook.
Comment: @MaoYiyi: Glad to help. To see how bad this approach is try approximating $\log_{10} 3025$. It's only useful if $(x-a)/a$ is small.
Comment: @oenamen Yes, I got that after trying a few. Just wanted to know how they did it. Don't worry, I'll still use my ti
Answer: A curve can be approximated with line segments.
If $4 \le x \lt 5$, then $\log(x) \approx 0.1(x+2)$.  For example, $\log(4.1) \approx 0.61$, $\log(4.2) \approx 0.62$, $\log(4.3) \approx 0.63, \ldots, \log(4.9) \approx 0.69$.
If $7 \le x \lt 10$, then $\log(x) \approx 0.1(x/2 + 5)$.  For example, $\log(7.2) \approx 0.1(7.2/2 + 5) \approx 0.86$.


Polynomial ring problem

Question: May I verify if my proof to this problem is correct?
Let $p \in \mathbb{P}.$ For $x \in \mathbb{Z},$ let $\overline{x}$ be remainder of $x$ when divided by $p.$  Let $f(X)= \sum^{n}_{i=0}a_iX^i \in\mathbb{Z}[X]$ such that $p$$ \not|a_n$ in $\mathbb{Z}.$  If $g(X)=\sum^{n}_{i=0}\overline{a}_iX^i $ is irreducible in $\mathbb{Z}_p[X],$ then $f(X)$ is irreducible in $\mathbb{Q}[X]. $
Proof: $\psi:\mathbb{Z} \to \mathbb{Z}_p, x \mapsto\overline{x},$ is a unital ring homomorphism.
So $\Phi:\mathbb{Z}[X] \to \mathbb{Z}_p[X], \ \sum a_iX^i \mapsto \sum\overline{a}_iX^i, \ $
is a ring homomorphism. If $f(X)=c,$ for some $c \in  \mathbb{Z},$ then $g(X)= \overline{c} \neq \overline{0},$ since $p$$\not | c$ in $\mathbb{Z}.$ Since $\mathbb{Z}_p$ is a field,  $g(X) \in  U(\mathbb{Z}_p[X]) =U(\mathbb{Z}_p),$ contradicting that $g(X)$ is irreducible in $\mathbb{Z}_p[X].$
Now, suppose $\text{deg}(f(X)) \geq 1$ and assume, to the contrary, $f$ is not irreducible in $\mathbb{Q}[X].$ This means $f$ is reducible in $\mathbb{Q}[X]. $ Since $\mathbb{Z}$ is $\text{UFD},  \ f$  is not irreducible in $\mathbb{Z}[X].$ Clearly, $f \not\in U(\mathbb{Z}[X]) \cup \{0\},$ so $f$ is reducible in $\mathbb{Z}[X].$
Let $f(X) =h(X)k(X)$, where $h(X)= \sum^{m}_{i=0}b_iX^i, \ k(X)= \sum^{k}_{i=0}c_iX^i \in \mathbb{Z}[X]$ and $\text{deg}(h), \text{deg}(k) \geq 1.$ Hence$, \ \Phi(f(X))=g(X)= \Phi(h(X))\Phi(k(X))=\sum^{m}_{i=0}\overline{b}_iX^i \sum^{k}_{i=0} \overline{c}_{i}X^{i}.$
Since $p$$\not |a_n, $ we have $ p$$\not| b_m$ and $p$$\not | c_k,$ so $\overline{b}_m  \neq \overline{0}, \overline{c}_k \neq \overline{0}.$
Hence $\Phi(h(X))$ and $ \Phi(k(X))$ are non-constant polynomials and hence are not units of $\mathbb{Z}_p[X].$ This contradicts that $g(X)$ is irreducible  in $\mathbb{Z}_p[X].$
p.s.  $U(R)$ denotes set of units of ring $R.$
Thank you for your attention.
Answer: It seems correct, but possibly too involved.

The projection $a\mapsto \bar{a}$ extends uniquely to a ring homomorphism $\def\Z{\mathbb{Z}}\varphi\colon\Z[X]\to\Z_p[X]$ by sending $X$ to $X$.
If $f\in\Z[X]$ is reducible, then $f=gh$ with $g$ and $h$ having degree at least $1$
$\varphi(f)=\varphi(g)\varphi(h)$ is, by hypothesis, irreducible, which means that at least one among $\varphi(g)$ or $\varphi(h)$ is constant (and nonzero)
Assume $\varphi(g)$ is constant: then $g=pg_1(X)+a$, where $a\in\Z$ is not divisible by $p$
In particular, the leading coefficient of $g$ is divisible by $p$, contradicting the fact that $a_n$ is not divisible by $p$
Therefore $f$ is irreducible in $\Z[X]$
Irreducibility in $\Z[X]$ implies irreducibility in $\mathbb{Q}[X]$ (Gauss' lemma)

Polynomial ring problem


how to add translation feature in custom module (hook_node_view) using google translation api key?

Question: I want to write a code to translate any node (content type: blog) into any other language using a button to translate. I purchased google translate api key but I do not understand how to implement it using hook_node_view with a button.
Answer: Hope, this module helps you GTranslate
Comment: Thank you. But, actually I already have google translate api keys and if I install GTranslate module then again I have to pay for GTranslate api. That's why I requisite for some solution other than this.


O que é esse :object = " "?

Question: Eu encontrei um trecho de código que eu não entendi o que faz.
Eu procurei, mas não encontrei uma resposta (ou não usei os termos corretos para pesquisar).
Código:

  <Object :object="returnedObject"> </Object>

Trecho específico que eu não compreendi:

:object="returnedObject"

Pediram que eu colocasse todo o código
Código completo
<template>

      Devolver objeto

        Entre com o código de devolução:

          <input type="text" class="input" v-model="devolutionCode" />
          <button
            type="button"
            class="button is-success"
            @click="returnObject()"
          >
            Devolver objeto
          </button>

        <Object :object="returnedObject"> </Object>

</template>

Comment: Seria bom dar um pouco mais de contexto de onde obteve este trecho. Provavelmente isto não é HTML puro. O HTML tem uma tag chamada object, mas a sintaxe não é esta do seu exemplo. Deve ter alguma tecnologia intermediária processando os dados antes de gerar o HTML "verdadeiro", ou então este trecho veio de algum mecanismo de layout que se assemelha a HTML mas não vai ser usado por um navegador normal.
Comment: Para mim parece um erro de sintaxe.
Comment: @letícia-a Se enviar o html completo, certamente terá melhores respostas.
Answer: Como a pergunta é unicamente sobre o :object no código, não vou explicar sobre a tag object ou algo assim.
Os dois pontos(:) antes do atributo é uma diretiva do Vue.js para dizer que o valor passado à propriedade é um javascript. Ele é um açucar sintático para uma outra diretiva, o v-bind.
Veja um caso de uso:

Vue.component('vue-component', {
  props: ['object'], // Espero pela propriedade "object"
  template: '
{{ object }}
'
});

new Vue({
    el: '#databinding',
    data: {
        returnedObject : "" // Crio a variável "returnedObject" para o contexto da div com id "databinding"
    }
});

    <input type="text" v-model="returnedObject">
    <vue-component :object="returnedObject" />

O que é esse :object = " "?


Statistical test to choose features correlated with the target variable

Question: Every time I have a binary target variable (like gender for example), and I want to choose the features that are the most informative, I use wilcoxon test, since it is only two groups. I do something like this:
p = apply(gene_expression_matrix,1,FUN=function(x) wilcox.test(x~metadata$Gender)$p.value)

And I can just pick the features according to the p-value.
But now, I have a continuous feature,age, as the target variable, and I want to choose the most informative features (I have aroud 11,000 genes and I want to pick only 10 or 15 at most). I cant use wilcoxon of course. What test can I use to do so?
The predictive features are gene expressions (so they are all continuous, named gene_expression_matrix in the line of code above). Here is a glimpse:
structure(list(EA595454 = c(30.2164549598862, 33.15472982718,
33.1168668509201, 33.4462790910655, 32.81331, 28.4089, 27.96669,
31.75017, 30.2672330352574, 34.2580821880517), EA595500 = c(29.6990111629723,
33.1091846617464, 34.6961953429537, 35.04752533625, 33.23422,
29.52738, 28.5988, 29.94425, 30.2917090730326, 34.1113435705727
), EA595522 = c(30.1226080040122, 32.4635957373198, 35.1005945051642,
34.6336450777183, 33.39675, 25.8611, 29.31165, 30.08221, 31.061397352459,
34.1756092385343), EA595529 = c(32.5465525771926, 32.7013456847345,
31.6635327751442, 32.9358067514439, 33.45026, 28.00596, 25.99824,
30.47032, 31.8664285765267, 33.9110874526159), EA595597 = c(31.4361458857461,
33.4179129770505, 33.9060231563796, 34.5115736452467, 33.0369,
28.02942, 29.68764, 31.39326, 30.6585915260075, 34.0716769346108
), EA595624 = c(30.4736738817874, 30.8289027505712, 34.5761979693053,
34.851895627338, 33.3998, 28.04667, 27.32396, 30.56988, 30.6148908548419,
34.024757317707), EA595632 = c(31.9171369712556, 32.6958971571296,
33.8183033615801, 34.909149630392, 33.44333, 28.02871, 29.80188,
29.95182, 29.9633898390567, 34.2902861791278), EA595635 = c(30.9578243452507,
33.2022811354514, 34.847170680293, 34.6831757047789, 33.16384,
28.12376, 30.82226, 32.04497, 31.064684305675, 34.9001181983966
), EA595647 = c(32.0170360984064, 33.2667207360548, 33.886907956777,
33.3616390602848, 31.82716, 28.13823, 31.00259, 31.70645, 32.1868849430291,
33.4547257007404), EA595654 = c(28.5455213784364, 32.3327903106071,
34.2575222117395, 34.0760753017882, 32.98319, 29.73313, 28.1375,
29.2608, 30.6220152928576, 32.9504526897301)), row.names = c("A1BG",
"ADA", "CDH2", "AKT3", "MED6", "DDTL", "NAALADL1", "SIGLEC14",
"ACOT8", "ABI1"), class = "data.frame")

Note - The number of samples that I want to predict is above 800, and the values in gene_expression_matrix are not normaly distributed (I say this because some tests assume normal distribution).
Answer: Picking features individually by p-value as you have been doing is not generally a good approach, for a couple of reasons. First, the p-values are very dependent on the particular sample at hand. Your choices might not extend well to new data. Second, that approach misses features that might be important when other features are taken into account.
I you consider age to be the continuous outcome variable of interest and you are asking if there is a small number of genes whose expression best predicts age, then a standard principled approach would be LASSO. See Chapter 6 of An Introduction to Statistical Learning. That returns a  limited number of features, whose number is determined by an adjustable penalty factor, that together are associated with outcome. The coefficient estimates for the features are appropriately penalized for your having used the outcome values to choose the features.
There is no requirement that either features or outcomes need to follow a normal distribution in linear models. Some forms of inference are based on an assumption that residuals between observations and model predictions are distributed normally, but inference following feature selection requires extra care. See Chapter 6 of Statistical Learning with Sparsity and the R selectiveInference package.


"Failed to execute 'respondWith' on 'FetchEvent': The event handler is already finished," after Request.clone().json()

Question: In my service worker's 'fetch' listener I want to examine the body of a POST request, and then later do event.respondWith(fetch(event.request)). I clone the request and then convert the clone's body to an object, which works fine, but then I get the "event handler is already finished" error from event.respondWith(fetch(event.request)). I thought if I cloned the request I was free to read the body of the clone without impacting the original request. How can I examine the request body in the 'fetch' listener and then still fetch the request later?
Here's the service worker:
'use strict';

self.addEventListener('fetch', async (event) => {
  try {
    const req_obj = await event.request.clone().json();
    console.log(req_obj);
  } catch (e) {
    console.error(e);
  }

  event.respondWith(fetch(event.request));
});

If I don't clone the request, or if I clone it but I don't call the .json() method of the clone, then everything is fine. Also, I tried new Request(event.request) instead of event.request.clone(), and I tried first using the constructor to copy the request and then calling the .clone() of that copy, but still I get the same error when finally doing event.respondWith(fetch(event.request));
At https://developer.mozilla.org/en-US/docs/Web/API/Request/clone I read some stuff about backpressure on teed streams and such, which I didn't really understand, and then the warning:

Beware when you construct a Request from a stream and then clone it.

Does this mean I can't clone my request and then later fetch it?
Comment: You need to pass a promise to `respondWith`, instead of making the entire event handler async. You can try an async IIFE and do the cloning inside of that; `event.respondWith((async () => { /* do the async stuff... */ })())`
Comment: Thanks @vrugtehagel, that was the fix I needed. If you want to make this an answer I'll accept it.
Answer: The issue is that calling event.respondWith is no longer valid after awaiting the .json() call. To resolve this, pass a promise to event.respondWith that includes the .json() call as well as the fetch:
self.addEventListener('fetch', (event) => {
  event.respondWith((async () => {
    try {
      const req_obj = await event.request.clone().json();
      console.log(req_obj);
    } catch (e) {
      console.error(e);
    }

    return fetch(event.request);
  })());
});


Find the set of values for $c\in \mathbb R$ that allows real solution for $\sqrt{x}=\sqrt{\sqrt{x}+c}$

Question:
Given $\{x,c\}\subset \mathbb R$, $\sqrt{x}=\sqrt{\sqrt{x}+c}~~~~ (1)$.
Find: set of values for $c$ such that $(1)$ has solution in $\mathbb R$.

Question from the Brazilian Math Olympiad 2004. No solution provided.
I'm not sure whether I'm setting the right constraints to find the asked set. Hints and full solutions are appreciated.
My attempt: as an initial observation, the solution must consider at least 2 constraints: $(c_1)$ $x\ge 0;$ and, $(c_2)$ $\sqrt{x}\ge -c$, to avoid negative arguments in the square root.
By assuming ($c_1$) and ($c_2$) hold, and squaring both terms in (1) we get
$$\sqrt{x}=\sqrt{\sqrt{x}+c}\Leftrightarrow x=\sqrt{x}+c\Leftrightarrow x-c=\sqrt{x}.$$
Now considering an addicional constraint $(c_3)$ $x-c\ge 0$, and squaring both terms, we get
$$x-c=\sqrt{x}\Leftrightarrow x^2-2cx+c^2=x \Leftrightarrow x^2-(2c+1)x+c^2=0$$
To solve this last equation, notice that
$$\triangle=(2c+1)^2-4c^2=4c+1$$
Therefore, another constraint, for real roots, is $\triangle\ge 0$ or $(c_4)$ $c\ge -1/4$. And the tentative solution for $x$, before checking constraints, will be given by
$$x=\frac{2c+1\pm\sqrt{4c+1}}{2}.$$
Now the set of values for $c$ that leads to a real solution in $x$, will be the set resulting from the intersection of 4 conditions:
$$\left\{
\begin{array}{l}
(c_1)~~x\ge 0 \Leftrightarrow \frac{2c+1\pm\sqrt{4c+1}}{2}\ge 0\Leftrightarrow 2c+1\ge\pm\sqrt{4c+1}\\
(c_2)~~\sqrt{x}\ge -c \Leftrightarrow \sqrt{\frac{2c+1\pm\sqrt{4c+1}}{2}}\ge -c\\
(c_3)~~x\ge c\Leftrightarrow \frac{2c+1\pm\sqrt{4c+1}}{2}\ge c\Leftrightarrow 1 \ge \pm\sqrt{4c+1}\Leftrightarrow 1 \ge \sqrt{4c+1}\Leftrightarrow c \le 0\\
(c_4)~~c\ge -1/4\\
\end{array}
\right.
$$
Question: (a) is this last step the right set of conditions to be intersected to give the asked set for $c$? (b) how to solve for the intersection of the conditions?
Hints and full answers are appreciated. Maybe I'm just complicating something that is a lot easier.
Comment: You can simplify $c_1$ since $2c+1\ge \sqrt{4c+1}$. Also you got $c_3$ wrong, it should read $x\ge c$. Then I think you can differentiate the cases $c>0$ and $c\le 0$; $c>0$ can simplify quite a bit of conditions
Comment: It seems you need conditions on $c$. So $c_4$ is the information you are looking for.
Comment: @user160738 thanks for the hint...you're right... just fixed $c_3$.
Answer: There is no problem ignoring the external square roots, as both are positive values.
Now
$$(\sqrt x)^2-\sqrt x-c=0$$
has real roots only when
$$1+4c\ge0,$$ and these roots are
$$\sqrt x=\frac{1\pm\sqrt{1+4c}}{2},$$ one of which is necessarily not smaller than $\dfrac12$.
With
$$c\ge-\frac14$$
both $x$ and $\sqrt x+c$ are guaranteed to be non-negative.
Comment: Why here we don't need another constraint, $c\le 0$, otherwise $\sqrt{x}< 0$... that doesn't make sense. Check that $\sqrt{x}< 0$,  $\forall c> 0$ in the negative sign. Am I missing something? Ahh...  this happens only on the negative sign solution.... no problem in the positive... Ok, i think i understand now...
Comment: By definition $\sqrt z\ge0$.
Answer: Just a slightly different point of view, which may be useful in a different situation. Since it is easier to express $c$ in terms of $x$ rather than the other way around, you might make this argument:
Let $f:\mathbb{R}_{\geq0} \to \mathbb{R}$ be given by $f(x) = x - \sqrt{x}$. Then
$$\exists x\in \mathbb{R} (x\geq 0 \land c = x - \sqrt{x} = f(x)) \Leftrightarrow c \in {\rm ran} (f)$$
(there is no need for any other conditions because the domain of $f$ is exactly $x \geq 0$). Now here the substitution $\sqrt{x} = t$ would make finding the range more convenient. I will do it by noting that $g:\sqrt{x}\mapsto x$, with domain and codomain $\mathbb{R}_{\geq0}$, is surjective and so ${\rm ran}(g) = {\rm dom}(f)$; not only can the two functions be composed, but also ${\rm ran} (f\circ g) = {\rm ran} (f)$.
So instead of studying the solutions of an equation for some (unspecified) $c$, you could examine the function $f\circ g: \mathbb{R}_{\geq0} \to \mathbb{R}$, given by $f(g(t)) = t^2 - t$. (All the talk about domains and ranges in the previous paragraph was to demonstrate that no additional constraints are needed.) It's a quadratic restricted to $[0, +\infty)$ whose vertex is easily found to be $(1/2, -1/4)$ so the range is $[-1/4, +\infty)$.
This isn't really any different from finding the roots (parametrically) and checking/requiring that at least one be non-negative (as Yves does). But if it had been something more complicated than a quadratic, it is usually easier to find the range than to solve the corresponding equation.
EDIT: Note that when solving equations with radicals on both sides, $\sqrt{f(x)} = \sqrt{g(x)}$, it is redundant to add both $f(x) \geq 0$ and $g(x) \geq 0$. For any solution of the squared equation, $f(x) = g(x)$ they are equivalent. In your approach, $(c_1) \Leftrightarrow (c_2)$. And later on, the second squaring produces $x = (x-c)^2$ which automatically guarantees $(c_1)$. So only $(c_3)$ and $(c_4)$ are left, and it is not hard to check that the latter implies the former, since it is enough for one of the roots to meet it (I think you had already figured that out).


Multiple authentication backends in lighttpd

Question: I have some users in a LDAP directory and I'd like to have another user in a plain or htpasswd file that can login although the connection with the LDAP server is not available.
Is it possible to have multiple authentication backends for the same host in lighttpd?
Answer: Unfortunately, no; the auth.backend configuration as written only supports being configured for the exact strings of the 4 backend types; there doesn't seem to be any mechanism for fallback to another method.
if (!buffer_is_empty(s->auth_backend_conf)) {
    if (buffer_is_equal_string(s->auth_backend_conf, CONST_STR_LEN("htpasswd"))) {
        s->auth_backend = AUTH_BACKEND_HTPASSWD;
    } else if (buffer_is_equal_string(s->auth_backend_conf, CONST_STR_LEN("htdigest"))) {
        s->auth_backend = AUTH_BACKEND_HTDIGEST;
    } else if (buffer_is_equal_string(s->auth_backend_conf, CONST_STR_LEN("plain"))) {
        s->auth_backend = AUTH_BACKEND_PLAIN;
    } else if (buffer_is_equal_string(s->auth_backend_conf, CONST_STR_LEN("ldap"))) {
        s->auth_backend = AUTH_BACKEND_LDAP;
    } else {
        log_error_write(srv, __FILE__, __LINE__, "sb", "auth.backend not supported:", s->auth_backend_conf);

        return HANDLER_ERROR;
    }
}

Comment: Ok, that was the answer I was afraid of :\


Can synthetic division be used to divide $8x^{5}-4x^{4}+6x^{3}-11x^{2}-2x+3$ by $\left(x^{2}-\frac{1}{4}\right)$?

Question: This is a peculiar case because a difference of two squares is a factor so if I perform synthetic division with each factor "separately" ie $\left(x-\frac{1}{2}\right)\left(x+\frac{1}{2}\right)$, then I get two distinct polynomials. Now I am not sure what to do with the two to get the final answer. Do I add, subtract, multiply, divide them?
Comment: Why don't you just divide by the quadratic in the first place?
Comment: What Fenris commented.  Also, **first** clear the $(1/4)$ fraction by multiplying both the dividend and the divisor by $4$.  This will make it easier on you.
Comment: If you *really* want to use synthetic division, there is a method for dividing by a general quadratic divisor on [Wikipedia](https://en.wikipedia.org/wiki/Synthetic_division#For_non-monic_divisors). If you're not bothered, you can always divide by $x - 1/2$ and then by $x + 1/2$.
Comment: To use regular synthetic division, Divide by one term first, then divide that divisor with the second term.
Comment: Notice that $f(1) = 0$, therefore $x - 1$ is also a factor for this particular problem.
Comment: @Fenris yes but you cannot synthetic divide with a quadratic (at least without adjustments)
Answer: You simply may 'compose' the two synthetic divisions:
$$\begin{array}{*7{r}}
&8&-4&6&-11&-2&3 \\\times\tfrac12&&4&0&3&-4&-3\\\hline
&\color{red}8&\color{red}0&\color{red}6&\color{red}{-8}&\color{red}{-6}&\color{cyan}0 \\
\times-\tfrac12&&-4 &2&-4&6 \\\hline
& \color{red}8 &\color{red}{-4}&\color{red}8&\color{red}{-12}& \color{cyan}0
\end{array},$$
whence the quotient $\:8x^3-4x^2+8x-12$.
Comment: *Elève Bernard ! Au tableau !* So long time I did not see such a thing ! Even for me, playing with the colors explains very well. Cheers and take care :-)
Comment: Il faut dire que j'ai pas mal pratiqué la méthode de Horner pour l'évaluation des polynômes.
Comment: Merci! I don't know why I didn't think of this
Comment: Also, What is Horner's method for polynomials? When I search it up only synthetic division comes up, and the thing about nested x's
Comment: @user71207: It is the method used to minimise the number of operations in evaluating a polynomial, by using nested parentheses, e.g. $ax^3+bx^2+cx+d=\bigl((ax+b)x+c\bigr)x+d$.
Answer: Let $f(x)$ be the given polynomial. Multiplying top and bottom by $4$, we get:
$$\frac{32x^{5}-16x^{4}+24x^{3}-44x^{2}-8x+12}{4x^2-1}$$
Now $f(1/2) = f(-1/2) = 0$, so we have no remainder, which means the quotient is a cubic polynomial, $ax^3+bx^2+cx+d$. Therefore:
$$(ax^3+bx^2+cx+d)(4x^2 - 1) = 32x^{5}-16x^{4}+24x^{3}-44x^{2}-8x+12$$
Comparing the $x^5$ term and the constant term on the RHS, we have that $4a = 32, a = 8$, and $-d = 12, d= -12$, as there is only one way to make these terms.
Now comparing the $x^4$ term, $a \cdot 0 + b \cdot 4 = -16$, so $b = -4$. With the $x$ term, $c \cdot -1 + d \cdot 0 = -8$, thus $c = 8$.
Therefore the quotient is $8x^3-4x^2+8x-12$.
Comment: Thanks for this! A different approah
Comment: No problem, not at all!


Proof of Sum of inverse squares Equaling $\pi^2/6$

Question: I'm a 15 year old interested in higher level mathematics. I've recently been studying Complex Analysis from notes of my math teacher from his college math classes. I've understood everything up until the very last 2 pages, when he provides part of a proof that the sum of $1/(n^2)$ from $n=1\to \infty$ is equal to $\pi^2/6$ using residues and the Residue Theorem.
He has written the Residues of the function
$$
f(z) = \frac{\pi \cot(\pi z)}{z^2}
$$
But I want to understand how he got them, so that I feel that I fully understand it myself. I got all the residues at $z = 0, 1, -1, 2, -2, 3, -3, \ldots$ but what I don't understand is this : Res at the pole $z=0$ is $\pi^2/3$. Why? Please explain how he got this to me. I've tried working it out using several methods but can not figure it out.
Thanks.
Comment: write the first few terms of the Taylor series for $z f(z)$, divide by $z^3$, the residue $Res(f(z),0)$ will be the coef of $z^{-1}$
Comment: okay hold on and I'll try that.
Comment: And see [WA](https://www.wolframalpha.com/input/?i=Res%5BPi*+cotan(Pi*z)%2Fz%5E2,%7Bz,0%7D%5D) and [this](https://www.wolframalpha.com/input/?i=Series%5BPi*+cotan(Pi*z)%2Fz%5E2,%7Bz,0,10%7D%5D)
Comment: see here i hope this will help you http://www.cs.nthu.edu.tw/~wkhon/random/tutorial/pi-squared-over-six.pdf
Comment: Okay thanks guys. I do know how to do this, and I did try what was said abut expanding the Taylor series and dividing by z^3. (it worked). I think I just overlooked something the first time I looked at it, because I'm confident I tried it before.
Comment: In case you're interested in other methods too, see this question: http://math.stackexchange.com/questions/8337/different-methods-to-compute-sum-limits-k-1-infty-frac1k2
Answer: I will outline Euler's second proof of the Basel problem. If we start with the identity:
$$ \frac{\sin(\pi x)}{\pi x}=\prod_{n\geq 1}\left(1-\frac{x^2}{ n^2}\right) \tag{1}$$
and consider $-\frac{d}{dx}\log(\cdot)$ of both sides, we get:
$$ \frac{1}{x}-\pi\cot(\pi x) = \sum_{n\geq 1}\frac{2x}{n^2-x^2}\tag{2}$$
then rearranging and expanding the terms of the sum in the RHS as geometric series,
$$\frac{1-\pi x\cot(\pi x)}{2}=\sum_{n\geq 1}\frac{x^2}{n^2-x^2}=\sum_{n\geq 1}\sum_{m\geq 1}\frac{x^{2m}}{n^{2m}}=\sum_{m\geq 1}\zeta(2m)\,x^{2m}\tag{3} $$
so the Taylor series of $g(x)=\frac{1-\pi x\cot(\pi x)}{2}$ in the origin gives us the values of $\zeta(2),\zeta(4),\zeta(6),\ldots$
In particular,
$$\zeta(2m) = (2m)!\cdot g^{(2m)}(0). \tag{4}$$
Comment: Thanks. I find this stuff really fascinating so I really appreciate that you and everyone else on here are so willing to help. And that does make sense. Thanks.
Comment: The first identity requires Weierstrass Factorisation Theorem which is deep...
Comment: @HenryW.: it is a way, but not the only one. For real values of $x$, $(1)$ can be proved through Chebyshev polynomials of the second kind. And for sure, $(1)$ was known to Euler way before Weierstrass and Mittag-Leffler machinery.
Answer: For a pole of order $n$, the residue can be evaluated SEE THIS using the formula

$$\text{Res}(f,z=z_0)=\frac{1}{(n-1)!}\lim_{z\to z_0}\frac{d^{(n-1)}}{dz^{(n-1)}}\left((z-z_0)^nf(z)\right) \tag 1$$

Let $f(z)=\frac{\pi \cot(\pi z)}{z^2}$.  Note that $f$ has a pole of order $3$ at $z=0$.  Using $(1)$ with $z_0=0$ and $n=3$, the residue of $f$ at $0$ is given by
$$\begin{align}
\text{Res}\left(\frac{\pi \cot(\pi z)}{z^2},z=0\right)&=\frac12\lim_{z\to 0}\frac{d^2((\pi z) \cot(\pi z))}{dz^2}\\\\
&=\pi^2\lim_{z\to 0}(\pi z \cot(\pi z)\csc^2(\pi z)-\csc^2(\pi z))\tag 2\\\\
&=\bbox[5px,border:2px solid #C0A000]{-\pi^2/3 }\tag 3
\end{align}$$

NOTE:
In going from $(2)$ to $(3)$, we used
$$\pi z\cot(\pi z)=\frac{1-\frac12 (\pi z)^2+O(z^4)}{ (1-\frac16 \pi^2 z^2+O(z^4))}=1-\frac13 \pi ^2z^2+O(z^4)$$
and
$$\csc^2(\pi z)=\frac{1}{\pi^2 z^2}\left(1+O(z^2)\right)$$

SUPPLEMENTAL DEVELOPMENT:
In THIS ANSWER, I evaluated the series $\sum_{n=1}^\infty \frac1{n^2}$ using real analysis only.  In that development, we used $$\sum_{n=1}^\infty \frac1{n^2}=\int_0^1\int_0^1 \frac{1}{1-xy}\,dx\,dy$$which can be shown by expanding the term $\frac1{1-xy}$ in a geometric series, interchanging the sum and the integrals, and carrying out the trivial integrals $\int_0^1 x^n\,dx$ and $\int_0^1 y^n \,dy$.
Answer: $$f(z)=\frac{\pi \cot(\pi z)}{z^2}=\frac{\pi \cos(\pi z)}{z^2 \sin(\pi z)}$$
$z=0$ is a pole of order 3 (because $\sin(\pi z)$ has a simple zero at $z=0$).
Therefore
$$res(f,0)=\frac{1}{2!} \lim_{z \to 0} \left(z^3\frac{\pi \cos(\pi z)}{z^2 \sin(\pi z)} \right)''=\frac{\pi }{2!} \lim_{z \to 0} \left(z \cot(\pi z) \right)'' \\=\frac{\pi }{2!} \lim_{z \to 0} 2 \pi^2 z \cot(\pi z)\csc^2(\pi z)-2 \pi\csc^2(\pi z) \\
=\pi^2 \lim_{z \to 0}  \frac{ \pi z\cos(\pi z)-  \sin(\pi z)}{\sin^3(\pi z)}\\
=\pi^2 \lim_{z \to 0}  \frac{ -\frac{\pi ^3 z^3}{3}+\frac{\pi ^5 z^5}{30}+...}{\pi ^3 z^3-\frac{\pi ^5 z^5}{2}+...}=-\frac{\pi^2}{3}\\$$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

Clearly,
  $\ds{{\pi\cot\pars{\pi z} \over z^{2}} \sim {1 \over z^{3}}}$ as $\ds{z \to 0}$
  because
  $\ds{\cot\pars{\pi z} \sim {1 \over \pi}\,{1 \over z}}$ as $\ds{z \to 0}$.

Then, I write
\begin{equation}
{\pi\cot\pars{\pi z} \over z^{2}} \sim
{b_{-3} \over z^{3}} + {b_{-2} \over z^{2}} + {\color{#f00}{b_{-1}} \over z}
\label{1}\tag{1}
\end{equation}
I'm interested in the $\ds{\color{#f00}{b_{-1}}}$ $value$. It's convenient to rewrite \eqref{1} as
\begin{equation}
\pi \sim
\tan\pars{\pi z}\pars{{b_{-3} \over z} + b_{-2} + \color{#f00}{b_{-1}}\,z}
\label{2}\tag{2}
\end{equation}
Note that
$\ds{\tan\pars{\pi z} = \pi z - {\pi^{3} \over 3}\,z^{3} +
{2\pi^{5} \over 15}\,z^{5} + \mrm{O}\pars{z^{7}}}$. \eqref{2} becomes
\begin{equation}
\pi \sim
\pars{\pi z - {\pi^{3} \over 3}\,z^{3}}\pars{{b_{-3} \over z} + b_{-2} + \color{#f00}{b_{-1}}\,z} \equiv \,\mc{F}\pars{z}
\label{3}\tag{3}
\end{equation}
Then, with expression \eqref{3}:
\begin{align}
\pi & = \bracks{z^{0}}\,\mc{F}\pars{z} = \pi b_{-3}\implies
\bbx{\ds{b_{-3} = 1}}
\\
0 & = \bracks{z}\,\mc{F}\pars{z} = \pi b_{-2}\,\,\,\implies b_{-2} = 0
\\
0 & = \bracks{z^{2}}\,\mc{F}\pars{z} =
\pi\color{#f00}{b_{-1}} - {\pi^{3} \over 3}\,b_{-3}\,\,\,\implies
\bbx{\ds{\color{#f00}{b_{-1}} = {\pi^{2} \over 3}\,b_{-3} =
\color{#f00}{\pi^{2} \over 3}}}
\end{align}


rolling a single die ten times

Question: I have the following problem on a homework assignment for my Probability theory course:
You roll a single six sided die ten times. What is the probability that you roll four 1's, three 2's, and three 3's?
I was hoping somebody could check my idea since I haven't done this sort of problem in a while.
So my idea is to count the total number of ways you could get this outcome. My way of counting it is to first count the number of ways the four 1's could show up on the ten rolls. So we get ${10 \choose 4}$ ways this could happen. Now of the remaining 6 rolls I want to count the ways you could get three 2's, which is ${6 \choose 3}$. Now only three rolls remain so they have to be the three 3's.
So what I'm getting is that there are ${10 \choose 4}{6 \choose 3}$ ways to get such an outcome.
What I'm not sure of is if the probability would then be:
$$
\frac{{10 \choose 4}{6 \choose 3}}{6^{10}},
$$
or if the probability should be,
$$
\frac{{10 \choose 4}{6 \choose 3}3^4 2^3 1^3}{6^{10}}.
$$
It's also possible that I could be completely wrong.
Any help is greatly appreciated.
Comment: I don't see what you mean by "four of them have 3 options, three of them have only 2 options, and then the remaining three have only one option.".  Four of them should be $1$'s, three of them $2$'s and then three of them $3$'s, right? Then again, I'm very sleepy...
Comment: Yeah, I think you are right. I think it should be the first option listed in the posting. In my reasoning for the second option I don't ensure the outcome I desire. I did a couple examples with a smaller number of die to confirm it for myself. Thanks for the help!
Comment: This is simply an example of a multinomial distribution: https://en.wikipedia.org/wiki/Multinomial_distribution
Comment: You're on the right track. What are your arguments for either of the last two expressions? Why should the factor $3^42^31^3$ be there (or not)?
Comment: Your first method is correct.
Comment: For the latter, I thought of it like for the ten slots four of them have 3 options, three of them have only 2 options, and then the remaining three have only one option. I then multiplied this by the number of ways to choose the 4, then multiplied by the number of ways to choose one of the three. Then to get the probability I divided by the total number of outcomes $6^{10}$.
Comment: That seems OK to me.
Answer: A little logic and computation will help you decide between your answers:
(1) Your answer has to be less than $(1/2)^{10} = 0.0009765625$.
That would be the probability all 10 rolls showed 3 or fewer spots.
(2) Your first answer computes to 0.00006946032, which $is$ smaller
than the answer in 1.
(3) Your second answer computes to  0.04501029, which is larger
than the answer in (1), so it can't be right.
(4) Finally, the multinomial formula in Wikipedia, as per @Brent's Comment is
$$\frac{10!}{4!\times 3! \times 3!}\left(\frac{1}{6}\right)^{10},$$
which is easily seen to be the same as (2).
[I suppose you've got it by now, but I wanted to clean this up
in case anyone looks at it later.]

rolling a single die ten times


What instruments are asked for in this original Sousa score?

Question: This answer by @NReilingh inspired me to trawl the web looking at Sousa music. Feeling that the clarity of orchestration contributes a significant amount to this music, I was pleased to find this original manuscript score of The Stars and Stripes Forever at IMSLP. Can anyone help me decipher what instruments Sousa has scored for (at the left of the first page of manuscript)?
Sure, he probably arranged this for other instrumentations; I'm sure his publisher and a great number of other arrangers have reorchestrated it too. But, I'm keen to find out the instrumentation Sousa originally asked for. Here's what I have so far:
Db Piccolo; Oboes; Bassoons; Eb Clarinet; Bb Clarinets; Alto Sax; Tenor Sax (?); ??; ??; ??; Cornets (?); Horns in Eb; not quite sure after this, although presumably Baritone, Trombones, Tuba and Percussion (?).
Comment: Yeah, that makes sense key-sig-wise, too. Having looked for a bit longer, I reckon it's then: 3 Tbns; Euphonium; couple of Tubas… If nobody else posts soon, I'll probably stick an answer up myself later… Would rather get an authoritative answer, from somebody who knows more about these kind of bands than me, though!
Comment: Based on the key signatures, you're right for all the woodwinds.  After Tenor Sax comes Baritone Sax.  Trumpets come before Cornets.
Comment: Take a peek at the "condensed score" on the same imslp page.  Sousa may have written a score for the band he had at that particular time. Re-scoring to match a specific group happens all the time.  I had a (college) conductor who added parts for weirdass stuff like contrabass clarinet :-)
Answer: With a little help from @Carl Witthoft (of course Baritone Sax would be an Eb bass clef instrument following Tenor Sax - doh!), I think I have a pretty good idea of the scoring in this manuscript:

Db Piccolo
Oboes
Bassoons
Eb Clarinet
Bb Clarinets (2 staves)
Alto Sax
Tenor Sax
Baritone Sax
Bb Trumpets (2 staves)
Bb Cornets
Eb Horns (2 staves)
Trombones
Euphonium
Tubas
Percussion

Apologies to anyone who thinks this question (and answer) are a little too specific, I genuinely wanted some help with working out what these instruments were! Hopefully the post has some value for future readers interested in interpretation of original manuscript scores, particularly with regard to instrumentation of this kind of band.
PLEASE DO POST AN ANSWER IF THIS SCORING IS WRONG...


render() and theme() fields

Question: I would like to assign some content from a node, lets say the body field, into a region. so I cannot theme this content in my node.tpl.php
In the template_process_page(&$vars) i can easily set $page['my_region'] = HTML.
with $vars['node']->body i can access to my body field dada. from there I would like to use the regular theme function to render the body field. to use theme('field',$variables) or render($variables) I need to bring the body-array from:
Array
(
    [und] => Array
        (
            [0] => Array
                (
                    [value] => TEXT
                    [summary] =>
                    [format] => full_html
                    [safe_value] =>  TEXT
                    [safe_summary] =>
                )

        )

)
to sth like:
Array
(
    [#theme] => field
    [#weight] => 1
    [#title] => Body
    [#access] => 1
    [#label_display] => hidden
    [#view_mode] => full
    [#language] => und
    [#field_name] => body
    [#field_type] => text_with_summary
    [#field_translatable] => 0
    [#entity_type] => node
    [#bundle] => article
    [#object] => stdClass Object
        (...)
    [#items] => Array
        (
            [0] => Array
                (
                    [value] => TEXT
                    [summary] =>
                    [format] => full_html
                    [safe_value] => TEXT
                    [safe_summary] =>
                )
        )
    [#formatter] => text_default
    [0] => Array
        (
            [#markup] => TEXT
        )
)

But I don't know how exactly.  how can a generate my field with the second array-achitecture. if possible without more db-queries.
thank you for help!
Answer: You are looking for field_attach_view
What you would need to do, with your loaded node is something like this:
$fields = field_attach_view('node', $node, 'full');
$body = $fields['field_body'];

Comment: perfect!!! thank you very much. i spend the whole day reading the api doc.

render() and theme() fields


Why the binary division of the two has the same quotent

Question: I am trying to divide 110000 with 1101 in binary (long division). I use XOR each time. The divisions above should have quotent 100. However I might must misunderstood something. Could please anyone help me with that?
basically I am doing the following
     ---011
1101/110000
     0000
     11000
      11010
       1101
       ----
       0111

Comment: In the 5th line, you subtracted `1101` from `11000` and got `110`.  That's wrong.  You should get `1011`.  I don't understand what you mean by XOR; you shouldn't be using XOR anywhere.  You should be using the same algorithm you use for long division of decimal numbers, which similarly does not use XOR anywhere.
Answer: 110000 : 1101 = 11 rem 1001
 1101
-----
 10110
  1101
 -----
  1001

Comment: Thank you @Hagen! very nice answer! thanks. However, I am trying basically to solve exersice 20 from chapter 2 from this book sahyadri.edu.in/SMCA/students_guide/3semnotes/network/… . However, the book says that I have to prove that the quotent is 100. Is the book wrong? Or did I understood something wrong?
Answer: OP has clarified his question to explain that he is doing long division of polynomials over $\Bbb Z_2$; here 1101 represents $x^3+x^2 +1$ and the coefficients are elements of $\Bbb Z_2$ where $1\oplus1=0$.
     ------
1101/110000

In ordinary division, $1101>1100$, so we would have to start dividing one place to the right of 1100.  But
in polynomial long division we have $\deg(1101)\le \deg(1100)$, so
1101 does divide into 1100, because $$x^3+x^2 = (x^3+x^2+1) \cdot 1 \oplus 1$$ so the quotient is 1 and the remainder is 1:
        1
     ------
1101/110000
     1101

        1
     ------
1101/110000
     1101
     ----
        1       (subtract mod 2)

Here "subtract mod 2" is the same operation as "XOR". It is also the same as addition mod 2, which I am writing as $\oplus$.
        1
     ------
1101/110000
     1101 \
     ----- |  bring down next digit
        10<'

Now $\deg(1101) = 3$ but $\deg(10) = 1$, so we cannot divide, and we  bring down the next digit:
        10
     ------
1101/110000
     1101  \
     ------ |  bring down next digit
        100<'

Again we can't divide because $\deg(1101) > \deg(100)$.
        100
     ------
1101/110000
     1101
     ------
        100

That was the last digit, so we're done; the quotient (at the top) is 100 and the remainder (at the bottom) is 100.  Or put in terms of the original polynomials, we should have
$$x^5 + x^4 = (x^3+x^2 + 1)\cdot x^2 \oplus x^2$$
where the first $x^2$ is the quotient and the second $x^2$ is the remainder.
You should check that this equality holds. (It does.) If not, we got the wrong answer.
Comment: Wow!!! very nice answer! thanks. However, I am trying basically to solve exersice 20 from chapter 2 from this book http://www.sahyadri.edu.in/SMCA/students_guide/3semnotes/network/Computer_Networks_Peterson__A_Systems_Approach__Fourth_Edition.pdf . However, the book says that I have to prove that the quotent is 100. Is the book wrong? Or did I understood something wrong?
Comment: You asked wrong! The book is doing *polynomial* long division, not binary long division, and you never mentioned this.  In polynomial long division, `1101` represents the polynomial $x^3+x^2+1$, and the addition is not the regular addition of binary numbers, in which `1101+1101 = 11010`, but the addition of polynomials mod 2, in which `1101+1101 = 0`.  I will try to rewrite my answer to take this into account.
Comment: Thanks. This makes it much more clear for me. Howerver, you mention that "In ordinary division, 1101<1100". Why 1101<1100? Isn't the same with 13<12 ?
Comment: I wrote $<$ when I meant $>$.
Comment: thanks again. I am sorry for interrupting you again. However, I did not understood why you said that deg(1101)≤deg(1100). Isn't both of them 3? That means also that deg(1100)≤deg(1101). In addition why below you made a XOR with 1?
Comment: Yes, both have degree 3, and $3\le 3$ is true.  `1101` divides into `1100`, but it leaves a remainder of `1`.  In general if $\deg(d)\le\deg(n)$ then you can divide $n\div d$, and you get a quotient $q$ and remainder $r$ such that $n = dq\oplus r$ where $\deg(r) < \deg(d)$.  Here we have $d=1101$ and $n=1100$, and we get $q=1$ and $r=1$.
Comment: Thanks again! You have been extremely helpful!


Specify a node type (bundle) in entity reference field

Question: I have a custom entity type which has an entity reference field.
<code>   $fields['referenced_article'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Article'))
  ->setDescription(t('The associated article.'))
  ->setSetting('target_type', 'node')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE);
</code>
This field returns now the nodes of all the node types when finding a match. How can I specify a node type? (I only want to show the nodes of type "article")
Do I need to use a specific setting for selecting content only one node type?
Comment: How can I change this setting per bundle?
Comment: answering myself: https://github.com/barraponto/attendance/blob/development/src/Form/AttendanceTypeForm.php#L101-L109
Answer: Try adding
<code>->setSetting('handler_settings', ['target_bundles' => ['article' => 'article']]),
</code>
Source
Comment: @hugronaphor you might have to check that you don't have conflicting `setSetting` or `setSettings` calls in the field definition. If you do, only the last one wins.
Comment: I'm on Drupal 8.5 and by adding this I get no results at all :(


Is there a continuous function $\theta: S^1 \to \mathbb{R}$ such that $e^{i \theta(x)} = x$ for each $x \in S^1$?

Question: I have stumbled accross this question while working out the details of why Example 1 of this document https://web.ma.utexas.edu/users/vandyke/notes/256a_notes/lecture21.pdf is not a sheaf. It seems to me that such a function cannot exist, for then it would be possible to define an angle function. But I couldn't find a rigorous proof of it.
Answer: If the composition
$$
S^1 \stackrel{\theta}{\to} \mathbb{R} \stackrel{\exp(i\cdot\_\ )}{\longrightarrow} S^1
$$
were the identity map, then it would induce the identity map on $\pi_1$, but $\pi_1(\mathbb{R})$ is trivial whereas $\pi_1(S^1)$ is not.
Comment: While accurate, slightly overkill for a question which is really the intermediate value theorem. There is no one-to-one function $S^1\to \mathbb R.$
Answer: For such a function to exist, the function must be one-to-one. That is $\theta(x)=\theta(y)$ only when $x=y.$
More generally, there is no one-to-one continuous function $\theta:S^1\to\mathbb R.$
The basic idea:

There are two directions to go from $1$ to $-1$ on the circle. $\theta(x)$ along each direction must pass through $\frac{\theta(1)+\theta(-1)}2.$ But that means their are at least two solutions to $\theta(x)=\frac{\theta(1)+\theta(-1)}2,$ so no $\theta$ can be one-to-one.

In more detail.
Assume a one-to-one $\theta$ exists.
Now, let $f_1,f_2:[0,\pi]\to S^1$ be defined as:
$$f_1(x)=e^{ix},f_2(x)=e^{-ix}$$
Then for $i=1,2,$ $f_i(0)=1, f_i(\pi)=-1.$
Then, for $i=1,2,$ define $g_i(x)=\theta(f_i(x)),$ which are continuous functions $[0,\pi]\to\mathbb R,$ with $g_i(0)=\theta(1),$ $g_i(\pi)=\theta(-1).$
Since $\theta$ is one-to-one, $\theta(1)\neq \theta(-1).$
In particular, by the intermediate value theorem, there is an $x_1\in(0,\pi)$ such that $g_1(x_1)=\frac{\theta(1)+\theta(-1)}2.$
Similarly, there is an $x_2\in(0,\pi)$ such that $g_2( x_2)=\frac{\theta(1)+\theta(-1)}2.$
So this gives us $$\theta(f_1(x_1))=g_1(x_1)=g_2(x_2)=\theta(f_2(x_2))$$
Since $\theta$ is one-to-one, then $f_1(x_1)=f_2(x_2).$ But this isn't possible for $x_1,x_2\in(0,\pi),$ because then the imaginary part of $f_1(x_1)$ is positive, while for $f_2(x_2)$ it is negative.
Comment: beatiful answer!


Comparing "Age of emergence" or "Age of onset" in a statistical model

Question: Say I have a set of participants and I follow them for a year to see when they first produce two behaviors, A and B. I'm interested in whether there is a relationship between the onset of these two behaviours. My overall question is: is it appropriate to conduct a regression analysis predicted the age-of-onset of behaviour B using the age-of-onset of behaviour A? Or to run a correlation between ages of onset (A) and ages of onset (B)?
I'm aware that generally, if you're interested in the appearance of some event, it is best practice to use a Cox regression to deal with censoring issues (since the event may not occur). However, there are a few reasons I don't want to here (just bare with me on this!):

I know every age of onset for every participant.
I'm not interested in the time-to-event per se, just whether the onset of behaviour A is related to the onset of behavior B- specifically, do those who tend to produce behaviour A earlier tend to produce behaviour B earlier?

I suppose I could have time-varying covariates here for each participant in a Cox regression. But surely just running a simple regression with ages-of-onset is simpler and still addresses my main question?
Is there any reason this is problematic, other than generally for a study you wouldn't know every age of onset? I'm unsure as I can't find any discussion of this anywhere online. Conceptually I can't see any issues, but I would appreciate guidance on this.
Answer: Survival modeling has advantages when time-to-event from some well defined starting time is of interest, particularly when you have censored data. You don't seem to have censored data with respect to "age of onset" of either behavior ("I know every age of onset for every participant") so the answer depends on the nature of your data with respect to event timing.
If the onset of Behavior A always precedes that of Behavior B, a simple survival model (Cox or otherwise) could use onset of Behavior A as the time = 0 reference for each individual, include age of onset of Behavior A as a covariate (potentially among other covariates), and determine whether the interval between ages-of-onsets is associated with "age of onset" of Behavior A. Those results could then be interpreted in the way you desire. For example, if there is no association between age-of-onset of Behavior A and that interval to onset of Behavior B, you then could infer that later age-at-onset of Behavior A means later age-at-onset of Behavior B.
If the behaviors can start in different orders, you could consider a a multi-state model, with each behavior onset modeled as a separate type of event and birth date (or other fixed age) as time = 0. That could provide interesting ways to evaluate whether the prior occurrence of one event alters the time course to the other event. See the vignettes for the R survival package as an introduction to ways to model different types of events in a single model. But if all you are interested in is the association between the two ages-at-events, that approach might be overkill.
Think carefully about precisely what hypothesis you wish to test, and choose accordingly.
Comment: Thank you for your comment, I appreciate it. Your first suggestion is a nice solution that I'd not thought of. And I was not aware of multi-state models, so thank you for mentioning those.

To clarify- are you suggesting that the kind of data I'm talking about should only be analysed using some kind of survival modelling? I.e., a linear regression/correlation should be avoided? I ask because really a simple association is what I'm primarily interested in. And I'm also wondering what the advantages of survival modelling are beyond censoring (in reference to the start of your comment). Thanks!
Comment: @Questioner4857 the choice is up to you, based on what hypothesis you wish to test. If the two Behaviors can start in either order with neither one thought to affect the initiation of the other, then (absent censoring) a simple correlation might be OK. Regression involves treating one as a predictor and the other as an outcome, which might not be appropriate depending on your situation. Survival modeling provides potentially richer analysis of timings and multi-state situations, but that might not be required to test the specific hypothesis you have in mind. Choose based on your needs.
Comment: Excellent, thank you, I'm really grateful for your explanations!


Why Olympics don't follow exact time to conduct a game?

Question: According to the Olympic schedule, the Women's Badminton semifinal between Nozomi and Sindhi should occur at 1700 IST. However, this game seems to have been held hours later, at 2030 IST.
Why would a game in the Olympics not be held at the time it is scheduled for?
Comment: Welcome to SE.Sport. Could you please add more info? Have you checked it on official website?
Comment: Please let us know the name of your country and broadcasting company, There is a possibility that the broadcasting company in your country was so poor that it didn't pay the premium for a live broadcast.
Comment: Vote to leave open. The question is clear if one bothers to try: *the game was scheduled for time X, but apparently played at time Z. Why would the game be played out of schedule?* to which Ale has already given an (insufficiently evidenced, but still potentially viable) answer. The fact that OP might simply be wrong in fact, doesn't make it an invalid question.
Answer: For all major badminton tournaments, not just the Olympics, they only use a limited number of courts for major games (e.g semifinals and finals). As a result the scheduling works in a way for example on one day, on a specific court:

Women's Doubles Semi Final #1 4pm
Men's Doubles Semi Final #1 5pm
Women's Singles Semi Final #1 6pm
Men's Singles Semi Final #1 7pm
Mixed Doubles Semi Final #1 8pm

Here apart from the first match, Women's Doubles Semi Final #1, all other times are estimates, and the matches may begin earlier or later than anticipated, accordingly with when the previous match finishes.
This is known as the "Order of Play" and each match will be numbered. Often the time estimates may not even be shown (apart for the first match), just the order in which the matches will proceed.
This is the reason why the game you wanted to watch did not quite appear at the scheduled time.
Answer: On official page the starting time is 16:00 BRT (Brasilia Time).
Maybe abroad there is possible that media scheduling move the streaming because of internal reasons
Comment: I read your comment, but what time is it in India when it is 16:00 BRT? The OP says the semifinal **should occur at 1700 IST** and it is 8:30 am BRT. Don't you think something is wrong with the question?


Magento Fancybox

Question: I am new to Magento, in the checkout page. I have a text field and onblur of the text field will open a fancy box popup.
so in the checkout.phtml I placed a div to show their content in the pop up and set CSS attribute display as none.
In on blur I called a JS function and load the poup, for that I write the JS function - jQuery(".zipformcont").fancybox().trigger('click');
zipformcont is class name of div.
The issue is pop up is loading with an error - "The requested content cannot be loaded.
Please try again later."
Please help me to fix this. thanks.
Answer: Instead of using .trigger(); why not call fancybox like this:
jQuery.fancybox();

Fancybox triggers depending on the selector its connected to. Not the div its going to open.
Comment: jQuery.fancybox(); is useful ONLY for click on id's.
i.e Open then I can use - jQuery("#openpopup").fancybox();

but I need the pop up onblur of text field.
Now I fixed it by commenting loading of jQuery.1.7.2.js

I am able to load the popup. but it is flickring. i.e click on the content of pop up window will load the pop up again.
Please check this demo URL - http://184.108.40.206/fancybox/popup.html
Type something in the text field. It popup the content. Them click on the text"Content for pop up window". It flicker/reload the popup again.
Please check it.
Answer: jQuery(function(){
   jQuery('#zipcode').blur(function(){
      jQuery.fancybox({
         "content":$('#formcontainer'),
         "hideOnContentClick": true,
         "hideOnOverlayClick": true
      });
   });
});

This should do it and get rid of the onblur attribute
Answer: I tried another option and it is working fine now.
Option
1) Created a div with CSS attribute - display  as none

test

2) In the textfield, Onblur called a JS function
<input type="text" name="namefld" id="namefld" value="" onblur="openpopup()" />

3) In the JS function, I trigered the click function of "azcodelink"
function openpopup() {
    $("#azcodelink").trigger('click');
}

4) The id - zipcode_form - has the pop up content
<form id="zipcode_form">
...
</form>

Thats all..
Thanks for all your support.
Comment: May I know the reason for minus?
Answer:

Magento Fancybox


Libgdx - Keeping an object at certain distance and direction from other object

Question: So let's say I have 2 objects. One with the sprite of a circle, other with the sprite of triangle.
My triangle object is set to the position of mouse in every step of the game, while circle is either standing in place or just moving in its own way, whatever.
What I want to do is to have the TRIANGLE move around the circle, but not on it's own, rather on the way your cursor is positioned.
So basically, calculate degree between circle's center and triangle's center. Whenever they are far from each other I just set triangle position to mouse position, BUT when you hover your mouse too close (past some X distance) you can't get any closer (the TRIANGLE is then positioned at maximum that X distance in the direction from circle center to mouse point)
I'll add a picture and hopefully you can get what I mean.
https://dl.dropboxusercontent.com/u/23334107/help2.png
Answer: Steps:
1. Calculate the distance between the cursor and the center of the circle. If it is more than the 'limit' then set the triangle's position to the cursor's position and skip to step 4.
2. Obtain the angle formed between the center of the circle and the cursor.
3. Calculate the new Cartesian coordinates (x, y) of the triangle based of off the polar coordinates we have now (angle and radius). The radius will be set to the limit of the circle before we calculate x and y, because we want the triangle to be prevented from entering this limit.
4. Rotate the image of the triangle to 1.5708-angle where angle was found in step 2. (1.5708, or pi/2, in radians is equivalent to 90°)

Details:
1. The distance between two points (x1, y1) and (x2, y2) is sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))
2. The angle (in radians) can be calculated with
double angle = Math.atan2(circleY-cursorY, cursorX-circleX);

The seemingly mistaken difference in order of circleY-cursorY and cursorX-circleX is an artefact of the coordinate system in most programming languages. (The y coordinate increases downwards instead of upwards, as it does in mathematics, while the x coordinate increases in concord with math - to the right.)
3. To convert polar coordinates to Cartesian coordinates use these conversions:
triangle.setX( cos(angle)*limit );
triangle.setY( sin(angle)*limit );

where limit is the distance you want the triangle to remain from the circle.
4. In order to get your triangle to 'face' the circle (as you illustrated), you have to rotate it using the libgdx Sprite function setRotation.  It will rotate around the point set with setOrigin.
Now, you have to rotate by 1.5708-angle – this is because of further differences between angles in mathematics and angles in programming! The atan2 function returns the angle as measured mathematically, with 0° at three o'clock and increasing counterclockwise. The setRotation function (as far as I can tell) has 0° at twelve o'clock and increases clockwise.  Also, we have to convert from radians to degrees. In short, this should work, but I haven't tested it:
triangle.setRotation(Math.toDegrees(1.4708-angle));

Hope this helps!


Name for a category

Question: Is there any name or notation for this category?
Let $U$ be a set. By "function" I will mean a function $U\rightarrow U$.

objects are functions;
morphisms from a function $A$ to a function $B$ are such functions $f$ that $y=A(x)\Rightarrow f(y)=B(f(x))$ for every $x,y\in U$.
Comment: This is related to http://ncatlab.org/nlab/show/arrow+category
Comment: You should specify the domain and codomain of the functions, and why you can apply $f$ to both $x$ and $y$.
Comment: You have not defined a category. As @StefanH notes, it's not clear why you can apply $f$ to both $y$ and to $x$.
Comment: For simplicity let limit both domains and codomains of all functions to some set $U$.
Comment: Instead of writing a comment you should edit this remark into your post so people become aware of your edit. Do you mean that for each function, domain=codomain, or that $U$ is domain and codomain globally?
Answer: Let $\mathcal{U}$ be the category with a single object $U$ and having as morphisms all functions $U\to U$, and consider the monoid $(\mathbb{N},+)$ as a category in the standard way. Then the category you described can be viewed as the functor category $Funct(\mathbb{N},\mathcal{U})$. Any functor $\mathbb{N}\to\mathcal{U}$ is arises from and is determined by where it takes the arrow generating the monoid $\mathbb{N}$, so you can think of the objects of this category as functions $U\to U$. Any natural transformation between two such functors (i.e. functions $A$ and $B$) arises from and determines a function $f\colon U\to U$ satisfying the equation you asked for.
You can get quite similar categories as functor categories of some kind or another. For example, if $\mathcal{C}$ is the category with two objects $A$ and $B$ and one non-trivial arrow $f\colon A\to B$, then $Funct(\mathcal{C},\mathrm{Set})$ is a category where the objects are essentially functions between sets and morphisms are pairs of functions making the obvious square commute.

Name for a category


Error parsing parquet file and importing data to sql table using pandas dataframe

Question: Seeing below error while trying to read parquet file and import the data to Microsoft SQL Server table, couldn't figure out where the problem is, any suggestions would be helpful.
code snippet:
from pandas import read_parquet
import numpy as np
df = read_parquet('<file-path>', engine='fastparquet')
df = df.fillna(value=np.nan)
cols = "],[".join([str(i) for i in df.columns.tolist()])
           for index, row in df.iterrows():
                sql = "INSERT INTO " + obj.table + "([" + cols + "]) VALUES (" + "?," * (len(row) - 1) + "?)"
                try:
                    cur.execute(sql, tuple(row))
                except:
                    print(sql, tuple(row))
                    tb.print_exc()
                    break
                conn.commit()

Error (printed record that failed insert):
<For debugging>
INSERT INTO table(col1, col2 col3 ...) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) (294958881.0, 0.0, 71142106.0, 5.0, 4.0, 4.0, 0.0, 4804102.0, 1.0, 1.0, Timestamp('2020-01-30 12:00:01.590000'), Timestamp('2020-01-30 12:05:12.480000'), nan, nan, nan, nan, nan, Timestamp('2020-01-30 12:05:00'), Timestamp('2020-01-30 12:05:12.420000'), Timestamp('2020-01-30 12:05:12.420000'), nan, nan, nan, 130864939.0, 1.0, 1.0, 0.0, 0.0, 253199575.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, nan, 0.0, 0.0, nan, nan, nan, nan, 1.0, 1.0, '63D861B100000001', Timestamp('2023-01-31 00:32:49.265000'), Timestamp('2023-01-31 00:32:49'))

Traceback (most recent call last):
  File "C:\temp\file.py", line 293, in method01
    cur.execute(sql, tuple(row))
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect.
Parameter 16 (""): The supplied value is not a valid instance of data type float. Check the source data for invalid values.
An example of an invalid value is data of numeric type with scale greater than precision. (8023) (SQLExecDirectW)')

I don't have any float values here that the error is reporting, not sure if I'm missing something. All my target columns are nullable.
Comment: You are using Pandas to read the parquet file. Is there some reason you are not using Panda's [`to_sql`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_sql.html) to insert the data in SQL Server?
Comment: Aside... `nan` is not a float and should probably get converted to `None`.
Comment: Thank you, I will give it a try with both suggestions and get back to you.
Comment: @AlwaysLearning I have tried two different things,
1. Replacing the nan to an empty string using `df.fillna(value='')`, this resolved the loading errors with an execution time of `20+ minutes` to load/insert 2M records.
2. using sqlalchemy create engine + `df.to_sql`, no errors reported but the loading time is `2+ hours` for same data set. I have tried the `fast_executemany=True` with sqlalchmey connection but the performance is same.
Answer: I have following two methods working with some exceptions,
Method 1: (Based on suggestion in one of the comments)

Using SqlAlchemy, pyodbc

import sqlalchemy as sa, pyodbc
con = sa.create_engine('mssql+pyodbc://'
                        +self.server+'/'
                        +self.database+
                        '?driver=SQL+Server+Native+Client+11.0'
                        , fast_executemany=True
                        , echo=False)

from pandas import read_parquet
df = read_parquet('<file-path>', engine='fastparquet')
df.to_sql(name=self.table, con=con, if_exists='append', chunksize=1000, index=False)
con.dispose()

Observations using method 1:

Slow loading.
No issues with NaN values from pandas df (My original problem).
5x slower than method 2, when tested with 100MB compressed parquet file.

Method 2: (If you are not worried of NaNs in the dataframe and need faster load time)

using pyodbc

import pyodbc
con = pyodbc.connect("DRIVER={SQL Server Native Client 11.0};"
                      "SERVER=" + self.server + ";"
                      "DATABASE=" + self.database + ";"
                      "Trusted_Connection=yes;")
cur = con.cursor()
from pandas import read_parquet
df = read_parquet('<file-path>', engine='fastparquet')
df.fillna(value='', inplace=True)
for index, row in df.iterrows():
     sql = "INSERT INTO " + self.table + "([" + cols + "]) VALUES (" + "?," * (len(row) - 1) + "?)"
     cur.execute(sql, tuple(row))
     con.commit()
con.close()

Observations using method 2:

Fast loading.
No issues with NaN values, as we are marking them to empty string.
5x faster than method 1, when tested with 100MB compressed parquet file.
Comment: The results you report are most unusual. I have never seen a situation where sending an individual INSERT statement for each row via `.execute()` is faster than a method that can use `.executemany()` like `.to_sql()` can.
Comment: I have tested this on multiple files, but the outcome is observed same. The only difference I have noticed with method 1 vs 2 is, with 1 there is single commit which means if my df has 2M rows, I'm seeing the commit happens only after all 2M  inserts whereas with 2 it is for each row as in loop. Not sure if that makes any difference with speed here.


Como Saber se o Form que é filho de um TPanel está aberto

Question: Opa!
Tenho uma duvida. Como saber se uma form atribuído como filho de uma TPanel está abeto?
Meu form está sendo criado assim:
if not(Assigned(Form2)) then
begin
  Form2 := TForm2.Create(self);
  Form2.Parent := Panel1;
  Form2.Show;
end;

O intuito é evitar Criar outra instancia do mesmo form. Já tentei assim, if not(Assigned(Form2)) then e sempre fala que ela não está Assigned e cria outro form.
Fonte da Unit1
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;

type
  TForm1 = class(TForm)
    Panel: TPanel;
    Button1: TButton;
    Panel1: TPanel;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses Unit2;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if not(Assigned(Form2)) then
  begin
    Form2 := TForm2.Create(self);
    Form2.Parent := Panel1;
    Form2.Show;
  end;
end;

end.

Fonte do Unit2:
unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm2 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

uses Unit1;

procedure TForm2.Button1Click(Sender: TObject);
begin
  Close;
end;

end.

O Fonte a Unit1 só muda que o Button da abre a Unit2
O FormStle tanto do Form2 como Form1 está setado com fsNormal.
Comment: Pode mostrar a criação da classe `TForm2` ?
Comment: A criação é padrão do Delphi não modifiquei nada
Comment: `Form2` é uma variável publica ou local?
Comment: Velho eu fui em New - VCL Application - Delphi o que gerou  a Unit1. Depois fui em New - VCl Form - Delphi o que gerou a Unit2, coloquei os dois Buttons não crie nada alen das duas procedure. tudo ai foi padrão do Delphi.
Answer: Pressione Alt+P+V exclua o formulário que ele incluí automaticamente, deve estar algo como: Application.CreateForm(TForm2, Form2);
Este teste lógico:
if not(Assigned(Form2)) then
Na documentação explica que Assignedpode não representar o estado de existência do objeto, se é = nil.
O correto é testar se ele é = ou diferente <> nil
if Form2 = nil then
Agora, o que há de fato errado é a manipulação da classe, você esta usando Form2 diretamente da classe TForm2. Funciona, mas não esta certo.
O correto é você declarar uma variável ali no { Private declarations } do tipo TForm2 e a partir deste controlar sua existência.
if vForm = nil then
begin
  vForm := TForm2.Create(Self);
  vForm .Parent := Panel1;
end;

vForm .Show;

Comment: @EduMendonça Tem que ser.
Comment: Eu vou declarar TForm2 no Private da Unit1?
Comment: No private do unit1 você declara `vForm: TForm2;`
Comment: Então para cada Formulário terá uma Variável?


How to delele tag according to its previous tag class value?

Question: How to delele tag according to its previous tag class value?
Input :

2014 has had some strange and negative commentary about publishing with HTML5. The comments appear to be focused on HTML for trade fiction books and the requirements of publishing genres beyond simple narratives seems to be ignored.

I have to delete all tags which contains dropcap-qc i.e. 2014
This is done.
XSL Code:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="no"/>
    <xsl:preserve-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

<xsl:template match="//*[@class='dropcap-qc']"></xsl:template>

</xsl:stylesheet>

I am creating above XSL by Python code. I get all deleted tag class names and then create XSL.
My Python code to get class names: https://stackoverflow.com/questions/30482435/how-to-get-count-of-every-column-value-of-table
I do not know XSL much.
My question is, I want to delete  all dropcap-qc tags but this should be next tag of dropcap-image-qc tag.
Can anyone help me to get correct xpath?
Answer:
Can anyone help me to get correct xpath?

Matching CSS class perfectly in xpath is a bit cumbersome. The following simpler xpath should work to get the elements to be deleted assuming you don't have any CSS class containing dropcap-image-rw (like f.e dropcap-image-qc-x) other than class dropcap-image-rw it self :
//*[@class='dropcap-qc' and preceding-sibling::*[1][contains(@class, 'dropcap-image-qc')]]

Above xpath selects all elements having class dropcap-qc that is located directly after element having class contains dropcap-image-qc.
more explanation about the xpath, as requested :

preceding-sibling::*[1] : gets direct preceding sibling element of current context element. That will be the element that is directly before current element at the same level.
[contains(@class, 'dropcap-image-qc')] : validates if current element -the element returned by previous bit of the xpath- has class attribute containing "dropcap-image-qc"

I'm not familiar with XSL too, so I can't suggest anything on that part
Comment: up1 I wil check and let you know.. Thank you.
Comment: @VivekSable Sure. Updated my answer with explanation about the xpath. Hope that makes sense
Answer:
Can anyone help me to get correct xpath?

The chrome extension Selector Gadget makes it quite easy to get XPaths. Just click on an element (or a selection of elements), and it churns out XPath or CSS selector.


Xamarin.Form CollectionView is checking RadioButtons randomly

Question: I have been trying to figure out this issue for days but without any progress.
In my project, I am generating questionnaire, which do achieved by a page with RadioButtons in pair - group. Those groups are repeating in CollectionView.
Even though each RadioButton group has its own GroupName, it is happening that upon radiobutton click and scrolling down other radio button is clicked as well. Also then if I am scrolling back and forth, others radio buttons are clicked.
This is really strange behaviour for me.
Initially I have following selection (left picture) and after scrolling up and down, it looks like right picture.

The code is really simple.
XAML page:
    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Mobile.ViewModels"
             xmlns:commonLogic="clr-namespace:Mobile.Models;assembly=Mobile"
             xmlns:buttons="clr-namespace:Syncfusion.XForms.Buttons;assembly=Syncfusion.Buttons.XForms"
             xmlns:behaviorsPack="clr-namespace:Xamarin.Forms.BehaviorsPack;assembly=Xamarin.Forms.BehaviorsPack"
             xmlns:resources="clr-namespace:Mobile;assembly=Mobile"
             NavigationPage.HasBackButton="False"
             NavigationPage.HasNavigationBar="False"
             x:Class="Mobile.Views.QuestionarePage"
             x:DataType="local:QuestionnaireViewModel"
             Shell.NavBarIsVisible="True"
             Shell.FlyoutBehavior="Disabled"
             Title="{x:Static resources:AppResources.QuestionnaireTitle}">
    <ContentPage.BindingContext>
        <local:QuestionnaireViewModel/>
    </ContentPage.BindingContext>
    <CollectionView x:Name="listView"  ItemsSource="{Binding StringQuestions}" SelectionMode="None">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout  Padding="10,5,10,8" Spacing="2" x:DataType="commonLogic:TestClass">

                        <RadioButton  GroupName="{Binding GroupName}" Content="{Binding GroupName}"></RadioButton>
                        <RadioButton  GroupName="{Binding GroupName}"  Content="{Binding GroupName}"></RadioButton>
                        </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
</ContentPage>

ViewModel class:
public class TestClass
{
public string GroupName { get; set; }

public TestClass(string name)
{
    GroupName = name;
}
}

Any help appreciated.
Thanks
Update
Even following code is causing me troubles
    <CollectionView x:Name="listView" ItemsSource="{Binding Questions}" SelectionMode="None">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout  Padding="10,5,10,8" Spacing="2" >

                    <RadioButton/>
                    <RadioButton/>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

Comment: 1) What platform (Android, iOS, UWP)? 2) Show the class that contains `StringQuestions`, and the method that created the testdata you show. 3) Click only one button, then scroll. Do you still get multiple ones? 4) Does the one you DID click ever get UNSELECTED merely by scrolling? (so the selection has completely changed). 5) Add a button and put a breakpoint in its click method. After scrolling, click button. Examine data - does it match what you are seeing, re which ones are selected?
Comment: 6) Add a method that runs when a radio button changes state (checked to unchecked or vice versa). Put breakpoint there. It should only fire when you click the first button. Scrolling shouldn't cause it to fire again, AFAIK. To prove it is just some display glitch involving CollectionView + RadioButtons. 7) remove `x:DataType="commonLogic:TestClass"`. If this fixes it, then there is some issue with compiled bindings.
Comment: 8) Any error messages or warning in Debug Output?
Comment: 1) The issue is on iOS. It looks like Android works fine.
2) I have already change the code, but if I simplify it according to paint 7, no class is used.
3) Yes, I do
4) Sometimes it does - but now, since I removed binding in 7) it looks like it does not.
5) It looks like also data are not correct.
Comment: 6) I have binded IsSelected property, different for each radio button. (IsSelectedFirst, IsSelectedSecond, etc ..) Then I added breakpoint and I can see that SETTER is indeed triggered, while releasing finger from the screen. The same was happening with event, which was fired as well. How is that possible?
7) The issue still happening, but behaves different. Now, if I select first button, 10th button is selected as well. Looks like those groups are somehow connected.
8) No error/warnings. 7) is really strange. By that I have cut off all binding logic and the issues is still happening.
Comment: Please see updated XAML file above, where binding was removed from RadioButtons.
Comment: I agree that this is a strange symptom. It seems suspiciously like a Xamarin Bug when Radio Buttons are used in a CollectionView's ItemTemplate. But I don't see any similar "issue" (bug report) at the Xamarin Forms github repo. Sorry, I don't have more time to investigate - and since no one else has responded to your Q, it may not be an issue anyone is aware of.
Comment: Now that you've reduced it down to minimal code, it would be worth creating an issue at https://github.com/xamarin/Xamarin.Forms/issues. You are welcome to go ahead and create that issue, with the explanation and minimal code you've given here. (Even better: create a public github repo, that anyone can download/build/run to see the symptom. This makes it MUCH more likely that someone will test and verify the problem.) Include a link back to this SO post.  And then post a link here, to the new issue you made.
Answer: You could try below two methods.
One,using ListView to replace CollectionView.
<ListView x:Name="listView"  HasUnevenRows="True" ItemsSource="{Binding StringQuestions}" SelectionMode="None" >
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                <StackLayout  Padding="10,5,10,8" Spacing="2" RadioButtonGroup.GroupName="{Binding GroupName}">

                    <RadioButton   Content="{Binding GroupName}"></RadioButton>
                    <RadioButton   Content="{Binding GroupName}"></RadioButton>
                </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
</ListView>

Two:define two property in your model.
public class TestClass
{
    public string GroupName { get; set; }
    public bool IsFirstCheck { get; set; }
    public bool IsSecondCheck { get; set; }
    public TestClass(string name)
    {
        GroupName = name;
    }
}

then bind to your RadioButtons:
<CollectionView x:Name="listView"  ItemsSource="{Binding StringQuestions}" SelectionMode="None" >
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout  Padding="10,5,10,8" Spacing="2" RadioButtonGroup.GroupName="{Binding GroupName}">

                    <RadioButton   IsChecked="{Binding IsFirstCheck}" CheckedChanged="RadioButton_CheckedChanged" Content="{Binding GroupName}"></RadioButton>
                    <RadioButton   IsChecked="{Binding IsSecondCheck}" CheckedChanged="RadioButton_CheckedChanged_1" Content="{Binding GroupName}"></RadioButton>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
</CollectionView>

in your code behind,change the IsFirstCheck and IsSecondCheck values.
private void RadioButton_CheckedChanged(object sender, CheckedChangedEventArgs e)
    {

        TestClass test = (TestClass)(sender as RadioButton).BindingContext;
        if (test !=null)
        {
            test.IsFirstCheck = e.Value;
        }

    }

private void RadioButton_CheckedChanged_1(object sender, CheckedChangedEventArgs e)
    {
        TestClass test = (TestClass)(sender as RadioButton).BindingContext;
        if (test != null)
        {
            test.IsSecondCheck = e.Value;
        }
    }


É correto criar uma variável dentro de um if?

Question: é correto criar uma variável dentro de um if ?
No código abaixo cria-se uma variável dentro do if, e evita-se usar duas vezes o mesmo filtro.
if($id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)):
    /* Código */
endif;

O que vocês acham da pratica dentro do IF?
Isso é contra alguma norma dos PSR's (PHP Standards Recommendation) ?
{Obrigado}
Comment: Eu acho bom colocar a questão das PSR no título, pq o resto meramente depende de opinião. Se vai usar a informação, o estranho seria justamente não criar a variável. Ainda que no caso do `if` você poderia criar antes.
Comment: Se não fosse coitada das pessoas que usam `while($busca=mysql_fetch_array($sql))`
Comment: Não tem problema nenhum, vai da necessidade de se fazer isso.
Comment: Qual seria a versão desse código sem o if? as vezes é últil outras não xD
Comment: Acredito que seja válido, porém a certas coisas que você pode utilizar o `&&` ou `||` antes de criar duas condições em sequência, mas vai da solução a se resolver....
Answer: Antes de mais nada, o if não é um bom exemplo, pois você pode "criar" a variável uma vez só, mesmo fora:
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)
if( $id ):
   /* Código que usa o $id, sem "criar" de novo */
endif;

Mas num while já complica, então vou usar isto como exemplo:
while ($row = $result->fetch_row()) {
    printf ("%s (%s)\n", $row[0], $row[1]);
}

Neste caso, não só e correto, como é um exemplo tirado do manual do PHP.
Já que no while não só é um caso comum, mas muitas vezes necessário, não vejo motivo pra não poder usar no if. No fim, a legibilidade é sempre o mais importante. E para isto, só depende do contexto onde você vai usar. No exemplo acima com certeza não houve ganho em separar as linhas.
Se tiver qualquer PSR dizendo o contrário, tem que consertar a PSR, em vez de complicar o código.
Comment: "em um caso que a variável só vai existir dentro do if essa opção não é valida" Isso nao é verdade, veja http://ideone.com/cvzNmW - se criou dentro do teste do IF, ela é do escopo externo. Diferente de criar dentro do BLOCO do if.
Comment: @jjdomroam De qq forma, é bom pra relembrarmos o escopo :) Estamos olhando um exemplo simples, se for um if complexo onde você cria a variável e faz operações com ela, chega a fazer sentido sim. Imagine isso: `if( ( $id = MegaCalculo() * 45.2 / Sqrt( 999999999) ) < AjusteSenoidalDoFatorX( 2347) )` Neste caso, fica interessante tirar o `$id = MegaCalculo() * 45.2 / Sqrt( 999999999 )` e deixar só `if( $id < AjusteSenoidalDoFatorX( 2347 ) )`, não? Como eu disse, o que manda é o contexto. Tem hora que é melhor de um jeito, tem hora que é melhor de outro. Vai da complexidade das expressões.
Comment: Acho que nesse caso(if) ainda se encaixe um ternario maroto ;)
Comment: @rray mas a premissa é ele usar o $id dentro do bloco do `if` depois né? Se eu botar um ternário lá, complica o reuso, se for em mais de um lugar.
Comment: Sim, pode ser criar a variável, porem em um caso que a variável só vai existir dentro do if essa opção não é valida. O if dessa forma me poupa ter de criar a variável dentro do if, pois a mesma já foi criada. Minha duvida mesmo é sobre esta de alguma forma errado, pois o Netbeans gera um alerta informando que foi acidental a criação da variável dentro do if!
Comment: @Bacco Falei errado, não quis dizer que ela não rodaria dentro do if, eu quis dizer que não faz sentido criar ela fora do if. Desculpa erro meu na hora de me expressar.
Comment: @Bacco Sim, faz sentido nesse caso criar a variável fora do if, ate mesmo no seu primeiro exemplo faz sentido tira ela do if se eu for usa-la em outros lugares fora dele. Minha duvida mesmo é por conta do meu NetBeans que gera um pequeno alerta falando que foi acidental a criação da variável, o que me passa a ideia que eu estaria fazendo algo errado!
Comment: @jjdomroam experimente usar `( )` pra deixar claro pra IDE que vc fez de proposito. Por exemplo: `if( ( $id = Funcao() ) ):` - nao sei se funciona no netbeans, mas talvez resolva. Se bem que eu nao sei o que é pior, o alerta ou os ( ) atrapalhando leitura.
Comment: @Bacco Funcionou perfeitamente :v, meu IDE não gera mais alerta na linha. Obrigado pela dica!
Comment: @Bacco Não atrapalha muito a leitura, agora fico na duvida mesmo se vale apenas incluir os () para o capricho do IDE.
Comment: @jjdomroam decisao complicada :) Veja se nao tem como desativar essa detecção específica nas opções. Nao conheço bem o netbeans
Comment: @Bacco Tem sim, já desativei, Obrigado!


Passing nested parameters in the extra_params of the load_context in Kedro

Question: I am trying to load a Kedro context with some extra parameters. My intention is to update the configs in parameters.yml with only the ones passed in extra_params (so rest of the configs should remain same). I will then use this instance of context to run some nodes/pipelines (Note: I don't want to modify the parameters.yml file, just update it for this run). I am able to do so for every configs defined at the top/root level in parameters.yml but only the passed configs are persisted in case of nested parameters.
To replicate the issue,
parameters.yml
config_root1: "name"
config_root2: "surname"
config_root3:
   config_leaf1: 10
   config_leaf2: 20
   config_leaf3: 30

Extra params defined as,
extra_params = {'config_root1': 'new_name', 'config_root3': {'config_leaf1': 11}}

Loading the context with extra_params by,
from kedro.framework.context import load_context
context = load_context(proj_path, extra_params=extra_params)

The parameters in context is updated to,
config_root1: "new_name"
config_root2: "surname"
config_root3:
   config_leaf1: 11

Points to note,

config_root1 was at root level and value was passed in extra_params, hence it was updated.
config_root2 was at root level and no value was passed, hence it remains the same.
config_leaf1 was at leaf level, value passed hence updated.
config_leaf{2, 3} were at leaf level, no value passed hence dropped.

It seems the issue has to do with how dictionary and nested dictionary are merged.
Any workarounds other than always passing all of the parameters in extra_params (even if only few needs to be changed)?
Thank you.
Answer: The issue in the replacement of key config_root3 to new value, and it cannot be omited easily.
I guess the best way to do it would be creation of two separate configs which override each other with Additional configuration environment, but it requires changes in the way you work with load_context.
Additionally, you can use config loader and merge parameters manually, then provide merge result as extra_params.
Answer: extra_params or the kedro run --params cli now accepts nested dict update.
With CLI:
kedro run --params=nested_key.nested_subkey:<value>
With Python API:
params = {'nested_level1':
     {'nested_level2' : 'some_value'}
}

with KedroSession.create(extra_params=params
                        ) as session:
    session.run()


Which test would be appropriate for my data?

Question: I did a questionnaire survey wherein I asked the respondents questions on their saving habits. One of the question had two options, either save formally or informally. These options has categories to choose from like follows
Q. Mode of saving
Formal
1. bank
2. property.
3. Gold
Informal
1. Cash
2. Informal groups
3. Buy livestock
The respondents can choose any option from these.
I want to see the relationship of mode of saving with demographics.
What should be the appropriate method and statistical tool to do that.
Answer: You can do two logistic regressions. The first is a standard logistic regression with the two-option outcome as the response and the demographics as the predictors. This would allow you to answer the broader question of what kind of people prefer to save formally or informally. The second logistic regression would be a multinomial logistic regression with all the possibilities as the response and the demographics as the predictors. From this model, you could compare how different demographics predict choosing one option versus another or make predictions about how certain combinations of demographics choose to save.
Answer: You can use chi square test of independence or odds ratio


ASP.Net ReportViewer control not working

Question: I am using Reportviewer control in my .aspx page. I set
<code>  ReportViewer1.ShowPrintButton = false;
</code>
but it didn't work. Not only this button, i tried to show refresh button but it didn't work. thanks.
<code>protected void Page_Load(object sender, EventArgs e) {

  if (!this.IsPostBack)
    PrintReport();
}
  private void PrintReport() {
    ReportViewer1.ShowPrintButton = false;
    ReportViewer1.ShowRefreshButton = false;
  }
</code>
Comment: please provide us with some more information. show us your aspx code as well as some code behind if necessary. what exactly did not work?
Comment: hi, here I provided code behind file details. Pls let me know if you need some more details.
Comment: ifyou mean this reportViewer class http://msdn.microsoft.com/de-de/library/microsoft.reporting.winforms.reportviewer(v=vs.80).aspx - this is a winForms control and it wont work on an aspx page...
Comment: Im talking about http://msdn.microsoft.com/en-us/library/ms251671(v=VS.100).aspx
Answer: You need to be running reports in remote mode in order for the buttons to work. In addition, if you want them to be shown, you have to set the values to True, not False as is shown in your code.
If you are running in local mode, there is an ActiveX control that can be downloaded, but this will only work for IE.
Here is a link to the MSDN documentation about printing from ReportViewer that should help you out.
Comment: Sorry, I would like to hide them. I have downloaded the control from here, started using it. http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=21916


Applying Runge's theorem

Question: Let $K\subset \mathbb{C}$ be a compact subset. The question here is to show that $\mathbb{C}\backslash K$ is connected if and only if for every $w\in \mathbb{C}\backslash K$ there exists polynomial $f(z)$  such that $|f(w)|>\sup_{w\in K} |f(z)|$.
I've attempted the above problem with very little success rate. Let us suppose $\mathbb{C}\backslash K$ is indeed connected. So for any $w\in \mathbb{C}\backslash K$ we may choose a neighbourhood $U_w\subset \mathbb{C}\backslash K$ containing $w$. (We can do so since $\mathbb{C}\backslash K$ is open) Then applying Runge's theorem we get that for any $f$ holomorphic on open subset containing $K$ we have some rational function with poles only in $U_W$ satisfying $\sup_{z\in K} |f(z)-R(z)| <\varepsilon$. I believe we need to make some clever choice of $f$ for this result to hold. Any hints (as well as for the converse claim) would be greatly appreciated.
Answer: Hints: First the converse, which is more elementary. In general $\Bbb C\setminus K$ has exactly one bounded component, so if it is not connected it has a bounded component $C$. If you show that $\partial C\subset K$ then the existence of a polynomial as above for $w\in C$ would contradict the maxium modulus theorem.
Now suppose $\Bbb C\setminus K$ is connected and $w\in\Bbb C\setminus K$. Let $K'=K\cup\{w\}$. Show that $\Bbb C\setminus K'$ is connected. Hence Runge's theorem shows that any function $g$ holomorphic in a neighborhood  of $K'$ can be uniformly approximated on $K'$ by a polynomial $f$;  the right choice of $g$ and $\epsilon$ gives the $f$ you want.
Comment: Hi, thank you v much for the hints! I am unable to find a suitable choice of g and $\varepsilon$ still. Does $\varepsilon$ have to depend on $|g(w)|$ or something?
Comment: You could let $g=0$ on $K$, $g(w)=1$.
Comment: If $g=0$ on $K$, then wouldn't the identity theorem asserts that $g=0$ on $K'$ as well?
Comment: That theorem has _hypotheses_. Can you state the theorem precisely?

Applying Runge's theorem