Quadratic term and variance inflation factor in OLS estimation

Question: One question I have carried around with me for a while is related to including quadratic terms for model specifications. I wonder why it is considered ok to include linear and quadratic terms into OLS analysis, despite the fact that the Variance Inflation Factor (VIF) gets high. A model specification that I was taught to be fine to use is the following:
$y = c + x + x^2 + \epsilon$
But this model has quite high numerical linear correlation between $x$ and $x^2$ and I do not understand why in this case the VIF does not matter.
An example for what I mean using R is the following:
<code># Load packages
require(car)
requre(lmtest)

# Create artificial data
dat <- data.frame(x = 1:1000, x2 = (1:1000)^2)
dat$y <- dat$x2 + rnorm(1000, 0, 10)

# Run model with linear term
dat.lm1 <- lm(y ~ x, dat)

# Run model with linear and quadratic term
dat.lm2 <- lm(y ~ x + x2, dat)
</code>
In this setup, the RESET test suggests using quadratic terms but the VIF is high.
<code>> reset(dat.lm1)
RESET test
data:  dat.lm1
RESET = 27344126617, df1 = 2, df2 = 996, p-value < 2.2e-16

> reset(dat.lm2)
RESET test
data:  dat.lm2
RESET = 0.4404, df1 = 2, df2 = 995, p-value = 0.6439

> vif(dat.lm2)
x       x2
16.03008 16.03008
</code>
So the question is:
Is this really a model specification that is valid and if yes, why does the VIF not matter in that case?
Answer: Generally collinearity only affects variance estimates of your parameters. You can avoid collinearity by data transformation. For your example:
<code># norm x to mean zero
dat$x_n <- dat$x - mean(dat$x)
dat$x2_n <- (dat$x_n)^2
dat.lm2_n <- lm(y ~ x_n + x2_n, dat)
</code>
This transformation doesn't affect your residuals but you get smaller confidence intervals.
<code>> summary(dat.lm2)

Call:
lm(formula = y ~ x + x2, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-37.505  -7.182  -0.146   7.016  36.599

Coefficients:
              Estimate Std. Error    t value Pr(>|t|)
(Intercept)  5.967e-01  9.626e-01      0.620    0.535
x           -1.185e-03  4.441e-03     -0.267    0.790
x2           1.000e+00  4.296e-06 232752.480   <2e-16 ***
---
Signif. codes:  0 `***` 0.001 `**` 0.01 `*` 0.05 `.` 0.1 ` ` 1

Residual standard error: 10.13 on 997 degrees of freedom
Multiple R-squared:     1,  Adjusted R-squared:     1
F-statistic: 4.342e+11 on 2 and 997 DF,  p-value: < 2.2e-16

> summary(dat.lm2_n)

Call:
lm(formula = y ~ x_n + x2_n, data = dat)

Residuals:
    Min      1Q  Median      3Q     Max
-37.505  -7.182  -0.146   7.016  36.599

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.505e+05  4.804e-01  521493   <2e-16 ***
x_n         1.001e+03  1.109e-03  902349   <2e-16 ***
x2_n        1.000e+00  4.296e-06  232752   <2e-16 ***
---
Signif. codes:  0 `***` 0.001 `**` 0.01 `*` 0.05 `.` 0.1 ` ` 1

Residual standard error: 10.13 on 997 degrees of freedom
Multiple R-squared:     1,  Adjusted R-squared:     1
F-statistic: 4.342e+11 on 2 and 997 DF,  p-value: < 2.2e-16
</code>
And the VIF shrinks of course:
<code>> vif(dat.lm2)
       x       x2
16.03008 16.03008

> vif(dat.lm2_n)
 x_n x2_n
   1    1
</code>
Comment: why is confidence interval smaller after the transformation?
Comment: @FMZ: The [variance estimate](http://en.wikipedia.org/wiki/Variance_inflation_factor#Definition) can be expressed so that it includes $R^2$ of a regression of the covariate using all other covariates. Therefore, if you reduce this factor the estimated variance will shrink and hence the CIs.
Comment: @Tim, thanks for the reference. It makes sense now.


Error in Search Server Express 2008

Question: I've installed Microsoft Search Server 2008 Express, and as a part of it, WSS 3.0
And for 6 month, it runs without fail, until yesterday. The search site refuses to perform search, and Search Central Administration gives cryptic error message
HRESULT: 0x80040D1B.

Looking at event log, I noticed there's a thousand error message from "Office Share Point Server" and "Windows Sharepoint Services 3.0 (timer)"
Here's the error message.
Application Server Administration job failed for service instance
Microsoft.Office.Server.Search.Administration.SearchServiceInstance
(6503413d-4031-4c19-aca7-927076e0b33f).

Reason: Exception from HRESULT: 0x80040D1B
.
.
.

Searching the internet leads me to this page, which describes method I'm too afraid to try since it's an old article and there's a high probability that all the documents that I've uploaded would be deleted.
Searching for HRESULT: 0x80040D1B gives me the impression that maybe the error has something to do with permission.
So, my question is this. How can I get Search Server working again? How do I ensure that is not a permission problem?
My Server Configuration
OS  : Win Server 2003 R2 SE 64
RAM : 8 Gigs
Web Server and SQL Server are in the same box, without any server farm

Answer: Did you change the password of any of your SharePoint service accounts recently?  Follow the steps in the following article to update the SharePoint passwords: http://support.microsoft.com/kb/934838
Comment: Unfortunately No. My Sharepoint service account is a domain account, and It's working properly.
Comment: I agree with Alex... everything I have seen on this error centers around the passwords needing to be updated.  It won't hurt anything and it should help.
Answer: I know you said you haven't changed any passwords. However why don't you try following the steps in KB article 934838 anyway. Provided you have all of the service account and password details, this won't hurt anything and will ensure your password configuration is correct.
Also, is there any chance the passwords have expired?

Error in Search Server Express 2008


Solving a separable differential equation: What's wrong with my calculation?

Question: Solve the following separable differential equation:$$\frac{dy}{dx}=(-4)\cdot e^y \cdot cos(4x)$$
My answer (which is incorrect but I don't know why):
$$\frac{dy}{dx}=(-4)\cdot e^y \cdot cos(4x)$$
$$= dy = (-4)\cdot e^y \cdot cos(4x)dx$$
$$= \frac{1}{-4e^y}dy=cos(4x)dx$$
$$= \int\frac{1}{-4e^y}dy=\int cos(4x)dx$$
$$= 4e^{-y}=\frac{1}{4}sin(4x)+c$$
$$= e^{-y}=\frac{1}{16}sin(4x)+c$$
$$= ln(e^{-y})=ln(\frac{1}{16}sin(4x)+c)$$
$$= y=-ln(\frac{1}{16}sin(4x)+c)$$
Answer: In your fifth line of working you should have $\frac{1}{4}e^{-y}$. Otherwise I see no issues.


Allow plus (+) Javascript keyCode

Question: I need to allow user to add plus (+) in mobile field. I have this javascript functions. How can I customize this code to allow plus (+) ?
function validateNumber(event) {
    var key = window.event ? event.keyCode : event.which;

    if (event.keyCode != 43 || event.keyCode === 8 || event.keyCode === 46) {
        return true;
    } else if (event.keyCode == 43) {
        return true;
    } else if (key < 48 || key > 57) {
        return false;
    } else {
        return true;
    }
}

Comment: In the desktop Chrome browser it already returns `true` for the `+` key on the number pad.  As well as using `CTRL` + `=`.
Answer: The value of event.key for a plus symbol is '+' and the value of event.which for a plus symbol is `187. You can use those facts to add an appropriate condition to you validation logic.
By the way, here is a fantastic ressource on key codes: https://keycode.info/
By the way, both the event.which and event.keycode properties are deprecated and so I would recommend using event.key instead for identifying which key is pressed.
Comment: Good suggestion, but still, filtering out keys is not the best solution for this problem. Check my answer here: https://stackoverflow.com/a/64091395/3723993
Answer: Both e.which and e.keyCode are deprecated. e.key or e.code should be used instead, which also makes the code easier to understand, as e.key === '+' for the + key. Just keep in mind some old browsers used non-standard codes for some keys, so, for example, left is usually 'LeftArrow' and right is 'RightArrow', but on IE it's just 'Left' and 'Right' instead.
If you need to check KeyboardEvent's properties values such as e.key, e.code, e.which or e.keyCode you can use https://keyjs.dev. I will add information about these kinds of cross-browser incompatibilities soon!

Disclaimer: I'm the author.
Anyway, you should not listen for keyboard events (keydown / keypress / keyup) to filter out certain characters, as the value of the input can also be updated by pasting or dropping text into it and there are many exceptions you should not prevent, such as arrows, delete, escape, shortcuts such as select all, copy, paste... so trying to come up with an exhaustive list of the ones that should be allowed is probably not a good idea.
Moreover, that won't work on mobile, where most keys emit the same values e.key = 'Unidentified', e.which== 229 and e.keyCode = 229.
Instead, just listen for the input event and update the input value removing all invalid characters while preserving the cursor's position:

const input = document.getElementById('input');

input.oninput = (e) => {
  const cursorPosition = input.selectionStart - 1;
  const hasInvalidCharacters = input.value.match(/[^0-9+]/);

  if (!hasInvalidCharacters) return;

  // Replace all non-digits:
  input.value = input.value.replace(/[^0-9+]/g, '');

  // Keep cursor position:
  input.setSelectionRange(cursorPosition, cursorPosition);
};
<input id="input" type="text" placeholder="Digits and + only" />

Here you can see a similar answer and example for a slightly more complex behaviour to allow only numbers with one single decimal separator: https://stackoverflow.com/a/64084513/3723993
Answer: Try this,
function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode != 43 && charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

Comment: I am getting error - This field is required.Should be a valid integr value
Comment: Both `e.which` and `e.keyCode` are deprecated, so `e.key` or `e.code` should be used instead.

Allow plus (+) Javascript keyCode


what to make out of it when Euler-Lagrange Equation is constantly zero

Question: I'm new to Calculus of Variations, and I'm trying to apply it to a simple vector calculus problem.
Let's consider finding a curve $C$ along which the work $W$ done by a given vector field $\textbf{F}$ is maximized. Obviously $W$ can be expressed by
$$W = \int_C \textbf{F}\cdot d\textbf{r}$$
Since a line integral in essence is a single-variable integral, we can rewrite the above integral as
$$W = \int_C \textbf{F}\cdot d\textbf{r} = \int_C \textbf{F}(\textbf{r}(t))\cdot \textbf{r'}(t)dt=\int_C L(t,\textbf{r},\textbf{r'})dt$$
where $\textbf{r}(t)$ is the displacement
I used the one-dimensional Euler-Lagrange Equation,
$$\frac{d}{dx}(\frac{\partial L}{\partial \textbf{r'}}) - \frac{\partial L}{\partial \bf{r}}=0$$
which actualy yields
$$\textbf{F'}(\textbf{r}) \cdot \textbf{r'} - \textbf{F'}(\textbf{r}) \cdot \textbf{r'} = 0$$
My question is :

Is there any mistakes in the steps?
what can we say about this constantly zero result? I noticed that the original derivation in 1-D Euler-Lagrange equation is to find the functional $y$ (in my case is $\textbf{r}(t)$) in terms of $t$ or $x$ that maximize a certain integral, and E-L equation is a necessary condition but not a sufficient for the extremal (similar to setting the derivative/gradient to zero). Does it mean this methods(E-L equation) fails in this case(we can't tell what curve maximize the line integral) or am I missing some underlying constraints here?
I've found a similar thread When the Euler Lagrange equation simplifies to zero. I'm not sure if I get this right but it seems the answer here implies a constantly zero E-L equation only tells us that the integral is of the same form regardless of the candidate function $\textbf{r}(t)$ here.
If we consider a special case, say, $C$ is a closed curve ($\textbf{r}(t)$ takes the same value at the both endpoints), then the original line integral (now turns into a contour integral) can be rewrite into a double integral of the curl using Stokes' theorem:

$$W = \oint_C \textbf{F}\cdot d\textbf{r} = \iint_D (\nabla \times \textbf{F}) \cdot d\textbf(A)$$
where $D$ is the region enclosed by the closed curve $C$, then clearly the extrema of the integral is also dependent on the vector field $\textbf{F}$, but how can I include this info in the E-L equation?
Answer: There was a mistake in your deviation.
First we note that $L = \sum_j F_j \dot r_j$
$$ \frac{\partial L}{ \partial r_i} = \sum_j \frac{\partial F_j}{ \partial r_i} \dot r_j$$
$$ \frac{\partial L}{ \partial \dot r_i} = F_i$$
$$\frac{d}{dt} \frac{\partial L}{ \partial \dot r_i} = \sum_j \frac{\partial F_i}{ \partial r_j} \dot r_j$$
Hence the Euler lagrange equation reads
$$ \sum_j\left (\frac{\partial F_i}{ \partial r_j}  - \frac{\partial F_j}{ \partial r_i} \right) \dot r_j = 0$$
This it clearly trivial iff $\nabla \times F = 0.$ In this case the field in conservative and the integral constant if the endpoints are fixed.
The consistently $0$ result is what happens when your integral is constant. It is basically analogous to how constant functions have derivative $0$.
Comment: For the first question yes that's right. And for the second, calculus of variations can totally be done (and very often is) with vectors and tensors. Often it is easier to do things with components then leave everything in vector notation though.
Comment: Ohh I see, so each component has to be treated separately. Thank you for your clarification! I also wanna confirm if it is safe to assume that $\frac{\partial F_i}{\partial r_j} - \frac{\partial F_j}{\partial r_i} = 0$ for all available $i,j$ here, because $\dot{r_i}$ are independent?
Comment: well might be another silly question, (I can't come up with another case for now), is Calculus of Variations mainly focusing on functions/maps from Field to Field rather than other more complexed functions/maps from sets to sets like vector spaces. or in other words, if Calculus of Variations have vector/tensor forms.
Comment: ohhh $\frac{\partial F_i}{\partial r_j} - \frac{\partial F_j}{\partial r_i}$ is actually a component of the curl of $\textbf{F}$, at least for the 2-D and 3-D cases


How many times will I have to send data, with a fixed data loss rate?

Question: Consider this:
I am trying to send the contents of a book to someone through the post, using only postcards. So I must split the book up into N parts. For each post card I send, the recipient must also send a postcard back, acknowledging that they received it (within an arbitrary timeframe). There is a probability P for every postcard that it will get lost, and for each of these lost cards I must resend a postcard with that same letter section until it is received.
My question is, how might I calculate the number of postcards I must send (lets say T), in terms of N and P?
Answer: If $p$ is the probability that a postcard gets lost in transit, then the probability that a particular section of book is successfully sent at $m$-th attempt is:
\begin{align}
Q_m\equiv p^{m-1}(1-p)
\end{align}
assuming that each sending event is independent of others. You want the probability that a total of $M$ postcards need to be sent so that the entire book is received. Obviously, we cannot have $M<N$, i.e. $P(M|N)=0$ for $M<N$. Therefore consider the case $M\geq N$.
Now consider partitioning $M$ into a sum of $N$ numbers using only positive integers excluding zero. For example for $N=3$ and $M=5$, one possible partition is $M=5=1+1+3$. Let $\Phi(M,N)$ be the collection of ordered sets whose elements are $M$ partitions of $N$. Again for $N=3$ and $M=5$ we have:
\begin{align}
\Phi(M=5,N=3)=\{(1,1,3),(1,3,1),(3,1,1),(1,2,2),(2,1,2),(2,2,1)\}
\end{align}
Each ordered set tells you how many attempts were required to send each section (in the example above there are only $N=3$ sections). For example $(1,1,3)$ means that each of first two sections was sent in 1 attempt, but the last section required 3 attempts before it was sent successfully. Let us call each ordered set, such as $(1,1,3)$, as the "sequence of number of attempts".
For a particular sequence of number of attempts, $\{m_1,m_2,...,m_N\}$, the corresponding probability is $Q_{m_1}\times Q_{m_2}\times ...Q_{m_N}\equiv Q'_{\{m_1,m_2,...,m_N\}}$. The total probability that $M$ postcards were sent is equal to sum of such probabilities for each distinct sequence of number of attempts:
\begin{align}
P(M|N)=\sum_{\mathbf{X}\in\Phi}Q'_{\mathbf{X}}
\end{align}
For even moderately large $N$ this is difficult to work out by hand, and you may wish to use some software like Mathematica to calculate the probabilities.


Erro ao enviar email: server response: 550 5.7.1 Must Authenticate

Question: Estou tentando usar a função mail() do
Porém, o seguinte aviso aparece quando rodo o script:

" Warning: mail() [function.mail]: SMTP
  server response: 550 5.7.1 Must Authenticate!"

Como configuro isso?
Segue o código:
$message = "Blablablablablablabla";

// In case any of our lines are larger than 70 characters, we should use wordwrap()

$message = wordwrap($message, 70);

// Send

mail('email@example.com', 'Solicitação de Cadastro de Fornecedor de Serviço - Numero - 111 - Controladoria - Marco Projetos e Construções', $message);

Comment: poderia colocar o código na pergunta, para entendermos melhor?
Comment: Código postado.
Answer: Para previnir o abuso do envio de e-mail, mais conhecido como SPAM, muitos servidores pedem que o cliente esteja autenticado e seja legítimo.
A função mail() não consegue realizar essa autenticação, sendo assim é necessário utilizar uma outra biblioteca que suporte a autenticação por SMTP. (PEAR Mail, phpmailer, Swift Mailer, etc)
Se você tem um interesse, recomendo esse ótimo tutorial para utilizar o PHPMailer.
Fonte
Fonte2
Comment: eu baixei a classe PHPMailer e tentei rodar, mas dá um aviso de erro na classe SMTP... Se não me engano, diz que SMTP não existe ou não funciona :(
Comment: Qual o servidor de SMTP que você está utilizando? É o fornecido pelo servidor?
Comment: Do terra @Lucas. smtp.poa.terra.com.br e o mesmo exige autenticação.
Comment: Consegui rodar o phpmailer... Só parece que não está chegando no destinatário!
Eu estava apontando o riquire(phpmailer.php) do lugar errado. Valeu mesmo assim
Answer: Alguns servidores não permitem que o campo from do email seja omitido. Ele é configurado como quarto argumento da função mail.
Configure ele da seguinte forma:
$headers = 'From: email@example.com' . PHP_EOL;
mail('email@example.com', 'titulo', $message, $headers);

Comment: o mesmo erro aparece.
Answer: Você tem de construir e enviar os headers do seu email:
    $headers  = 'From: email@example.com'."\r\n";
    $headers .= 'Reply-To: firstname.lastname@example.com'."\r\n";
    $headers .= 'MIME-Version: 1.0'."\n";
    $headers .= 'Content-type: text/html; charset=UTF-8'."\r\n";

    if(mail('firstname.lastname@example.com', 'Solicitação de Cadastro de Fornecedor de Serviço - Numero - 111 - Controladoria - Marco Projetos e Construções', $message, $headers))
        echo "Email enviado";
    else
        echo "Ocorreu um erro no envio do email!";

Comment: O aviso aparecer na tela.
Estou desenvolvendo local.
Comment: estou recebendo o mesmo aviso: " Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Must Authenticate!"
Comment: esse erro aparece na consola do seu browser? está a desenvolver localmente ou num servidor?
Comment: para desenvolver aplicativos de email localmente você precisa instalar e/ou configurar outros componentes para conseguir ultrapassar a restrições de autenticação. Aconselho que experimente carregar o seu código para um servidor e testar as funcionalidades de email aí.
Comment: Certo @CIRCLE, vou fazer isso.


How to bind to AJAX complete event in regard to styling the AJAX button submit throbber

Question: With this I can bind to the AJAX button submit event:

Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {
...
}

My question, how to bind to the opposite (i.e. when AJAX button submit finishes)? Thanks.
Answer: You can use success function. You can refer this for its usage.
/**
 * Handler for the form redirection completion.
 */
Drupal.ajax.prototype.success = function (response, status) {
  ...
}


How to skip route if not user access

Question: I have two routes (from views module) with path "/test".
Route N1 required "role_1" user role, route N2 required "role_2" user role.
Rote N1:
class Symfony\Component\Routing\Route#9524 (9) {
  private $path =>
  string(5) "/test"

...

  private $defaults =>
  array(3) {
    '_controller' =>
    string(47) "Drupal\views\Routing\ViewPageController::handle"
    'view_id' =>
    string(4) "test"
    'display_id' =>
    string(6) "page_1"
  }
  private $requirements =>
  array(2) {
    '_role' =>
    string(6) "role_1"
    '_method' =>
    string(8) "GET|POST"
  }

...

Route N2:
class Symfony\Component\Routing\Route#9524 (9) {
  private $path =>
  string(5) "/test"

...

  private $defaults =>
  array(3) {
    '_controller' =>
    string(47) "Drupal\views\Routing\ViewPageController::handle"
    'view_id' =>
    string(4) "test"
    'display_id' =>
    string(6) "page_2"
  }
  private $requirements =>
  array(2) {
    '_role' =>
    string(6) "role_2"
    '_method' =>
    string(8) "GET|POST"
  }

...

How to skip route N1 if current user have "role_2" but does not have "role_1"?
Answer: You can't have multiple routes on the same path with different access checks, it just doesn't work like that.
If you want something like this, then you need to create your own route, check permission/role of the user there and then display the right view based on that.
Comment: I'm created module for this feature :)
Answer: I'm created module for this feature.
See sandbox.

How to skip route if not user access


Find the value of the integral $\int_{0}^{1}\int_{y}^{1}y \sqrt{1+x^3}dxdy$

Question: I am stuck on the following problem :

Find the value of the integral  $\int_{0}^{1}\int_{y}^{1}y \sqrt{1+x^3}dxdy=?$

I see $\int_{0}^{1}\int_{y}^{1}y \sqrt{1+x^3}dxdy=\int_{0}^{1} y[\int_{y}^{1} \sqrt{1+x^3}dx]dy$ . Now I am having the problem to find $\int_{y}^{1} \sqrt{1+x^3}dx$
Comment: **Draw a picture**, use it to identify geometrically the region of integration. Then use the picture to integrate first with respect to $y$, from $0$ to $x$. The rest is easy.
Comment: Hint: try the substitution $u = x^{3/2}$, which transforms the inner integrand to something like $\sqrt{a^2 + u^2}$. This should be much easier to solve.
Answer: Reverse the order of integration:
$$\begin{align*}
\int_0^1\int_y^1y\sqrt{1+x^3}dxdy&=\int_0^1\int_0^xy\sqrt{1+x^3}dydx\\
&=\frac12\int_0^1\sqrt{1+x^3}\left[y^2\right]_0^xdx\\
&=\frac12\int_0^1x^2\sqrt{1+x^3}dx\;.
\end{align*}$$
That last integral is straightforward.


Concentration bounds for dependent Bernoulli random variables

Question: Let $X_0,X_1,...,X_T$ be independent random variables from $\mathcal{N}(0,1)$.
Define $Y_t=\mathbb{1}\{ X_t > \max_{i=0,...,t-1}X_i \}$, then $\mathbb{E}[Y_t]=\text{Pr}(X_t > \max_{i=0,...,t-1}X_i)$.
What I want is a bound similar to Chernoff, i.e.,
$$\text{Pr}(\sum_{t=1}^{T}Y_t \geq (1+\delta)\sum_{t=1}^{T}\mathbb{E}[Y_t]) \leq \text{"a small value"}.$$
The method of this question  can give the explicit form of $\sum_{t=1}^{T}\mathbb{E}[Y_t]$.
However, $Y_t$'s are not independent of each other, and martingale inequality doesn't seem to work here. To be specific,  this question may be useful. But this bound holds for conditional expectations.
If the upper bound of Chernoff-type  is difficult to prove, is there a more relaxed bound?
I have done a lot of experiments with $T \in [10^3,10^8]$, and the results show that  $\sum_{t=1}^{T}Y_t \leq 2\sum_{t=1}^{T}\mathbb{E}[Y_t]$ is always true. The results are consistent when $X_i$'s come from a uniform distribution.
Answer: From symmetry, since any of $X_0,X_1,\dots,X_t$ is equally likely to  be the largest one (and there are no ties as $X$s are continuous random variables) we get $\mathbb{P}(Y_t=1)=\frac1{t+1}$, so if $S=\sum_{t=1}^{T}Y_t$ then $\mathbb{E}[S]=\frac12+\frac13+\dots+\frac1{T+1}=\ln(T)+\gamma-1+o(1)$.
Also, $Y_i$'s are independent, as for $j>i$ the fact that $X_j$ is the largest amongst $X_0,X_1,\dots,X_i,X_{i+1},\dots, X_j$ is irrelevant to the fact that $X_i$ is the largest amongst $X_0,X_1,\dots,X_i$; the second largest amongst $X_0,X_1,\dots, X_j$ is equally likely to be any of $X_0,X_1,\dots, X_{j-1}$.
Hence $Var(S)=\sum_{k=2}^{T+1} \frac1k\left(1-\frac1k\right)=\mathbb{E}[T]+O(1)$.
Now you can use Chebyshev's inequality.
Comment: $Y_i$'s are independent is  hard to understand at first. Thank you.


Windows Server 2008 R2 Terminal Server (RDS) redirected printers

Question: I'm sure this has come up a million times but i'm looking for a quick answer / solution. I have a client that uses a database program that creates an .ini file for printer settings. The problem is that everytime the enduser logs in her printer is redirected to a "TSXXX" port. this port is constantly changing which is of course normal, but each time she logs in since it has changed the .ini file entry for the printer is incorrect as it has changed. The EU then has to go through the whole printer setup each time she logs in to the TS. Is there a way to statically assign the port? or some how make it constant so each time she log in the port remains the same?
Comment: If it's not possible, can you share her printer out and install it on the 2008R2 server?
Answer: The ugly: make a batch that find the port and update the ini file at logon.
Exemple of script to parse printer (vbscript) (it set default printer to MYSPECIALPRINTER):
use objprinter attributes (Path i think) to get tsclient path
<code>Set objNetwork = CreateObject("WScript.Network")
Set objWMIService = GetObject("winmgmts:" & _
    "{impersonationLevel=Impersonate}!\\" & "." & "\root\cimv2")
Set colInstalledPrinters = objWMIService.ExecQuery _
        ("SELECT * FROM Win32_Printer")
    For Each objPrinter in colInstalledPrinters
        '''wscript.echo ("Imprimante : " & objPrinter.Name & VbCrLf)
        If (left(LCase(objPrinter.name),4) = "MYSPECIALPRINTER") then

            objNetwork.SetDefaultPrinter(objPrinter.Name)
''wscript.echo ("Imprimante : " & objPrinter.Name & VbCrLf)

        End If

    Next
</code>


How to make the dialog in the HTML page to select a local file path?

Question: I am writing a server application that has a web interface for configuration. Some of the options - the paths to local files. Now it's just
<input type = "text" ... >

but I want a button opening the file selector. I know that there is
<input type="file"...>,

but it does not allow then to get the path. This is implemented in different ways in different browsers. Sometimes the path is empty, sometimes it is fake. This is due to the security policy in your browser, so that attackers have not seen the structure of user file storage. Is it possible to somehow realize that dialogue with the possibility of obtaining the selected file path?
Answer: hmm I don't think you could do it, for the rules you already mentioned. The only bug you could use would be:

Restrict the usage of getting dynamic path only under IE
Implement ActiveX management from IE
Communicate with windows' API "GetOpenFileName"

This is really dirty but if you don't mind here is a solution.
rgds


SQL Statements should come out the same, but don't

Question:
Possible Duplicate:
SQL NOT IN not working

Hey All,
I have the following two queries:
select distinct ID from db2.tran tr
where ID not in(
select distinct id from db2.tran
join (select distinct id from db1.client) as c on c.id = tr.id)

select distinct id from db2.tran tr
where id not in (select distinct id from db1.client)

Now in my mind, these queries should be equivelant, however, the first one returns rows, and the second one does not.  Am i going crazy or is thier logic behind why these two are not coming out the same.
Thanks
Comment: `WHERE X NOT IN (1,2,NULL)` etc. always returns zero rows as it is equivalent to `X<>1 AND X<>2 AND X<>NULL` and anything `AND UNKNOWN` is `UNKNOWN` not true.
Comment: Does `db1.client` have any `NULL` ids?
Comment: Thanks!  that solved the problem.  I'm suprised i never ran into this issue before (guess i just kept my data cleaner than others programmers  ;)
Comment: yes, it does, but I'm not sure why that would cause i difference
Comment: `NOT IN` does not handle `NULL` as you would sometimes expect.
Comment: Is this just an issue with certain DBs?  I'm currently working in SQL server, but i worked 10 years in Oracle and never ran across this problem.
Comment: @Limey - DBs handle `NULL` differently.  Google `ANSI NULLS` in SQL for config options.
Comment: @Limey - Slight amend to my previous comment. `False` and `Unknown` is `False` of course! You might find this interesting http://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/
Answer: With your second query
select distinct id
from   db2.tran tr
where  id not in (select distinct id
                  from   db1.client)

As the sub query brings back NULL values the query as a whole will always return an empty resultset for the reasons described in the comments. (See also SQL and the Snare of Three Valued Logic)
With your first query
select distinct ID
from   db2.tran tr
where  ID not in(select distinct id
                 from   db2.tran
                        join (select distinct id
                              from   db1.client) as c
                          on c.id = tr.id)

One effect of the JOIN condition c.id = tr.id will be to exclude all NULL values from the result of the sub query therefore this issue doesn't arise.
Answer: we have seen very inconsistent results when using IN/NOT IN statements.
this should also be equivalent:
SELECT
distinct ID
FROM db2.tran tr
where ID NOT IN (

   SELECT distinct a.id from db2.tran a join db1.client b on (a.id = b.id)

)

Comment: This isn't really an answer.  FWIW the issue is `NULL` and `NOT IN` - `NOT IN` fails when it hits `NULL` since you can't say for certain that a value is `NOT IN NULL` as `NULL` is unknown.


Using jquery to get an alt attribute with a link

Question: One jquery plugin that I know supports links in the captions is the NIVO slider. Basically what I have is a jquery plugin that uses the alt attribute of an image to display it as a caption. I was wondering how difficult it would be to reference a DIV in the alt attribute and have it display the DIV.
Here's the jquery:
<code>$('.thumb_container').click(function(){

      var handler = $(this).find('.large_image');
      var newsrc  = handler.attr('src');
      var newcaption  = handler.attr("alt");
      loadPhoto(newsrc, newcaption);

 });
</code>
So what I want is the alt attribute of an image to reference a DIV (i.e. alt="#example") and in the DIV will be a link that will be shown as the caption. Is there any easy way to do this? What I have above works, but the caption displays #example not what is in the #example DIV.
Answer: try this:
<code>$('.thumb_container').click(function(){
    var handler = $(this).find('.large_image');
    var newsrc  = handler.attr('src');
    var newcaption  = $(handler.attr("alt")).html();
    loadPhoto(newsrc, newcaption);
});
</code>
focus on the jquery selector around handler.attr("alt")
Comment: No, that's not right. `$()` creates a jQuery object, it isn't important (or usable) to display text.
Comment: So you want the text of the div or the div itself?
Comment: The contents of the div. So the text of the div because I have a link in the div.
Comment: If you want the text of the div then you can put .html() or .text() at the end depending on what you want to do.
Comment: Could you elaborate more? Sorry I dont fully understand where you want that tag.
Comment: I lied, I figured it out. Thank you very much.


Can React Router basename be configured to respect asset URLs in CSS?

Question: I am using BrowserRouter as Router from react-router-dom. I want to host my application at a path that is not /. I used the basename attribute on the router tag, and it works great.
<Router basename={'/my-cool-path'}>

I am referring to images in my react components like this:

The HTML reference works great. But in my CSS files, this breaks:
background-image: url(one.svg);

I tried this but it breaks for prod builds (dev env works) :
background-image: url(/one.svg);

This works, but only for production builds (react-scripts build). It breaks during dev (react-scripts start command).
background-image: url(/my-cool-path/one.svg);

I want to be able to have CSS URL paths that work when I do BOTH a production build and during dev (hot reloading with react-scripts start command).
Any ideas for a solution? Is this possible?
Answer: Short answer: not the way you're hoping.
Problem is, React is Javascript, and your CSS is not handled by Javascript.
You could be saved, if you're compiling CSS - from SCSS for example - you could create a file ie. env-vars.scss, and have it define a variable like $basePath, setting it to /my-cool-path/. ( like $basePath: "/my-cool-path/";)
Import that file into your main scss file, and have git (or whatever repo you use) ignore the file. Then you can manually recreate that file on the server, setting the $basePath to / ( $basePath: "/"; ).
You can then use the $basePath in your urls in scss, say for example background-image: url($basePath + "img/some-background.png");
When ever the scss is compiled, it'll pull the var from that file, and if your repo is ignoring it, you can create different values depending on the environment you're running the compile on.
However building with react-scripts start and react-scripts build might also provide you a way to set an ENV variable and import it into your scss, but I'm not entirely familiar with this so I'd have to direct you to google for that one I'm afraid.
If you're not compiling your CSS from a preprocessor, it'll be a tougher task.
Comment: I understand, sounds like a valid workaround! I turned my css file into a scss file and added the npm package. According to my debugger network tab, the asset URLs are correct! However, the `react scripts start` is serving the app from `/my-cool-path/` and it is serving the app assets from `/` so all the images are broken in dev, but working in prod build. Any idea of how to get the dev env to serve assets from `/my-cool-path/`?


Como definir a opacidade de um elemento de dentro de uma div maior que o da própria div

Question: Como pode-se ver, a opacidade do button está maior que a da div, mas mesmo assim ele está na mesma opacidade, como eu poderia mudar isso ??

.div1
{
  width: 100px;
  height: 100px;
  background: #6a6a6a;
  opacity: 0.5;
}
.button
{
  width: 50px;
  height: 50px;
  margin-left: 25px;
  margin-top: 25px;
  opacity: 1.0;
}

  <input type="image" class="button" src="https://image.freepik.com/free-icon/users-group_318-48680.jpg">

Comment: .button
{
  width: 50px;
  height: 50px;
  margin-left: 25px;
  margin-top: 25px;
  opacity: 1.0;
}

Note que, a opacity está marcada como 1.0, isto equivale a sua opacidade normal (100%), para poder usar um uma opacidade menor, atribua (0.1 até 0.9)
Answer: Você pode fazer usando position absolute e posicionando um em cima do outro.
.div1
{
  width: 100px;
  height: 100px;
  background: #6a6a6a;
  opacity: 0.5;
  position:absolute;
  z-index:1;
}
.button
{
  width: 50px;
  height: 50px;
  top:25px;
  left:25px;
  opacity: 1.0;
  position:absolute;
  z-index:2;
}

Dependendo da cor do background você pode alterar a própria cor do elemento principal e definir uma opacidade para ela:
div1{
   width: 100px;
   height: 100px;
   background: rgba(106, 106, 106, 0.5);
}

Answer: Boa tarde.
Notei que o button está com o valor original da imagem definido em opacidade, o que não implicará em qualquer mudança, teste este código e veja se os problemas foram sanados.

.div1{
  width: 100px;
  height: 100px;
  background: #6a6a6a;
  opacity: 0.5; /*Neste caso, utilize de 0.1 até 0.9 para definir uma opacidade, e 1.0 para seu valor original.*/
}

.button{
  width: 50px;
  height: 50px;
  margin-left: 25px;
  margin-top: 25px;
 opacity: 0.5;

}

    <title>Teste</title>

  <input type="image" class="button" src="https://image.freepik.com/free-icon/users-group_318-48680.jpg">

Answer: O que esta acontecendo é o seguinte, seu elemento div1 esta com opacidade 0.5 ou seja tudo que estiver dentro dele vai fica com opacidade, se você quer um background transparente a melhor opção é usar cores no formato rgba segue exemplo:

.div1
{
  width: 100px;
  height: 100px;
  background-color: rgba(106, 106, 106, 0.5);
}
.button
{
  width: 50px;
  height: 50px;
  margin-left: 25px;
  margin-top: 25px;
}

  <input type="image" class="button" src="https://image.freepik.com/free-icon/users-group_318-48680.jpg">

Observe que converti sua cor de hexadecimal para rgba.
Comment: Sim, porem algumas cores acredito que não fiquem igual, como por exemplo, essa `#69e673`;
Comment: @LucasCarezia como assim? tudo depende de quanto vc quer de transparência um bg black com opacidade 0.5 equivale a `rgba(0,0,0,.5)`


mkdir permission error while importing email@example.com with email@example.com

Question: While I am trying to import email@example.com using Node 10.9.0, I am getting below error,
oracledb Beginning installation
oracledb Verifying installation
oracledb Continuing installation
oracledb ERR! NJS-054: Binary build/Release/oracledb.node was not installed.
oracledb ERR! Failed to install binary package oracledb-v3.0.0-node-abi64-linux-x64.gz
oracledb ERR! EACCES: permission denied, mkdir 'build'
oracledb ERR! For help see https://oracle.github.io/node-oracledb/INSTALL.html#troubleshooting

Since above code seems to be permission issue, I also tried sudo npm i email@example.com but then it gives below error
sudo: npm: command not found

Question:
How can I give permission to create directory or execute command npm with sudo rights, any help would be deeply appreciated.
Answer: Utilize --unsafe-perm=true and --allow-root flags with npm install.
npm install -g email@example.com --unsafe-perm=true --allow-root

You can read more o this here : https://docs.npmjs.com/getting-started/fixing-npm-permissions

mkdir permission error while importing oracledb@3.0.0 with Node@10.9.0


"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

Question: I use Anaconda 1.7, 32 bit. I downloaded the correct version of the netCDF4 installer from here.
I attempted to copy the HKEY_LOCAL_MACHINE\SOFTWARE\Python folder into HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node. No luck.
Does anyone have any idea why this might be happening? Anaconda installed in the default location, C:/.
Yes, I know Anaconda has netCDF4 in the packages list - but if you look closely, it's only offered for Mac and Linux.
Answer: This error can occur if you are installing a package with a different bitness than your Python version.  To see whether your Python installation is 32- or 64-bit, see here.
Some superpacks (e.g. for Scipy) available on SourceForge or python.org are for 32-bit systems and some are for 64-bit systems. See this answer. In Windows, uninstalling the 32-bit and installing the 64-bit version (or vice versa if your installation is 32-bit) can solve the problem.
Comment: Thanks, I had Python 2.6.5(x64)and PSUTIL for 2.6 is only available in x86. I just had to switch my Python version to x86
Answer: I had the same issue when using an .exe to install a Python package (because I use Anaconda and it didn't add Python to the registry). I fixed the problem by running this script:
#
# script to register Python 2.0 or later for use with
# Python extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://email@example.com/msg10512.html

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_CURRENT_USER, regpath)
    except EnvironmentError as e:
        try:
            reg = CreateKey(HKEY_CURRENT_USER, regpath)
            SetValue(reg, installkey, REG_SZ, installpath)
            SetValue(reg, pythonkey, REG_SZ, pythonpath)
            CloseKey(reg)
        except:
            print "*** Unable to register!"
            return
        print "--- Python", version, "is now registered!"
        return
    if (QueryValue(reg, installkey) == installpath and
        QueryValue(reg, pythonkey) == pythonpath):
        CloseKey(reg)
        print "=== Python", version, "is already registered!"
        return
    CloseKey(reg)
    print "*** Unable to register!"
    print "*** You probably have another Python installation!"

if __name__ == "__main__":
    RegisterPy()

Comment: For python 3, just add parentheses around the `print` calls, and replace `import _winreg` by `import winreg` and it works perfectly
Comment: you shall be named "The Oracle"
Comment: God bless you. Thanks
Comment: OK @duahime, but automatic (programmatically) operations on the Registry are not safe at all. That's why people ALWAYS suggest manual solutions. So, can you please also write how to do all that manually, in just 2-3 lines (which is usually all that it takes)?
Answer: Try the steps described here:
http://avaminzhang.wordpress.com/2011/11/24/python-version-2-7-required-which-was-not-found-in-the-registry/
Answer: Just download Python 2.7.6 Windows Installer from the official Python download page, and launch the install package.
Comment: That's not too helpful. The same error may still occur, e.g. if you want to install two versions of Python, and then the Windows installer fails just the same. I think it would really be better to look at what the reason is here.
Comment: @SirJane:  I agree it could be 32 vs. 64-bit difference. The link goes to 32-bit version of Python that should work.
Comment: True, for this case your suggestion should work. But this error can also arise when you install 3.x before 2.x, and then the installer doesn't solve the problem, see my little answer below.
Comment: @SirJane: I cannot confirm that. I usually have at least the last Python 2, and the last Python 3 side-by-side. Besides the Python 2.7 and 3.5, I often have Python 2.x or Python 3.x with different subversions for trying some features of some packages or trying to solve the problem of others. Having all the versions installed at the same time, I never had problems like that with official distributions of Python for Windows.
Answer: I think it really depends on why this error is given. It may be the bitness issue, but it may also be because of a deinstaller bug that leaves registry entries behind.
I just had this case because I need two versions of Python on my system. When I tried to install SCons (using Python2), the .msi installer failed, saying it only found Python3 in the registry. So I uninstalled it, with the result that no Python was found at all. Frustrating! (workaround: install SCons with  pip install --egg --upgrade scons)
Anyway, I'm sure there are threads on that phenomenon. I just thought it would fit here because this was one of my top search results.
Comment: In my case I was trying to install amd64 package on win32 python, your comment opened my eyes
Answer: I had such problem. Solution was simple :

Install python 2.7 64bit version.
Export HKEY_LOCAL_MACHINE\SOFTWARE\Python.
Remove Python 2.7.
insert exported reg file.
rename all C:\Python27 to C:\Anaconda ( insert your path ).

P.S. Sorry, for bad grammar.
Answer: Check for the 32/64 bit you trying to install. both python interpreter and your app which trying to use python might be of different bit.


Azure CORS Not working after configured

Question: As a learning exercise I have created an Azure mobile service, added a very similar implementation to their TODO list example. I have deployed to Azure and configured the allowed origin (to an MVC site that I have also deployed to azure):
http://mr-mob-html-test.azurewebsites.net
I have re-started the service and try * as suggested by the configuration screen, however I keep getting this issue (which I am sure is CORS related):

XMLHttpRequest cannot load https://mr-todolist-dotnet.azure-mobile.net/tables/EventItem. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <code>'http://mr-mob-html-test.azurewebsites.net'</code> is therefore not allowed access. The response had HTTP status code 400.

Am I missing something?
Answer: Finally I found the problem in case someone happens to have the same issue.
I was testing the mobile service in my machine and modified the web.config adding a couple of origins for my localhost, I guess this was interfering with the configuration in the portal. I just added the new origin to the Web.config and re-published it:

I haven't tried removing this configuration and only trying with the configuration through the portal.
Anyway I hope this helps.

Azure CORS Not working after configured


How to make ASP.Net WebAPI Server available on LAN

Question: I'm trying to Host ASP.NET WebAPI and make that available for all devices connected on the LAN.
I can able to access the API from my localhost
Getting Proper Response from API
When i try to access the API from Other computer in the same LAN, API is getting into Bad Request - Invalid Hostname HTTP Error 400
Bad Request - Invalid Hostname
I have also added the Inbound Rules for port number 52022
My binding configuration in

C:\Users***\Documents\IISExpress\config\applicationhost.config

<code>       <sites>
            <site name="WebSite1" id="1" serverAutoStart="true">
                <application path="/">
                    <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:52022:localhost" />
                    <binding protocol="http" bindingInformation="*:52022:" />
                </bindings>
            </site>
            <siteDefaults>
                <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
                <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
            </siteDefaults>
            <applicationDefaults applicationPool="Clr4IntegratedAppPool" />
            <virtualDirectoryDefaults allowSubDirConfig="true" />
        </sites>
</code>
Still I could not be able to access API from another Computer which are connected in the same LAN.
Answer: In order to make Web application available on Lan Simply You need to deploy your service on local host.
Here are some links
Deploy web api on localhost
and
Deploy asp.net web api on localhost
Comment: I have published my webapi project as file type like you mentioned but still I couldn't able to access my API
Comment: https://drive.google.com/open?id=0Byrmhv4D-ohEc1VTd1dIVHVDdlE  See the error screenshot
Comment: Please check out your web config file
Comment: What kind of configurations should be checked in web config file.
Comment: Please check for the connection string and permissions.
Comment: ok, thank you. I have check connection string that is fine. What kind of permission should I give.
Comment: I have reconfigured my web configuration file.


Terminal window won't stay open when running popen via ssh in Python

Question: I'm writing a Python program that runs on Linux server. It monitors some log file and displays lines from that log file in a GUI, based on a given keyword.
I added a new feature that opens a terminal window with "less" showing the line that the user double-clicked on in my program.
My problem is this:
When i run my program locally (on my computer) it works perfectly.
But when I run my program from the main server while connected to it via SSH,
the programs runs well, but when I double-click one of the lines, I see a console window that opens and closes quickly.
Here is the code that responsible for opening the "Less Terminal":
p = subprocess.Popen(args = ["gnome-terminal", "--command = less -p " + "\"" +searchString + "\"" " -j 10 " + "\"" + path + "\""], stdout = subprocess.PIPE)

How can I keep it open?
P.S. If I add shell = TRUE, it just opens a new terminal window without the less results.
Comment: This is not a solution, but if you add `&& read` to the end of your string, you should be able to see what it outputs (waits for user input before continuing)
Answer: My problem wasn't related to ssh; I managed to recreate it on my local machine. When testing the program locally, I used short pattern strings for testing, but when I moved to the server and started to use the actual strings, they were too big!
What happened is: I gave less a pattern bigger then 99 chars. And I got: "ungetcc overflow", a known bug, which was subsequently fixed in version 438 of less.
Answer: It work for me
if sys.platform != "win32": sp.Popen(command.split(), shell=False)
else: sp.Popen(command.split(), shell=True)


What is the process by which singers identify their voice type/fach?

Question: I am trying to gain insight about the process by which vocalists identify their voice type or fach. I am not looking for any discussion about the basic distinctions between, say, soprano and alto. Voice types, such as coloratura soprano or lyric soprano, often overlap in many ways. There are several factors including range, tessitura, and voice color, that go into voice type, and as I said, there are various overlaps between types based on these qualities. Further, the roles associated with some fachs can be performed by those in a different fach.
Still further, these types are only categories; every human voice has its own unique characteristics that may generally resemble one type or another, but may have interesting quirks. Lastly, the voice evolves over many many years, generally not settling until late 20's or even 30's (and even that might not be the end of it), further confusing issues regarding specific voice type.
My question is, with all of this ambiguity and complexity, how does a vocalist and their teacher reach conclusions about what voice type they belong to? How does that process evolve over time?
I should note that I am fairly familiar with this process from first-hand experience as a sometimes-singer, although I'm not really looking for information for my use as a singer but to better understand singers as a conductor. I am looking for specific anecdotes and/or knowledge from singers who have gone through this process of discovery.
Answer: To answer your question head on, an experienced teacher will listen to the student's voice for all the qualities you mentioned: "range, tessitura, and voice color". The teacher will then mentally compare those qualities to other singers that they know. They will also be comparing that voice to the kinds of voices they are used to hearing in various roles. In some cases the singer will be a clear fit in one of the fachs, in others the voice will sit between fachs, be suitable to sing multiple fachs, or perhaps be capable of only a subset of one fach. Of course, the voice matures as it ages and as the singers technique changes, so this assessment is fluid and should be constantly reconsidered. These assessments are also fluid depending on the production. A voice that can sing heavy repertoire in a small house with a reduced orchestra may only be suitable for lighter repertoire in a big house with a full orchestra.
Unfortunately, much like musical genres often do a poor job of defining the subtleties of music, the human body and composer's imaginations don't conform very tightly to our categorical constructs. That being said, we need a vocabulary to discuss and even internally proces the qualities that make a voice suite a role and, like musical genres, this is the best method we have.
When I was doing my undergraduate degree in voice, I became very frustrated with singers over identifying with a fach and either limiting themselves, over extending themselves, or trying to learn repertoire that would probably be in their future but was not yet healthy for their voice. To help combat that trend, I started a website that skips the system of fach pigeon-holes and helps singers find appropriate roles directly.
The website asks a singer for roles which they feel suit their voice right now, and then searches through it's database of over 16,000 singers careers for singers who sang those roles. The site then lists other roles most commonly performed by those singers.
It's not a silver bullet but it's a useful tool for brainstorming and it has the advantage that it's based on actual data. If your curious you can find it here:

http://fachme.com

For a very insightful 45 minute discussion on this exact topic with Nathan Gunn, Nicola Luisotti and Sheri Greenawald check out the VoiceBox podcast hosted by Choloe Veltman. Their website does not have a link directly to the episode, but the mp3 can be found here. (Full disclosure: They mention my website in this interview)


Standard deviation of $x_1,x_2,x_3,....,x_{18}$

Question: If $\sum^{18}_{i=1} (x_i-8)=9$ and $\sum^{18}_{i=1} (x_i-8)^2=45$, then find standard deviation of $x_1,x_2,x_3,...,x_{18}$
Using $\sum^{18}_{i=1} (x_i-8)=9$, I got mean mean of $x_1,x_2,x_3,...,x_{18}$ as $\frac{17}{2}$ but how to use second condition to find variance so that standard deviation can be found?
Answer: \begin{align}\sum_{i=1}^{18}(x_i-8.5)^2=\sum_{i=1}^{18}(x_i-8-0.5)^2=\sum_{i=1}^{18}(x_i-8)^2-\sum_{i=1}^{18}2\cdot0.5\cdot(x_i-8)+\sum_{i=1}^{18}0.5^2\end{align}
Answer: $$\sum^{18}_{i=1} (x_i-8)=-8\times 18+\sum^{18}_{i=1}x_i=9$$
thus
$$\sum^{18}_{i=1}x_i=153\implies \bar x=\frac{153}{18}=8.5$$
on the other hand
$$\sum^{18}_{i=1} (x_i-8)^2=\sum^{18}_{i=1}x_i^2-16\sum^{18}_{i=1}x_i+64\times 18=45$$
therefore
$$\sum^{18}_{i=1}x_i^2=1341$$
Finally we have
$$\frac{\sum^{18}_{i=1}x_i^2}{18}-\bar x^2=\frac{1341}{18}-8.5^2$$


Rails Search with query

Question: I want to filter jobs on the parameter passed onto the model, currently search works flawlessly without query passed into the model, but when I type query it doesn't return anything. How can I perform this query with query and criteria.
results << model.with_query(query).where(criteria). any idea would be really appreciated.
module Refinery
  class SearchEngine
    # How many results should we show per page
    RESULTS_LIMIT = 100

    # Perform search over the specified models

    def self.search(query, job_region, job_division, country, job_type, page = 1)
      results = []

      Refinery.searchable_models.each do |model|

      criteria = {:job_region => job_region,
                    :job_division => job_division,
                    :country => country,
                    :job_type => job_type

        }.select { |key, value| value.present? }

        if query.present?
          results << model.with_query(query).where(criteria)
        else
          results << model.limit(RESULTS_LIMIT).where(criteria)
        end

      end

      results.flatten[0..(RESULTS_LIMIT - 1)]
    end

  end
end

Comment: It may sounds stupid but try the other way: `model.where(criteria).with_query(query)` (where returns an ActiveRecord::Relation which is able to chain-scope, and maybe .with_query just returns an Array)
Comment: what is the expected content of "query"? Raw SQL? A hash of conditions?
Comment: Hash of conditions, if there is no query pass into model it returns what is expected, but with_query it doesn't work. I am using act_as_index gem to perform query search.
Comment: MrYoshiji, this is not stupid, this is magic :-). it is working now. really appreciated for your time. thank you
Answer: The problem here is that the method .with_query(qry) returns an Array. You want to do chain-scoping, so you must use scopes that returns ActiveRecord::Relation objects.
model.with_query(query)
# returns an Array

model.with_query(query).where(criteria)
# calling .where on an Array object => NoMethodError

model.where(criteria)
# returns an ActiveRecord::Relation

model.where(criteria).with_query(query)
# calls the query on an AR::Relation object, which is doable

Short version: Change this:
results << model.with_query(query).where(criteria)

To this:
results << model.where(criteria).with_query(query)

Rails Search with query


Abnormal feature of Java where Multiple Inheritance is visible

Question: The Oracle docs states very clearly that Java Language has no Multiple Inheritance feature i.e. Any class declared in Java cannot inherit features from two separate classes.
But there lies a statement that Class Object is the super class of every other class created by user.
Consider a sample Class as follows:
Class Base {
.....
}

Class Derived extends Base {
.....
}

Now if we look onto Class Derived then it is clearly visible that it inherits from Class Base and also from Class Object, then that proves that Java does has Multiple Inheritance.
Solution as provided from one of the pages of Oracle Sites
Excepting Object, which has no superclass,
every class has one and only one direct superclass (single inheritance).
In the absence of any other explicit superclass,
every class is implicitly a subclass of Object.

This means that any class which doesn't have a single-inheritance available will only have an implicit single-inheritance with Class Object.
Refer
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Comment: It is Multilevel inheritance not Multiple Inheritance.
Comment: No my friend... Class Derived doesnt directly extend Object... The Highest Level parent of class Derived extends Object. i.e, here Base extends object.
Comment: I can't see any thing like multiple inheritance here. We normally call multiple inheritance if one class has more than one parent class. `Java` never ever had that.
Comment: `Derived -> Base -> Object`
Comment: Java does not have multiple inheritance. `Base` inherits from `Object`, if it isn't one of the primitive types (or an enum) then it is an Object in Java.
Comment: possible duplicate of [Multiple Inheritance](http://stackoverflow.com/questions/3466783/multiple-inheritance)
Comment: @gowtham - Please remember that interfaces were not introduced to support multiple inheritance in Java.
Comment: ya Agreed and corrected myself
Comment: My question is mistaken. Before I get further down votes, I would like to share a material read from Oracle Sites
http://www.oracle.com/technetwork/java/object-142075.html#6681

"Ultimately, all classes eventually inherit from the Object class, forming a tree structure with Object as its root."

Oracle sites clearly state that every class created by user has class Object as its superclass.
Comment: Please find the solution in the question section
Answer: One could modify your code to
class Base extends Object{
.....
}

class Derived extends Base {
.....
}

So since only Base (and not Derived) extends Object, the class Derived inherits Object through Base, no multiple inheritance exists that way.
Answer: If one class has(extends ) more than one parent class we called it as multiple inheritance. In Java never ever had that, In this case just a multi level inheritance not multiple inheritance.
Answer: This is a case of Multi-Level Inheritance not Multiple Inheritance.

Multiple Inheritance : we can inherit more than one class in the same class.

Multi-Level Inheritance: where one class can inherit only one base
  class and the derived class can become base class of some other class
Comment: Please find the solution in the question section
Answer: In Java, you can't extend from 2 separate class hierarchies. However, you can have multiple classes within a hierarchy. One class definition can have only one "extends" in it.
For example, Mammal extends Animal and Dog extends Mammal is acceptable. Dog will get the behaviors and states of Mammal and Animal (through Mammal).
What is not allowed is one class extending multiple classes.
So in your example, if you have 2 base classes BaseA and BaseB, class Derived cannot extend both BaseA and BaseB at the same time.
Comment: Please find the solution in the question section
Answer: I think you're misunderstanding inheritance.
Multiple inheritance allows a class to inherit the properties of two distinct classes.  From Wikipedia, here is an illustration of one such hierarchy (known as the "diamond problem"):

Take note:  D is inheriting from both B and C.
To bring it to a better illustration, multiple inheritance would allow you to have a class structure like this:
public class Bike {
    // properties of a bike
}

public class Car {
    // properties of a car, namely that it has a motor
}

public class Moped extends Bike, Car {
    // properties inherited combine that it is both a Bike and a Car
}

The current way that Java classes are wired now is that their inheritance is hierarchal; that is, one class may only ever have one parent class.
A good way to think of inheritance in this manner is the "is-a" relationship test.
For your example:

A Derived is a Base.
A Base is an Object.
A Derived is an Object.
Comment: Please find the solution in the question section


Pandas read_csv() - Case insensitive column names for converters/dtypes

Question: I'm using pd.read_csv() to load file that might have column names of unknown case. Using lambda for usecols argument as described here, I can choose which columns to load regardless the case, and with method from here I can access these columns like this:
df = pd.read_csv(myfile, usecols=lambda x: x.lower() in ['foo', 'bar'])
df.columns = df.columns.str.lower()

print(df['foo'])  # Works no matter which column name case is in the file

But is there a way to use the dtypes/converters parameters in this case?
I had two workaround ideas in mind:

Load all the data as strings and do the conversions in my code later. This seems way less performant.
Open the file just to read the header, analyze it, then open again with prior knowledge of the actual case of the column names (wrap it all as a function).

Are there other approaches?
Answer: You can read in just the first line of data to grab the columns. I'd recommend doing this via the built-in csv module, or even with pandas since they'll both have easy handling of quoting.
Using pandas you can do something like this:
from io import StringIO
from pandas import read_csv

data = StringIO('''
a,B,c,D
1,2,3,4
5,6,7,7
'''.strip())

# expected lower-case column names mapped to dtypes
# intentionally left out column 'D'
dtypes = {'a': 'Int64', 'b': 'int32', 'c': 'float64'}

# `nrows=0` will only read in the column names and an empty DataFrame
columns = read_csv(data, nrows=0).columns

# only need to do this since `data` acts as an open file-handle
data.seek(0)

# create mapping of actual column names → dtype based on a matching `.casefold()`
#  if you're unfamiliar with `string.casefold()` you can think of it like `string.lower()`
new_dtypes = {
    col: dtypes[col.casefold()]
    for col in columns if col.casefold() in dtypes
}
df = read_csv(data, usecols=new_dtypes.keys(), dtype=new_dtypes)

print(df)
   a  B    c
0  1  2  3.0
1  5  6  7.0

Comment: So basically, you say my 2nd workaround is the best approach. Thanks!


Como eliminar valores em uma coluna de texto de um arquivo csv no R?

Question: Eu estou aprendendo R e preciso de ajuda com arquivos CSV. Eu consigo fazer a leitura do arquivo, mas preciso executar operações com algumas colunas:
O arquivo está assim:
1   {date:2018-08-01    state:RN    store_id:3162633    sale_id:326463633336323 off_product_id:613665646663346  quantity:1  price:229.0 customer_id:null}
2   {date:2018-08-01    state:RN    store_id:3162633    sale_id:333331346330323 off_product_id:343739666265353  quantity:1  price:179.0 customer_id:null}
3   {date:2018-08-01    state:RN    store_id:3162633    sale_id:393461383633336 off_product_id:373034633762613  quantity:1  price:269.0 customer_id:null}
4   {date:2018-08-01    state:RN    store_id:3162633    sale_id:616531626536373 off_product_id:343634373062363  quantity:1  price:29.0  customer_id:null}
5   {date:2018-08-01    state:RN    store_id:3162633    sale_id:626462353638383 off_product_id:616339353035393  quantity:1  price:459.0 customer_id:null}
6   {date:2018-08-01    state:RN    store_id:3162633    sale_id:653363623539323 off_product_id:346165376638356  quantity:1  price:369.0 customer_id:null}

Mas eu quero deixar desta forma:
Comment: Adicione a forma que você deixar diretamente à pergunta. (transcreva a imagem)
Answer: dados <- read.table(text =
  "1   {date:2018-08-01    state:RN    store_id:3162633    sale_id:326463633336323 off_product_id:613665646663346  quantity:1  price:229.0 customer_id:null}
   2   {date:2018-08-01    state:RN    store_id:3162633    sale_id:333331346330323 off_product_id:343739666265353  quantity:1  price:179.0 customer_id:null}
   3   {date:2018-08-01    state:RN    store_id:3162633    sale_id:393461383633336 off_product_id:373034633762613  quantity:1  price:269.0 customer_id:null}
   4   {date:2018-08-01    state:RN    store_id:3162633    sale_id:616531626536373 off_product_id:343634373062363  quantity:1  price:29.0  customer_id:null}
   5   {date:2018-08-01    state:RN    store_id:3162633    sale_id:626462353638383 off_product_id:616339353035393  quantity:1  price:459.0 customer_id:null}
   6   {date:2018-08-01    state:RN    store_id:3162633    sale_id:653363623539323 off_product_id:346165376638356  quantity:1  price:369.0 customer_id:null}",
  stringsAsFactors = FALSE)

# Remove a primeira coluna (desnecessária)
dados <- dados[, !(names(dados) %in% "V1")]

# Remove os colchetes
dados[] <- lapply(dados, gsub, pattern = "\\{|\\}", replacement = "")

# Pega os nomes das colunas
colnames(dados) <- gsub(":.*$", "", dados[1,])

# Remove caracteres até ":"
dados[] <- lapply(dados, gsub, pattern = ".*:", replacement = "")

> dados
        date state store_id         sale_id  off_product_id quantity price customer_id
1 2018-08-01    RN  3162633 326463633336323 613665646663346        1 229.0        null
2 2018-08-01    RN  3162633 333331346330323 343739666265353        1 179.0        null
3 2018-08-01    RN  3162633 393461383633336 373034633762613        1 269.0        null
4 2018-08-01    RN  3162633 616531626536373 343634373062363        1  29.0        null
5 2018-08-01    RN  3162633 626462353638383 616339353035393        1 459.0        null
6 2018-08-01    RN  3162633 653363623539323 346165376638356        1 369.0        null

Os dados estarão todos no formato character; você terá o trabalho adicional de converter para os formatos adequados.
Arquivo JSON
Pela aparência dos seus dados brutos, você tem um arquivo JSON que foi erroneamente salvo como CSV. Se é esse caso e é você quem está capturando os dados, corrija o script para salvar no formato json. A leitura pode ser feita de maneira simples e preservando os formatos com o pacote jsonlite:
library(jsonlite)

dados.json <- '[{"date":"2018-08-01","state":"RN","store_id":3162633,"sale_id":326463633336323,"off_product_id":613665646663346,"quantity":1,"price":229.0,"customer_id":"null"},
                {"date":"2018-08-01","state":"RN","store_id":3162633,"sale_id":333331346330323,"off_product_id":343739666265353,"quantity":1,"price":179.0,"customer_id":"null"},
                {"date":"2018-08-01","state":"RN","store_id":3162633,"sale_id":393461383633336,"off_product_id":373034633762613,"quantity":1,"price":269.0,"customer_id":"null"},
                {"date":"2018-08-01","state":"RN","store_id":3162633,"sale_id":616531626536373,"off_product_id":343634373062363,"quantity":1,"price":29.0,"customer_id":"null"},
                {"date":"2018-08-01","state":"RN","store_id":3162633,"sale_id":626462353638383,"off_product_id":616339353035393,"quantity":1,"price":459.0,"customer_id":"null"},
                {"date":"2018-08-01","state":"RN","store_id":3162633,"sale_id":653363623539323,"off_product_id":346165376638356,"quantity":1,"price":369.0,"customer_id":"null"}]'

dados <- fromJSON(dados.json)

> dados
        date state store_id      sale_id off_product_id quantity price customer_id
1 2018-08-01    RN  3162633 3.264636e+14   6.136656e+14        1   229        null
2 2018-08-01    RN  3162633 3.333313e+14   3.437397e+14        1   179        null
3 2018-08-01    RN  3162633 3.934614e+14   3.730346e+14        1   269        null
4 2018-08-01    RN  3162633 6.165316e+14   3.436344e+14        1    29        null
5 2018-08-01    RN  3162633 6.264624e+14   6.163394e+14        1   459        null
6 2018-08-01    RN  3162633 6.533636e+14   3.461654e+14        1   369        null

> str(dados)
'data.frame':   6 obs. of  8 variables:
$ date          : chr  "2018-08-01" "2018-08-01" "2018-08-01" "2018-08-01" ...
$ state         : chr  "RN" "RN" "RN" "RN" ...
$ store_id      : int  3162633 3162633 3162633 3162633 3162633 3162633
$ sale_id       : num  3.26e+14 3.33e+14 3.93e+14 6.17e+14 6.26e+14 ...
$ off_product_id: num  6.14e+14 3.44e+14 3.73e+14 3.44e+14 6.16e+14 ...
$ quantity      : int  1 1 1 1 1 1
$ price         : num  229 179 269 29 459 369
$ customer_id   : chr  "null" "null" "null" "null" ...

Comment: Muito obrigado ajudou muito


Qual a diferença entre parâmetro e argumento?

Question: Sempre utilizei os termos "parâmetro" e "argumento" como se fossem sinônimos: aquilo que é passado para uma função e/ou que a função recebe como entrada. Da mesma forma, tenho lido um e outro termo, em inglês e português, ora sendo usado um ora outro, mas não consegui perceber nenhum critério na escolha entre um e outro.
Há diferença entre eles? Ou são sinônimos mesmo? Já cheguei a pensar que "parâmetro" era o único termo correto (pois é usado na matemática) e que "argumento" era algum erro de tradução, mas depois percebi que não é o caso (em inglês também temos "parameter" e "argument"). Qual a forma correta de se usar esses termos?
Comment: Grande pergunta, sempre tenho a mesma dúvida. Não mais :)
Comment: O parâmetro é a exigência que a função empresa para o valor a ser passado como argumento (que  pode ser válido ou não) :)
Answer: Parâmetro é a variável que irá receber um valor em uma função (ou método) enquanto que um argumento é o valor (que pode originar de uma variável ou expressão) que você passa para a função (ou método).
Você não passa parâmetros, você passa argumentos. Você recebe argumentos também, mas recebe em parâmetros. Você parametriza sua função com informações que virão posteriormente. Você argumenta com o que deseja executar uma função devidamente parametrizada.
Pode haver menos os mais argumentos para cada parâmetro já que existem parâmetros que são opcionais e outros que podem ser listas variáveis de dados. Portanto não há uma relação de um para um e a distinção entre eles é importante.
Frequentemente é confundido por todos e eu mesmo admito que intercambio os termos erroneamente, mas para uma boa comunicação é importante todos saberem o correto.
Achei uma pergunta no SO com algumas respostas sobre o assunto.
Exemplo
void Func1(int i, bool flag = true) { //declarou dois parâmetros
    // execução
}

void Func2(params int[] lista) { //declarou um parâmetro
    //execução
}

void Func3(bool x, bool y) {
    int z = 0;
    Func1(1); //chamou com 1 argumento
    Func1(z, x && y); //chamou com dois argumentos vindos de variável e expressão respectivamente
    Func2(1, 2, 3); //chamou com 3 argumentos
    Func1(flag : false, i : 2); //argumentos nomeados
}

Coloquei no GitHub para referência futura.
Lembrando que todos os parâmetros são nomeados. Pelo menos é assim na maioria das linguagens. O nome da variável é o nome do parâmetro.
Em linguagens dinâmicas a falta de relação direta entre parâmetros e argumentos fica ainda mais evidente.
Veja um detalhe importante sobre como pegar argumentos no primeiro comentário do mgibsonbr abaixo. Existem outras linguagens que possuem recurso semelhante. É possível acessar os argumentos sem saber exatamente quais são os parâmetros.
Comment: Faz sentido: JavaScript por exemplo expõe a lista de valores usados na chamada através da variável `arguments` - que pode ter tamanho maior ou menor que o número de parâmetros declarados. E em linguagens que aceitam parâmetros opcionais e/ou parâmetros *default*, não importa como a função foi chamada, o seu corpo sempre tem acesso a uma lista fixa de variáveis (ainda que com valores nulos). Nunca tinha pensado dessa forma...
Comment: @mgibsonbr é, você tem acesso desta forma à lista de *argumentos* e não de parâmetros declarados. Em tese poderia ter acesso ao parâmetros também, mas em geral a utilidade seria limitada. Não sei em JS (provavelmente dá pela filosofia da linguagem), mas em Java e C# você consegue obter a lista de parâmetros por *reflection* (isto você sabe :) )
Comment: Isso é desnecessário em JavaScript porque não existe sobrecarga de funções, nem tipos estáticos, e qualquer função pode ser chamada com qualquer número de, aham, argumentos (já estou me acostumando... :P). O máximo que você consegue é obter o número de parâmetros formais, através da propriedade `length` ([fonte](http://stackoverflow.com/q/4833399/520779)).
Comment: Em JavaScript o único jeito de conseguir a lista de parâmetros é obter o código-fonte da função com `toString()` e parseá-los da própria declaração (não funciona com funções *built-in*). Mas eu nunca precisei disso... @mgibsonbr
Comment: Não sei se é besteira o que estou falando: Mas então por que no `python` declaramos def `fn(**kwargs)` ao invés de `def fn(**kwparams)`????
Comment: Porque a variável `kwargs` é um parâmetro, mas o conteúdo dela é uma lista de argumentos. O nome das variáveis devem dizer o que tem nelas, não o que elas são no código.
Comment: @GabrielKatakura pode ser mesmo, pode ser que seja usado em âmbito acadêmico, talvez em âmbito específico, ou em outro âmbito. Nenhum local que pesquisei fala sobre isso. O que obviamente só quer dizer isso mesmo. De maneira nenhuma estou dizendo que está errado, pelo contrário, faz muito sentido, ainda que eu não goste dessa definição. Talvez possa dar uma resposta. Se tiver alguma referência que fala sobre isso ajudaria um pouco, mas nada que seja obrigatório. Eu acredito em você. Eu acho seu ultimo comentário contraditório, diz que aceita, mas não aceita... :) Se aceitar é isso mesmo.
Comment: Não tenho tanta autoridade no assunto porque não vi tantos debates sobre os termos (então se tiver referência e como refutar, estou de braços abertos), mas nos meus estudos acadêmicos eu aprendi que os valores passados na chamada da função (que aqui está sendo chamado de "argumentos") são conhecidos como os parâmetros reais e os que são definidos no cabeçalho da função/procedimento são os parâmetros formais.
Comment: Eu sei que o pessoal abstrai a ideia de parâmetros reais como "argumentos", isso é válido, assim como o pessoal abstrai a ideia de parâmetros formais somente falando que são parâmetros... eu não vejo problema nisso, mas eu discordo no fato de dizer que "Você não passa parâmetros"... porque argumentos são parâmetros reais.
Answer: A função define o parâmetro, e o código de chamada passa o argumento a esse parâmetro.

Por analogia, podemos considerar o parâmetro como um espaço de estacionamento e o argumento como um automóvel.
Portanto ...

Parâmetros

São definidos na declaração (ou assinatura) da função/método;
Os parâmetros de uma função recebem os argumentos;
O nome de cada parâmetro serve como uma variável local dentro da função;
Uma boa mnemónica é pensar que um Parâmetro é como um Placeholder para um Potencial valor.

Argumentos

Representam os valores/variáveis atuais passadas para os parâmetros da função, quando é invocada;
Cada argumento corresponde a um parâmetro (na mesma posição);
Uma boa mnemónica é pensar que um Argumento é o valor Atual.
Comment: Essas analogias são muito boas para explicar o assunto.
Comment: Show! Com a ilustração ficou melhor ainda.
Answer: Um parâmetro é a variável que declaras na signature da função. Um argumento é o valor que passas á variável quando chamas a função. Mas esta distinção é puramente convencional.
Answer: Parâmetros
Parâmetro representa um valor que o procedimento espera que você passe quando você chamá-lo. A declaração do procedimento define os seus parâmetros.
Argumentos
Um argumento representa o valor que você passa para um parâmetro de procedimento, quando você chama o procedimento. O código de chamada fornece os argumentos quando chama o procedimento.
Answer: A maioria dos programadores utiliza estes termos sem distinção de significado. Na prática, falar o termo errado ou certo não fará o código funcionar ou não, isso dependerá de você, mas sempre é bom saber e entender as diferenças.
Imagine um parâmetro como uma variável que pode ser recebida por uma função ou um método. Para entender melhor veja esse exemplo em JavaScript:
function somar(param1, param2) {
   return param1 + param2;
};

Essa função irá sempre receber dois parâmetros (param1 e param2). Além disso a sua saída sempre dependerá necessariamente da entrada. Portanto, com essa pequena explicação já podemos concluir que o parâmetro sempre estará vinculado a sua entrada.
As regras para como os parâmetros são passados para as funções são determinados pela linguagem de programação, por exemplo, essas regras pode especificar a ordem dos parâmetros, se serão passados da esquerda para direita, ou o contrário. Além disso as regras podem definir se os parâmetros serão passados por referência ou valor.
Observação: Os parâmetros podem ser de qualquer tipo, um array, um inteiro, uma String, ou outro tipo de dado (claro que isso varia nas linguagens de programação).
Por um outro lado temos o argumento, que seria o valor passado (pode ser mais que um) a função na hora de sua chamada. Veja:
let valor1 = 10;
let valor2 = 20;

let valorSoma = somar(valor1, valor2);

Durante a execução do código acima, as variáveis "valor1" e "valor2" são inicializadas e passadas, como argumentos para a função somar(). Dentro da mesma, os parâmetros são avaliados e os argumentos '10' e '20' são obtidos. Estes valores são somados, o resultado é retornado e atribuído à variável "valorSoma ". É importante notar que variáveis não são parâmetros e nem argumentos.
Acredito que só com a explicação acima é possível entender a lógica e diferença parâmetros e argumentos, mas vamos ver de maneiras mais simples o que cada um pode significar.
Já ouvi definições (e que não deixam de ser verdade) de que um argumento poderia ser a instância de parâmetro, não literalmente, mas é uma analogia interessante.
Outro modo de identificar (para não esquecer mais) a diferença de cada um:

Parâmetro -> Algo que receberá os valores quando chamar a função.
Argumento -> Valor/objeto ou qualquer coisa que colocar dentro da chamada da função.

Referências:

Pergunta do SO
Diferença entre parâmetro e argumento
Definição de parâmetro (em inglês)
Answer: Em resumo:
Parâmetro pode ser entendido como uma variável(local), um lugar, um recipiente, etc.
Por outro lado, o Argumento é o valor "atual" do Parâmetro.
EXEMPLO:
(X + Y)  EM QUE "X" E "Y" SÃO PARÂMETROS QUE RECEBERÃO OS ARGUMENTOS (1 + 2) OU (5 + 50) ETC.
Answer: Por exemplo:
def multiplicar(x, y): # Parâmetros
    return x * y

multiplicar(4, 3) # Argumentos


elementary question about definability

Question: My understanding is that an object, m, from the domain of a model, M, is definable by a formula, F(x), just in case M |= (Vx)[F(x) <----> x = m].  However, this assumes that there is a name for the object defined in the language in question, which seems to undercut the point of defining m.  If we do not suppose this, then how do we characterize the definability of m in M?  Could we just say that M |= F(x) under the assignment of x to m, and ~(M |= F(x)) under any other assignment?
Comment: Your last statement is correct, which can be denoted most accurately by the first notation I mentioned in my answer.
Answer: No, the $\leftrightarrow$ is not in the formula. $m$ is definable in $M$ if for some formula $\varphi(x)$, for all $n$ in $M$, $M\models\varphi(n) \iff n=m$.
The quantification is external.
Comment: Oh!  That makes much more sense.  Thank you.  So, this is saying that M satisfies the formula with x assigned to n just in case n is m?
Comment: @davidp: Yes, and note that "$φ(n)$" here is not a formula, but semantically evaluated. If you extend that idea of semantic evaluation to what you originally had written, it would still make sense. You just need to be careful to track what is in the language and what is not.
Comment: Got it.  Thank you again!
Answer: Free variables in a formula $φ$ can be interpreted as elements of the model. Some texts are very precise and write "$M[x=a] \vDash φ$" to mean that $M$ satisfies $φ$ with $x$ interpreted as $a$, where $a$ is an element in the model. Some others might write something like "$M \vDash φ[a/x]$", which is similar to the term substitution notation, but now used to denote interpretation instead. This can be a bit cumbersome so sometimes people just say that $φ$ has $1$ parameter and write "$M \vDash φ(a)$" instead. Similarly, we often write "$\mathbb{N} \vDash 0 < 2$" to mean "$\mathbb{N}[x=2] \vDash 0 < x$", if over a language that does not have the symbol for $2$.
In your case:

Given any model $M$ over a language $L$, an element $a$ in $M$ is said to be first-order definable over $L$ iff there is a $1$-parameter first-order formula $φ$ such that $( M \vDash φ(b) ) \Leftrightarrow ( a = b )$ for any element $b$ in $M$.

This turns out to be equivalent to:

Given any model $M$ over a language $L$, an element $a$ in $M$ is said to be first-order definable over $L$ iff there is a $1$-parameter first-order formula $φ$ such that $M \vDash \forall x\ ( φ(x) \leftrightarrow x=a )$.

But remember that in both variations, what is on the right of "$M \vDash$" is not strictly speaking the formula itself. In the first variation "$φ(b)$" is semantically evaluated, and in the second case the entire "$\forall x\ ( φ(x) \leftrightarrow x=a )$ is semantic because "$a$" is not in the language.
Comment: Thank you!  This is very helpful!

elementary question about definability


Why defining seperable topological space we use "COUNTABLE" dense set?

Question: My question is the caption itself. Thanks for helping.
Comment: Don't understand. The definition is exactly that. A separable space is one that contains an at most countable dense subset. What do you mean why? Perhaps, such a feature has been observed about some spaces and dubbed "separability".
Comment: @MoisheCohen: I would argue that not many people care about topological space at all, if that's the attitude one is taking. (One should never be too cavalier in mathematics when saying things like "not many people care about this or that", since there is always the risk of being myopic and seeing only what is in your research field and its close-by neighbors.)
Comment: It's a historic name, admittedly, not very good since it has nothing to do with "separation axioms" in topology. The countability assumption is closely related to other things like sequential convergence (and 1st countability), 2nd countability property. In principle, there is nothing wrong considering a similar property for dense subsets of higher cardinality, just not very useful in applications of general topology to other areas of math. (For instance, not too many people care about topological spaces of cardinality higher than continuum.)
Comment: @AsafKaragila: Dear Asaf, I respectfully disagree. Indeed, not many people care about modern research in topology (say, validity of the Novikov conjecture, for example). However, if you choose any field of math in the AMS subject classification in the interval  from 11 (number theory)  through 59 (this covers most of pure math, sorry, I skipped your area), as well as some areas outside that range, e.g. 05, 74, 76, 81, 83, 85, I will explain why people in that area care about the topology at least in its most basic (general topology) form.
Answer: It is convenient to be able to name each point in a space. If the space is countable, then there is no difficulty in doing so. If the space is uncountable, then attaching a name to each point is impossible. However, if a countable dense set is present, then you can name each point in the space by a sequence from that countable set. This gives you a rather simple mechanism to be able to 'reach' every point in the space.
In more technical terms, having a countable dense set allows for recursive constructions and inductive proofs in the space without the need for any transfinite arguments past $\omega$.
Answer: It's just a clever definition where the key appears to be taking a small number of points as being dense. For one thing a larger number of points has an easier time being dense...  I guess one might try replacing countable with finite,  and look at a smaller class of spaces.  But to make things more interesting,  countable was used in the definition.  Of course countable is the smallest level of infinity.   A countable set can be put in a list.  In the case of a separable topological space, I guess you could almost think of the points being partitioned, if you will, or separated by the subset.
If you went in the other direction and said, instead of countable,  $\aleph_3 $, or $\aleph_{1000}$, or higher cardinality yet, you would have something a little more obscure and hard to get a feel for...  though still interesting perhaps. ..
Of course,  it's a definition...  When you define something,  you can be creative and define whatever you want, quite apart from whether such things even exist,  or proving theorems about them...
Answer: First reason: it is a useful definition. If a space $X$ is separable and we want to prove some properties of it, we can first work on the countable subset $C$ which is much easier to handle. Afterwards we can take the closure of $C$, i.e. limits.
Second reason, omitting the condition "countable" makes the definition useless, because every space is dense in itself.


Passar objeto para uma proc sql server

Question: Tem como eu fazer uma SP que receba um objeto? Essa é a minha SP
ALTER PROCEDURE [dbo].[sp_alt_funcionarios]
    -- Add the parameters for the stored procedure here
(
     @id int,
     @nome varchar(60)
    ,@dataNascimento DateTime
    ,@cpf bigint
    ,@cidade  int
)
AS
BEGIN
    ---- SET NOCOUNT ON added to prevent extra result sets from
    SET NOCOUNT ON;

        -- Insert statements for procedure here
        update funcionarios set
            nome = @nome
            ,dataNascimento = @dataNascimento
            ,cpf = @cpf
            ,cidade = @cidade
         where
            id = @id

END

e esse é o meu serviço que pega usa essa SP
public class PutFuncionario
    {
        BancoContext banco = new BancoContext();

        public HttpResponseMessage updateFuncionario(Funcionario funcionario)
        {
            banco.Database.ExecuteSqlCommand("exec sp_alt_cidade @id, " +
                                             "@nome," +
                                             "@dataNascimento, " +
                                             "@cpf, " +
                                             "@cidade",
                                             new SqlParameter("@id", funcionario.id),
                                             new SqlParameter("@nome", funcionario.nome),
                                             new SqlParameter("@dataNascimento", funcionario.dataNascimento),
                                             new SqlParameter("@cpf", funcionario.cpf),
                                             new SqlParameter("@cidade", funcionario.cidade));

            return new HttpResponseMessage(HttpStatusCode.OK);
        }

ao invés de eu passar assim:
funcionario.id,
funcionario.nome
e etc
Passar o objeto inteiro funcionario? É mais elegante e etc
Comment: Não[.](https://pt.stackoverflow.com/q/321338/18246)
Comment: Existe uma forma: você pode serializar o objeto em XML e passar como argumento para uma SP. Veja o artigo: https://www.itworld.com/article/2960645/development/tsql-how-to-use-xml-parameters-in-stored-procedures.html
Comment: Veja que, um objeto como você diz, é algo que existe numa linguagem, para o banco não faz muito sentido, a não ser que seja um formato padrão, como `xml` ou `json`, mas isso não torna em nada "mais elegante". A procedure foi criada para receber parâmetros e assim funciona muito bem. Passar objetos em linguagens de programação tem outros conceitos envolvidos, objetos pode ser passados por referência, podem ter comportamentos, etc, coisas que não fazem o menor sentido para uma procedure. Apenas apontando que, embora seja possível, com esse número reduzido de parâmetros não faz muito sentido
Comment: Também é possível através do uso de table-valued parameter (TVP). Sugestão de leitura: "Using Table-Valued Parameters in SQL Server" -> http://sommarskog.se/arrays-in-sql-2008.html
Answer: Pode serializar o objeto e passá-lo para a SP como XML, depois transporta a informação para uma temporária e trabalha com ela:
Precisa alterar ligeiramente a classe Funcionario:
[Serializable]
[XmlType("funcionario")]
public class Funcionario
{
    [XmlElement("id")]
    public int id { get; set; }
    [XmlElement("nome")]
    public string nome { get; set; }
    [XmlElement("datanascimento")]
    public DateTime dataNascimento { get; set; }
    [XmlElement("cpf")]
    public int cpf { get; set; }
    [XmlElement("cidade")]
    public int cidade { get; set; }
}

Depois é necessário serializar o objeto e devolver uma string com o XML completo e estruturado:
private string SerializeXml()
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Funcionario));
    Funcionario funcionario = new Funcionario()
    {
        nome = "Joel",
        dataNascimento = new DateTime(1980, 10, 15),
        cidade = 1,
        cpf = 123456778,
        id = 1
    };
    string xml = string.Empty;

    using (StringWriter sw = new StringWriter())
    {
        using (XmlWriter xmlwriter = XmlWriter.Create(sw))
        {
            xmlSerializer.Serialize(xmlwriter, funcionario);
            xml = sww.ToString();
        }
    }

    xml = $"<Funcionarios>{xml}</Funcionarios>";

    return xml;
}

Passar apenas o XML para a SP:
banco.Database.ExecuteSqlCommand("exec sp_alt_cidade @xml", new SqlParameter("@xml", xml));

Por fim tratar a informação na SP e passá-la para uma temporária:
DECLARE @intXML INT

EXEC sp_xml_preparedocument @intXML OUTPUT, @xml

INSERT INTO #TmpFuncionario
SELECT [id], [nome], [datanascimento], [cpf], [cidade]
FROM OPENXML (@intXML, 'Funcionarios/Funcionario')
    WITH([id] INT, [nome] VARCHAR(60), [datanascimento] DATETIME, [cpf] BIGINT, [cidade] INT)

Não testei o código, mas será algo deste género (pode precisar de algumas afinações).

Passar objeto para uma proc sql server


Novice trying to resolve Error CS1001 "Identifier Expected"

Question: I'm a complete novice trying to learn C# by making mods for a game called RimWorld. I obtained the source code of a mod that does something similar to what I'm trying to do, and have been tweaking it to see what I can make work. The following error has me stumped, as the bit of code in question is unmodified from the source code that I obtained from a working mod. I also don't know C# well enough to know what specifically Visual Studio is looking for, and copying solutions from similar questions hasn't yielded any results.
Error: CS1001 - Identifier Expected - File: GetPawnThing.cs - Line 20
using System;
using RimWorld;
using Verse;

namespace VehicleSpawnerName
{
    // Token: 0x02000002 RID: 2
    public class GetPawnThing : MoteThrown
    {
        // Token: 0x06000001 RID: 1 RVA: 0x00002050 File Offset: 0x00000250
        public override void Tick()
        {
            bool flag = base.Map == null;
            if (flag)
            {
                this.Destroy(0);
            }
            PawnKindDef Vehicle_Name = PawnKindDefOf.Vehicle_Name;
            PawnGenerationRequest pawnGenerationRequest;
            pawnGenerationRequest..ctor(Vehicle_Name, null, 2, -1, true, false, false, false, true, false, 20f, false, true, true, false, false, false, false, null, null, null, null, null, null, null, null);
            Pawn pawn = PawnGenerator.GeneratePawn(pawnGenerationRequest);
            pawn.ageTracker.AgeBiologicalTicks = 70000000L;
            GenSpawn.Spawn(pawn, base.Position, base.Map, 0);
            this.Destroy(0);
        }
    }
}

The line in question (according to the error report) is:
pawnGenerationRequest..ctor(Vehicle_Name, null, 2, -1, true, false, false, false, true, false, 20f, false, true, true, false, false, false, false, null, null, null, null, null, null, null, null);

Any help is greatly appreciated!
Comment: `pawnGenerationRequest..ctor`? That's not source code, that's reverse-engineered code. Normally, that would have been `new PawnGenerationRequest(...)`
Comment: Decompiling a binary is not guaranteed to produce valid code.  That line is trying to call a constructor.
Comment: Thats good to know, I wouldn't know enough to tell the difference. Does that mean I can't expect this code to work at all?
Comment: You need to interpret what it is trying to do and rewrite it into correct code.  Do you know how to call an object constructor?
Comment: No, but I will go read some tutorials on how to go about it. Thanks for pointing me in the right direction.
Comment: I'll give you a hint.  `pawnGenerationRequest..ctor(....)` is the decompiler saying "call the `PawnGenerationRequest` constructor with these arguments".  If you can't get it, come back and we can help further.  This is a good learning exercise.
Answer: I think you are missing your parameter types is your method.
Here is a link of a similar error. c# identifier expected?
Comment: Hi Branden, welcome to Stack Overflow! Please expand your answer a little, explain the reasoning and the approach you would take to solving the problem. Also please provide the actual solution instead of linking to the solution.