iframe com designMode pegar html gerado dentro do iframe?

Question: Galera, estou usando um iframe junto com JavaScript para criar um editor de texto da forma citada abaixo:

E o código JavaScript é esse:
function MINI_EDITOR_DE_TEXTO(){
    this.frameEdit = window.frames['MINI_EDITOR'].document;
    this.frameEdit.designMode = 'on';
}

function ADD_NEGRITO(){
    this.frameEdit.execCommand('bold', false, null);
}

Quando o usuário selecionar um texto e chamar a função ADD_NEGRITO, o texto muda para negrito e dentro do iframe é adicionada uma tag texto selecionado.
A minha pergunta é, eu preciso pegar todo o html que é gerado dentro do iframe e passar para uma variável. Tentei da seguinte forma, mas não deu certo:
var IFRAME_PRICIPAL=document.querySelector(.MINI_EDITOR'').innerHTML;
alert(IFRAME_PRICIPAL);

Como posso fazer para que funcione? Desde já agradeço.
Answer: Você pode acessar o conteúdo do iframe dessa forma:
iframe.contentWindow.document.body.innerHTML;

e você consegue alterar o conteúdo assim:
iframe.contentWindow.document.body.innerHTML = "
novo conteúdo
";

O seu código então ficaria assim:
var IFRAME_PRINCIPAL = document.querySelector('.MINI_EDITOR');
var conteudo = IFRAME_PRINCIPAL.contentWindow.document.body.innerHTML;
alert(conteudo);


Problems with coins related to the generating function

Question: I'm solving a discrete math problem, but I have no idea how to solve the following problems. Regarding No. 1, should I just multiply the generating functions a (x) = 1 / 1-x and b (x) Σbn x ^ n? Would you please write what it would look like?
No. 2 is b (x) = 1 / (1-x) ^ 2 as a result of differentiating a (x). Is this way of thinking correct?
To be honest, I'm sorry, but I don't know what to do about numbers 3 and 4.
Suppose there are an infinite number of  1$,5$, and 10$ coins. At this time, n (n = 0, 1, 2, ...) coins are allowed to be duplicated from these coins. Let fn be the total number of choices to choose.
Also, let f (x) be the population function of the sequence f0, f1, f2, ....
1: Let a (x) be the generating function of the sequence 1, 1, 1, ..., and b (x) be the generating function of the sequence b0, b1, b2 .... At this time, Express the coefficient of the nth order term of a(x)b(x) using b0, b1, b2, ....
2: Let b (x) be the generating function of the sequence 1, 2, 3, ... again. Express b (x) in a closed form.
3: Explain that it is given by f (x) = (1 + x + x2 + x3 + ...) ^ 3.
4: Express fn by the formula of n.
Answer: For #1, note that
\begin{align}
a(x)b(x)
&= \sum_{n \ge 0} x^n \sum_{k \ge 0} b_k x^k \\
&= \frac{1}{1-x}\sum_{k \ge 0} b_k x^k \\
&= \sum_{k \ge 0} b_k \frac{x^k}{1-x} \\
&= \sum_{k \ge 0} b_k \sum_{n \ge k} x^n \\
&= \sum_{n \ge 0} \left(\sum_{k=0}^n b_k\right)x^n,
\end{align}
so $a(x)b(x)$ is the generating function of the partial sums of $(b_n)$.
For #2, you can differentiate $\frac{1}{1-x}$, but you can also use #1 by noting that $1,2,3,\dots$ is the sequence of partial sums of $1,1,1,\dots$, so just multiply $\frac{1}{1-x}$ by $\frac{1}{1-x}$.
For #3 and #4, please start a new question.


Método recursivo em Python que devolva quantas vezes um determinado elemento aparece num vetor

Question: Quero fazer um método recursivo em Python que devolva quantas vezes um elemento aparece em um vetor. Abaixo segue meu código usando a busca binária:
    def binaryrec(valor, itens, menor, maior):
    vezes = 0
    maior = len(itens) if maior is None else maior
    pos = menor + (maior - menor) // (len(itens) // 2)

    if pos == len(itens):
        return False
    for i in range(len(itens)):
        if itens[pos] == valor:
            vezes = vezes + 1
            return vezes
    if maior == menor:
        return -1
    elif itens[pos] < valor:
        return binaryrec(valor, itens, pos + 1, maior)
    else:
        assert itens[pos] > valor
        return binaryrec(valor, itens, menor, pos)

itens = [0, 10, 20, 30, 40, 30, 30, 70, 80]
valor = 30
maior = 80
menor = 0
r = binaryrec(valor, itens, menor, maior)
print(r)

Comment: Primeira observacao, voce tem que ordenar o seu array de itens para conseguir fazer uma busca binaria efetiva. seu array: itens = [0, 10, 20, 30, 40, 30, 30, 70, 80] tem 30 depois do 40. Se seu array itens nao estiver em ordenado eh mais rapido voce ir elemento por elemento para contar as ocorrencies. Se seu array itens ja estiver ordenado busca binaria eh uma solucao mais rapida.
Answer: Primeiramente, recursão não é a melhor forma de resolver esse problema (veremos opções não-recursivas no final). E busca binária só faz sentido em listas ordenadas (mesmo assim, a busca binária serve para encontrar um único elemento, não para contar quantas vezes um elemento ocorre).
Enfim, uma forma de resolver é:
def count(lista, valor):
    if not lista: # lista vazia
        return 0
    c = 1 if lista[0] == valor else 0
    return c + count(lista[1:], valor)

itens = [0, 10, 20, 30, 40, 30, 30, 70, 80]
print(count(itens, 30)) # 3

Ou seja, se a lista for vazia, retorna zero. Senão, verifica se o primeiro elemento é igual ao valor (e aí eu decido se contabilizo 1 ou 0).
Depois eu somo isso (o 1 ou 0) com a contagem do restante da lista: lista[1:] cria uma sub-lista contendo do segundo elemento em diante.
Não é lá muito eficiente porque cria várias sub-listas, além de poder estourar a pilha se a lista for muito grande, veja.

Outra alternativa é passar o índice a ser verificado:
def count(lista, valor, i=0):
    if i >= len(lista):
        return 0
    c = 1 if lista[i] == valor else 0
    return c + count(lista, valor, i + 1)

itens = [0, 10, 20, 30, 40, 30, 30, 70, 80]
print(count(itens, 30)) # 3

Essa é menos pior que a anterior porque não cria sub-listas, mas também tem o problema do estouro de pilha, veja.

Até dá para usar busca binária
Você pode usar busca binária para encontrar a posição do elemento. Mas como já dito, busca binária só funciona se a lista estiver ordenada, então primeiro você deve ordená-la.
Em seguida, como a lista está ordenada, basta verificar os elementos da direita e da esquerda do elemento encontrado e obter a contagem total:
# retorna a posição do valor na lista (ou -1 se não for encontrado)
def busca_binaria(lista, inicio, fim, valor):
    if (fim < inicio):
        return -1

    meio = inicio + (fim - inicio) // 2
    if lista[meio] == valor:
        return meio

    if lista[meio] > valor:
        return busca_binaria(lista, inicio, meio - 1, valor)

    return busca_binaria(lista, meio + 1, fim, valor)

def count(lista, valor):
    # busca o índice do elemento
    ind = busca_binaria(lista, 0, len(lista) - 1, valor)
    # elemento não existe na lista
    if ind == -1:
        return 0

    count = 1
    # verifica os elementos à esquerda
    left = ind - 1
    while left >= 0 and lista[left] == valor:
        count += 1
        left -= 1

    # verifica os elementos à direita
    right = ind + 1
    while right < len(lista) and lista[right] == valor:
        count += 1
        right += 1

    return count

itens = [0, 10, 20, 30, 40, 30, 30, 70, 80]
itens.sort()
print(count(itens, 30)) # 3

Não use recursão para este caso
Como já dito, as melhores soluções são as não-recursivas. A mais simples é usar o que já tem pronto na linguagem:
print(itens.count(30))

Mas se quiser fazer manualmente:
cont = 0
for valor in itens:
    if valor == 30:
        cont += 1
print(cont)

Ou ainda:
print(len(list(filter(lambda x: x == 30, itens))))

# ou
print(sum(1 for _ in filter(lambda x: x == 30, itens)))


Why do we have $E_0(\Bbb N^\Bbb N)\sim_c E_0$?

Question: Let $E_0$ and $E_0(\Bbb N^\Bbb N)$ be the relations of eventual agreement on $2^\Bbb N$ and $\Bbb N^\Bbb N$, so $$xE_0y\iff\exists m\forall n\geq m x(n)=y(n)$$ and similarly for $E_0(\Bbb N^\Bbb N)$. Clearly $2^\Bbb N\hookrightarrow\Bbb N^\Bbb N$ is a continuous reduction of $E_0$ to $E_0(\Bbb N^\Bbb N)$. Why do we have a continuous reduction in the opposite direction as well?
Comment: You can find a proof in Gao's book Invariant descriptive set theory (Proposition 6.1.2).
Comment: thanks for the reference @timon92, this seems to be less straightforward than I imagined
Answer: Here's one way to do it:
Let $(A_i)_{i\in\mathbb{N}}$ be a partition of $\mathbb{N}$ into infinitely many infinite pieces, and let $a_{i,j}$ be the $j$th smallest element of $A_i$. Given $f\in\mathbb{N}^\mathbb{N}$, we'll build a set $S_f\in 2^\mathbb{N}$ by coding $f(i)$ into $S_f\upharpoonright A_i$: $$S_f(\langle i,j\rangle)=\begin{cases}
1 & \mbox{ if $f(i)<j$,}\\
0 & \mbox{ otherwise.}\\
\end{cases}$$
Here $\langle\cdot,\cdot\rangle$ is your favorite pairing function. The infinite binary sequence $S_f$ is built by interweaving infinitely many infinite binary sequences $S(\langle i, -\rangle)$, each of which is eventually zero; this latter point guarantees $(S_f,S_g)\in E_0$ whenever $(f,g)\in E_0(\mathbb{N}^\mathbb{N})$, while the other direction follows since for all $m$ there is some $n$ such that for all $k>n$ we have $A_k\cap\{0,1,...,m\}=\emptyset$.
Comment: I'll accept the answer after checking the details that $f\mapsto S_f$ is continuous, but that's a very nice construction!
Comment: @confusedstudent Note that to check whether $S_f(\langle i,j\rangle)=0$ or $=1$, we just check a corresponding bit of $f$ - this is the reason the construction is continuous.
Comment: Could you elaborate a little on what you mean?


doing research/project on spacetime curvature

Question: So I recently undertook the daunting task of presenting a project on general relativity for a differential geometry course.
Does anyone have any suggestions for topic or topics to narrow it down to?
I have about a month and a half to work on this.
Reading material suggestions would also be greatly appreciated!
Comment: What is the level of the class? i.e. how much differential geometry do you know?
Comment: I have heard that without Riemannian geometry one can not present theory of relativity well.So perhaps start at that
Comment: beginning graduate level, we've learned up to curves and surfaces (local)
Answer: Semi-Riemannian geometry : with applications to relativity by Barrett O'Neill
The Cauchy Problem in General Relativity by Ringstrom
On the Topology and Future Stability of the Universe by Ringstrom


How to assign the link path out of the application in asp.net?

Question: How to assign the link path out of the application in asp.net?
Normally the application will be stored in

C:\Documents and Settings\MyName\My Documents\Visual Studio
  2010\Projects\

I only able to let the user to access the file within the Projects.
in web browser, it will be displayed as http://localhost:4783/Images/image.bmp
my question is how to enable the user to access the item out of the application?
for example:

C:\Documents and Settings\ITEMS\

if i just assign the absolute path which is
Click

The result will be http://localhost:1888/C:/Documents and Settings/ITEMS/image.bmp
and it is not correct.
Comment: This is really a web server setup issue, where you need to set up a virtual directory on whatever web server you are using pointing to your ITEMS directory.  Then you can point your hrefs to the new virtual directory and not a physical directory.
Comment: Try use protocol `file://`, for example 'file:///c:/Documents and Settings/ITEMS/image.bmp'
Comment: @fliptheweb the `file://` protocol is local
Comment: @DEN: Here's a [link](http://msdn.microsoft.com/en-us/library/bb763173.aspx) on how to setup virtual directories in IIS
Answer: The Problem is that you use a local path, the user cant access that because it is not part of
your webserver virtual directory.
The File URI Sheme should be
file:///c:/Documents and Settings/ITEMS....

But, again, this only works on your machine if the users dont have direct access
from their machines to this path.
more informations about the File URI Sheme
But you should read Configuring IIS Web Sites and Virtual Directories
Comment: it is only working in internet explorer but google chrome fail to open it. any alternative?
Comment: this is a security restriction, i think, because. Please check out how to configure your webserver to prevent links like that.
Answer: Users don't have a permission to access the resources outside the virtual folder. You must have to add/copy the resources (images or other files) under virtual folder.
Answer:
If you want the file to be opened on the client side, your best bet is
  to create and HTTP Handler

For more information, you can look to this question:
How to open file with its application?


Bash function to get all dependencies recursively

Question: I've got a command that provide me the list of direct dependencies of some package.
Here it is, for example:
# get-dep some-random-package
libunistring-1.0
libidn2-2.3.2
glibc-2.35-163
xz-5.2.7
gcc-11.3.0-lib
attr-2.5.1
acl-2.3.1
gmp-with-cxx-stage4-6.2.1
coreutils-9.1
findutils-4.9.0
bash-5.1-p16
pcre-8.45
gnugrep-3.7
zstd-1.5.2
zstd-1.5.2-bin
zlib-1.2.13
openssl-3.0.7
libxml2-2.10.3
bzip2-1.0.8
libarchive-3.6.1-lib
libarchive-3.6.1
gzip-1.12
some-random-package

I need to get the whole list of dependencies.
by using this get-dep command I am trying to write bash function that give me the whole list of dependencies recursivly.
At first glance this function should recursivly pass through each package.
I tried to do next:
#!/bin/bash -e

get_the_whole_list_of_dependencies() {
  local list=$(get-dep "${1}")
  local cnt=$(echo "${list}"| wc -l)
  if [ "${cnt}" == 1 ]; then
    echo "${list}"
  else
    for f in ${list}; do
      get_the_whole_list_of_dependencies "${f}"
    done
  fi
}

get_the_whole_list_of_dependencies some-random-package

However something goes wrong and the function is turned to be an endless loop.
Does anybody help me with that issue?
Comment: Then you may have some circular dependency... Anyway, printing the whole stuff (counts and lists) shall help understanding where the endless loop comes from.
Comment: @Jayjargot this is a great advice (about list of package that have been analyzed). I've just realized that my loop doesn't seem to be endless but it is really really really long.
Comment: Better use bash arrays than strings, `echo` and `wc -l`, it would be a bit safer. But as for your issue could it be that you have an extra newline at the end of your list of dependencies? You could print the `cnt` count and investigate why it is not equal to 1 when it should be.
Comment: Hi. Thanks for reply. Regarding extra newline, think it is not possible. I used `set +x`, `set -x` to debug and saw that sometimes cnt==1.
Comment: When using recursive call, It is needed to pay attention that each sub sequence call is applied on a reduce set of data: I mean that the chain of calls is gonna end.

Thinking about @RenaudPacalet remark on the circular dependencies, maybe it is wise to use an additional bash array variable, global, (a list) containing all the dependencies already analyzed...

The goal is to avoid analyzing twice the same lib
Answer: As discussed in comments your algorithm is inefficient because it processes the same package as many times as it is encountered. Another bash array could be used to keep track of the already seen packages and avoid this.
Note also that your script prints only the leaves of your dependency tree while you state that you want the whole list of dependencies recursively.
If you use a bash array to avoid processing twice the same package, and if your bash supports them, better use an associative array (local -A seen) as it makes very easy to check if a package has already been seen.
Example:
_get_the_whole_list_of_dependencies() {
  printf '%s\n' "$1"
  local -a list=($(get-dep "$1"))
  seen["$1"]=1
  local -i cnt=${#list[@]}
  if (( cnt > 1 )); then
    for f in "${list[@]}"; do
      if ! [[ -v seen["$f"] ]]; then
        _get_the_whole_list_of_dependencies "$f"
      fi
    done
  fi
}

get_the_whole_list_of_dependencies() {
  local -A seen=()
  _get_the_whole_list_of_dependencies "$1"
}

And then:
$ get_the_whole_list_of_dependencies zlib
zlib
xz
gettext
gettext-runtime
libiconv
gperf
gettext-tools-libs
libtextstyle
ncurses

Comment: Thank you again. Could you tell me please what this line means:
```seen["$1"]=1```
Comment: It sets to `1` the value corresponding to key `"$1"` in associative array `seen`. Associative arrays are arrays which indexes are not numbers but any string. In other programming languages they are sometimes named dictionaries, hashes, maps... Here we use it to "_remember_" that we already encountered package `"$1"`. And we test this with `[[ -v seen["$f"] ]]`.
Comment: Everything works. Thank you so much!!! @renaud-pacalet I promise to vote your answer when I gain enough rating. I tried to vote, but system doesn't accept my voice, unfortunately.
Answer: This is an alternative (and Shellcheck-clean) way to implement a function to print all of the dependencies of a package recursively:
function get_all_dependencies
{
    local packages=( "$1" )     # packages whose dependencies need to be found

    local -i first=0 last=0
    local -A is_printed
    local pkg get_dep_output dep
    while (( first <= last )); do
        pkg=${packages[first++]}
        get_dep_output=$(get-dep "$pkg")
        while read -r dep; do
            [[ -z $dep ]] && continue
            [[ -n ${is_printed[$dep]-} ]] && continue
            printf '%s\n' "$dep"
            is_printed[$dep]=_
            packages[++last]=$dep
        done <<<"$get_dep_output"
    done
}

Comment: `get_all_dependencies` does not call itself. Didn't you forget to recurse?
Comment: @RenaudPacalet, it doesn't need to use explicit recursion.  It puts packages in the `packages` array instead of calling itself recursively, and it continues until every package in the array has had all of its dependencies checked.  I have tested the function (lightly) with multiple levels of package dependencies.
Comment: But recursively means that is `a` depends on `b`, `b` on `c`, and `c` on `d` you want to catch `d`, not just `a` and `b` or `a` and `b` and `c`. The length of dependency chains is not limited. You must explore the tree from root to leaves, even if the leaves are very far from the root.
Comment: @RenaudPacalet, the code explores the entire tree from root to leaves.  It employs a standard algorithm: using a queue (implemented with the `packages` array) to do a breadth-first traversal.  The algorithm can handle chains of arbitrary length.
Comment: Oh, I see, sorry, I was so obsessed by recursivity that I did not realize the `while (( first <= last ))`. I beg your pardon. This is more iterative than recursive, but it's perfect, and maybe more efficient than a recursive approach, especially with deep trees.


Let $X$ and $Y$ normed spaces and $T:X\rightarrow Y$ one bounded surjective linear transformation. Show that they are equivalent:

Question: $(I)$ $T$ is reversible and $T^{-1}:Y\rightarrow X$ is bounded.
$(II)$ Exists $b>0$ such that $||T(x)||\geq b||x||,\forall x\in X.$
$(III)$ All linear inverse on right of $T$ is bounded, and $$\sup \{||S||: S\text{ is linear inverse on right of }T\}.$$
I proved that $(I)\Leftrightarrow(II)\Rightarrow (III)$. Now, I triyng prove that $(III)\Rightarrow (II)$ or $(III)\Rightarrow (I)$.
Comment: Is there meant to be $< \infty$ in (III)?
Comment: What did you get so far?
Comment: @LucasHenrique Im trying use $||T(x)||\leq ||T|| ||x||$ and surjective $T^{1}(y)=x$ for some $y\in Y$.
Comment: @KennyLau I dont know! maybe have one error. But, in my exercise I do not have this hypothesis. You mean dim$X<+\infty$?
Answer: Suppose that $T$ is not injective, and let $U$ be a bounded right inverse, and $e\in Ker(T), \|e\|=1$. Let $\alpha$ be a bounded non zero $1$-form defined on $Y$, defined $U_n(x)=U(x)+n\alpha(x)e$, $U_n$ is a right inverse and the sequence $U_n$ is not bounded since $\|U_n(x)|\geq |n\alpha(x)\|-\|U(x)\|$. If $\|x\|=1$ and $\alpha(x)\neq 0$, $lim_n\|U_n(x)\|=+\infty$. Contradiction.
Comment: I couldn't understand how $U_n$ is a inverse on right of $T$.
Comment: $TU_n(x)=T(U_n(x)+n\alpha(x)e)=TU(x)+n\alpha(x)T(e)=TU(x)=x$.
Comment: Oh man! thanks! you are my Hero!


Logistic vs. linear regression for "inherently continous" variable - comparing probability

Question: This is a situation that arises commonly in my area (medicine).

Suppose there is an inherently continuous variable $y$
Suppose there is some normal range for this variable, say 80 - 120
Suppose there is a dichotomous categorization of $y$ as "within normal limits", and "outside normal limits" that are commonly used

This sort of setting is exceptionally common.
Now, let's say you wanted to build a prediction model for the patient's categorical status of $y$:
$y_{status} = f(x_1, x_2, ..., x_k)$, where $x_i$ are various measures like age, body weight, smoking status, ...
The usual approach seems to be to use logistic regression. However, it seems you could also predict the blood pressure as a continuous variable, say using a Bayesian approach producing a posterior distirbution, then estimate how much of the posterior is within or beyond the normal limits.
The two approaches yield (at least slightly) different answers, in my experience. Also, I basically never see the latter (Bayesian) approach - which suggests to me there is something fundamentally wrong with this idea. However, I can't understand where the logic is incorrect.
Any guidance on this would be greatly appreciated.
Answer: Turning a continuous variable into a binary variable is almost always a bad idea. It has been termed dichotomization. Frank Harrell (@FrankHarrell)explains and gives some examples. Steven Senn gave it the name dichotomania: Dichotomania: an obsessive-compulsive disorder that is badly affecting the quality of analysis of pharmaceutical trials
Basically, the problem is that information is lost when you convert a continuous reading into a binary normal vs. not normal. Worse, it can encourage investigators to try different cutoffs for defining the two groups, and then only publish the results with the cutoff value that gives the results closest to what they were hoping for.
Comment: Although I agree regarding dichotomisation of continuous variables, I believe the true issues are deeper than just information loss. Statisticians discard information all the time: they perform PCA, discard variables etc. I believe to have read somewhere that statistics is essentially a (lossy) data compression technique: Summarise large amounts of data into a handful of numbers easy to interpret. So the problem of dichotomisation is not information loss by itself; it is about which information is discarded, why, and how.
Comment: Thank you for the reply. It seems to support my notion that examining the Bayesian posterior is a legitimate (possibly superior?) approach. Nevertheless, the overwhelming preponderance of examples in the literature exhibit the dichotomania you refer to.

If this Bayesian/Posterior approach is legitimate (maybe even preferable) - I wonder why virtually every stats book I have seen - including relatively advanced ones from Bayesians (e.g., Regression and other stories by Gelman et al.) never mention this - but, instead, stick to the logistic regression model.
Answer: Medical doctor and researcher here. I have often thought about this as well. I believe there are 2 main reasons, but ofcourse these are personal opinions and open to discussion:
First, the medical world, including doctors and patients, are mainly interested in whether or not the tests are normal. As a basic example, doctors are not usually interested if the fasting blood sugar (FBS) of a patient is 80 or 85. While this 5 units of change may be statistically significant in the appropriate context, this will in no way change how the doctor treats the said patient. Thus, statistical analyses that predict an average of 5 units of increase in FBS are of secondary importance to doctors and policy makers, the actual audience of medical papers, compared to a predicted 1.5 odds of higher than normal FBS values which may have implication for the diagnosis of diabetes.
As a side-note,  I believe this is mainly because of the dichotomized nature of medical education and guidelines on how to treat patients. Although this is gradually changing and doctors are paying more attention to the spectrum of diseases rather than absolute states, we still have a long way to go.
Second, as the established medical literature is accustomed to dichotomized outcomes, future studies are more likely to go that way as well. Its not that the Bayesian and continuous approaches are wrong, in fact, in my experience, they provide more reasonable results. However, as researchers read the previous literature, they are more likely to use the already well established analyses as well, creating an unending cycle of dichotomized outcomes. Nevertheless, I am seeing more and more of Bayesian analyses recently. While it maybe a confirmation bias on my part, I am hopeful.
Comment: Your second reason is probably correct, but it suggests that medical research is kind of a cargo cult: Everyone else is doing it, they get their papers published, so we need to do it, too. But I don't think this attitude is limited to medicine. It took computer security some 40 years or so to stop forcing users to periodically change their passwords.


Efficient method to approximate Euler sums to high precision

Question: I'm trying to approximate four weight $9$ Euler sums with high precision (say over $100$ digits) with Mathematica:
$$\sum _{n=1}^{\infty } \frac{H_n^7}{n^2}, \sum _{n=1}^{\infty } \frac{H_n^5 H_n^{(2)}}{n^2}, \sum _{n=1}^{\infty } \frac{H_n^3 (H_n^{(2)})^2}{n^2}, \sum _{n=1}^{\infty } \frac{H_n^4 H_n^{(3)}}{n^2}$$
Commands I used are 'NSum' and 'WorkingPrecision'. However, the system failed to give an answer as I set the precision to be more than 50 digits.

Can somebody help me approximate these sums to $100$ digits?   Any kind of help will be appreciated.
Comment: @ MHZ What have you tried so far, especially with your own proposal 2?
Comment: Converted to an "answer".
Answer: A simple approach to make the software working is to replace \begin{align}H_n&=\gamma+\psi(n+1),\\H_n^{(k+1)}&=\zeta(k+1)+(-1)^k\psi^{(k)}(n+1)/k!,\end{align} which also "enables" E-M or A-P. The PARI/GP's sumnum "eats" it readily, producing
9043.5457472804393012140336705009063803732500237462521720823751494909142839177775416429118400246572080585...
355.94366198574004821936879947387876635374807856929634213045666004180991906871389314621941008708634541009...
28.236409513469581058820149577025324285151921286209876113436627856083937411911651120050250992517528455771...
54.648104639270712275307375212263275727767707498351542016967915613175186045675893730980305009885779661998...

Comment: Thank you. It seems that this software is much stronger than Mathematica in the range of numeric approximation.


Decomposition of a non chain ring

Question: I'm dealing with decomposition of the quotient ring
${{\mathbb{Z}_2}\left[ {x,y} \right]}$ over
${\left( {{x^3} - 1,{y^3} - 1} \right)}$. I know that I should use the Chinese remainder theorem but I failed. How can this ring be decomposed?
Comment: While saying you tried this and failed is OK, it would be a lot more helpful to know what steps you took and how that failed.
Comment: Is it a *requirement* that you apply the CRT or are you just saying that's what you thought of?
Comment: It is not a requirement. Indeed, I want to determine the zero-divisors and units in the ring ${\mathbb{Z}{_p}\left[ {x,y} \right]}$ over ${\left\langle {{x^n} - 1,{y^m} - 1} \right\rangle }$
Answer: Here's a hint for the direction using the Chinese Remainder theorem:
Natural candidates for ideals would be $(x-1,y-1),(x-1,y^2+y+1),(x^2+x+1,y-1),(x^2+x+1,y^2+y+1)$.
This decomposes the ring into four subrings, three of which are fields. The reducible one splits into two fields. (Your job is to figure out all of these fields :) )
Another way to go about it is to look at the idempotents. This is particularly easy to compute in a ring with characteristic $2$ since $p(x,y)^2=p(x^2,y^2)$ for any polynomial here. After checking what an idempotent has to look like, you quickly find out there are 32 idempotents. Another way to approach this is as a group ring  $F_2[C_3\times C_3]$. This helps with finding idempotents because in this case, the sum of elements in any subgroup of $C_3\times C_3$ is idempotent.
In a few minutes I whipped up a program to find the five primitive idempotents. Working by pencil and wits to compute this is still possible.

Decomposition of a non chain ring


Escaping SQL "ILIKE" usando a bilbioteca psycopg2

Question: Eu segui essa topico aqui no stack para tentar criar um select no qual eu procuro por uma pessoa usando a função ILIKE, porém eu tenho o retorno de "None", mesmo fazendo alterações na coluna e tabela para ver se me gera um erro diferente, o retorno é o mesmo "None"
def searchPeople(name):
    try:
        conn = Connection()
        cur = conn.cursor()
        conn.set_client_encoding('LATIN1')
        name= name.replace('=', '==').replace('%', '=%').replace('_', '=_')
        result = cur.execute("SELECT * FROM people WHERE name ilike %(like)s",dict(like='%'+ name+'%'))
        print result
        cur.close()
    except Exception as e:
        return e
    finally:
        conn.close()

Comment: Erro de sintaxe na expressão SQL, corrija para: `SELECT * FROM people WHERE name ilike '%(like)s'`. Mas você efetivamente quer as linhas onde o campo `name` contenha a string `'(like)s'`?
Comment: Me desculpa, na hora de passar para o fórum eu escrevi junto `nameilike` . Estou fazendo um formulário autocomplete e vou passar essa função para a view, nesse caso o usuário começará a escrever uma letra e o restante vai aparecer, essa string `%(like)s` foi a maneira que eu encontrei de fazer o escape, depois eu substituo ela
Answer: Usando o operador de concatenação de strings ||:
cur.execute("SELECT * FROM people WHERE name ilike '%%' || %s || '%%'; ", (name,))

Usando a função de concatenação de strings CONCAT():
cur.execute("SELECT * FROM people WHERE name ilike CONCAT('%%', %s, '%%'); ", (name,))

Escaping SQL “ILIKE” usando a bilbioteca psycopg2


Apostol - Mathematical Analysis - Theorem 1.1

Question: I realize there are several questions dealing with Theorem 1.1 from Apostol's "Mathematical Analysis", but those questions are mostly about how to prove the result or the geometrical intuition around it. My question is about the application of the theorem. The theorem states:
If $a\leq b+\varepsilon$
for all $\varepsilon>0$, then
$a\leq b$.
Take an example.
$a=2$, $b=1$ and $e = 3$; $e := \varepsilon$ Then, $2 \leq 1 + 3$;
$2 \leq 4$
These meet the conditions required in the theorem.
But, now I get the absurd result: $2 \leq 1$
What is wrong in my usage of the theorem?
Comment: In "for all ε>0", you are missing "for all".
Answer: The premise says for all $\epsilon>0.$ You have only shown the inequality holds for one $\epsilon$ (namely $\epsilon=3$). But it fails for $\epsilon = 1/2,$ for example, so the premise does not hold and you cannot draw the conclusion.
Comment: Thanks. Live to learn and fight again.
Answer: It must hold for all $\varepsilon > 0$ that $a \leq b + \varepsilon$.
In your example, you consider $a = 2, b = 1$. Then that gives us $2 \leq 1 + \varepsilon$. However, notice, if you solve for $\varepsilon$, this requires $\varepsilon \geq 1$.
Since your example does not hold for all $\varepsilon>0$ - namely, for all $\varepsilon \in (0,1)$ - then the conclusion doesn't follow, because the theorem itself doesn't apply.
In other words, if there exists $\varepsilon > 0$ for which $a > b + \varepsilon$, then the theorem doesn't apply.
Comment: Many many thanks. It is a universal quantifier.


Como fazer um balanceamento de classes em um problema de regressão em machine learning com Python?

Question: Problema usando o dataset do livro "Hands-On Machine Learning with Scikit-Learn and TensorFlow"
https://github.com/ageron/handson-ml
dataset de preços de casas. Objetivo: criar uma modelo de previsão de preços de casas.
Obtive o histograma abaixo:

Dá para ver que há um "desbalanceamento" de preços das casas.
Fazer "resampling" com 2 classes/classificacao é relativamente fácil. Agora como fazer o mesmo no problema acima, em que a classe não é binária? Cada valor de casa é uma classe...
Código fonte (é um jupyter notebook):
<code> #!/usr/bin/env python
# coding: utf-8

import sys #ver python path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

get_ipython().run_line_magic('matplotlib', 'inline')

housing = pd.read_csv('/Dados/Estudo_ML/handson-ml-master/datasets/housing/housing.csv',dtype={"srcip":object ,})

housing.head(20)

# # Análise de dados exploratória e Pré-processamento
#

#quero prever "median_house_value"

vars = ['longitude', 'latitude','housing_median_age','total_rooms','total_bedrooms',
       'population','households','median_income']

sns.pairplot(housing)

housing['median_house_value']#a classe!

housing

housing.isna().sum()
# Podemos ver que os dados faltantes estão exclusivamente na coluna 'total_bedrooms'

housing.isnull().sum()

housing['total_bedrooms']

fig, ax = plt.subplots(figsize=(10,10))
sns.heatmap(housing.isnull(),yticklabels=False,cbar=False,cmap='viridis',ax=ax)# dados faltantes:concentracao nas colunas

housing['median_house_value'].hist()#classes desbalanceadas?????? SIMMMMMMMMMMMMMMMMMMMMMM

sns.boxplot(x='median_house_value',y='total_bedrooms',data =housing )

# Criando variáveis do tipo dummies!

housing.columns

housing.iloc[:,housing.columns.isin(('ocean_proximity','ocean_proximity')) ]##ocean_proximity : é uma variável categórica

pd.get_dummies(housing['ocean_proximity']) #Dummy

# # Escalonamento de variáveis
# (importante para alg que calculam distâncias como a euclidiana (KNN...)

import sklearn
from sklearn.preprocessing import StandardScaler, MinMaxScaler

scaler = StandardScaler()

type(housing['ocean_proximity'])

scaler.fit_transform(housing[['median_income']])

# # Normalizando

min_max_scaler = MinMaxScaler()

min_max_scaler.fit_transform(housing[['population']]) #normalize the columns of this dataframe where each value is between 0 and 1

# # Balanceamento (Resampling) e escalonamento do datset:

##Fazer balancemento no treinamento para equilibrar a qtd de amostras de casa de cada categoria de preco

housing[housing['median_house_value']>=100000].count()

housing[housing['median_house_value']>=500000].count()

housing['median_house_value'].hist()#classes desbalanceadas!

# # Abordagem escolhida: Down-sample Majority Class

from sklearn.utils import resample

# Separate majority and minority classes

df_majority_down = housing[housing.median_house_value<=300000]
df_minority_down = housing[housing.median_house_value>=400000]
</code>
Comment: Você está fazendo um algortimo para prever os preço: isso significa que é um algoritmo de regressão (ele cospe um número que é o preço previsto) ou um de classificação (ele cospe um número que é um bucket da faixa de preço)? Se for o de preço, porque você precisa fazer balanceamento? Você n tem classes, apenas valores finais, certo?
Comment: @Victor Capone: A dúvida começa aí... Faz sentido balanceamento em regressao? é que há faixas de preços que tem poucas casas...
Answer: Não tenho vasta experiência no assunto mas, acredito que, nesse caso, se tratando de um problema de uso de regressão, na minha visão não há necessidade do uso de balanceamento de classes, até porque é possível notar que há valores finais (como dito nos comentários da pergunta) e não classes em si.
Talvez você possa usar algum dos algoritmos de regressão, como Support Vector Machines (SVM) ou Nearest Neighbors através do Scikit-learn.
Comment: Mas será que nao daria para criar "faixas de preço" como se fossem classes para fazer o balanceamento?
Answer: Uma classe é a definição para um conjunto de atributos que diferenciam características próprias entre eles, como frutas, cores, marcas, etc. Tudo isso pode e deve ser balanceado para que não ocorra underfitting ou overfitting. Algo como o preço não se define como uma classe de algo, por isso ele não pode ser balanceado, mas pode ser normalizado, para que os números fiquem bem comportados, além de também ser retirados outliers.


Why does the equal to operator not work if it is not surrounded by spaces?

Question: I tried the following script:
#!/bin/bash
var1="Test 1"
var2="Test 2"
if [ "$var1"="$var2" ]
  then
    echo "Equal"
  else
    echo "Not equal"
fi

It gave me Equal. Although it should have printed Not equal
Only when I inserted space around = it worked as intended:
if [ "$var1" = "$var2" ]

and printed Not equal
Why is it so? Why is "$var1"="$var2" not same as "$var1" = "$var2"?
Moreover, when I wrote if [ "$var1"= "$var2" ], it gave
line 4: [: Test 1=: unary operator expected

What does it mean? How come it's expecting a unary operator?
Comment: If you do a `test STRING` or (equivalently `[ STRING ]`),  this always evaluates to true (see _man test_).  `"$var1"="$var2"` is obviously a single string, while `"$var1" = "$var2" ` are three arguments, in which case the middle argument is taken as operator. When you do a `[ "$var1"= "$var2" ]`, you are passing two arguments, and in this case, the first argument must be an unary operator - for instance `-n`. This is also explained in _man test_.
Comment: Your title is misleading. There is not even an attempt to do a regex matching in your code. The bash regex operator is `=~`, and is available inside a `[[ ... ]]` construct.
Answer: test (or [ expr ]) is a builtin function. Like all functions in bash, you pass its arguments as whitespace separated words.
As the man page for bash builtins states: "Each operator and operand must be a separate argument."
It's just the way bash and most other Unix shells work.
Variable assignment is different.
In bash a variable assignment has the syntax: name=[value]. You cannot put unquoted spaces around the = because bash would not interpret this as the assignment you intend. bash treats most lists of words as a command with parameters.
E.g.
# call the command or function 'abc' with '=def' as argument
abc =def

# call 'def' with the variable 'abc' set to the empty string
abc= def

# call 'ghi' with 'abc' set to 'def'
abc=def ghi

# set 'abc' to 'def ghi'
abc="def ghi"

Comment: That man page applies to the `test` builtin function. In bash a variable assignment is part of the shell grammar, it's not a function. It requires no spaces.
Comment: Thanks Charles Bailey. There is one thing more, as man page says "each operator and ...." then why `var = "test" ;` does not work? To make it work, I have to remove spaces `var="test";` Is assignment `=` is not an operator?
Comment: ...and 'abc = def' invokes the command abc with two arguments '=' and 'def'
Answer: When the shell reads

if [ "$var1" = "$var2" ]

it invokes the command [ with 4 arguments.  Whether [ is a builtin or an external command is irrelevant, but it may help to understand that it may be the external command /bin/[.  The second argument is the literal '=' and the fourth is ']'.  However, when the shell reads

if [ "$var1"= "$var2" ]

[ only gets 3 arguments: the expansion of $var1 with '=' appended, the expansion of $var2, and ']'.  When it gets only 3 arguments, it expects the last argument to be ']' and the first argument to be a unary operator.
Answer: To add to the existing explanation, "$var1"="$var2" is just a single non-empty string, and thus always evaluates as true in a conditional.
[ "$var1"="$var2" ] && echo true

The above command will always print out true (even if var1 and var2 be empty).
Answer: In bash the best is to use [[ ]]:
x="test"
y="test"
if [[ "${x}" = "${y}" ]]; then
    echo "Equals"
else
    echo "No equals"
fi

Comment: Still, this does not attempt to address the OP's question, and should be posted as a  comment instead (if at all).
Comment: Bash`[[` is governed by the same shell syntax as all other constructs. Switching to `[[` would not  solve the OP's problem. As to whether this is "better" depends on whether you prioritize convenience over portability. If you are committed to Bash-only, it's probably true.
Comment: As I wrote, I meant **bash**. Of course if you want your code to be portable, you should use **/bin/sh**
Comment: @knesenko you should read better both questions and comments...


Successive Morphing Animation in SceneKit

Question: I struggle animating through different Morph-Targets in SceneKit.
I have an array of morph-targets I want to iterate through an show them with an animation between each of them.
So from one geometry to the other, this is easy.
In the SCNMorpher Class Reference there is an example to do this for one Morph-Geometry (morpher.weights[0]):
let animation = CABasicAnimation(keyPath: "morpher.weights[0]")
animation.fromValue = 0.0;
animation.toValue = 1.0;
animation.autoreverses = true;
animation.repeatCount = Float.infinity;
animation.duration = 5;

What I want to do is, to animate the morphs successive. I tried to setup several animations, for each target. But after completing the first animation, the weight of the first target is set to 0 again.
override func viewDidLoad() {
    super.viewDidLoad()

    // create a new scene
    let scene = SCNScene()

    let vbasic_geom: [Vertex] = [
        [ [0, 0, 0],      [+1.0, +0.0, +0.0] ],
        [ [0, 2, 0],      [+1.0, +0.0, +0.0] ],
        [ [2, 2, 0],      [+1.0, +0.0, +0.0] ]
    ]

    let vmorph1: [Vertex] = [
        [ [0, 0, 0],      [+1.0, +0.0, +0.0] ],
        [ [0, 4, 0],      [+1.0, +0.0, +0.0] ],
        [ [2, 2, 0],      [+1.0, +0.0, +0.0] ]
    ]

    let vmorph2: [Vertex] = [
        [ [0, 0, 0],      [+1.0, +0.0, +0.0] ],
        [ [0, 2, 0],      [+1.0, +0.0, +0.0] ],
        [ [4, 2, 0],      [+1.0, +0.0, +0.0] ]
    ]

    let basic_geom = gen_geometry(vbasic_geom)

    let morph1 = gen_geometry(vmorph1)

    let morph2 = gen_geometry(vmorph2)

    let morpher = SCNMorpher()
    morpher.targets = [morph1, morph2]

    let object = SCNNode(geometry: basic_geom)
    object.morpher = morpher

    //needed for model-layer refresh; implicit animation
    morpher.setWeight(1.0, forTargetAtIndex: 0)
    morpher.setWeight(1.0, forTargetAtIndex: 1)

    //set up animations
    let animation = CABasicAnimation(keyPath: "morpher.weights[0]")
    animation.fromValue = 0.0
    animation.toValue = 1.0
    animation.duration = 5
    animation.beginTime = 0.0
    animation.removedOnCompletion = false

    let animation2 = CABasicAnimation(keyPath: "morpher.weights[1]")
    animation2.fromValue = 0.0;
    animation2.toValue = 1.0
    animation2.duration = 5
    animation2.beginTime = 5.0
    animation.removedOnCompletion = false

    let animationgroup = CAAnimationGroup()
    animationgroup.duration = 10.0
    animationgroup.autoreverses = false
    animationgroup.repeatCount = 10000;

    animationgroup.animations = [animation, animation2]

    object.addAnimation(animationgroup, forKey: "morpher.weights")

    scene.rootNode.addChildNode(object)

Output GIF
Tried several Solutions, but I never succeeded:

Perhaps possible to change the ´keyPath: "morpher.weights[0]"´to ´morpher.weights´ and set the from- and toValues to something like an array. Including changing the valueFunction.
Because the animations happens on the presentation-layer, it must be a way to preserve already animated properties to the finished value. It tried "removedOnCompletion", but doesn't seem to work.

Has anybody a clue or a solution?
I can post a link, to the whole code, if this is necessary - don't think it is asked for here.
Answer: This is a common problem with CAAnimation - not just with SceneKit: explicit animations are removed on completion by default and the presentation value is reset to the model value (which is never modified by an explicit animation).
There are 2 solutions for that:

use an implicit animation instead (a SCNTransaction with a
completion block that will trigger the next animation).
set removedOnCompletion to NO AND set the fillMode to FillForward.

optionally for #2: you can set a delegate to your animation, and remove the animation in animationDidStop after having sync'ed the modelValue to the presentationValue.


Fitting exponential curve to histogram using R

Question: I am trying to fit a curve to a histogram that looks roughly like exponential decay.
Since this is roughly similar to exponential decay, I figured a good model was
counts ~ counts[1] * exp(-a * mids)

Which is calculated as
h1 <- hist(data[1,])
#find position that is closest to 10, our cutoff, and save only mids before
#that (these are now our x values)
mids <- h1$mids[1:which.min(abs(h1$mids-10))]
#find y values
counts <- h1$counts[1:which.min(abs(h1$mids-10))]
mdl <- nls(counts ~ counts[1] * exp(- a * mids))

But when I plot this, I do not get a very good fit:
lines(mids, predict(mdl, list(x = mids)))

Is the problem related to my model? Or am I just fitting to this histogram incorrectly?
This what the data are like:
> mids
  [1] 1.025 1.075 1.125 1.175 1.225 1.275 1.325 1.375 1.425 1.475 1.525 1.575 1.625 1.675
 [15] 1.725 1.775 1.825 1.875 1.925 1.975 2.025 2.075 2.125 2.175 2.225 2.275 2.325 2.375
 [29] 2.425 2.475 2.525 2.575 2.625 2.675 2.725 2.775 2.825 2.875 2.925 2.975 3.025 3.075
 [43] 3.125 3.175 3.225 3.275 3.325 3.375 3.425 3.475 3.525 3.575 3.625 3.675 3.725 3.775
 [57] 3.825 3.875 3.925 3.975 4.025 4.075 4.125 4.175 4.225 4.275 4.325 4.375 4.425 4.475
 [71] 4.525 4.575 4.625 4.675 4.725 4.775 4.825 4.875 4.925 4.975 5.025 5.075 5.125 5.175
 [85] 5.225 5.275 5.325 5.375 5.425 5.475 5.525 5.575 5.625 5.675 5.725 5.775 5.825 5.875
 [99] 5.925 5.975 6.025 6.075 6.125 6.175 6.225 6.275 6.325 6.375 6.425 6.475 6.525 6.575
[113] 6.625 6.675 6.725 6.775 6.825 6.875 6.925 6.975 7.025 7.075 7.125 7.175 7.225 7.275
[127] 7.325 7.375 7.425 7.475 7.525 7.575 7.625 7.675 7.725 7.775 7.825 7.875 7.925 7.975
[141] 8.025 8.075 8.125 8.175 8.225 8.275 8.325 8.375 8.425 8.475 8.525 8.575 8.625 8.675
[155] 8.725 8.775 8.825 8.875 8.925 8.975 9.025 9.075 9.125 9.175 9.225 9.275 9.325 9.375
[169] 9.425 9.475 9.525 9.575 9.625 9.675 9.725 9.775 9.825 9.875 9.925 9.975
> counts
  [1] 83429     0     0     0     0     0     0     0     0     0     0     0     0     0
 [15]     0     0     0     0     0 43939     0     0     0     0     0     0     0     0
 [29]     0     0     0     0     0     0     0     0     0     0     0 25437     0     0
 [43]     0     0     0     0     0     0     0     0     0     0     0     0     0     0
 [57]     0     0     0 14877     0     0     0     0     0     0     0     0     0     0
 [71]     0     0     0     0     0     0     0     0     0  8876     0     0     0     0
 [85]     0     0     0     0     0     0     0     0     0     0     0     0     0     0
 [99]     0  5410     0     0     0     0     0     0     0     0     0     0     0     0
[113]     0     0     0     0     0     0     0  3450     0     0     0     0     0     0
[127]     0     0     0     0     0     0     0     0     0     0     0     0     0  2081
[141]     0     0     0     0     0     0     0     0     0     0     0     0     0     0
[155]     0     0     0     0     0  1275     0     0     0     0     0     0     0     0
[169]     0     0     0     0     0     0     0     0     0     0     0   788

Answer: Many points to make.
1) you're fitting the zeroes between your actual data (it looks like the data can take only integer values), fitting zeroes where you can't have data is pulling your curve down.
2) you're dealing with a discrete distribution (in fact, insertion length sounds like a count of how many whatevers were inserted in whatever), so the relevant distribution with exponential-like decay is called the geometric.
3) Maximum likelihood estimation is easy in this case. $\hat{p}=1/\bar{x}$. (what's mean(data[1,])?). From that estimate you can then obtain the fitted exponential curve.
4) Even if you do want to directly fit an exponential curve, the problem with nonlinear least squares (even if you do it right by only fitting where the data can occur) is that the counts in each of the bins are not equally variable (you're putting relatively too much weight on observations that are less certain).
One could use a GLM with log-link instead, and take proper account of the multinomial nature of the data. But it won't do any better than just fitting the geometric via maximum likelihood.
Comment: What did you do to use `fitsdistr` in `MASS`? Note that your smallest value is 1, while R's geometric distribution starts at 0. (If you look at the Wikipedia link to the geometric distribution it lists *two* possible parameterizations of the distribution, one for a smallest value of 0, and one for a smallest value of 1. If you confuse them, *you're going to have a bad time*.) 2) The fitted distribution gives the probability of an observation at each value. Did you try multiplying by the total number of observations? ... (ctd)
Comment: (ctd)... Note also that if you make your histogram bins of width $h$ that will scale the height by $1/h$, so you also have to adjust for that effect (but seriously, don't use histograms for discrete data).
Comment: Rather than a histogram, try `hx=hist(x,breaks=(min(x):(max(x)+1))-0.5,plot=FALSE); with(hx,plot(mids,counts,type="h",lwd=2))`
 for example.
Comment: Thanks. I am confused on two things - 1) via that MLE estimate, `p=0.376`. But with `fitdistr` in `MASS`, I got `p=0.273`. Second, once I have my fit, how do I scale it so that the values match the data? I am trying `plot(dgeom(seq(1,10), p))` which gives a correct looking curve which is obviously on a very different x scale than the data are.
Comment: Thanks. I got a good looking fit with creating my own geometric function using the other parameterization `function(p, x) {p*(1-p)^(x-1)}` then plotting it as `lines(g(p, seq(1:10))*length(data[1,]))` over my (admittedly bad) use of histograms for discrete data


How to use reflection to serialise and deserialise (generic way). Not using an dll

Question: I'm trying to create a Class with a method where I can load a file (In this case CSV) and convert it to any predefined datastructure within my program.
With a lot of help from other articles I've written the following code, But I got stuck. (so the placed code has errors).
The idea is that I use the method CsvSerialise, the input is a byteArray and transform it to an object list where the input is what kind of output type I want.
If anyone has some Ideas, please give them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Text.RegularExpressions;

namespace DocumentArchiveV2.Util
{
    public class CsvSerialiser
    {
        public List<Output> CsvSerialise<Output, DestinationFormat>(byte[] csvData, Type destinationType)
        {
            try
            {
                List<List<string>> lislistCsvData = BinaryDataToList(csvData);
                List<string> columnNames = lislistCsvData[0];
                List< destinationType >  = new List<DestinationFormat>();

                // loop over de regels / records
                for (int i = 1; i < lislistCsvData.Count - 1; i++)
                {

                    var Instance = Activator.CreateInstance(destinationType);
                    var properties = Instance.GetType().GetProperties();

                    foreach (var property in properties)
                    {
                        int index = columnNames.FindIndex(x => x == property.Name);
                        if (index >= 0)
                        {
                            PropertyInfo propertyInfo = destinationType.GetProperty(lislistCsvData[i][index]);
                            Type propertyType = propertyInfo.GetType();
                            var geconverteerdeWaarde = VindPropertyNaam(propertyType, lislistCsvData[i][index]);
                            propertyInfo.SetValue(propertyInfo, geconverteerdeWaarde);
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public object VindPropertyNaam(Type type, string popertyName)
        {
            try
            {
                var parse = type.GetMethod("Parse", new[] { typeof(string) });
                if (parse == null) throw new NotSupportedException();
                return parse.Invoke(null, new object[] { popertyName });
            }
            //or don't catch
            catch (Exception)
            {
                return null;
            }
        }

        private object LoadRecord(Type propertyType)
        {
            throw new NotImplementedException();
        }

        private List<List<string>> BinaryDataToList(byte[] csvData)
        {
            try
            {
                List<List<string>> serialised = new List<List<string>>();

                foreach (var line in Regex.Split(Encoding.ASCII.GetString(csvData), "\r\n"))
                {
                    string[] splittedLine = line.Split(';');
                    serialised.Add(line.Split(';').ToList());
                }
                return serialised;
            }
            catch (Exception ex)
            {
                DiagnoseLib.Logging.Logger.Error(ex.Message);
                return null;
            }
        }
    }
}

Comment: Yep. That's code alright.
Comment: https://github.com/JamesNK/Newtonsoft.Json is serializing objects from json strings and back. maybe you can borrow an idea or two from their source code
Comment: So what specifically is the issue?
Comment: Hi,
The problem is that I cannot give a destination output. I need to declare a output list List and add the values to this., The editor keeps giving errord.
Comment: Thanks FrankM, Ill take a look at that
Comment: Basic problems: **1.** You're looping through the data twice. **2.** You're reflecting the properties for each cell, which will be slow. Building an array for each column, with nulls for missing properties, will be faster. **3.** You're catching all exceptions and just rethrowing. **4.** Your CSV reader will break if you have a quoted string with a delimiter value `;` within. **Aside:** You say the editor is giving errors. We're not psychic, so you need to give us the full error messages and tell us where they occur if you want help.
Comment: With regard to #2 you can make it faster again, I believe, by using expression trees to create setters for each property, and then caching that for reuse each time you deserialize to that type. But that's for your own research.
Answer: I found where I went wrong.
I was trying to return a generic type while it should have been an objecttype
Thanks all who have given insight.
     public List<object> CsvSerialise(byte[] csvData, object destinationType)
            {
        // The rest of the code with some small adjustments
            }

Answer: I pretty much dislike your code due to numereous violations of OOP practicies known to be the best. However, since it is not the question you're asking, I'd like to ignore those and focus on what you'd like to get right now.
So basically what you're doing is called "parsing". It's all about taking a somehow formatted (CSV in your case) text and converting to internal data structures. Since yoy eager to come up with generic solution (which by itself is perfect thing to do, though as well much harder), you objectively don't know what kind of data structure it gonna be. Hence, you need be able to configure this process. How? Typically, with help of higer order functions. Something like new DataStructureBuilder<TDataStructure>((environment, result) => result.Text = environemt["Text"]). It is far from being a real code, however gives you an idea: there is a generic datastructure of (assuming) TDataStructure type and you specify the way it should be filled with data explicitly. environment stands for parsed text (that very moment, when you read the values you'd like you data strutctures to ship further, however yet those are stored into raw form of dictionaries, lists, hashsets, etc.).


Prove that if $|A \cup B|=|A \cap B|$, then $|A|=|B|$

Question: Let A and B be sets. Prove that if $|A \cup B|=|A \cap B|$, then $|A|=|B|$
Comment: This seems like a silly question, because the stronger result $A=B$ holds (if the sets are finite).
Answer: WLOG let $|A| \le |B|.$ Then
$$|B| \le |A \cup B| = |A|+|B| - |A \cap B| \le 2|B|-|A \cap B|.$$
With $|A \cup B|=|A \cap B|$ this gives
$$|B|=|A \cup B|.$$
Can you proceed ?
Answer: Hint
$$|A \cup B|=|A|+|B|-|A \cap B|$$
if $|A \cup B|=|A \cap B|$ then
$$|A \cap B|=\frac{|A|+|B|}{2}$$
Suppose $|A|>|B|$, then
$$|A \cap B|=\frac{|A|+|B|}{2}>|B|.$$
However, by definition, $A \cap B\subset B$.
Did you get it?
Answer: Well, this is certainly false for the infinite case, take for example $\mathbb{Z}$ and $2\mathbb{Z}$ (the even numbers). But in the finite case it is true, as $A \cap B \subset A \cup B$ so if their cardinal is equal, then $|A\cup B|=|(A\cap B)\cup ((A\cup B)-(A\cap B))|$ and as this sets are finite and that union is disjoint, we have that $|A \cap B| = |A\cup B|=|(A\cap B)|+| (A\cup B)-(A\cap B)|$ which implies that $| (A\cup B)-(A\cap B)|=0$ and so that set is the empty set and every element of B is in the union an so in the intersection (by the emptyness) and therefore in A and similary every element of A is in the union and then in the intersection and therefore it is also in B. Deducing that both sets are equal


Rate of convergence in law of large numbers

Question: Let $X_1, X_2, ...$ be i.i.d random variables  in $\mathbb{L}^p$ for some real number $p\geq 1$ and with $\mathbb{E}[X]=0$.

Find $\alpha>0$ (as large as possible) such that $n^{\alpha}\frac{S_n}{n}\rightarrow 0$ in $\mathbb{P}$.
Find $\alpha>0$ (as large as possible) such that $n^{\alpha}\frac{S_n}{n}\rightarrow 0$ a.s.

My Approach: For the second one, using Borel Contelli lemma we may take advantage of the first one to come up with an $\alpha$. For the first one I have tried to use truncation, by defining ${X}_i^R = -R\vee X_i \wedge R$ to get the following:
$$
\mathbb{P}(\frac{\mid S_n \mid}{n^{1-\alpha}}>\epsilon)\leq \mathbb{P}(\frac{\mid S_n-S_n^R \mid}{n^{1-\alpha}}>\frac{\epsilon}{2}) + \mathbb{P}(\frac{\mid S_n^R \mid}{n^{1-\alpha}}>\frac{\epsilon}{2})
$$
Now I want to send $n\to \infty$ first and then $R \to \infty$. So far I have not used independency of random variables. It seems that I need to use chebyshev inequality at this stage and use independency of random variables to get to a good point but I got stuck here. Any help? How can I proceed? Or maybe I should take another route?
Comment: CLT tells us that $\sup \alpha_{p}\leq \frac 1 2$ for all $p$ and we can also see that $\sup \alpha_p$ is non-decreasing in $p$..
Comment: I have little formal higher-level mathematics education beyond calculus, algebra and statistics, but I have been wondering about the rate of convergence for the law of large numbers. How is this generally calculated?
Answer: We will consider the case where $p \geq 2$. The $p<2$ case is discussed as a footnote.
Claim: Suppose that $p \geq 2$. Then there exists $C_p>0$ (not depending on the sequence $(X_i)$) such that for every $n \in \Bbb N$, we have that $\|S_n\|_p \leq n^{1/2} C_p \|X_1\|_p$.
We will prove the claim later (that is where independence will be used), but for now we return to the question at hand. Recall the general form of Chebyshev's inequality, which says that for any $Y\in L^p$, $$P(|Y|>\epsilon) \leq \epsilon^{-p}\|Y\|_p^p$$
Using this as well as the above claim tells you that $$P\bigg( \frac{|S_n|}{n^{1-\alpha}}>\epsilon \bigg) \leq \frac{\|S_n\|_p^p}{n^{p(1-\alpha)}\epsilon^p} \leq \frac{C_p^p n^{p/2}\|X_1\|_p^p}{n^{p(1-\alpha)}\epsilon^p} = \frac{C_p^p \|X_1\|_p^p}{\epsilon^p} n^{p(\alpha-1/2)} = C_p' \cdot n^{p(\alpha-1/2)} $$
As $n \to \infty$, this tends to zero whenever $p(\alpha-1/2)<0$, i.e, whenever $\alpha<\frac{1}{2}$. Therefore $\frac{S_n}{n^{1-\alpha}} \to 0$ in probability whenever $\alpha<\frac{1}{2}$. (Note that by CLT, this is the best possible bound.)
Similarly, $n^{p(\alpha-1/2)}$ is summable whenever $p(\alpha-1/2)<-1$, i.e, whenever $\alpha< \frac{1}{2}-\frac{1}{p}$. Therefore Borel-Cantelli tells you that $\frac{S_n}{n^{1-\alpha}} \to 0$ almost surely whenever $\alpha< \frac{1}{2}-\frac{1}{p}$.
Proof of claim: Suppose that the $X_i$ are defined on the probability space $(\Omega, \mathcal F, P)$.

From now on fix $n \in \Bbb N$. Let us define $\Phi$ to be the measure space $\Omega \times \{1,...,n\}$ with measure $P \times c$, where $c$ is just counting measure. Each $f \in L^p(\Phi)$ can be denoted $f=(f_1,...,f_n)$ where $f_i \in L^p(\Omega)$ is just the map $\omega \mapsto f(\omega,i)$. These $f_i$ are the "slices" of $f$ on $\Omega \times \{i\}$, and completely determine $f$ (thus the $n$-tuple notation is unambiguous). We will also think of $\Omega^n$ as a probability space with product measure $P^n$.

For each $p$ we define $L_0^p(\Phi)$ as the closed subspace consisting of all $(f_1,...,f_n) \in L^p(\Phi)$ such that all of the $f_i$ have the same distribution, and $E[f_1]=0$. For $p \geq 1$, define a map $A: L^p_0(\Phi) \to L^p(\Omega^n)$ which sends $(f_1,...,f_n) \mapsto \sum_1^n f_i \circ \pi_i$ where $\pi_i : \Omega^n \to \Omega$ is the natural projection. From now on we will denote $\overline{f_i}:= f_i \circ \pi_i$. One can see that for $k \in \Bbb N$ and for $f = (f_1,...,f_n) \in L^{2k}_0(\Phi)$, the independence of the $\overline{f_i}$ implies that $$\| Af \|_{L^{2k}(\Omega^n)}^{2k} = E_{P^n}\bigg[ \bigg(\sum_1^n \overline{f_i} \bigg)^{2k}\bigg] = \sum_{j_1+...+j_n=2k} \binom{2k}{j_1,...,j_n}E_{P^n}[\bar{f_1}^{j_1} \cdots \bar{f_n}^{j_n}] $$$$ =\sum_{\substack{j_1+...+j_n=2k \\ j_1,...,j_n \neq 1}} \binom{2k}{j_1,...,j_n}E_{P^n}[\bar{f_1}^{j_1} \cdots \bar{f_n}^{j_n}]$$$$ \leq (2k)! \cdot \big| \big\{ (j_1,...,j_n) : j_1+...+j_n = 2k, \; j_1,...,j_n \neq 1\big\} \big| \cdot E_P[f_1^{2k}] $$$$ \leq  B_k \; n^k \; E_P[f_1^{2k}] = B_k \; n^{k-1} \|f\|_{L^{2k}(\Phi)}^{2k}$$ where $B_k$ is some integer not depending on $n$. Some justification is required here. In the first equality, we merely used the definition of the $L^{2k}$ norm on $\Omega^n$. For the second equality, we used the multinomial expansion. For the third equality, we used the fact that the $\bar{f_j}$ are independent and have mean zero in order to eliminate terms in which a first power appears. In the following inequality, we used the fact that the multinomial coefficients are bounded above by $(2k)!$, as well as the fact that the $\bar{f}_j$ are i.i.d. to deduce that $E_{P^n}[\bar{f_1}^{j_1} \cdots \bar{f_n}^{j_n}] \leq E_P[f_1^{2k}]$. In the next inequality, we used the fact that if $\;j_1+...+j_n=2k$ with $j_1,...,j_k \neq 1$, then at most $k$ of the $j_i$ can be nonzero (and hence the $O(n^k)$ bound). And in the final equality, we used that $E_P[f_1^{2k}] = n^{-1} \|f\|^{2k}_{L^{2k}(\Phi)}$, simply by definition of the $L^{2k}$ norm on $\Phi$.

 Thus by taking $(2k)^{th}$ roots, we see that $\|Af\|_{L^{2k}(\Omega^n)} \leq n^{\frac{1}{2}-\frac{1}{2k}} C_{2k} \|f\|_{L^{2k}(\Phi)}$ where $C_{2k}:= B_k^{\frac{1}{2k}}$. Since $k$ was arbitrary, the Riesz-Thorin Interpolation Theorem tells us that whenever $p \in [2k,2k+2]$ for some $k \in \Bbb N$, we have that $\|Af\|_{L^{p}(\Omega^n)} \leq n^{\frac{1}{2}-\frac{1}{p}} C_p \|f\|_{L^{p}(\Phi)} $, where $C_p = C_{2k}^t C_{2k+2}^{1-t}$ with $t \in [0,1]$ satisfying $\frac{1}{p} = \frac{1-t}{2k+2} + \frac{t}{2k}$.

 To finish the proof of the claim, note that since the $X_i \in L^p(\Omega)$ are independent, we see that $S_n$ has the same distribution as $A(X_1,...,X_n)$, and therefore $$\|S_n\|_{L^p(\Omega)} = \| A(X_1,...,X_n) \|_{L^p(\Omega^n)} \leq n^{\frac{1}{2}-\frac{1}{p}} C_p \cdot \|(X_1,...,X_n) \|_{L^p(\Phi)} $$$$ = n^{\frac{1}{2}-\frac{1}{p}} C_p \cdot n^{\frac{1}{p}} \|X_1\|_{L^p(\Omega)} = n^{1/2} C_p \|X_1\|_{L^p(\Omega)}$$
Note: For the case when $1 \leq p \leq 2$, we can obtain the weaker bound $\|S_n\|_p \leq n^{1/p} \|X_1\|_p$ using similar interpolation techniques between $p=1$ and $p=2$. Using Chebyshev's inequality as above then gives us convergence in probability whenever $\alpha< 1-\frac{1}{p}$, but there is not enough information get bounds on a.s. convergence (however, SLLN gives zero).
Comment: An explicit bound on $B_k  n^k $ is given by $(2k)! \sum_1^k \binom{n}{j} \binom{2k-j-1}{j-1}$.
Comment: Actually, there is a much simpler proof of the claim using burkholder-Davis-Gundy.


What is the optimum strategy? Game Theory.

Question: If you invest Rs 1000, you would get a paid back of Rs 4000 at the end of the day, provided atleast 90% of the students invested. If the number of students investing falls below 90%, all those invested will lose their money. Those who decide not to invest will neither lose nor gain anything.
Q What is the optimum strategy for any individual investing in the game?
Q What is the nash equilibrium for the game?
Comment: this type of problem is often called the Stag Hunt Game (if enough cooperate, you get the deer, otherwise it escapes).
Answer: It's not clear to me what you mean by "the optimum strategy for any individual".
The question about "the nash equilibrium for the game" seems to assume that there is exactly one Nash equilibrium. This is not the case. Both the strategy profile in which no one invests and the strategy profile in which everyone invests are pure Nash equilibria (if there is more than one student). It is straightforward to see that in both cases the individuals can only lose by individually changing their strategy.
Comment: The question is relevant insofar Game Theory is concerned.
Comment: @ShashankSharma: Which question? How does this relate to my answer?


UIPageControl UIScrollView animated effect

Question: I'd like to be able to swipe the screen to the left and right to display different user details (see link to screenshot below). I'd also like the animated effect where you see the items leave the screen on one side and the new items appear from the opposite side.
Elements used on storyboard.

UIViewController
UIImageView
UILabel x 3
UIPageControl

For starters, I don't know which elements I need to get this effect. I'm looking for someone to tell me what elements I need and sample code to go with it.
Screenshot of my ViewController - http://oi60.tinypic.com/k3roqp.jpg
I do not want to use UIPageViewController
Answer: You can use either a UIScrollView with paging enabled or a UIPageViewController to display multiple view controllers as pages. There are plenty tutorials on the web for those.
You can find documentation for those controls directly at Apples website:

UIScrollView: https://developer.apple.com/library/ios/documentation/uikit/reference/uiscrollview_class/Reference/UIScrollView.html
UIPageViewController: https://developer.apple.com/library/ios/documentation/uikit/reference/UIPageViewControllerClassReferenceClassRef/UIPageViewControllerClassReference.html


Differential form volume

Question: For a closed curve $C$ that bounds the region $B$ in the plane, we have that $\int_Cxdy-ydx=\int_B2dxdy=2vol(B)$. Are there similar formulas for 3 or more dimensions? Instead of $xdy-ydx$, what would the corresponding 2 form $\omega$ be such that $d\omega=dxdydz$?
Answer: What you have observed is Green's theorem in the plane can be used to write down a formula for the integral over any region bounded by a simple closed curve. The general case requires generalizing the concepts of vector calculus that lead to that formula, because essentially what you want to do is be able to say something like:
$$ \int_{\text{Region}} 1 dV = \int_{\text{boundary of that Region}} \text{Something } dS$$
The question is essentially how you should find that something. The fundamental theorem of calculus has the following generalization (the generalized Stoke's Theorem) for differential forms.
$$\int_M \ d \omega = \int_{\partial M}\omega$$
where $\omega$ is now a differential form and $M$ a manifold.
So the answer to your question then boils down to figuring out how to find a differential form $\omega$ so that $d\omega$ is the volume form. How to find these on manifolds can be difficult, if not impossible, as there is no guarantee the volume form actually is exact (in fact on compact manifolds without boundary it is never exact, by Stoke's theorem), but on $\mathbb{R}^n$ this is not so hard, as the formula for $d$ is very simple, and the volume form has a very easy to write down expression as $dx^1 \wedge ... \wedge dx^n$. In particular, if $\omega$ is a form, it can be represented on Euclidean space as $\sum u_I dx^I$, where $I$ is a multi-index. The expression for the exterior derivative is just
$$\sum_{k=1}^n\frac{\partial }{\partial x^k}\bigg(\sum u_I dx^I \bigg) \wedge dx^k$$
Then we can at least see from direct calculation that the form $$\omega = \sum_{k=1}^n (-1)^{k+1} x^k dx^1 \wedge ... \wedge \overline{dx^k} \wedge ... \wedge dx^n$$ will have the desired property, as taking $d$ term by term inserts the missing partial and is $0$ when terms are repeated.
Comment: should it be $(-1)^{k+1}$? In the case of $n=2$, wouldn't the formula you wrote give $-xdy+ydx$?
Comment: Originally had the wrong form $\omega$. I think I got it right now. I'm worn out from exams. Feel free to correct me if anything in here is wrong.
Comment: Indeed. I'm off by one. Thanks.
Answer: You stated Green's theorem for the case $L dx = -y dx$ and $M dy = x dy$.
Its generalization is Stoke's theorem. A differential form for this is $\omega = x dy \wedge dz + y dz \wedge dx + z dx \wedge dy$
Comment: Shouldn't the middle term be $ydzdx$?
Comment: You're right. I've now edited this answer with that correction.

Differential form volume


How can I prove this inequality by M.I. or otherwise?

Question: This question is from the past examination:
$$f(n)=\frac{2}{3}(n^{3/2}-1)+\sqrt{n}$$
$$g(n)=1+\frac{2}{3}((n+1)^{3/2}-2^{3/2})$$
My task to prove $f(n)≥g(n)$ for all $n≥1$.
I have tried M.I here.
But the problem is that I do not know how to expand the term $(n+2)^{3/2}$ in the inductive steps. Can anyone tell me what method should I use to finish the proof.
Comment: How about using some calculus?
Comment: Binomial theorem?
Comment: How? Any details provided?
Answer: Note that $$f(n)-g(n)=\frac{2}{3}(n^{3/2}-1)+\sqrt{n}-1-\frac{2}{3}((n+1)^{3/2}-2^{3/2})=\int_1^n\left(\sqrt{x}+\frac1{2\sqrt{x}}-\sqrt{x+1}\right)\mathrm dx,$$ hence it suffices to show that, for every $x\geqslant1$, $$\sqrt{x}+\frac1{2\sqrt{x}}-\sqrt{x+1}\geqslant0.$$ The LHS is $$\frac1{2\sqrt{x}}-(\sqrt{x+1}-\sqrt{x})=\frac1{2\sqrt{x}}-\frac1{\sqrt{x+1}+\sqrt{x}}=\frac{\sqrt{x+1}-\sqrt{x}}{2\sqrt{x}(\sqrt{x+1}+\sqrt{x})}\gt0,$$ hence the proof is complete.
Answer: set $h(x)=f(x)-g(x)=\Big( \frac{2}{3}(x^{3/2}-1)+\sqrt{x} \Big)- \Big(1+\frac{2}{3}((x+1)^{3/2}-2^{3/2})\Big).$
Differentiate w.r.t x, we get $h'(x)=\frac{x+1/2-\sqrt{x(x+1)}}{\sqrt{x}}>0$
So $h$ is strictly increasing function. Then check $h(1)=0$, and we get the result.
Answer: Since $f(n)\geq g(n)$ holds for $n=1$, it is sufficient to show that:
$$\begin{eqnarray*} f(n+1)-f(n) &=& \frac{2}{3}((n+1)^{3/2}-n^{3/2})+(n+1)^{1/2}-n^{1/2}\\&\geq& \frac{2}{3}((n+2)^{3/2}-(n+1)^{3/2})=g(n+1)-g(n)\end{eqnarray*}$$
that is equivalent to:
$$\frac{2}{3}\left((n+2)^{3/2}-2(n+1)^{3/2}+n^{3/2}\right)\leq (n+1)^{1/2}-n^{1/2}\tag{1}$$
or to:
$$(2n+4)(n+2)^{1/2}+(2n+3)n^{1/2}\leq (4n+7)(n+1)^{1/2}\tag{2}$$
that is equivalent to:
$$\frac{2n+4}{4n+7}\left(1+\frac{1}{n+1}\right)^{1/2}+\frac{2n+3}{4n+7}\left(1-\frac{1}{n+1}\right)^{1/2}\leq 1. \tag{3}$$
In virtue of the Cauchy-Schwarz inequality the LHS of $(3)$ is less or equal than:
$$\frac{\sqrt{2}}{4n+7}\cdot\sqrt{(2n+4)^2+(2n+3)^2}=\sqrt{1+\frac{1}{(4n+7)^2}},$$
that, however, is bigger than one. Using $\sqrt{1+x}+\sqrt{1-x}\leq 2-\frac{x^2}{4}$ we get that the LHS of $(3)$ is less or equal than:
$$1-\frac{1}{8(n+1)^2}+\frac{1}{8n+14}\left(\left(1+\frac{1}{n+1}\right)^{1/2}-\left(1-\frac{1}{n+1}\right)^{1/2}\right)$$
and since over $(0,1]$ we have $\sqrt{1+x}-\sqrt{1-x}\leq\frac{x}{1-x^2/3}$, it follows that the LHS of $(3)$ is less than:
$$ 1-\frac{1}{8(n+1)^2}+\frac{1}{(8n+14)(n+1)\left(1-\frac{1}{3(n+1)^2}\right)}\leq 1.$$
Answer: Let $h(x)=\sqrt{x}$.
Then $\displaystyle f(n)\ge g(n)\iff\int_{1}^{n}h(x)dx+\sqrt{n}\ge1+\int_{2}^{n+1}h(x)dx\iff$
$\displaystyle{\hspace 1.4 in}\int_{1}^{2}h(x)dx-h(1)\ge\int_{n}^{n+1}h(x)dx-h(n)$,
so let $\;\;\displaystyle k(x)=\int_{x}^{x+1}h(t)dt-h(x)$.
Since $k^{\prime}(x)=h(x+1)-h(x)-h^{\prime}(x)=h^{\prime}(c)-h^{\prime}(x)$ for some $c$ with $x<c<x+1$
and $h$ is concave down, $k^{\prime}(x)<0$ and so $k$ is decreasing.
Therefore $k(1)\ge k(n)$ for all $n\ge1$, so $f(n)\ge g(n)$ for all $n\ge1$.


Who provides the p.a?

Question: I hope this is acceptable - it is about musical practice after all.
In a band situation (where a lot of us are or have been), who is expected to provide the p.a? Obviously on quite large gigs, it's provided - that's not a problem. But there are many occasions when one's not available, so apart from hiring is the question.
All the instrumentalists will have to provide their own instruments, at varying costs and portability, but who owns the p.a. is a question that has just popped up again. A vocalist forming a new band has neither p.a. nor mic. and I'm appealing for experienced band players to share whether bands they are, or have been in, would have a shared p.a. or does the vocalist own it. If it's shared, surely it becomes problematic should one member leave? Or - worse still - "yes, you can join but it'll cost you for a share in our p.a..."
Comment: Does "p.a." mean "public address system" here?
Comment: Why are you asking about the vocalist? Don't the other instruments need PA and monitors too?
Comment: @user1079505 - I was considering the bands I've worked with where the vocalist just turns up and asks "where's my mic?" My reply was usually "still in the shop, you obviously haven't bought it yet" And yes, others use the p.a. too, but in a way, they 'make use of' my k'bds, gtr, bass, drums, when I gig with them.
Comment: This sort of seems like a survey question. Like you're taking a poll to see how bands handle PAs. What am I not understanding that makes this question objective and answerable?
Comment: Are you asking about gigs or rehearsal? Both the answer and the PAs are likely to be different. Or are you curious about both situations?
Comment: Related thread: [What are the steps involved in organizing a new band?](https://music.stackexchange.com/q/99056/70803).
Comment: @ToddWilcox - both, really. Gigs mainly. In a rehearsal situation, I can get away with some bands singing without mics (yes!), but then the instrumentalists still have to provide instruments, but vox turns up with nothing!
Comment: @TannerSwett - yes. Public Address.
Comment: @ToddWilcox - it's answerable - by those who have the experiences. I am wondering - and have done for ever - what the general consensus is about p.a. ownership and responsibility. Where better to ask than here, where so many have band experience, and can provide their own stories. I'm also trying to provide some wherewithall to a singer who wants to form a new band, but I'm reticent to be the p.a. guy as well as arranger, player and backing singer, while he may be happy to tag along with little, or no, contribution gear-wise. The answers so far have been enlightening, including yours.
Comment: Yeah… my understanding is that SE is more about questions that have a single, verifiable, correct answer, or at least a narrow class of correct answers. The word "consensus" also seems like a poll, to me.
Comment: @ToddWilcox - you may well be correct. However, there are many questions here in similar vein, which must have guided players who become band members, with very useful points and anecdotes. And the 'practice' part surely gives licence for that sort of query. With 750 views so far, it's obviously of interest to more than a few. And to feature as a top question... shame to see it go.
Comment: Voting to keep open. My understanding is that the question was hoping for "oh yeah, it's common knowledge that it's always ___." Questions about such functional practices ought to be on topic, like "Who gives the pitch to tune an ensemble?" (Answer can then discuss symphony orchestra vs piano qt vs early music band.) In this case the answer *happened to be* "shrug, there's no common practice," but there might have been one.
Comment: @AndyBonner - thank you for your support. I feel that if this question is closed, there's a proportion of the site lost to musicians. But there are plenty of zealots out there.
Answer: I guess it depends, maybe no two will be the same…
I used to work occasionally for a function band who commanded enough money for a show that they just hired a PA, lighting rig & engineer/roadies each time.
I mean, who's got room in their garage for a 5k rig & all the lighting too… who is also happy to lug it themselves to every gig?
Every smaller band I've ever been in bought their own, between them, then if anyone left or joined, the rig still belonged to the band. You leave it behind if you move on, but the guy replacing you gets free, temporary usage.
If the outfit disbands completely, whoever is left at that point who contributed originally gets a share of the sale price.
I've heard of singers owning their own; also I've worked solo, me plus guitar  & backing tracks & had my own little rig that would work for pubs/small clubs, but I've never shifted it up to a full band.
Comment: Actually, I did just that! Looked after a big rig, for B'ham Jazz - artistes from all over the world - and humped it all, set it all up, ran the desk, and stored it! Younger then though... And never got a penny for it. foolish as well, maybe - but that was different, as BJ generated enough money to buy it all, so not the same scenario. I can imagine your 4th & 5th  para. would cause many upsets!
Comment: My nephew started out with a couple of lights he could use at the local am dram, for free, just so he could join in, as he can't act, can't sing & his sister can do both. She gave it up eventually, he runs rigs across half the big theatres in the North now. No longer fits in a garage, 40' trucks these days ;)) [I've never known anyone leave a band & want their share of the rig back, but I can imagine it happening]
Answer: I have been in bands with a variety of arrangements regarding sound reinforcement equipment.  Some rented PA systems for gigs where there was no house system.  In other cases, one member owned a PA and shared while each vocalist (who also happened to be an instrumentalist) owned their own microphone.  There's no "standard" approach, and each band member is likely to come to the table with their own tacit assumptions!
So, I think your question is a subset of a larger issue that bands need to be aware of:  The need to have some kind of agreement in place when you join.  In addition to equipment ownership issues, a band agreement can also cover things like:

Responsibility for storage and transportation of equipment.
Ownership of copyright on band compositions/arrangements.
Whether the band is fully egalitarian, or has "leader"
Whether the leader has the right to terminate other members.
Whether some majority of members can terminate another member.
Who owns the name, logo, etc.

Agreeing upon these things early in the band's existence can help avoid animosity, resentment, legal or financial battles, etc.
There are standard forms available online for band agreements. Here's one example (not an endorsement): Sample Band Agreement
Comment: I think this is the best answer so far, which is "there is no one answer, you need to figure this out between you and make sure everybody agrees and there are no surprises".
Comment: @Tim If you think of it as a business arrangement, then the person on the losing end of the unfairness has a responsibility to themselves to work to mitigate it.  Splitting the cost of a rental PA might help the members understand the value of one owned by a member.
Comment: @JörgWMittag - there probably is no one answer. I'm searching for the experience of contributors to this site, myself having been in many bands over the last 60 odd yrs, with many different arrangements. But the one that rankles most is a vocalist with nothing of his own. Reading ideas will also help others forming bands, and maybe avoiding the situations we find where some poor guy has the responsibility of their own gear, and then the p.a. on top of that. Pretty unfair in my book.
Answer:
I'm appealing for experienced band players to share whether bands they are, or have been in, would have a shared p.a. or does the vocalist own it.

My experience is "neither". Either no one in the band has owned a PA or I've owned the PA, as the guitarist, or another non-vocalist has owned a PA in their house. In one of my bands, the only gear we used that I didn't own was the drum kit (owned by the drummer) and anything provided by venues.
Specific situations include:

Every practice with drums is at a practice space with PA included in the hourly rate - rate split evenly among members.
One band member (usually the drummer) has a practice space in their house or garage and one member (usually the drummer or me) has a PA or at least monitors set up in that space.
We shared a practice space with another band and the other band owned the PA and let us use it.

For gigs it's mostly been the venue has a PA already set up, but I've been in bands that had to hire a PAs for some gigs. Even if we had one at the practice space it usually wasn't big enough and worth the hassle to gig with it.
I rehearsed maybe 2-4 times with a vocalist who had a mic and a powered speaker kinda like a musician with an amp, but he was a coke fiend and that last about two weeks.
Note that I was only ever seriously in one band that had a dedicated vocalist. Every other band the singer(s) also played instruments. So there wasn't much split between singers and players. Most of us both sang and played. I owned a PA because I was an engineer, not because I sang. Add a mix engineer to the band and you should be set. ;-)
Comment: Thanks for this. I was considering more the situation where the singer did just that. It complicates it more when the vox also plays an instrument! I have several p.as, but am reticent to add one to the gear I already have to lug about, set up, break down, and store. Let alone repair when something breaks.

Who provides the p.a?


Show that when $n$ balls are thrown into $n^3$ cells, the chance that (at least) two balls will collide goes to zero as $n\to \infty$

Question: Show that when $n$ balls are thrown into $n^3$ cells, the chance that (at least) two balls will collide goes to zero, as a function of $n$:
$$\lim_{n\to \infty }P(\exists\, x,y:x,y\text{ collide})=0$$
Comment: What have you tried?
Comment: Hint: two balls do not collide if they land into different cells.
Comment: Tried Markov's inequality
Answer: Markov's inequality is the right idea. Let $X$ be the number of pairs of balls which are in the same cell. For example, when $n=6$, and the arrangement of balls is

Cell 1: Balls $1$ and $2$.
Cell 2: Balls $3,4$ and $5$.
Cell 3: Ball 6.
All other cells: empty.

then $X=4$, since the pairs are $(1,2)$, $(3,4),(3,5)$ and $(4,5)$.
You want to prove the probability of $X\ge 1$ goes to zero, so we can use Markov's inequality $P(X\le 1)\le E[X]$ to get an upper bound on this probability and instead show that $E[X]$ goes to zero.
By linearity of expectation, $E[X]$ is easy to calculate. There are $\binom{n}2$ pairs of balls. For each pair, the probability they are in the same cell is $\frac1{n^3}$. Therefore, $E[X]=\underline{\hspace{1.5cm}}$ (fill in the blank). Does this go to zero as $n\to\infty$?
Comment: Thank you, that's great. To calculate E[X] I"ll have to know the possible values of X. Are they {0,1,2,..., $n(n-1)/2$}?
Comment: @Osure Yes, those are the possible values. However, you do not want to use the formula $E[X]=\sum_{k} kP(X=k)$ to compute $E[X]$. Instead, you should use the method outlined in my last paragraph.


Inequality in products of probability measures

Question: For each $i=1,\ldots,N$ let $X_i$ be a compact subset of a t.v.s Hausdorff.
Let $M_i$ be the set of regular probability measures on $X_i$ and $u_i: \prod X_i \rightarrow \mathbb{R}$ a measurable bounded function.
If $\lambda=(\lambda_1,\ldots,\lambda_N) \in \prod M_i$ , there exists a $\tilde{x}_i \in X_i$ such that
$$ \int_{X_{-i}}u_i(\tilde{x}_i,y)d\lambda_{-i}(y) \geq \int_{X}u_i(x,y)d\lambda_i(x)d\lambda_{-i}(y)  $$
Is it true?
Thanks.
Comment: What are $X_{-i}$ and $\lambda_{-i}$?
Comment: I'm sorry. $X_{-i}= \prod_{j\neq i} X_j$ and $\lambda_{-i} = \otimes_{j\neq i}\lambda_j$.
Answer: Yes. If the inequality is false for every $\tilde {x_i}$ just integrate w.r.t. $\lambda_i$ to get a contradiction.
Comment: I'm sorry, I dont not understand well. If I integrate the inequality wrt $\lambda_i$ I form an equality.
Comment: If $f(x)<a$ for all $x$ and $\mu$ is a probability measure then $\int f(x)d\mu(x) <c$. So if we know that $\int f(x)d\mu(x) =c$ then we have a contradiction. So it is the equality you have quoted which leads to a  contradiction.
Comment: You're right, I was considering non-strict inequality. Thanks a lot!


How can I create a APNS Platform application on Simple Notification Service (SNS) using AWS PHP SDK?

Question: I'm having some problems to create a Platform Application on SNS using php AWS SDK to Apple APNS.
I created an GCM application and it's working fine, but I have no idea of how to create a PlataformApplication  to APNS.
Any one can show me an example?
I have the necessary certificates but I don't know how to use it.
The code that I'm using to create the GCM Plataform Application is:
<code>$result = $this->_sns->createPlatformApplication(array(
  'Name'       => Yii::app()->params['SNS_APPLICATION_NAME'],
  'Platform'   => 'GCM',
  'Attributes' => array('PlatformCredential' => Yii::app()->params['GCM_API_KEY']),
));
</code>
Thanks!
Answer: I finally found the answer of this question. To create a APNS platform application ARN is very simple.
After you generate the .pem certificate, you just need to separate the content of this file in two different files (private_key and certificate), and call the aws sis client like this:
<code>  $result = $this->_sns->createPlatformApplication(array(
    'Name'       => Yii::app()->params['SNS_APPLICATION_NAME'],
    'Platform'   => 'APNS_SANDBOX',
    'Attributes' => array(
      'PlatformCredential' => file_get_contents(dirname(__FILE__) . '/../runtime/key.txt'),
      'PlatformPrincipal'  => file_get_contents(dirname(__FILE__) . '/../runtime/certificate.txt'),
    ),
  ));
</code>
It will generate a APNS_SANDBOX or APNS platform applications ARN depending of your certificate.
I hope this help.
Thanks.


Explain overfitting / data leakage to a colleague

Question: I have a situation where we are calculating a customer life time value using some binary variables (ie have they purchased xyz widget?, etc.) and multiplying by a number that we believe approximates the value of these behaviors.
CLV = x1 * 500 + x2 * 300 + x3 * 100

The problem comes when a colleague wants to do a logistic regression to determine which customers will have CLV's above a certain threshold (ie if CLV >= 1000, y = 1, else y = 0)and use x1,x2 and x3 as variables.  I'm pretty certain this is a no-no as it's basically leaking info to the model but I'm having a hard time explaining this to my colleague.
Has anyone dealt with this issue before or know of a good source to explain this to someone who is math literate and intelligent but just doesn't have a ton of experience with modeling?
Comment: I don't see a problem here... You have a model and this logistic regression seems to be just a way of interpreting it, that's all. I guess I'm one of those guys who need that better explanation :)
Answer: I think the key here is is OLS won't give you any new information. It might be significant, but it is circular reasoning. You created your weights based on some reason, and it gives you this CLV value. What might be interesting is to look at the unweighted relationship between x1, x2, and x3, and use that to predict someone is likely to pass your threshold.
So it isn't wrong... it's just a waste of time, I think.
Answer: (I'm just waiting for Frank Harrell to tell you not to unnecessarily dichotomize)
Do you have any indication that the CPV should follow a logistic function of your $x$s?
Otherwise, I think what you are after is a tolerance interval for the regression.
  I liked the explanations (in German) in Nachweisvermögen von Analysenverfahren. There's also a paper in JSS which gives a general introduction before discussing how to calculate them.


Apache redirect Absolue url to relative url

Question: So I want to load a web-app from a subfolder. Current configuration looks like this
<VirtualHost *:80>
    ServerName YOUR IP ADDRESS/DOMAIN

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/

    <Directory /var/www/html/monica/public/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted

        # Everything under this line has been added by me to try to make the redirect work
        RewriteEngine  on
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$           /var/www/html/monica/public/$1  [R]
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

The pages are being served correctly, but since the files contain absolute url, it keeps on failing. I'm really new to Apache so I don't know what I'm doing wrong and searching for answer has been futile.
If I make the DocumentRoot /var/www/html/monica/public/ it works correctly but I want to access it from a subdirectory, something like localhost/monica/
A note: This webapp was made to be be accessed from the base ( https://github.com/monicahq/monica/)
Comment: "The pages are being served correctly" - Can you give an example URL? Are you directly serving physical files from the filesystem? It's just that I'm looking at your `RewriteRule` directive - there's no way that can work - you can't reference an absolute filesystem path in a _directory_ context (so I guess that isn't doing anything or you've not restarted your webserver?). "but since the files contain absolute url, it keeps on failing" - "files" as in HTML files? An absolute URL is normally a good thing so I'm not sure why that is a problem - can you include an example?
Comment: "If I make the DocumentRoot `/var/www/html/monica/public/`" - from the information given, I can't see why that would make a difference?
Comment: @MrWhite Yes, I'm serving physical files.The index.php file is in the `/public/` path which references absolute path for assets like image, js, css etc and those absolute paths are based on the assumption that the root folder is `/var/www/html/monica/public/`. I can't show you a live example since the project is hosted locally, but this is the file structure https://github.com/monicahq/monica/tree/master/public
Answer: I think I understand what you are referring to now (although an example "absolute path" of how you are referencing your assets would be useful). I assume you are referencing your assets something like /img/image.jpg (or https://example.com/img/image.jpg)? Whereas the actual resource is located at /monica/public/img/image.jpg? So, you basically need to rewrite all your URLs (for static assets) to the /monica/public subdirectory. But doesn't this also affect your inter-page URLs? (Unless you are using solely relative URLs between pages?)
For example, instead of your existing <Directory> block, try the following. Note the Directory path references your document root.
<Directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted

    RewriteEngine  on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule (.+\.(?:jpg|png|css|js))$ /monica/public/$1  [L]
</Directory>

The purpose of the check for file extensions (of your static assets) is to avoid the "file exists" check on every request (which is relatively expensive).
This assumes that you have a .htaccess file located at /monica/public/.htaccess (as shown in your file structure) that then routes the request. (Otherwise this could result in a rewrite loop if the asset really doesn't exist.)

If I make the DocumentRoot /var/www/html/monica/public/ it works correctly but I want to access it from a subdirectory, something like localhost/monica/

However, this sounds like you should "fix" your URL-paths (routing within Laravel) instead of rewriting your resources?

UPDATE:

can you tell me how would I do that?

I'm not sure, this would seem to be a Laravel/PHP issue? The document root would be /var/www/html/monica/public/ (filesystem path), but you want to effectively serve your content from a /monica subdirectory in the URL-path. Note that "monica" in /var/www/html/monica/public/ is a different "monica" to the one in your URL. You could have your webapp in a /monica subdirectory on the filesystem (so the absolute filesystem path would be /var/www/html/monica/public/monica) OR you change all the URLs in your webapp  to include /monica/ at the start of the URL-path.
Regardless of how you do it, all the URLs in your webapp (for static resources and everything) need to start /monica. So, I don't see any way other than modifying your routing within Laravel.
Apache can help with moving content from say the document root to the /monica subdirectory by issuing an external redirect. But this is only for SEO benefit, not to be used all the time by your users (slower, extra load on server, etc.).

If I change it to this ... the assets stop loading again. Do you have any idea why?
<Directory /var/www/html/monica>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted

    RewriteEngine  on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule (.+\.(?:jpg|png|css|js))$ /public/$1  [L]
</Directory>

Because (if my assumption at the start of my answer is still correct) you are referencing your assets like /img/image.jpg and not /monica/img/image.jpg.
Comment: I've updated my answer.
Comment: This works; I swear I tried this exact same thing. I'm kind of new to this, so can you tell me how would I do that?
Comment: If I change it to this https://pastebin.com/fkni1Sxm the assets stop loading again. Do you have any idea why?


What is the most classically correct way to play this fast run?

Question: I am trying to figure out the best way to play the first run in Francesco Tarrega's Caprice Arabe. This run is meant to be played really really really fast.
First way:

       p     i    p     i   p   p i p
       4  1  2  1  4 2  2 1 4 2 4
    E|-15p12-10p9-12p10-6p5-8p6---0-0-|
    B|--------------------------8-----|
    G|--------------------------------|
    D|--------------------------------|
    A|--------------------------------|
    D|--------------------------------|

Second way:

       p     i    p     i   p   p   i
       4  1  2  1 4  2  2 1 4 2 4 1 0
    E|-15p12-10p9-12p10-6p5-8p6-----0-|
    B|--------------------------8p5---|
    G|--------------------------------|
    D|--------------------------------|
    A|--------------------------------|
    D|--------------------------------|

The first keeps most of its notes on one string, which is a plus. (One voice)
The second doesn't mute the first E tone string when it's played again which makes it sound more convincing. This comes at the expense of there being no easy way of pre-positioning your left hand's index finger for the 8-5 pulloff, which may make it difficult or impossible to ever play rapidly.
Which is the most orthodox method with respect to traditional classical theory?
Answer: I agree both versions' benefits are desirable, but neither actually works – at least not for me.
Keeping everthing on one string is particularly appealing as this makes it easy to start with a nice dolce in the 12th position and "automatically" develop it to a more clearly pronounced sound as you gather speed in the lower positions. You could in fact be consequent and keep every note on the e-string, except for the last one, for which I would aim for a sweet sound again, with a very gentle vibrato. (Definitely if you want it to be "classically correct": open strings in such an exposed place are acceptable in baroque or modern styles, but hardly in a romantic piece like this.)So that would be
<code>   4  1  2  1 4  2  2 1 4 2 1 0 2
e|-15p12-10p9-12p10-6p5-8p6-3p0----
b|------------------------------5--
</code>
Of course, you need to be careful with this solution: the last notes on the e string can easily start to sound harsh, so I'd also put both of them on the b string as in your second version. It's a nice idea to play both e's in the end on different strings, but again I would definitely not put the last note on the empty string. How about the g string? You should avoid using the thumb three times in a row, so I'd go for
<code>   p     i    m     p   i   p   p
   4  1  2  1 4  2  2 1 4 2 4 1 4
e|-15p12-10p9-12p10-6p5-8p6--------
b|--------------------------8p5----
g|------------------------------9--
</code>
But I shouldn't be sure about it, it's probably better after all to simply play the e twice on the b string as in the video linked by horatio. I also tend to prefer the apoyando plucking used there, i.e.
<code>   i     m    i     m   i   i   m
   4  1  2  1 4  2  2 1 4 2 4 1 1
e|-15p12-10p9-12p10-6p5-8p6--------
b|--------------------------8p5-5--
</code>
Comment: I posted the one video, but I looked at a number of them, and they all seem to agree on where they stop. Personally, I think some of them play e on both the b and e strings, allowing vibrato on the b string.
Answer: It looks to me like you are making this passage harder than it needs to be. I play it like this:
<code>15p12-10p9-12p10----------------0-0-
-----------------11p10-13p11--------
-----------------------------12-----
</code>
The only challenging part is making the first 4 notes sound smooth (and even that isn't too hard). After that it is really easy using this fingering. The other suggested ways seem harder and not as pleasing to my ear. Although, the vibrato at the end is nice. Also, this is the fingering shown in the original Tarrega score for this song (or so the book I have says).
Answer: a quick perusal of youtube videos says (this:

 ) neither 1 nor 2, but mostly 2
Comment: He did -8p5-5-.