Pascal's Triangle Python Recursive

Question: I want to write a function that will take a number (n) and the Pascal's Triangle of it. I have some code written but it doesn't work, it only works for the base case of 1 because it's just an if statement. The code is written here:
def pt_row(n):
  if n == 0:
    return []
  elif n == 1:
    return [1]
  else:
    new_row = [1]
    result = pt_row(n-1)
    last_row = result[-1]
    for i in range(len(last_row)-1):
      new_row.append(last_row[i] + last_row[i+1])
    new_row += [1]
    result.append(new_row)
  return result

The code crashes with anything above 2, because "int object do not have a len" or something like that and I can't figure out how to fix it.
Here's some test cases:
#What it should do
pt_row(1)
>>> [1]
pt_row(6)
>>> [1, 5, 10, 10, 5, 1]
#What it really does
pt_row(1)
>> [1]
pt_row(6)
CRASH

How do I fix this? Would I just need to turn the variable into a list or would I have to rewrite all the code?
Comment: Does this answer your question? [python recursive pascal triangle](https://stackoverflow.com/questions/10628788/python-recursive-pascal-triangle)
Comment: It doesn't that is obviously where I got the code but the code crashes with an number above 1 still.
Answer: result[-1] is an integer, you can't get its len. You just need to return the last row only, so the code can be simplified to:
def pt_row(n):
  if n == 0:
    return []
  elif n == 1:
    return [1]
  else:
    new_row = [1]
    result = pt_row(n-1)
    for i in range(len(result) - 1):
      new_row.append(result[i] + result[i+1])
    new_row += [1]
  return new_row

Pascal's Triangle Python Recursive


The roots of $ax^2+bx+c$ are 6 and $P$. The roots of $cx^2+bx+a$ are $Q$ and $R$ what is the value of $P\times Q\times R$

Question: Problem
The roots of $ax^2+bx+c$ are 6 and $P$. The roots of $cx^2+bx+a$ are $Q$ and $R$
And we are asked to find $P\times Q\times R$ by using the identities:
$P(x)=Q(x)\times D(x)+R(x)$
where $P(x)$ is the equations and $Q(x)$ is the quotient and $D(x)$ is the divisor and $R(x)$ is the remainder.
My thought process
so I had set $$ax^2+bx+c=Q(x)\times(x-6)\times(x-P)+0$$
and in the next equation:
$$cx^2+bx+a=Q(x)\times(x-P)(x-Q)+0$$
I really don't know where to go from here
Answer: Hint:
Think of Vieta's relations.
Answer: $$ax^{ 2 }+bx+c=0\\ 6p=\frac { c }{ a } \\ cx^{ 2 }+bx+a=0\\ \\ qr=\frac { a }{ c } \\ 6pqr=1\Rightarrow \quad pqr=\frac { 1 }{ 6 } $$
Answer: It is true that $x=0$ is not a root of $ax^2+bx+c$, since if so then $c$ would be zero, and the second polynomial $cy^2+by+a$ is linear with at most one root. Similarly, $y=0$ is not a root of $cy^2+by+a$.
Consider
$$cy^2+by+a = y^2 \left(c+\frac by + \frac a{y^2}\right)$$
If $x=0$ is not a root of $ax^2+bx+c$, i.e. $p\ne 0$, then $y=\dfrac16$ and $y=\dfrac1p$ are the two roots of $cy^2+by+a$. Then
$$pqr = p\cdot \frac 16\cdot \frac1p$$
Answer: Considering roots of $ax^2+bx+c$ as $\frac{-b\pm \delta}{2a}$ the roots of $cx^2+bx+a$ will be $\frac{-b\pm \delta}{2c}$. So, the product of all the four roots are $$6PQR=\frac{(-b+ \delta)(-b-\delta)}{2a}\times\frac{(-b+ \delta)(-b-\delta)}{2c}=\frac{4ac}{4ac}=1$$ Thus, we have $$PQR=\frac16$$


Is it true that is $\lambda \min\{a,b\}=\min\{\lambda a,\lambda b\}$ where $a ,b$ and $\lambda \in \mathbb{R^{+}}$?

Question: Is it true that $\lambda \min\{a,b\}=\min\{\lambda a,\lambda b\}$
where $a,b$ and  $\lambda \in \mathbb{R^{+}}$? If is it true how to prove it?
Answer: Hint. What's the definition of $\min\{a, b\}$?
If $a > b$, then $\min\{a, b\} = ?$...
If $b > a$, then...
If $a = b$, then...
Multiply all three cases by $\lambda$. Now what is $\min\{\lambda a, \lambda b\}$? (Use the same process as above, extended.)


Prove that 3S=2Q+P for a geometric progression

Question: I did Arithmetic Progression and Geometric Progression two years ago but this is challenging to me.
If 27 is the Pth term,8 is the Qth term and 12 is the Sth term of a G.P,then show that 3S=2Q+P
Comment: You need to state that they are the Pth term of which sequence. Is it an arithmetic progression, geometric progression, natural numbers??
Comment: Geometric Progression
Answer: As usual, let $a$ be the first term of the geometric progression, and let $r$ be the common ratio.
So we know that
$$ar^{P-1}=27, \qquad ar^{Q-1}=8, \qquad ar^{S-1}=12.$$
Now note that $12^3=(8^2)(27)$.
It follows that
$$(ar^{S-1})^3 =(ar^{Q-1})^2(ar^{P-1}).\tag{1}$$
Expand, and the result falls out. On the left, we have $a^3r^{3S-3}$ and on the right we have $a^3 r^{2Q+P-3}$. Cancel the $a^3$. We get that $r^{3S-3}=r^{2Q+P-3}$ and therefore $3S-3=2Q+P-3$.
Remark: We cheated a little. The equality $12^3=(8^2)(27)$ looks as if it was pulled out of a hat, but it really wasn't. By looking at (1), one can see that the desired result is equivalent to the assertion that the cube of $Ar^{S-1}$ is equal to the square of $ar^{Q-1}$ times $ar^{P-1}$. But the condition  $(12)^3=(8^2)(27)$ is easy to verify by multiplying, or, better, factoring.


Skew-symmetric matrix and quadratic form

Question: Show that the quadratic form of a matrix is $0$ if and only if the matrix is skew–
symmetric, i.e., show that $q_A(x) = 0$ for all $x$ iff $A^t = −A$.
Thanks a lot!
Comment: Please rephrase your question so it doesn't sound like you are assigning us homework. Also, if you have gotten anywhere thinking about the problem, it might help to let people in on your work.
Comment: What did you try? Can you express $q_A(x)$ with $x$ and $A$?
Comment: @Gerry Myerson I think it's suffice to show x*Px=0 iff P=0, but I don't know whether that's correct.
Comment: Related: http://math.stackexchange.com/questions/12172/does-there-exist-a-nonzero-linear-transformation-t-such-that-alphat-t-a/
Answer: Here is the if part,
$$x^TA x = x^TA^Tx= - x^TA x \in \mathbb{R}$$
Only if part does not hold, counter-example
$$
\begin{pmatrix} 1\\ 0\end{pmatrix}^T\begin{pmatrix} 0&1\\1& 0\end{pmatrix}\begin{pmatrix} 1\\ 0\end{pmatrix}=0
$$
unless you are missing "for all $x$" before the "iff"
Comment: I mean for all x. Sorry for that.
Answer: If $A^t=-A$ then for $x\in\mathbb R^n$ we have $-x^tAx=x^tA^tx=(x^tAx)^t=x^tAx$ since $x^TAx$ is a real number hence $x^tAx=0$.
For the controverse, let $S:=A^t+A$. Since for all $x\in\mathbb R^n$ we have $q_A(x)=x^tAx=0=-x^tAx$, we get $x^tSx=0$ for all $x$. We denote by $e_j$ the vector whose entries are $0$, except the $j$ which is $1$, and $s_{ij}$ the entries of $S$. Since $e_j^tSe_j=0$ for all $j$ we get $s_{jj}=0$ and for $i\neq j$ we have $$0=(e_i+e_j)^tS(e_i+e_j)=e_i^tSe_i+e_j^tSe_i+e_i^tSe_j+e_j^tSe_j=e_j^tSe_i+e_i^tSe_j=s_{ji}+s_{ij}.$$
Since $S$ is symmetric, we have $s_{ji}=-s_{ij}$ hence $s_{ij}=s_{ji}=0$.
Comment: brilliant! But no need to introduce $S=A+A^T$. The below is a simpler proof.

Since $x^TAx=0, \forall x$,

$e_i^TAe_i=0$, so $A_{ii}=0$;

$(e_i+e_j)^TA(e_i+e_j)=0$, so $A_{ij}+A_{ji}=0$.

Hence $A=-A^T$.
Comment: @Shiyu: you're right. I agree we don't need to introduce the matrix $S$, we it show that if a symmetric matrix is such that $x^tSx=0$ for all $x$ then $S=0$. I think it's an interesting property in itself, especially when we study quadratic forms.
Comment: Yes, it is useful that symmetric matrix $A$ will be zero if $x^TAx=0,\forall x$. But I think it is merely a special case because a matrix is zero if it is both symmetric and skew-symmetric.


Is there a method to perform a derivative by inbuilt function in python 3.5?

Question: I don't want to use numpy because it isn't permitted in competitive programming.I want to take derivative of for instance m=a(a**2-24a).
Now,a=0 and a=8 are critical points. I want to find this value.Is it possible by using any python library function excluding numpy.
Comment: There is no "derivative" implementation in the standard library. You can, of course, *implement your own*.
Comment: Why are you posting this in the comments of this question? If you have another question, start another question.
Comment: Oh sorry I am new over here hence didn't knew. thanks
Answer: m=a(a**2-24a) does not make sense as a Python expression, regardless of what a is.  The first a( implies a function; a** implies a number, and 24a is I-don't-know-what.
Derivative is a mathematical concept that's implemented in sympy (symbolic math).  numpy also implements it for polynomials.  numpy also implements a finite difference approximation for arrays.
For a list of numbers (or two lists) you could calculate a finite difference approximation (without numpy).
But for a general function, there isn't a derivative method for Python nor numpy.
Your question might make more sense if you give examples of the function or lists that you are working with.
Answer: You can check the implementation in the numpy repository and use that information to implement your own version. You should start with polyder. Probably you do not need half of the code in their implementation.


How valid is this Stacking Model (input features to weak learners are different)?

Question: I have a set of features with 6 of them being categorical, 1 continuous and 2 textual in type.
I have to predict the labels ( 10 in number) for them.
I tried applying several models and came to a conclusion that one predictive model is not enough to get the required efficiency. So I applied a stacking model using Random Forest, K- Nearest Neighbors and Multinomial Naive Bayes algorithms.
Since RF and KNN can take only integer/float values, I was able to encode my 6 categorical features to give as input.
But as for the 2 text fields, i had to use NLP libraries(nltk) in python and apply Naive Bayes to get some predictions. However, it has less efficiency.
Nonetheless, I took the predictions of all of the above three models and fed it to a third model (again RF or KNN). The prediction outputs on the test set looks good with up to 98% accuracy score.
So, in short, I am sending different features as inputs to the weak learners, and then combining them for input to the stronger model. Is this  a valid way of stacking?
Comment: None of these models are weak learners IMO. Also, applying RF to only 3 inputs seems a bit odd to me.
Answer: You do NOT want to train your layer 1 models with complete data since that will leak information to layer 2 model.
You should be doing train-test split or k-fold to more accurately test your model. You can check here for more details about how to apply stacking: http://blog.kaggle.com/2016/12/27/a-kagglers-guide-to-model-stacking-in-practice/
Comment: Thanks for the reply. I have corrected my data leakage problem. But now the accuracy score for test data is 57% while it remains 98% for train data (even with k-folds). The accuracy score is further decreasing for test data in layer 2 model, when it is expected to improve. Do you have any idea why this happening? Why is the model not able to learn?


Type inferred from readonly class property

Question: Given is the following test class:
class Test {
    private readonly testString = "hello";
    private readonly testStringImplicit: string = "hello";

    public constructor() {
        this.testString = "world";
        this.testStringImplicit = "world";
    }
}

Currently, Typescript 2.8.2 (and even current 2.9.2) produces the following error for the first property testString:
TS2322: Type "world" is not assignable to type "hello".
My Question: Is this a bug?
I guess not, but i don't understand, why the type of the readonly property can be the value of them.
Thank you for every helpful answer
Comment: Just a side note: You meant `testStringExplicit`, not `testStringImplicit`. (Your first one is implicit, relying on type inference; your second one is *ex*plicit, providing the type annotation.)
Answer: It's a bit confusing, but the type of your testString isn't string, it's "hello", the string literal type with the sequence of characters h, e, l, l, o. Your testStringImplicit is explicitly typed string, so you can assign any string to it, but your testString is only allowed to have that one string literal value.
It has that type because it's readonly, and that's the string you initialized it with. If it weren't readonly, the inferred type would be string, but because it's readonly, tsc is assuming the initialization is the only place you're going to write to it, and so gives it the "best common type" for "hello", which is the string literal type.
As jcalz helpfully points out, this is intended behavior. The relevant bullet point from that link:

The type inferred for a const variable or readonly property without a type annotation is the type of the initializer as-is.

whereas

The type inferred for a let variable, var variable, parameter, or non-readonly property with an initializer and no type annotation is the widened literal type of the initializer.

The word "constructor" doesn't appear in that pull request's text, so this effect that you can't assign a different value to testString in the constructor, even though you're allowed to by readonly's rules, doesn't seem to be discussed there. It may be discussed elsewhere.
Comment: This behavior is [intended](https://github.com/Microsoft/TypeScript/pull/10676), so I wouldn't file an issue about it.  I'd say the use case of "change a `readonly` property after you set it" is probably not one they would go out of their way to support...
Comment: @jcalz - Thanks for that link! I've incorporated it into the above. It's interesting, though, that tsc already goes out of its way to support "change a `readonly` property after you set it" in a constructor (which is why `this.testStringImplicit = "world";` in the question isn't an error; it *is* an error if it appears in a method instead). But I wouldn't want to be the person trying to argue that it should consider assignments in the constructor and assign the widened type if the initialization and assignment differ, not when you can just put `: string` on it. :-)
Comment: I never thought this is an intended behavior..
I'm amazed. Thank you both for ya help!


adding noise to prediction task

Question: Say that a teacher wishes to use a standard prediction task from Kaggle as a course assignment, and the idea is to have students submit their predictions, and award grades based on a test set (students are given the feature values for the test set). The teacher changes the names of the variables so that students are unable to directly google the variable names, but this is probably not sufficient to properly anonymise the data. What are some good ways to modify the  train/test data so that the task is still do-able, but the students are unable to cheat and submit existing predictions. For example, perhaps one could add noise to each variable, but how much noise can be added and what kind of noise maintains the structure of the problem?
Answer: You might try altering the target variable rather than the features. Each persons target variable might be offset by some secret constant, which preserves the relationships between variables and adjacent values but will ultimately change the parameter estimates (making some assumptions about model and data here).
Then, their submitted predictions will be specific to the secret offset that only you can decode

adding noise to prediction task


Is their any way to connect to oracle database via UNIX shell without using sqlplus

Question: is there any command string in unix which will provide access to oracle database. i dont want to use sqlplus command.
thanks for help...
Comment: So this is actually a Java problem when calling sqlplus...
Comment: So what is wrong with SQL*Plus then? (And what are "*ldt files*"?)
Comment: Do you want to run SQL commands once connected? Or do you just want to check if the database is reachable?
Comment: i just want unix command to connect to database without using sqlplus
Comment: And what do you want to do, once you are connected?
Comment: i need to run procedures and ldt files etc after connecting..
Comment: when i am running through java it is not detecting sqlplus command but through unix i am able to execute directly
Answer: SQLPlus has its own commands as well as being able to issue SQL and run PROCs. If Java is your thing, try SQL Developer here from Oracle - a great full-featured tool. You can also look here for open source clients - I can personally recommend SQuirreL SQL and SQL Workbench isn't bad (I've only really looked at it, YMMV).
You might also look at this question. Maybe an example of what you're trying to do might help?
HTH, Paul...


What is the difference between a tree and commit type in Git?

Question: I checked in one file into a simple git repo.
From my investigations; there are three types of objects placed in .git/objects

commit
tree
blob

As an example:
$ git cat-file -t 8b4e834eba22e60c284c7b77e43d3c29e619f92f
commit

$ git cat-file -t c7c5b03aea0b8c970c93de3670c28f2108948266
tree

$ git cat-file -t e965047ad7c57865823c7d992b1d046ea66edf78
blob

If I tried to run git-ls-tree on a blob, it throws an error.
But it is equally possible for me to run it on a commit or tree object.
$ git ls-tree -t c7c5b03aea0b8c970c93de3670c28f2108948266
100644 blob e965047ad7c57865823c7d992b1d046ea66edf78    readme.txt

$ git ls-tree -t 8b4e834eba22e60c284c7b77e43d3c29e619f92f
100644 blob e965047ad7c57865823c7d992b1d046ea66edf78    readme.txt

Is a commit object also a tree ?
What are their differences, if any ?
Answer: A commit object is an object that references a tree and associates other metadata (author, committer, timestamps, etc) with it.
         Commit
       /        \
      /          \
(parent SHA)     Tree
(author)        /    \
(committer)   Blob   Blob
(timestamps)
(etc)

Multiple commit objects can reference the same tree (if the state of files in each commit is identical).
For instance, if two people make the same change to a file and commit, it will result in two different commit objects (since both the timestamps and the authors will differ). However, since the end result is the same file contents, both commits will point to the same tree.
When you run git ls-tree on a commit SHA, it automatically uses the tree SHA referenced by that commit instead.


Create new tables from columns in main SQL table

Question: I have a main SQL table, for example:

I wish to create new tables from it.
It would split such that each column from the main table is a new SQL table (named "column"), and the columns in the new table are date (sorted earliest -> newest):
Table called "Weight" would be:

Table called "Salary" would be:

I am using python 3 and sqlite, and I am able to retrieve the (~200) column names of the main table into a dictionary or pandas dataframe using:
<code>conn = sqlite3.connect(database)
tbl_info_command = "PRAGMA TABLE_INFO({table});".format(table=table)
df = pd.read_sql_query(tbl_info_command, conn)
attributes_wanted = ['name', 'type']
df_shrunk = pd.DataFrame(df, columns=attributes_wanted)
</code>
But unsure how to translate this into the above tables, or even whether a loop from a dict/ df is the most efficient approach. Or does sql have this functionality built in?
Comment: you can just pivot the tables, are you using pandas? you can do it within sql lite too quite easily
Answer: You can use Pandas.DataFrame.pivot. See the implementation below:
<code>>>> df = pd.DataFrame({
    'Name': ['John', 'Allison', 'John', 'Allison'],
    'Date': ['20160101', '20160101', '20170605', '20170605'],
    'Weight': [80, 55, 84, 58],
    'Salary': [10000, 22000, 18000, 30000]
})
>>> df

    Name    Date    Weight  Salary
0   John    20160101    80  10000
1   Allison 20160101    55  22000
2   John    20170605    84  18000
3   Allison 20170605    58  30000

>>> df.pivot(index='Name', columns='Date', values='Weight')

Date    20160101    20170605
Name
Allison 55          58
John    80          84

>>> df.pivot(index='Name', columns='Date', values='Salary')

Date    20160101    20170605
Name
Allison 22000       30000
John    10000       18000
</code>
Comment: Excellent! Do I need to ensure date order (or is it automatic)? Is there a way to write the tables without loading into memory first? The main df is proving quite big.
Comment: The date order is alphabetical in the pivot table. There are a lot of ways how you can ensure low memory consumption for your df. I won't be able to answer unless I know your specific use case. If you're loading your df from CSV, you may want to look into `chunksize` parameter of [pandas.read_csv()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html) method.


Formulário não envia dados

Question: Estou tentando fazer com que os dados digitados pelo usuário apareçam em outra página quando ele clicar no botão só que a página é atualizada mas não contem as informações digitadas.
Arquivo HTML
 <form action="php/dados.php" method="post">

        <input type="text" id="cNome" name="tNome" size="20" maxlength="20" placeholder="       Digite Seu Nome"/>
     <input type="submit" value="Enviar"/>
    <input type="reset" value="Cancelar"/>
  </form>

Arquivo PHP
<?php

    $nome = $_POST["tNome"];
    echo "Obrigado $nome";
?>

Já olhei várias vezes mas não consigo achar o erro,qual seria?
Comment: Não use stacksnippets (trecho de código) sem necessidade, eles não são pra formatar e sim pra executar códigos js+css+html que façam alguma coisa, se não for pra fazer nada use a **marcação normal.**
Answer: Você deve estar usando ou protocolo file:/// ao invés de http:// (por exemplo acessou file:///c:/Users/Lone/Documents/projeto/form.php ao invés de http://localhost/form.php) ou você deve estar usando Apache sem PHP.
Como expliquei aqui https://pt.stackoverflow.com/a/62797/3635, se for Windows instale ou Xampp ou Wamp ou easyphp
Se já tiver instalado é porque talvez esteja acessando algo assim pelo navegador file:///c:/wamp/www/form.php, veja se a URL no navegador "parecido" com isto:

Isso não vai funcionar, o protocolo file é para rodar arquivos locais, o Apache é um servidor, mesmo que local e você precisa rodar por ele.
Depois de instalar o Xampp, Lamp (linux), Wamp, Mamp (Mac OSX), você deve copiar teus arquivos para as seguintes "possíveis" pastas (estas pastas são de exemplo, mas o caminho deve ser parecido):

Windows e Wamp: c:/wamp/www
Windows e Xampp: c:/xampp/htdocs
Linux e Lamp/Xampp: /otp/lamp/htdocs
Linux instalado via repositório: /var/www

Claro que é possível apontar outras pastas, mas isto é outra história.
Comment: @LoneTonberry se não estiver "online" não tem como a pessoa ver, afinal online é online né? Agora Xampp, Wamp, `http://localhost`, etc não tem nada haver com "online", eles rodam só na tua maquina e isso é usado para você desenvolver suas páginas e scripts. **Agora** se você quer exibir remotamente para alguém a página você pode colocar em uma hospedagem (deve ser o online que se refere) ou tentar usar no-ip, isso deve ajudar: [**acesso externo com wamp**](http://pt.stackoverflow.com/a/50934/3635)
Comment: @LoneTonberry isso mesmo, tem que ter instalado, por isso chamamos de ambiente de desenvolvimento, não tem como criar um script PHP sem ter o programa PHP (vem junto com Xampp ou Wamp, ou outros, só precisa de um deles), também não tem como rodar um script PHP para servidor HTTP sem ter um servidor HTTP na maquina. O Xampp e outros tem o Apache (servidor) e o PHP (interpretador), basta instalar, se não tiver eles seria o mesmo que querer editar um arquivo do MSWord (.doc e .docx) sem ter o Office 2007 ou Office 365 instalado.
Comment: @LoneTonberry sim scripts php só rodam se tiver o programa PHP e o Apache precisa de uma pasta padrão. Arquivos .php são criados para rodar em sites e esses sites usam um servidor, como Apache, Nginx, Lighttpd, etc. Esses servidores tem que ter uma pasta aonde está aonde ficariam os dados que vão para o site, como eu disse arquivos .php precisam do programa php.exe, não ter ele é como tentar editar um .doc sem ter o Office, recomendo que leia isto http://pt.stackoverflow.com/a/115690/3635
Comment: Então no caso se eu precisar mostrar esse arquivo para alguém sem deixar online não vai ser possível ?
Comment: Quis dizer que eu vou precisar levar esse trabalho para outra máquina, mas não quero deixar o site online.Então no caso eu teria que ter instalado naquela máquina esses programas também ou não ?
Comment: Então quer dizer que o correto seria eu pegar todos os meus arquivos de HTML, JS, CSS , PHP  e jogar ele dentro das respectivas pastas dos programas ?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/52504/discussion-between-lone-tonberry-and-guilherme-nascimento).

Formulário não envia dados


Calculo de desconto em JavaScript

Question: Preciso fazer a soma de produtos e dar 10% de desconto no valor total dos produtos, segue o código abaixo.
let produtos1 = 150.00
let produtos2 = 100.00
let produtos3 = 228.00

soma = produtos1 + produtos2 + produtos3

if (soma >= 200) {
  console.log('voce acaba de ganha um desconto de 10%')
  console.log('novo subtotal '+ desconto)
} else {
  console.log('adicione mais produtos para ganha o desconto')
}

Comment: Sei que já tem um comentário e uma resposta te dando o caminho, mas não posso deixar de comentar: esse não é um problema de programação, e sim de matemática. Acredito que conseguiria resolver sozinho caso fizesse antes um exercício no papel, sem pensar em código, só na matemática. Encare isso como um conselho, se não conseguir fazer esse tipo de operação matemática sozinho, vai ser complicado dominar a lógica de programação.
Comment: let desconto = soma-(soma*.1);
Comment: é a pandemia que não deixa ir pra aulas de matematica
Answer: Para "descontar" 10% de um valor, você pode fazer algo assim:
desconto = valor * 0.1; // 10% do valor
descontado = valor - desconto; // 90% do valor (10% de desconto)

Ou simplesmente calcule o complemento do que você quer descontar. No caso, como quer descontar 10%, basta calcular 90% do preço. Temos, então:
descontado = valor * 0.9; // 90% do valor (10% de desconto)

Assim:

let produtos1 = 150;
let produtos2 = 100;
let produtos3 = 228;

let soma = produtos1 + produtos2 + produtos3;

if (soma >= 200) {
  let descontado = soma * 0.9;

  console.log('voce acaba de ganha um desconto de 10%');
  console.log('total sem desconto:', soma);
  console.log('você pagará:', descontado);
} else {
  console.log('adicione mais produtos para ganha o desconto');
}
Answer: function ganharDesconto(...products) {
  const total = products.reduce((a, b) => a + b, 0)

  if (total > 200) {
    return `Você recebeu desconto e o valor ficou: ${total * 0.9}`
  }

  console.log('Adicione mais produtos para ganhar desconto.')
}

ganharDesconto(100, 101) // "Você recebeu desconto e o valor ficou: 180.9"
ganharDesconto(10, 20, 30, 40) // "Adicione mais produtos para ganhar desconto."

Calculo de desconto em JavaScript


Generating function - What is the coefficient of $x^{26}$?

Question: What is the coefficient of $x^{26}$ given the function:
$${\left[ {{{1 + {x^{10}}} \over {{{(1 - x)}^7}}}} \right]^2}$$
My work:
$${\left[ {{{1 + {x^{10}}} \over {{{(1 - x)}^7}}}} \right]^2} = \left( {1 + 2{x^{10}} + {x^{20}}} \right){1 \over {{{(1 - x)}^{14}}}} = \left( {1 + 2{x^{10}} + {x^{20}}} \right)\sum\limits_{n = 0}^\infty  {\left( {\matrix{
   {n + 13}  \cr
   {13}  \cr
 } } \right)}  \cdot {x^n}$$
Recitation's notes work:
$$... = \left( {{x^{26}} + 2{x^{16}} + {x^6}} \right)\sum\limits_{n = 0}^\infty  {\left( {\matrix{
   {n + 13}  \cr
   {13}  \cr
 } } \right)}  \cdot {x^n}$$
I don't understand why multiplying by $x^{26}$. What's the reason?
Comment: Your work is getting the right answer by comparing with the direct computation answer.
Comment: the result from the recitation notes is:
$$\left( {\matrix{
   {26 + 13}  \cr
   {13}  \cr

 } } \right) + 2\left( {\matrix{
   {16 + 13}  \cr
   {13}  \cr

 } } \right) + \left( {\matrix{
   {6 + 13}  \cr
   {13}  \cr
 } } \right)$$

do you have a guess what was the intention of multiplying by $x^{26}$?
Comment: The Maple command $$coeftayl(((x^{10}+1)/(1-x)^7)^2, x = 0, 26) $$ produces $8258180406 $.
Answer: You are perfectly right. Using the notation $[x^n] f(x)$ for "the coefficient of $x^n$ in (the series expansion for) $f(x)$" we can write:
\begin{align}
[x^{26}] \left( \frac{1 + x^{10}}{(1 - x)^7} \right)^2
  &= [x^{26}] (1 + x^{10})^2 \cdot (1 - x)^{-14} \\
  &= [x^{26}] (1 +  2 x^{10} + x^{20})
                \cdot \sum_{n \ge 0} (-1)^n \binom{-14}{n} x^n \\
  &= [x^{26}] (1 +  2 x^{10} + x^{20})
                \cdot \sum_{n \ge 0} \binom{13 + n}{13} x^n \\
  &= ([x^{26}] + 2 [x^{16}] + [x^6]) \sum_{n \ge 0} \binom{13 + n}{13} x^n \\
  &= \binom{39}{13} + 2 \binom{29}{13} + \binom{19}{13}
\end{align}
Looks like a typo of some sort to me (perhaps forgot the $[]$ for "coefficient of" in the above derivation?).
Comment: Can you expand about this notation? For example, why $1$ becomes $[x^{26}]$?
Comment: @AnnieOK, edited the answer to add a brief explanation.


file_get_contents with empty file not working PHP

Question: I try to use file_get_contents form PHP but it's not working.
There is my code :
$filename = "/opt/gemel/test.txt";

if($filecontent = file_get_contents($filename)){

    $nom = fgets(STDIN);

    file_put_contents($filename, $nom, FILE_APPEND);
}
else
    echo "fail";

And my file test.txt is empty. (0 octets). He exists but he is empty.
When i write something into it, my code works perfectly but if he is empty my code echo "fails"
Why that, why he can't open the file text.txt ?
Answer: The function file_get_contents returns the string that's in the file. If the file contains no data, then file_get_contents returns an empty string. If you would try to var_dump('' == false); you would get true. So, even though the file can be read, the contents of the file evaluates to false.
If you would use this line, your code should work:
if($filecontent = file_get_contents($filename) !== false){

Edit; link to the documentation of the Comparison operators.
Comment: It has to do with the types of the variables. file_get_contents returns `false` (a boolean) if it can't open the file, it returns `''` (a string) if it opens an empty file. The triple character comparison (`!==`) also checks if the types of the variables are the same. Please check the link to the documentation in my answer for more information.
Comment: you say **file_get_contents** return an empty string like a false. So this line **file_get_contents($filename) !== false** is supposed to be false, because file_get_contents return false. So why it's work and not echo "fail"?
Comment: Ok, I did not grasp the nuance between "type" and "equal to". Thank you for your explanations.


React native send a message to specific whatsapp Number

Question: I'm trying to send a text message to a WhatsApp contact from a react-native apps , i found that i can do it through Linking
Linking.openURL('whatsapp://send?text=hello');

the code above opens only whats app , i need to open a chat with a specific number is there a paramter i have to send like text ?!
Comment: also can you show my the format of abid ?
Comment: whatsapp://send?abid=\(ID)&text=hello
Comment: this opens only screen sharing and ask me to choose which account i want to share my message with ! i need to open a direct chat with specific user
Answer: You can use this to send a message to specific number:
Linking.openURL('whatsapp://send?text=hello&phone=xxxxxxxxxxxxx')
Comment: How to send image along with text
Comment: How to send to WhatsApp business
Comment: Hi, what about linkedIn! I'm the same for linkedIn profile
Comment: Hi, How can i share specific text or data  in other social media like facebook, twitter, pinterest, google plus etc.
Comment: @ShaileshPrajapati i think the same link open the available one on mobile or option to select one if both available
Comment: How does one find all of the Linking URL possibilities?
Comment: Is there some way to specify multiple phone numbers in the link?
Answer: share message to whatsapp to a specific predefined number independent to platform
sendWhatsApp = () => {
  let msg = "type something";
  let phoneWithCountryCode = "xxxxxxxxxx";

  let mobile =
    Platform.OS == "ios" ? phoneWithCountryCode : "+" + phoneWithCountryCode;
  if (mobile) {
    if (msg) {
      let url = "whatsapp://send?text=" + msg + "&phone=" + mobile;
      Linking.openURL(url)
        .then(data => {
          console.log("WhatsApp Opened");
        })
        .catch(() => {
          alert("Make sure WhatsApp installed on your device");
        });
    } else {
      alert("Please insert message to send");
    }
  } else {
    alert("Please insert mobile no");
  }
};

Please Note: send + in front of phone with country if opening in android
Comment: it works without + too now in android as well as ios
Answer: You can use this method to send whatsApp message direct to a number.
Example link: https://wa.me/919234567812?text=%7B0%7D+Balaji+CTest
export const sendWhatsAppMessage = link => {
 if (!isUndefined(link)) {
  Linking.canOpenURL(link)
   .then(supported => {
     if (!supported) {
      Alert.alert(
        'Please install whats app to send direct message to students via whats
         app'
      );
    } else {
      return Linking.openURL(link);
    }
  })
  .catch(err => console.error('An error occurred', err));
} else {
  console.log('sendWhatsAppMessage -----> ', 'message link is undefined');
 }
};

Comment: The API url can be this: `https://api.whatsapp.com/send?phone=+31612345678`


Under what condition does $\int_a^b|f(x)|=0$ imply $f=0$? ( at least a.e.).

Question: I'm working through Real Analysis by Royden & Fitzpatrick, and on the first section on $L^p$ spaces they always skip the last property of norms without much commentary. Namely, that $||f||=0 \iff f=0$.
For example, they discuss a norm of $L^1$ given by $||f||=\int_a^bx^2|f(x)|dx$. To show $||f||=0 \implies f=0$, they just claim $\int_a^bx^2|f(x)|dx=0$ gives $f=0$ a.e.
Unfortunately, I do not see how this is immediately obvious, neither from the definition of Riemann or Lebesgue integration. Is this somehow trivial for non negative functions? I've seen some proofs of this for continuous functions, but $f\in L^1$ and is not necessarily continuous here.
Comment: In $L^p$ theory, always use the Lebesgue integral.  (If you use Riemann, your space will not be complete.)
Comment: Integral is riemann sum, and if sum of non - negative numbers is zero.. then what does that imply?
Comment: @SiddharthJoshi Thanks, I see that for non-negative functions. Not sure if there is a theorem that clears this up for a greater class of functions.
Comment: why non - negative functions? it must imply $f = 0$ irrespective of whether $f$ is positive or negative, because you' re taking riemann sum of $|f|$
Comment: @SiddharthJoshi What about $f(x)=x$ over $[-a,a]$. Then $\int_{-a}^ax=0$ but $f(x)=x$ is not zero.
Comment: @GEdgar I did and then I accidentally accepted someone's edit who turned it into Riemann. I'm fixing it back now.
Comment: No, but  I suppose you're asking how does $\int_a^b|f(x)|dx = 0 \Rightarrow f(x) = 0 \ \mathbb{for \ all \ x \in (a, b)}$
Answer: (1) if $f$ is measurable, and $\int_a^b |f(t)|\;dt = 0$, then $f(t) = 0$ for almost all $t$.
Proof.  Suppose $|\{t : f(t) \ne 0\}| > 0$.  (I used $|\cdot|$ for Lebesgue measure.)  Then $|\{t : |f(t)|>0\}| > 0.$  But
$$
\{t : |f(t)|>0\} = \bigcup_{n \in \mathbb N} \left\{t : |f(t)| > \frac{1}{n}\right\}
$$
so by countable additivity, there exists $n$ such that
$\left|\left\{t : |f(t)| > \frac{1}{n}\right\}\right| > 0$.  Thus
$$
\int_a^b |f(t)|\;dt \ge \left|\left\{t : |f(t)| > \frac{1}{n}\right\}\right|\cdot\frac{1}{n} > 0.
$$
(2) If $f$ is measurable, and $\int_a^b t^2|f(t)|\;dt = 0$, then $f(t) = 0$ for almost all $t$.
Applying (1) to the function $t^2|f(t)|$, we get $t^2|f(t)|=0$ for almost all $t$.  The points where $f(t)$ are zero, together with (possibly) one point where $t^2=0$, give us the points where $t^2 |f(t)| = 0$.  So from $t^2|f(t)|=0$ a.e. we get $f(t)=0$ a.e.
Comment: thanks this is very insightful
Answer: Let $a\leq t\leq b$.
As $x^2|f(x)|\geq0$,
$$0\leq\int_a^t x^2|f(x)|dx\leq\int_a^b x^2|f(x)|dx$$
So, for any $a\leq t\leq b$,
$$\int_a^t x^2|f(x)|dx=0$$
Now differentiate it and you get
$$t^2|f(t)|=0\quad (a\leq t\leq b)$$
$$|f(t)|=0\quad (a\leq t\leq b, t\ne0)$$
$$\therefore f(t)=0\quad (a\leq t\leq b, t\ne0)$$
Comment: The above relies on the fact that $f$ be continuous -- [the generalization of the Fundamental Theorem of Calculus to merely locally integrable functions](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus#Generalizations) will give something similar, but slightly different.
Comment: So $f(x)$ could be $\delta(x)$ [Dirac-Delta function] if $a\leq0\leq b$. And then $f(x)\ne0$.?


Webform javascript CSS selectors with table

Question: I'm currently trying to add javascript via the settings tab for a webform that is supposed to dynamically update the displayed totals at the bottom of the webform page for the user.
A part of this involves me targeting a custom webform composite I created myself for this webform so I can hook onto an event that runs every time a value within this composite element changes.
The composite element looks like this:

Here's the JavaScript I have for selecting the product select element, summarized:
jQuery('table[data-drupal-selector|="edit-product-list-items"]').on('change', 'select.form-select[required]', updateValues);

function updateValues(event){
//perform updates here
}

As it is, The event is called whenever a value changes as long as the user just fills in the fields in the currently displayed table rows and nothing else.
However, once they add a new item to the table, this event no longer gets called.
I've tried using the data-drupal-selector and ID attributes, but both give the same outcome. Not to mention, every time a row is added to the composite table, the ID of the table has a random string appended onto it.
Is there a better way to select the elements in this table so that my function runs consistently?
Answer: My heart is bleeding each time a developer starts working with Drupal and adds code to a Drupal site that doesn't take advantage of its features.
When using JavaScript with Drupal, please ALWAYS familiarize yourself with the concept of libraries (to manage JavaScript dependencies and inclusion to your site), as well as the relatively simple but powerful Drupal  JavaScript behaviors (and while you're at it, the once feature, as you'll very often use it as well).
In brief, a Drupal JavaScript behavior is a JavaScript object provided by your module or theme JavaScript that features an attach and/or a detach method. Attach is called whenever a page load completed. That is the initial page load, as well as after dynamically loading page content using AJAX requests. It receives a context parameter that holds the wrapper DOM element of the changed part.
That said, your JavaScript didn't fire for dynamically added content, because you didn't use Drupal behaviors and thus the change event handler won't be bound to dynamically added page content.
The "workaround" you posted in your own answer on the other hand will cause the updateValues callback to fire on every change of a select element of your site. Regardless of whether it's part of your webform or not.
A solution that works better and conforms with the Drupal JavaScript API (for simplicity of code, I kept your jQuery dependency):
js/my-update-values.js:
(function (Drupal, $, once) {

  'use strict';

  Drupal.behaviors.myUpdateValues = {
    attach: function (context) {
      // Apply once to all required select elements within the
      // current context.
      once('myUpdateValues', 'select.form-select[required]', context)).forEach(function (element) {
        var $element = $(element);
        // Ensure the select element is part of the custom webform.
        // A CSS class selector would be better here.
        if ($element.closest('table[data-drupal-selector|="edit-product-list-items"]').length === 0) {
          return;
        }
        // Bind the change handler.
        $element.on('change.myUpdateValues', updateValues);
      });
    },
    detach: function (context) {
      // Process all required select elements of the detaching context
      // that where previously processed by our attach function, and
      // unbind the change handler.
      $(once.remove('myUpdateValues', 'select.form-select[required]', context)).off('change.myUpdateValues');
    }
  };

  function updateValues(event) {
    // Your code here.
  }

}(Drupal, jQuery, once));

This example depends on the Drupal 9.2+, jQuery and Drupal once libraries. So your library definition may look as such:
libraries.yml:
myUpdateValues:
  js:
    js/my-update-values.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/once

On older versions of Drupal, you may have to use jquery.once instead.
Comment: Apologies for your bleeding heart, I'm fairly new to Drupal so I'm still learning how to integrate its features with JS. This solution worked great, I realize now that my posted solution is pretty sloppy and leads to way more function calls then needed.
Comment: Question: If I wanted to include multiple DOM elements as the selector parameter for the once() function, how would that have to look? Because I get a TypeError when just including the selector strings in a normal array.
Comment: If you provide an array, it must be an array of DOM elements/jQuery objects. If you want to use selectors, it will work the same as with the document.querySelectorAll function. A comma separated list of selectors will do. You can check the examples mentioned here: https://www.npmjs.com/package/@drupal/once#readme
Answer: I found a solution: using bubbling to attach the event to something other than the table stops the listeners from being removed every time a new row is added.
jQuery('body').on('change', 'select.form-select[required]', updateValues);

Comment: This is not recommended. Depending on where that code is placed, it might get injected and executed multiple times. Use a proper [Drupal Javascript Behavior](https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview) instead


Integrating kernel density estimator in 2D

Question: I'm coming from this question in case anybody wants to follow the trail.
Basically I have a data set $\Omega$ composed of $N$ objects where each object has a given number of measured values attached to it (two in this case):
$$\Omega = o_1[x_1, y_1], o_2[x_2, y_2], ..., o_N[x_N, y_N]$$
I need a way to determine the probability of a new object $p[x_p, y_p]$ of belonging to $\Omega$ so I was advised in that question to obtain a probability density $\hat{f}$ through a kernel density estimator, which I believe I already have.
Since my goal is to obtain the probability of this new object ($p[x_p, y_p]$) of belonging to this 2D data set $\Omega$, I was told to integrate the pdf $\hat{f}$ over "values of the support for which the density is less than the one you observed". The "observed" density is $\hat{f}$ evaluated in the new object $p$, ie: $\hat{f}(x_p, y_p)$. So I need to solve the equation:
$$\iint_{x, y:\hat{f}(x, y) < \hat{f}(x_p, y_p)} \hat{f}(x,y)\,dx\,dy$$
The PDF of my 2D data set (obtained through python's stats.gaussian_kde module) looks like this:

where the red dot represents the new object $p[x_p, y_p]$ plotted over the PDF of my data set.
So the question is: how can I calculate the above integral for the limits $x, y:\hat{f}(x, y) < \hat{f}(x_p, y_p)$ when the pdf looks like that?

Add
I did some tests to see how well the Monte Carlo method I mention in one of the comments worked. This is what I got:

The values appear to vary a bit more for lower density areas with both bandwidths showing more or less the same variation. The largest variation in the table occurs for the point (x,y)=(2.4,1.5) comparing Silverman's 2500 vs 1000 sample value, which gives a difference of 0.0126 or ~1.3%. In my case this would be largely acceptable.
Edit: I just noticed that in 2 dimension Scott's rule is equivalent to Silverman's according to the definition given here.
Comment: Have you noticed your estimator is not unimodal, but that the recommendation you are following explicitly applies only to "unimodal" distributions?  That doesn't mean you're doing something wrong, but it should generate some hard thinking about what the answer might mean.
Comment: My main concern is that the KDE may be sensitive to the choice of bandwidth and I expect your integral, especially for marginal places like that shown in the illustration, will be *very* sensitive to the choice. (The calculation itself, by the way, is easy once you have created a raster image like this: it is proportional to the average value in the image among points whose value is less than that of the "probe" point.)  You can approach this by computing the answer for a full range of reasonable bandwidths and see whether it changes in any material way within that range. If not, you're fine.
Comment: I won't comment on the solution, but the integration can be done by simple Monte Carlo: sample points from $\hat{f}$ (that's easy, since the kde is a mixture of densities that are easy to sample from), and count the fraction of points that fall inside the integration region (where the inequality holds).
Comment: How many observations do you have in your dataset?
Comment: I've been given a way to perform this integration in python here (http://stackoverflow.com/q/17822282/1391441) The idea is pretty simple and I can confirm the code works but since I'm not versed in statistics I can't 100% be sure of the mathematical validity behind it. I use a default _Scott's rule_ as a bandwidth but I can also try _Silverman_ and a scalar. I'll report back if I get different results with either of them @whuber. Hong I have from a thousand points to ~20000 (and sometimes even more) What do you guys think of the solution given over at Stackoverflow? Is it correct?
Comment: MC integration will indeed be slow and impreceise. As I mentioned, a simple way (even easier than the MC method and much more accurate) is to rasterize the domain of integration and compute a discrete approximation.
Comment: @whuber would you mind posting your comment in the form of an answer with a bit more detailed explanation on how to perform the integration with the method you describe?
Comment: Hi @whuber, actually the answer in that question says that it is "well behaved" for unimodal distributions, so I thought that perhaps it _could_ work on my problem with some modification. Does "well behaved" mean "works only" in statistical jargon (honest question)? Cheers.
Answer: A simple way is to rasterize the domain of integration and compute a discrete approximation to the integral.
There are some things to watch out for:

Make sure to cover more than the extent of the points: you need to include all locations where the kernel density estimate will have any appreciable values.  This means you need to expand the extent of the points by three to four times the kernel bandwidth (for a Gaussian kernel).
The result will vary somewhat with the resolution of the raster.  The resolution needs to be a small fraction of the bandwidth.  Because the calculation time is proportional to the number of cells in the raster, it takes almost no extra time to perform a series of calculations using coarser resolutions than the intended one: check that the results for the coarser ones are converging on the result for the finest resolution.  If they are not, a finer resolution may be needed.

Here is an illustration for a dataset of 256 points:

The points are shown as black dots superimposed on two kernel density estimates.  The six large red points are "probes" at which the algorithm is evaluated.  This has been done for four bandwidths (a default between 1.8 (vertically) and 3 (horizontally), 1/2, 1, and 5 units) at a resolution of 1000 by 1000 cells.  The following scatterplot matrix shows how strongly the results depend on bandwidth for these six probe points, which cover a wide range of densities:

The variation occurs for two reasons.  Obviously the density estimates differ, introducing one form of variation. More importantly, the differences in density estimates can create large differences at any single ("probe") point.  The latter variation is greatest around the medium-density "fringes" of clusters of points--exactly those locations where this calculation is likely to be used the most.
This demonstrates the need for substantial caution in using and interpreting the results of these calculations, because they can be so sensitive to a relatively arbitrary decision (the bandwidth to use).

R Code
The algorithm is contained in the half dozen lines of the first function, f.  To illustrate its use, the rest of the code generates the preceding figures.
library(MASS)     # kde2d
library(spatstat) # im class
f <- function(xy, n, x, y, ...) {
  #
  # Estimate the total where the density does not exceed that at (x,y).
  #
  # `xy` is a 2 by ... array of points.
  # `n`  specifies the numbers of rows and columns to use.
  # `x` and `y` are coordinates of "probe" points.
  # `...` is passed on to `kde2d`.
  #
  # Returns a list:
  #   image:    a raster of the kernel density
  #   integral: the estimates at the probe points.
  #   density:  the estimated densities at the probe points.
  #
  xy.kde <- kde2d(xy[1,], xy[2,], n=n, ...)
  xy.im <- im(t(xy.kde$z), xcol=xy.kde$x, yrow=xy.kde$y) # Allows interpolation $
  z <- interp.im(xy.im, x, y)                            # Densities at the probe points
  c.0 <- sum(xy.kde$z)                                   # Normalization factor $
  i <- sapply(z, function(a) sum(xy.kde$z[xy.kde$z < a])) / c.0
  return(list(image=xy.im, integral=i, density=z))
}
#
# Generate data.
#
n <- 256
set.seed(17)
xy <- matrix(c(rnorm(k <- ceiling(2*n * 0.8), mean=c(6,3), sd=c(3/2, 1)),
               rnorm(2*n-k, mean=c(2,6), sd=1/2)), nrow=2)
#
# Example of using `f`.
#
y.probe <- 1:6
x.probe <- rep(6, length(y.probe))
lims <- c(min(xy[1,])-15, max(xy[1,])+15, min(xy[2,])-15, max(xy[2,]+15))
ex <- f(xy, 200, x.probe, y.probe, lim=lims)
ex$density; ex$integral
#
# Compare the effects of raster resolution and bandwidth.
#
res <- c(8, 40, 200, 1000)
system.time(
  est.0 <- sapply(res,
           function(i) f(xy, i, x.probe, y.probe, lims=lims)$integral))
est.0
system.time(
  est.1 <- sapply(res,
           function(i) f(xy, i, x.probe, y.probe, h=1, lims=lims)$integral))
est.1
system.time(
  est.2 <- sapply(res,
           function(i) f(xy, i, x.probe, y.probe, h=1/2, lims=lims)$integral))
est.2
system.time(
  est.3 <- sapply(res,
           function(i) f(xy, i, x.probe, y.probe, h=5, lims=lims)$integral))
est.3
results <- data.frame(Default=est.0[,4], Hp5=est.2[,4],
                      H1=est.1[,4], H5=est.3[,4])
#
# Compare the integrals at the highest resolution.
#
par(mfrow=c(1,1))
panel <- function(x, y, ...) {
  points(x, y)
  abline(c(0,1), col="Red")
}
pairs(results, lower.panel=panel)
#
# Display two of the density estimates, the data, and the probe points.
#
par(mfrow=c(1,2))
xy.im <- f(xy, 200, x.probe, y.probe, h=0.5)$image
plot(xy.im, main="Bandwidth=1/2", col=terrain.colors(256))
points(t(xy), pch=".", col="Black")
points(x.probe, y.probe, pch=19, col="Red", cex=.5)

xy.im <- f(xy, 200, x.probe, y.probe, h=5)$image
plot(xy.im, main="Bandwidth=5", col=terrain.colors(256))
points(t(xy), pch=".", col="Black")
points(x.probe, y.probe, pch=19, col="Red", cex=.5)

Comment: Your understanding is correct.  ("p5" means ".5".)  The default is computed automatically by `kde2d` using `bandwidth.nrd`. For the sample data it equals $3$ in the horizontal direction and $1.85$ in the vertical direction, roughly halfway between the values of $1$ and $5$ in the test. Notice that these default bandwidths are large enough to place an appreciable proportion of the total density well beyond the extent of the points themselves, which is why that extent needs to be expanded *regardless* of what integration algorithm you might choose to use.
Comment: Scratch the above. I *do* have a way of knowing if the implementation is working and even of quantifying how well it is working. It's a bit complicated and time consuming but I can (should be able to) do it.
Comment: Amazing answer, although I'm not sure I understand the meaning of the `Default` and `Hp5` bandwidths (I assume `H1` and `H5` mean `h=1` and `h=5`) Is `Hp5` the value `h=1/2`? If so what is `Default`?
Comment: So am I understanding correctly if I say that as I increase the bandwidth used the extent of the resulting `kde` also increases (and so I need to extend the integration limits)? Given that I can live with an error of `<10%` in the resulting value of the integral, what do you think about using Scott's rule?
Comment: I think that because these rules were developed for entirely different objectives, you should suspect they might not perform well for your purposes, especially if it is to implement a suggestion made at http://stats.stackexchange.com/questions/63263. It is premature to be worrying about whose rule of thumb you might use for the KDE; at this stage you should be seriously concerned whether the entire approach will even work reliably.
Comment: The thing is that I have *no way of knowing* (or quantifying) if the approach worked reliably. I am in fact planning to implement this in the question you mentioned and I have no way of comparing the results with a "true" value. I just have to trust that I'm making the best possible guess. That's why I'm concentrating on the bandwidth I should use.
Comment: I can't comment on the section I want, but I have a really dumb question. I am new to using spatstat in R. In the accepted answer section, A simple way is to rasterize the domain of integration and compute a discrete approximation to the integral, what do the values in the scale represent (the color images with the 1/2 and 5 bandwidths)? Is it the intensity?? TIA.
Answer: If you have a decent number of observations, you may not need to do any integration at all. Say your new point is ${\bf{x}}_0$. Assume you have a density estimator $\hat f$; sum up the number of observations ${\bf{x}}$ for which $\hat f({\bf{x}}) < \hat f({\bf{x}}_0)$ and divide by the sample size. This gives you an approximation to the required probability.
This assumes that $\hat f({\bf{x}}_0)$ is not "too small" and your sample size is large enough (and spread-out enough) to give a decent estimate in the low-density regions. 20000 cases does seem large enough though, for bivariate ${\bf{x}}$.
Comment: Some quantitative analysis of this recommendation, or at least one example of an actual application, would be welcome. I suspect that the accuracy of your proposal is *heavily* dependent on the shape of the kernel. This would make me reluctant to rely on such a calculation without substantial study of its properties.


Plot two lists with different color with stem

Question: I plot a list (s_n_hat) with the Matlba-like stem(), like this:
markerline, stemlines, _ = plt.stem(s_n_hat, '-.')
plt.setp(markerline, 'markerfacecolor', 'b')
plt.setp(baseline, 'color','r', 'linewidth', 2)
plt.show()

In my real application I want to plot the hits with blue and the misses with red, how should I do that? So, some elements should be colored blue and some red.
Assuming that my vector has its first part with hits and its second one with misses, I tried to do this:
s_n_hat = [1, -1, 1, 1, -1, 1, 1, 1, 1]
markerline1, stemlines, _ = plt.stem(s_n_hat[0:5], '-.')
plt.setp(markerline1, 'markerfacecolor', 'b')
markerline2, stemlines, _ = plt.stem(s_n_hat[6:9], '-.')
plt.setp(markerline2, 'markerfacecolor', 'r')
plt.setp(baseline, 'color','r', 'linewidth', 2)
plt.show()

and I would expect the first elements to be blue and all the others red, but they seem to be mixed:

Any idea?
Comment: @lbellomo mixed, updated with a picture!
Comment: What do you mean by "random"? Have a blue dot and a red dot for the same x? That they overlap?
Answer: From the documentation:

If no * x * values are provided, the default is (0, 1, ..., len (y) -1)

Then you need to pass an x, but the points overlap. Something like:
s_n_hat = [1, -1, 1, 1, -1, 1, 1, 1, 1]
x1 = list(range(0, 5))
x2 = list(range(5, 8))
markerline1, stemlines, _ = plt.stem(x1, s_n_hat[0:5], '-.')
plt.setp(markerline1, 'markerfacecolor', 'b')
markerline2, stemlines, _ = plt.stem(x2, s_n_hat[6:9], '-.')
plt.setp(markerline2, 'markerfacecolor', 'r')
plt.show()


derive formula for height of tower on a hill

Question: I'm working through a book to learn trig on my own and I got stuck with the following.  This is the image given and the text in the book reads:

Suppose you are standing an unknown distance away from a cliff of height $h$.  You need to know the height $t$ of a tower located on top of the cliff.   You know that the angle of elevation of the bottom of the tower is $B$ and the angle of elevation of the top of the tower is $A$.  Derive a formula for the height of the tower.

The solution they gave is $t = h\left({{tan A}\over{tan B}}-1\right)$.  I don't quite understand how to derive that answer. I think that the height is going to be $d(tanA - tanB)$ where $d$ is the unknown adjacent side. I get stuck after that.  The more verbose the answer the better.  Thanks!
Comment: Note: your answer is in terms of $A,B$, and $d$, while theirs is in terms of $A,B$, and $h$.  They may be both right.
Answer: We have $$\tan A=\frac{t+h}d\iff d=\frac{t+h}{\tan A}$$
Similarly, $$\tan B=\frac hd\iff d=\frac h{\tan B}$$
Compare the two values of $d$
Answer: Call the distance to the hill $d$.
Then $\tan B = \frac{h}{d}$ and $\tan A = \frac{h+t}{d}.$
Eliminating $d$ gives the desired result:
$$\frac{h}{\tan B} = \frac{h+t}{\tan A}$$
$$\frac{h}{\tan B} = \frac{h}{\tan A}+ \frac{t}{\tan A}$$
$$\frac{t}{\tan A} = \frac{h}{\tan B} - \frac{h}{\tan A}$$
$$t = (\tan A)\left(\frac{h}{\tan B} - \frac{h}{\tan A}\right)$$
$$t = h(\tan A)\left(\frac{1}{\tan B} - \frac{1}{\tan A}\right)$$
$$t = h\left(\frac{\tan A}{\tan B} - \frac{\tan A}{\tan A}\right)$$
$$t = h\left(\frac{\tan A}{\tan B} - 1\right).$$
Comment: I don't understand how you're pulling out the $t$.  I tried cross multiplying and distributing the $tanA$ across the $(h+t)$ but I'm missing some step.
Comment: I added the part that pulls the $t$ out into its own fraction. Does that help?
Comment: I understand how you pulled it into its own fraction but then you  jump to the final expression and I'm not sure of the steps that you used to get there.
Comment: Straight algebra.  I added the intermediate steps.
Comment: Thank you so much.  I didn't understand when $h$ was pulled out and a 1 placed in its place.   Thanks again!
Comment: It was my pleasure.


Operator '+' can't be applied to operands of types 'decimal' and 'double' - NCalc

Question: Estou a usar a lib NCalc
Uma simples formula como "Abs(-1) + Cos(2)" dá a seguinte excepção:

Operator '+' can't be applied to operands of types 'decimal' and 'double'

Porquê? Como resolver?
O calculo esta a ser executado da seguinte forma:
new Expression("Abs(-1) + Cos(2)").Evaluate()

A única discussão relacionada no site do projecto é um pouco antiga e fala sobre editar o codigo fonte https://ncalc.codeplex.com/discussions/346702
Comment: @Omni e todos. Por favor não atirem sugestões para o ar. Se nunca usaram o NCalc não vão compreender a minha questão.
1º Não posso passar -1m e 2m pois não são números válidos.
2º Não são os parametros de Abs e Cos que têm o problema. É a soma do resultado de Abs e Cos
Comment: A sua resposta não é construtiva. Apenas traduziu o texto da excepção. A minha questão prende-se com o facto de Math.Abs(-1)+Math.Cos(2) functionar em C# mas não na biblioteca NCalc. Se nunca usou nem conhece a biblioteca nem devia estar comentando aqui.
Comment: ok, sem problemas.
Comment: Uma das funções, `Abs` ou `Cos`, está retornando um valor `decimal` e outra está retornando um `double`. Acredito que se você tem acesso ao fonte da lib seria melhor alterar o tipo de retorno de uma das funções para evitar o erro ou utilizar algum recurso de conversão de tipos se ela possuir.
Comment: @RichardDias, a lib é open source. Já coloquei a questão no [codeplex](https://ncalc.codeplex.com/discussions/613634)

Não tenho conhecimento suficiente para tentar perceber se é um problema do código ou se estarei a fazer alguma coisa errado do meu lado.
Comment: Acredito que seja da lib ou uma má utilização dela pela sua parte. Você passa uma `string` para o construtor da class `Expression` e essa string é avaliada e transformada em uma fórmula correto?
Comment: Acho que você já tem a resposta na sua pergunta: https://ncalc.codeplex.com/discussions/346702 Agora é colocar as mãos na massa e alterar o código fonte para corrigir este problema
Comment: Não entendo de NCALC, mas sua expressão está entre aspas duplas, pelo que eu entendo isso seria uma concatenação e não uma soma, não uma expressão aritmética.
Answer: Não existe nenhum problema com a lib NCalc, a questão é que um método retorna Decimal e o outro retorna Double. O compilador .NET não permite operações entre estes dois tipos de objeto devido ao fato de a precisão dos dois serem muito diferentes.
O correto é converter o resultado de um dos métodos para o tipo de dados do outro método.
using System;

public class Program
{
    public static void Main()
    {
        double dbl = 1;
        decimal dec = 2;

        // Neste exemplo converti o valor double para decimal.
        var result = Convert.ToDecimal(dbl) + dec;

        Console.WriteLine(result);

        // Esta operação retorna a exceção Operator '+' can'tbe applied to operands of types 'decimal' and 'double'
        Console.WriteLine(dbl + dec);
    }
}

Comment: Existe sim um problema com a lib. Está corrigido no codigo fonte mas não na última versão do binário
http://ncalc.codeplex.com/SourceControl/changeset/5a719518101d
Comment: Na realidade o que falta é sair um build definitivo com a correção, mais da forma que foi proposta resolve temporariamente até a liberação dos arquivos binários.
Answer: Existe um problema com a lib NCalc que já está corrigido no codigo fonte.
http://ncalc.codeplex.com/SourceControl/changeset/5a719518101d
esta revisão não está disponível como um binário.
Comment: Criei um clone no [github](https://github.com/pitermarx/ncalc-edge), liguei ao [AppVeyor](https://ci.appveyor.com/project/pitermarx/ncalc-edge) E publiquei no [Nuget](https://www.nuget.org/packages/NCalc-Edge/) uma versão mais actulizada.

Também [iniciei](https://github.com/pitermarx/ncalc2) um novo [projecto](https://ci.appveyor.com/project/pitermarx/ncalc2) que pretende [actualizar](https://www.nuget.org/packages/NCalc2) para o antlr4
Answer: using System;

class Program
{
  public void Main()
  {
    double a  = 1;
    decimal b = 2;
    a = Convert.ToDouble(1);
    b = Convert.ToDouble(2);

    int valor = a + b;

    Console.Write(int.ToString());

    return 0;
  }
}


How can table_name be a property in my post query?

Question: I want this query to be generic on the table_name meaning that there is in my JSON file a new property named "device" which indicates in which table the data will be inserted.
the problem is that in my SQL request I can't specify it. Here is what I tried:
 INSERT INTO ${device} (adc_v, adc_i, acc_axe_x, acc_axe_y, acc_axe_z, temperature, spo2, pa_diastolique, pa_systolique, indice_confiance, received_on, bpm)' +
            'values(${adc_v}, ${adc_i}, ${acc_axe_x}, ${acc_axe_y}, ${acc_axe_z}, ${temperature}, ${spo2}, ${pa_diastolique}, ${pa_systolique}, ${indice_confiance}, ${received_on}, ${bpm})'

here is my JSON on postman:
{
"device": "tag_7z8eq73",
"adc_v": 130,
"adc_i": {{RandomCourant}},
"acc_axe_x": {{RandomAccX}},
"acc_axe_y": {{RandomAccY}},
"acc_axe_z": {{RandomAccZ}},
"temperature": {{RandomTemp}},
"spo2": {{RandomSpo2}},
"pa_diastolique": {{RandomDias}},
"pa_systolique": {{RandomSys}},
"indice_confiance": {{RandomIndiceConf}},
"received_on": "{{$isoTimestamp}}",
"bpm": {{RandomBpm}}}

The table name is : tag_7z8eq73
here is the error that is returned to me:
error: erreur de syntaxe sur ou près de « 'tag_7z8eq73' »

Looks like I am close to the solution but there is a syntax problem, the quote ? is my way the right one?
Comment: "*a property which indicates in which table the data will be inserted*" - this sounds like a bad idea. Surely there's a lot of tables where you don't want anyone to insert values?
Comment: Please post the js code that builds and executes this query. What library do you use to connect to postgres?
Answer: const device = req.body.device;
console.log(device)
return db.none('INSERT INTO '+device+' (adc_v, adc_i, acc_axe_x, acc_axe_y, acc_axe_z, temperature, spo2, pa_diastolique, pa_systolique, indice_confiance, received_on, bpm)' +
        'values(${adc_v}, ${adc_i}, ${acc_axe_x}, ${acc_axe_y}, ${acc_axe_z}, ${temperature}, ${spo2}, ${pa_diastolique}, ${pa_systolique}, ${indice_confiance}, ${received_on}, ${bpm})',
        req.body)

try this
Comment: Please don't, that's a prime SQL injection! Use parameterised queries instead, and/or at least escape the table name
Comment: How to destroy your database and / or create data breaches… This is how.


How to substract current url in C#?

Question: I want to get root url?
@Request.Url.AbsoluteUri

This is example if i have somthing like this
http://www.example.com/contact if I am  on page contact page
I want to get this like http://www.example.com is this possible?
Comment: Duplicate of http://stackoverflow.com/questions/61817/whats-the-best-method-in-asp-net-to-obtain-the-current-domain
Answer: var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

Answer: To get base URl use
Request.Url.Authority

How to substract current url in C#?


Summation of Piecewise Function

Question: Does the following equation makes any sense at all?
$$
    \frac{1}{|X|\cdot|Y|}\sum\limits_{x \in X}\sum\limits_{y \in Y}\begin{cases}
        1 & \mathrm{if~} x > y\\
        0.5 & \mathrm{if~} x = y\\
        0 & \mathrm{if~} x < y
    \end{cases}
$$
For every comparison of $x$ and $y$, I want to add 1, 0.5 or 0 according to the case statements, and then multiply by the left part of the equation. Is it correct the way it is written? Is there any more beautiful way of designing that equation?
Answer: It looks correct to me. I don't know what you mean by something more beautiful, but you could use the sign function.
$$\frac{1}{|X|\cdot |Y|} \sum_{\substack{x\in X \\ y \in Y}} \frac{1+\operatorname{sgn}(x-y)}{2} $$
Comment: Thanks for your response. By "beautiful" I meant something more didactic, such as splitting into two equations ($f(x)$ for the case statement and another equation for the summation). But what you provided is nice. I am more relieved to know that I didn't mess the equation by designing it the way I did.
Answer: $$\frac{1}{|X|\cdot|Y|}\left(|\{(x,y):x \in X,y\in Y:x>y\}|+\frac12|\{(x,y):x \in X,y\in Y:x=y\}|\right).$$

Alternatively,
$$\frac1{|X|\cdot|Y|}\left(\sum_{\substack{x\in X \\ y \in Y}}(x>y)+\frac12\sum_{\substack{x\in X \\ y \in Y}}(x=y)\right)$$
Comment: I think that this is a bit less readable than the original equation or than the one posted by Farnight. Nevertheless, thanks for your response.
Comment: That's right, the $|\{\cdot\}|$ notation is not ideal. A $\#$ could be used as well. Anyway, this form uses pure counting, whereas the $\text{sgn}$ approach hides this fact.
Comment: I agree with you. The ideal solution would be to show every component in a more didactic way. For instance, I had to search for $sgn()$ to know what it meant. Your second equation seems a lot better, despite having two sum iterations. Thanks.

Summation of Piecewise Function


Our datacentre is forcing us to change IP addresses, what is the best way to take advantage of the period when they're both active (failover gateway)?

Question: The subnet of IPs the datacentre gave us was apparently on loan, so they assigned us a new block and gave us two weeks to swap them over, during which both will be active. They're on totally different networks and subsequently have different gateways. The machines are a mixture of Debian, Ubuntu, Windows 2003, Windows 2008 R2.
Is it best just to add the second gateway with a higher metric (numerically speaking)? Most of the documentation I've found for running multiple gateways has been under the assumption that both will be active indefinitely. Whereas I'm after more of a failover model.
Comment: Do your machines have a second NIC? Do they need to talk to each other continuously?
Answer: Adding a second IP address and another gateway might be a problem indeed. Dead gateway detection mechanisms are not very sophisticated and far from perfect. Also, your ISP might be doing Reverse Path Filtering and thus preventing any kind of asymmetric routing.
What I would do is making sure your new gateway would route your old subnet's traffic out (chances are that it is the same router interface simply with another IP address added to it) and simply exchange the old default route for the new one after setting up the IP interface aliases with the new addresses instead of adding a new default route.


CKeditor via CDN optional plugins

Question: The latest Drupal Ckeditor Module 1.14 loads the Ckeditor library via CDN.
The table on http://ckeditor.com/presets-all shows the 5 possible packages to be used via CDN.
I am using the Full-all package.
This package has a lot of optional plugins.
How can I activate these optional Ckeditor plugins in Drupal ????
Answer: In the CKEditor profile area if I am hearing you correctly:

admin/config/content/ckeditor

CKeditor via CDN optional plugins


Node template only on specific page (Drupal 7)

Question: I've been reading through a ton of Drupal 7 theming docs but can't seem to find my answer.
Here's what I'm trying to do. I have two content types article and feature.
Nodes of both content types are displayed on my /blog page via the Views module. All working great so far.
When the node of type article is listed, it uses the node--article.tpl.php template, and when a node of type feature is listed on the blog listing page, is uses node--feature.tpl.php.
This is all as expected, BUT for feature types, I want to display the node--article.tpl.php template only on the /blog page, and use node--feature.tpl.php (the default) for that type otherwise.
In other words, I'd like to keep the templates separate, but use the same template for both article and feature types on the blog listing page (node--article.tpl.php).
Is there way to create a node-page-specific template file (use this template for this node ONLY if on this page)?
Answer: add template.php:
function THEMENAME_preprocess_node(&$vars) {
  if (request_path() == 'specific/page') {
    $vars['theme_hook_suggestions'][] = 'node__specific';
  }
}

and create file node--specific.tpl.php in theme dir
Answer: If you're using views why not just switch to field display rather than node display? You could probably then just copy your node--article.tpl.php to the right views tpl and it would just pick it up.
Answer: While considered evil in certain circles, you could certainly put something like:
<?php

$foo=explode('/',$_GET['q']);

if ($foo[0]=='blog') {

    ALL YOUR BLOG SPECIFIC TEMPLATE PHP GOES HERE

} else {

    TEMPLATE PHP FOR EVERYWHERE ELSE GOES HERE

}

in your node template file.


Migrate users from a table with non-unique email column

Question: I'm using the Migrate module to migrate users from a non-Drupal PHP/MySQL site to Drupal 7.  The users are spread across two tables, the second of which has a non-unique email column, many values of which are present in the first table.
Generally, how do I import the second table, inserting users with new email addresses, and updating a couple fields whenever the email address is already present among the users created from the first table and avoiding duplication errors from the second?
The users from the first table are administrators.  The users in the second table are clients.  There are other tables that references administrators and clients by ID.  The ID columns for the two types of users are unique only within its respective table.
I made all the client uid's globally unique by adding 10,000 to all their uid's and updating their references in the other tables accordingly.
Answer: It depends on what kind of method, modules, tools you'd like to use to migrate the data as each of them might have their own settings for the kind of situation you had described.
If it's just a custom script migrating data between databases, then I would treat all users the same and import any of the tables first and then import the second one ignoring the error message - Drupal won't be importing users with the existing e-mail twice. After the migration you could go over each admin to assign appropriate role.
Comment: Thanks.  I neglected to mention I'm using the Migrate module for the migration.  I updated my question with that detail.
Comment: So how many admins you have? If not many, then why don't you migrate all the regular users first and deal with few admins manually?
Comment: Well, they're actually pretty weak admins.  There are about seven or eight thousand.
Comment: Wow, seven or eight thousand admins? Well, then you have to import admins first assigning admin roles to them and then only regular users, because Drupal should reject registering users with already existing e-mails.
Comment: I suspect a huge number of them are either spammers or testers, but I can't be sure.  I haven't found a way to do this with Migrate yet, so I wrote a script to look at each client, if the client email matches an admin email then change the uid to match too.  Next I'll write a script to add the client role to all the admins that are also in the client table.  When that's done I'll run Migrate on the clients; the new ones will be imported; the duplicates will error out.
Comment: Having several thousand admins is really abnormal. In most cases websites have quite limited number of admins, thus my suggestion to deal with users the same way and only mark few admins with appropriate roles afterwards come. Anyway, would you mind marking my answer as accepted if the general approach outlined works for you? Or at least suggest your own solution. Whatever you do, please do not leave your questions with no any answer accepted, so other users keep helping you.


Remove a certain amount of files with a sequence of characters in a directory

Question: I stopped a process to troubleshoot something. Now, I would like to start the process where it left off in CentOS 6.4.
This script I stopped runs a perl script in a loop to process all of the files in /dev/shm/split/. These files were split into many parts from a larger file. An example of how they are named are as follows:
file.txt.aa
file.txt.ab
file.txt.ac

...and so on.
I have identified that the script left off at file.txt.fy. So, I would like to remove all of the files in /dev/shm/split/ that are from file.txt.aa through file.txt.fy.
I tried to create a whitelist for the rm command by doing:
ls /dev/shm/split/ > whitelist
cat whitelist | egrep -v 'file.txt.[aa-fz]' | tee whitelist.tmp

This did not do what I had intended.
Please help me! Thank you!
Comment: Thank you. However, that only printed all of the files just likes /dev/shm/split/ did. Is there a way to maybe use rm -fvr /dev/shm/split/file.txt.[aa-fz] ?
Answer: The problem with your command is that you cannot match two characters with the square bracket pattern in bash. You should use something like that instead:
ls file.txt.[a-e]? file.txt.f[a-y]

Basically decompose your range into two ranges, the first will match .aa to .ez, and the second .fa to .fy (included).
Note that I have used the ls command here. I always find it a good idea to first echo or ls the commands/files you're going to run when the operations you do are potentially destructive. When you're sure it produces the right output, go on and use rm instead of ls.
Comment: Perfect! I did rm -fvr /dev/shm/split/file.txt.[a-e]? /dev/shm/split/file.txt.f[a-w] and it worked great. I realized I need to keep file.txt.fz because the process was midway through that file. Thank you so much!


Regex python para encontrar todos os valores com math na moeda brasileira

Question: Preciso de uma regex para encontrar todos os valores monetários do brasil, já fiz varias pesquisas e teste mas não consegui chegar a um resultado satisfatório.
1.566.545,00 = True
154.565,00 = True
22.555,00 = True
1.550,00 = True
11,10 = True
1100 = false

regex utilizada: '\d{0,}\W{0,}\d{1,}\d{0,}\W{0,}\d{0,}\,{0,1}\d{0,}'

Comment: *"já fiz varias pesquisas e teste ..."* coloca na pergunta o que já tentou e o que está errado, assim fica mais fácil de alguém sugerir uma correção
Comment: Inclui a regex utilizada
Comment: humm isso da muito trabalho (do jeito que está ai), poderia fazer algo assim "veja se a cada ponto existe um grupo de 3 digitos a seguir", que ficaria assim `(.\d{3})` ou seja, se houver um ponto precisa precer um grupo de 3 digitos, assim faz isso uma vez apenas
Comment: *não consegui chegar a um resultado satisfatório* nesse caso o que é um resultado satisfatório?
Comment: Entendi, vou fazer alguns teste pra ver
Comment: @AugustoVasques posso ter me expressado mal, um resultado satisfatório seria dar True nos valores informados
Answer: \d{0,} significa "zero ou mais dígitos", então se não tiver nenhum dígito, também vai encontrar um match.
Enfim, um valor monetário da forma que você quer segue as seguintes regras:

pode ter até 3 dígitos iniciais
depois, pode ter um ponto seguido de mais 3 dígitos, e isso pode se repetir várias vezes (ou nenhuma)
sempre termina com vírgula e dois dígitos

Uma primeira tentativa seria:
import re

regex = re.compile(r'^\d{1,3}(\.\d{3})*,\d{2}$')

valores = ['1.566.545,00', '154.565,00', '22.555,00', '1.550,00', '11,10', '1100']
for v in valores:
    print(f'{v} = {bool(regex.match(v))}')

Usei os marcadores ^ e $, que indicam o início e final da string, assim eu garanto que ela só tem o que está na regex.

\d{1,3} quer dizer "no mínimo 1 e no máximo 3 dígitos"
Depois temos um ponto, seguido de exatamente 3 dígitos (o {3} indica que são exatamente 3). Tudo isso está entre parênteses e com o quantificador *, que significa "zero ou mais vezes" (é o mesmo que {0,}). Ou seja, o ponto seguido de 3 dígitos pode se repetir várias vezes (ou nenhuma)
Depois temos a vírgula e mais dois dígitos

A saída do código acima é:
1.566.545,00 = True
154.565,00 = True
22.555,00 = True
1.550,00 = True
11,10 = True
1100 = False

Mas isso ainda não trata alguns casos, como por exemplo 012,12 - deveria começar com zero? Os únicos casos que talvez pudessem começar com zero seria 0,15 ou 0,00 por exemplo. Se for o caso, aí já começa a complicar. Teria que ser algo como:
regex = re.compile(r'^((?!0)\d{1,3}(\.\d{3})*|0),\d{2}$')

Agora usei alternância (o caractere |, que significa "ou"). E ela tem duas alternativas:

(?!0)\d{1,3}(\.\d{3})*: o trecho (?!0) é um lookahead negativo, que verifica se não tem um zero à frente. O restante é o que já vimos acima (os dígitos e as sequências de ponto + 3 dígitos). Ou seja, esta sequência não pode começar com zero.
0: é um único dígito zero

Isso quer dizer que, ou tem um zero e logo depois a vírgula, ou tem vários dígitos, desde que o primeiro não seja zero.
Depois disso temos a vírgula e os dois dígitos. Com isso, a regex aceita valores como 0,00 e 0,15, mas rejeita 00,00 e 012,12.
Comment: `regex = re.compile(r'^((?!0)\d{1,3}(\.\d{3})*|0),\d{2}$')` essa aqui funcionou exatamente como eu precisava. Muito obrigado pela ajuda! e pela explicação


Qual o code gml do MOVE FIXED no game maker?

Question: Gostaria de saber como é a função move fixed em gml (linguagem do game maker):

Encontrei alguns movimentos similares com os quais eu posso fazer algumas "gambiarras" para que os mesmos ajam da mesma forma que o move fixed, porém se o move fixed existe nas "actions" certamente que existe seu código em gml.
Answer: Bem a solução na realidade é bem simples.
Quando fiz a pergunta eu estava querendo que houvesse uma randomização na direção em que o objeto fosse (esquerda/direira) depois de colidir com um outro, isso pode ser feito com o if.

if (condiction01 == true){

  //ir para a direita com a velocidade 10
  move_towards_point(object.x+1,y,10);
  //valores positivos adicionados a x, o levam para a direita na horizontal

}else{

  //ir para a esquerda com a velocidade 10
  move_towards_point(object.x-1,y,10);
  //valores negativos adicionados a x, o levam para a esquerda na horizontal

}

Lembrando que mesmo o applies estando "selfie" é necessário essa indicação object.x (+ ou -) 10 e não somente x (+ ou -) 1 para ser relativo à sua posição.
O y é o contrário do convencional. Com - se vai para cima e com + se vai para baixo.
Onde a imagem começa? Imagino que tenha pensado que no canto superior esquerdo, pronto é por isso. O ponto 0, 0 (x , y) fica no parte extrema superior esquerda, logo qualquer valor para baixo ou para o lado direito aumenta o seu valor.


Export DataStage Job Designs to .dsx file

Question: I am trying to export the DataStage job designs with executables. Below is the screenshots I use to export from the GUI.

This is the two commands I use:
<code>dsexport.exe /h=XX /U=XX /p=XX projectXXX /job=XXX jobname.dsx
dsexport.exe /h=XX /U=XX /p=XX projectXXX /job=XXX /EXEC /APPEND jobname.dsx
</code>
The file generated from commands is bigger than the one from GUI. Anyone knows how to use dsexport command to export jobs with the options as in the GUI screenshots. much appreciated. I am using Designer V8.5.
JS
Answer: C:\IBM\InformationServer\Clients\Classic>dsexport /d={ip address of server} /u={user id} /p={password} /job={job to export} {Project where job is located in} {FileName.dsx}
try this, it will export a single dsx file with all informations
P.S.I am using version 11.3
Answer: As you can see GUI is excluding some read-only files which is not excluded in command line this is why the file size difference is there.
Answer: You have "Include Dependent Items" unchecked in the GUI. The command line will include dependent items by default (i.e. shared containers or routines). You can disable this behaviour on the command line by using the /NODEPENDENTS command switch.


STR_REPLACE com Array

Question: Como eu faço para trocar o espaço por %20 com valores que vem de um Array ?
Cheguei até aqui seguindo exemplos, mas continua dando erro:
<code>foreach ($jsonArr['data'] as $row) {
    $nome[] = $row['artist']['name']; //artista
    $titulo[] = $row['title'];//nome da música
    $musica[] = $row['preview'];//audio de 30 segundos
    $album[] = $row['album']['cover_xl'];//foto do album
    $titulo2 = str_replace(array(' ', '%20'), '', $titulo);
    echo $titulo2; }
</code>
Preciso disso para por na url de outra API
Answer: Vou deixar aqui a solução, pode ajudar alguém.
<code>$i = 0;
foreach ($jsonArr['data'] as $row) {
    $nome[] = $row['artist']['name']; //artista
    $titulo[] = $row['title'];//nome da música
    $musica[] = $row['preview'];//audio de 30 segundos
    $album[] = $row['album']['cover_xl'];//foto do album
    $titulo2 = str_replace(' ', '%20', $titulo[$i]);
    echo $titulo2;
$i++;
</code>

STR_REPLACE com Array


How to show data from external api to theme template?

Question: I am totally new to Drupal. I have given one assignment to build Drupal site which shows courses from our company site. I am totally stuck in one point. I need to show data from our api into theme template.
Can you please guide me on this? If you have any example, please share with me. I will dig into it and I will try to solve my problem.
Comment: First of all I would not create a template for this unless absolutely necessary. There are so many options depending on your specific needs. Please narrow it a little. For instance just a shot in the dark, try to populate a custom table with the data and use Views to display it. [`hook_views_data`](https://api.drupal.org/api/views/views.api.php/function/hook_views_data/7) Will allow Views access to the custom table.
Answer: There are a few answers to that question, and it depends on the design (appearence and behaviors), but the Drupal foundation is usually the same.
1st step
Create a custom block and place it in a page (node of a generic type is a good option or a programmatically created page.
OR
Create a custom page (see ´hook_menu´)
2nd step
Create a custom theme function using ´hook_theme´ (template file is usually easier to maintain)
3rd step (connect to the API)
Due to performance considerations (async vs. sync request) I prefer to use JavaScript to get the data and present it on the page / block we created. (AngularJS is my friend..)
If JS is not an option, then you can make the request in ´hook_block_view´ in case you used custom block, ´hook_page_build´ or in your ´hook_menu´'s callback in case you chose a page in step 1.
Comment: You should note that this would be a good option (3rd step) if the data retrieved from  the API changes on a frequent basis. Otherwise, say it changes every few months or so, you should probably save the data to your server to make use of all the cache options.
Comment: This case is way more advanced and involves using Drupal's cache API with or wo custom entity or content type, maybe even cron task.. :) This case deserves another thread
Comment: I'll prefer 3rd option.But my issue is my block is not loading. I want show data in grid format. But $view->result is empty in
template_preprocess_views_view function of theme.inc, hence it is not even loading empty block.
Comment: Those are not 3 options, those are 3 steps. Why are you using Views? How do you retrieve the data with a view? Or are you just using View's theme function??


Services, OAuth and a mobile app

Question: I'm struggling with Drupal, OAuth and a (Cordova) mobile app I'm developing. I've made a custom module and it exposes data to the Services module. What I want to do now is get that data into my mobile app.
I've set up my endpoint, but I need authentication of course.
I've read the tutorials on 3-legged and 2-legged authentication, but from what I've read, I (think I) want the Client-flow. This is the flow where the user enters his/her username and password in the app.
Can anyone get me started on this flow? Is it even possible with Services and OAuth?
Tell me if you need any more info. I'm a developer, but mainly in the .NET space. I've managed with Drupal modules so far, but I find OAuth quite complicated.
Answer: First, this is a poorly worded question, so I'm answering the questions you asked, probably not what you really want though..
Both 3-legged and 2 legged work in Services with the OAuth module and the Services_oauth module enabled. I wrote a lengthy article on how to set this up here, and documentation here
But that doesn't really answer your question in terms of If I can help you get started with your flow. I suggest you ask a new question with the problems you're currently having rather than asking if we can help you get started on a solution we know nothing about.
This may help you understand why this is an extremely tough question to answer. Asking smart questions
Comment: True, it is a badly worded question (even though I'm no newbie to the SO platform :s ). I should probably just delete it... I'll be sure to check out your blog, thanks.
Comment: Not to worry, just try to be more specific about where you're falling flat and maybe we may be able to help you stand back up!

Services, OAuth and a mobile app


what does "eth0: link up" mean? /var/log/messages

Question: My server is being attacked (SYN flood attack) and what I see in /var/log/messages is a ton of:
r8169: eth0: link up
r8169: eth0: link up
r8169: eth0: link up

1. What does this mean?
I can't access the server during the attack, but I also can't access it after the flood has stopped, I have to restart the server.
2. Is it possible to avoid this restart? Is it possible to "autoreset" the connection without restarting the server manually?
Additional information:
Ubuntu server 10.04 64 bits
8GB RAM, dual core. Firewall: CSF (IPTables)
SYN flood attack against port 80 (apache2) with up to 50-70Mbps traffic
EDIT: @TimHaegele was right, it is a driver problem, once Ubuntu was upgraded the problem gone.
Answer: have you tried a new driver for the NIC?
It ist very likely that your kernel suffers a bug in the included module for the NIC.
Because it is really simple to build a new kernelmodul for your nic I really suggest to try it:
Here is a good tutorial:
http://ubuntuforums.org/showthread.php?t=1022411
I experienced a similar bug with incuded kernel from 10.04 more the once, and got it fixed with the driver from realtek.
Comment: it's not a random problem, it only happens during (and after) syn flood attack. I haven't had any problems with connectivity before (and I've been using this server for months). And it works fine after a reboot. Are you sure this will solve the problem? What does "link up" means?
Comment: well, you were right! The eth link up was caused by the driver (and the attacks of course), and seems to be solved since I upgraded ubuntu. Now there is no need to restart after attacks.
Answer: Your server should be accessible even after the attack if you have the right measures in place.
Take a look at your /etc/sysctl.conf
And add the following
# TCP SYN Flood Protection
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 3

Furthermore are you using local dns or external dns? If it's internal DNS then you might wanna try an external DNS such as 188.8.131.52 188.8.131.52 and see if that happens after.
Seems odd that you would keep getting these attacks, I operate many VPS and hardly ever see them :P
Comment: syncookies is enabled, tcp_max_syn_backlog = 1024 and tcp_synack_retries is not set. I will change it once the server is accessible again.
Comment: /etc/sysctl.conf edited (this guide also helped: http://linuxstuffs.wordpress.com/2009/10/25/drop-syncddos-attack/)
but I'm being attacked again.
internal/external DNS? I don't know, I will check my bind config files, but I haven't changed anything there.


How to prove this formula. Formula is for evaluate limits which answers are e to the power something.

Question: I would like to ask you about how to prove this formula.
I come up with this formula when i was browsing internet.
It works when i used it on given examples, but i would like to know if it works in general and how to prove it.
The formula is
$$\lim_{x \to \infty} f(x)^{g(x)} = \lim_{x \to \infty} e^{g(x)\cdot(f(x)-1)}$$
Consider f is polynomial function of first degree.
Thanks for answers.
Comment: Comparison with the correct substitution $(f(x))^{g(x)}=e^{g(x)\ln f(x)}$ would suggest the answer to be "NO".
Comment: But when i use it the answer is always right how is that possible. :)
Comment: Have you tried to find a case where $\lim_{x\to \infty}g(x)\ln f(x)\ne \lim_{x\to\infty}g(x) (f(x)-1)$ ?
Answer: This formula is true Only when $$\lim_{x \to \infty} f(x) = 1 \space \& \lim_{x \to \infty} g(x) \to \infty$$
Proof:
let $$L = \lim_{x \to \infty} f(x)^{g(x)}$$
Taking log on both sides, we get $$log(L) = \lim_{x \to \infty} g(x) \space log(f(x))$$
now, since $\lim_{a \to 0} \frac{log(1+a)}{a}=1$, if we substitute $1+a$ as $f(x)$, the limit changes to $\lim_{x \to \infty} \frac{log(f(x))}{f(x)-1}=1$ or $\lim_{x \to \infty} log(f(x)) = f(x)-1$
substituting the above result in the expression for $log(L)$, we obtain
$$ log(L) = \lim_{x \to \infty} g(x) \cdot (f(x)-1)$$
On taking an exponent both sides and removing the log, we get
$$L = \lim_{x \to \infty} e^{\space g(x) \cdot (f(x)-1)}$$
which is the required result
Answer: This is not generally true:
Take $f \equiv2$ and $g \equiv3$ the left side is equal $8$, the right side is equal $e^3$.
Comment: Ok but when it is function f is like $(x-2)/(x+5)$ it works
Comment: Lacking assumptions about functions, start by assuming they are degree 1 polynomials for example.


Cramér–Rao bound to multiple parameters

Question: I was reading Cramér–Rao bound to multiple parameters from Wikipedia page,  but I could not follow this line in the article:

Let $\displaystyle {\boldsymbol {T}}(X)$ be an estimator of any    vector function of parameters...

I could not understand what $\displaystyle {\boldsymbol {T}}(X)$ and $\displaystyle {\boldsymbol{\psi}}({\boldsymbol {\theta}})$ mean.
Can someone help?
Thanks
Answer: $\displaystyle {\boldsymbol {T}}(X)$ is a vector of estimators and $\displaystyle {\boldsymbol{\psi}}({\boldsymbol {\theta}})$ is its expectation. That is
$$
\mathbb{E}\left[\displaystyle {\boldsymbol {T}}(X)\right] = \displaystyle {\boldsymbol{\psi}}({\boldsymbol {\theta}}).
$$
As an example, consider a random sample from a univariate Normal distribution. Then ${\boldsymbol {\theta}} = (\mu, \sigma^2)^T$, $\displaystyle {\boldsymbol {T}}(X) = \left(\sum_i X_i , \sum_i X_i^2\right)^T$ and $\displaystyle {\boldsymbol{\psi}}({\boldsymbol {\theta}}) = (n\mu, n\sigma^2 + n\mu^2)^T$.
Comment: Thank you @Taylor, you have been generous enough and spared time to answer my doubts. I thought the $t$s are same. I will give it another try, if I could not succeed, I will draft an another question. Thank you again.
Comment: This may sound silly and I am sorry for that. I am interested in deciding a confidence interval for two parameters, then how do I get $\displaystyle {\boldsymbol {T}}(X)$ and $ {\boldsymbol{\psi}}({\boldsymbol {\theta}})$
Comment: yes I understand that, CRLB provides me a confidence interval. My problem: I have optimized a loss function with respect to two parameters and I am interested in obtaining a confidence band for them. I am available with Hessian matrix.
Comment: @pkj oh my fault, yeah if you're using maximum likelihood, you can get the "observed information" by looking at the negative Hessian. Then to get the covariance matrix you take the inverse of that; that's the CRLB.
Comment: on the last page of this document http://www.stat.umn.edu/geyer/old03/5102/notes/fish.pdf , you have $\mathbf{t}$ and I do not know what is that
Comment: @pkj that's a different "t". That one is a vector of weights. If you want to only have a CI for the first parameter, $\mathbf{t} = (1,0,0,\ldots)$. If you want an interval for the difference of the first two parameters, then $\mathbf{t} = (1,-1,0,\ldots)$. If you have separate questions, those should go in a different thread. Regarding what to do with your Hessian, that depends if you're minimizing the negative log likelihood or maximizing the log-likelihood. It will also depend on whether or not you scaled it.

Cramér–Rao bound to multiple parameters